From fcf83dbf9effab3bd98bad2b83b2468b7eb05cfd Mon Sep 17 00:00:00 2001 From: Tim Foley Date: Fri, 9 Jun 2017 11:34:21 -0700 Subject: Initial import of code. --- .gitignore | 26 + LICENSE | 2 +- README.md | 40 +- build/slang-build.props | 11 + examples/hello/README.md | 9 + examples/hello/hello.cpp | 589 + examples/hello/hello.slang | 73 + examples/hello/hello.sln | 28 + examples/hello/hello.vcxproj | 296 + examples/hello/hello.vcxproj.filters | 9 + external/glext.h | 12261 +++++++++++++++++++ external/stb/stb_image.h | 7177 +++++++++++ external/stb/stb_image_write.h | 1092 ++ slang.h | 897 ++ slang.sln | 460 + source/core/allocator.h | 62 + source/core/array-view.h | 131 + source/core/array.h | 146 + source/core/basic.h | 21 + source/core/common.h | 48 + source/core/core.natvis | 105 + source/core/core.vcxproj | 802 ++ source/core/dictionary.h | 1018 ++ source/core/exception.h | 115 + source/core/func.h | 216 + source/core/hash.h | 105 + source/core/int-set.h | 166 + source/core/link.h | 336 + source/core/linq.h | 669 + source/core/list.h | 674 + source/core/memory-pool.cpp | 135 + source/core/memory-pool.h | 126 + source/core/secure-crt.h | 75 + source/core/slang-io.cpp | 145 + source/core/slang-io.h | 63 + source/core/slang-math.cpp | 9 + source/core/slang-math.h | 220 + source/core/slang-string.cpp | 166 + source/core/slang-string.h | 740 ++ source/core/smart-pointer.h | 468 + source/core/stream.cpp | 220 + source/core/stream.h | 333 + source/core/text-io.cpp | 344 + source/core/text-io.h | 320 + source/core/type-traits.h | 49 + source/slang/check.cpp | 4973 ++++++++ source/slang/compiled-program.h | 96 + source/slang/compiler.cpp | 659 + source/slang/compiler.h | 156 + source/slang/diagnostic-defs.h | 338 + source/slang/diagnostics.cpp | 204 + source/slang/diagnostics.h | 218 + source/slang/emit.cpp | 2537 ++++ source/slang/emit.h | 24 + source/slang/intrinsic-defs.h | 94 + source/slang/lexer.cpp | 1012 ++ source/slang/lexer.h | 101 + source/slang/lookup.cpp | 311 + source/slang/lookup.h | 41 + source/slang/parameter-binding.cpp | 1252 ++ source/slang/parameter-binding.h | 32 + source/slang/parser.cpp | 3106 +++++ source/slang/parser.h | 23 + source/slang/preprocessor.cpp | 2032 +++ source/slang/preprocessor.h | 35 + source/slang/profile-defs.h | 123 + source/slang/profile.cpp | 20 + source/slang/profile.h | 84 + source/slang/reflection.cpp | 1404 +++ source/slang/reflection.h | 39 + source/slang/slang-stdlib.cpp | 1855 +++ source/slang/slang-stdlib.h | 23 + source/slang/slang.cpp | 699 ++ source/slang/slang.natvis | 14 + source/slang/slang.vcxproj | 427 + source/slang/slang.vcxproj.filters | 48 + source/slang/source-loc.h | 47 + source/slang/syntax-visitors.h | 21 + source/slang/syntax.cpp | 1484 +++ source/slang/syntax.h | 2771 +++++ source/slang/token-defs.h | 93 + source/slang/token.cpp | 22 + source/slang/token.h | 50 + source/slang/type-layout.cpp | 1125 ++ source/slang/type-layout.h | 550 + source/slangc/main.cpp | 644 + source/slangc/slangc.vcxproj | 391 + source/slangc/slangc.vcxproj.filters | 22 + test.bat | 34 + tests/bindings/README.md | 29 + tests/bindings/binding0.hlsl | 27 + tests/bindings/binding1.hlsl | 41 + tests/bindings/explicit-binding.hlsl | 55 + tests/bindings/multi-file-extra.hlsl | 60 + tests/bindings/multi-file.hlsl | 64 + tests/bindings/packoffset.hlsl | 40 + tests/bindings/resources-in-cbuffer.hlsl | 68 + tests/bindings/resources-in-structs.hlsl.disabled | 42 + tests/bindings/targets-and-uavs-structure.hlsl | 36 + tests/bindings/targets-and-uavs.hlsl | 28 + tests/diagnostics/break-outside-loop.spire | 4 + .../diagnostics/break-outside-loop.spire.expected | 6 + tests/diagnostics/call-argument-type.spire | 11 + .../diagnostics/call-argument-type.spire.expected | 6 + tests/diagnostics/continue-outside-loop.spire | 4 + .../continue-outside-loop.spire.expected | 6 + tests/diagnostics/expected-token-eof.spire | 6 + .../diagnostics/expected-token-eof.spire.expected | 6 + tests/diagnostics/expected-token.spire | 7 + tests/diagnostics/expected-token.spire.expected | 6 + .../function-redefinition.spire.disabled | 5 + .../function-redefinition.spire.expected | 6 + .../hull-shader-invalid-domain.spire.disabled | 53 + .../hull-shader-invalid-domain.spire.expected | 6 + .../hull-shader-no-domain.spire.disabled | 53 + .../hull-shader-no-domain.spire.expected | 6 + tests/diagnostics/illegal-character.spire | 5 + tests/diagnostics/illegal-character.spire.expected | 6 + tests/diagnostics/missing-file.spire.disabled | 3 + tests/diagnostics/missing-file.spire.expected | 7 + tests/diagnostics/missing-include-file.spire | 4 + .../missing-include-file.spire.expected | 6 + tests/diagnostics/parameter-already-defined.spire | 4 + .../parameter-already-defined.spire.expected | 6 + tests/diagnostics/undefined-identifier.spire | 7 + .../undefined-identifier.spire.expected | 6 + tests/diagnostics/variable-void-type.spire | 7 + .../diagnostics/variable-void-type.spire.expected | 6 + tests/diagnostics/while-predicate-type.spire | 10 + .../while-predicate-type.spire.expected | 6 + tests/front-end/lexer-comments.spire | 13 + tests/front-end/parser-decls.spire | 60 + tests/front-end/parser-empty.spire | 1 + tests/front-end/parser-error-unclosed-curly.spire | 3 + .../parser-error-unclosed-curly.spire.expected | 6 + tests/front-end/parser-using-file-a.spireh | 3 + tests/front-end/parser-using-file.spire.disabled | 6 + tests/front-end/pipeline-simple.spireh | 41 + tests/front-end/struct.spire | 49 + tests/front-end/typedef.spire | 15 + tests/glsl/sascha-willems/LICENSE.md | 21 + tests/glsl/sascha-willems/README.md | 8 + tests/glsl/sascha-willems/base/textoverlay.frag | 14 + tests/glsl/sascha-willems/base/textoverlay.vert | 18 + tests/glsl/sascha-willems/bloom/colorpass.frag | 18 + tests/glsl/sascha-willems/bloom/colorpass.vert | 31 + tests/glsl/sascha-willems/bloom/gaussblur.frag | 48 + tests/glsl/sascha-willems/bloom/gaussblur.vert | 18 + tests/glsl/sascha-willems/bloom/phongpass.frag | 34 + tests/glsl/sascha-willems/bloom/phongpass.vert | 42 + tests/glsl/sascha-willems/bloom/skybox.frag | 16 + tests/glsl/sascha-willems/bloom/skybox.vert | 28 + .../sascha-willems/computecullandlod/cull.comp | 127 + .../computecullandlod/indirectdraw.frag | 21 + .../computecullandlod/indirectdraw.vert | 46 + .../glsl/sascha-willems/computenbody/particle.frag | 18 + .../glsl/sascha-willems/computenbody/particle.vert | 36 + .../computenbody/particle_calculate.comp | 75 + .../computenbody/particle_integrate.comp | 36 + .../sascha-willems/computeparticles/particle.comp | 80 + .../sascha-willems/computeparticles/particle.frag | 19 + .../sascha-willems/computeparticles/particle.vert | 25 + .../sascha-willems/computeshader/edgedetect.comp | 48 + .../glsl/sascha-willems/computeshader/emboss.comp | 48 + .../glsl/sascha-willems/computeshader/sharpen.comp | 57 + .../glsl/sascha-willems/computeshader/texture.frag | 16 + .../glsl/sascha-willems/computeshader/texture.vert | 27 + tests/glsl/sascha-willems/cubemap/reflect.frag | 36 + tests/glsl/sascha-willems/cubemap/reflect.vert | 42 + tests/glsl/sascha-willems/cubemap/skybox.frag | 16 + tests/glsl/sascha-willems/cubemap/skybox.vert | 27 + .../glsl/sascha-willems/debugmarker/colorpass.frag | 14 + .../glsl/sascha-willems/debugmarker/colorpass.vert | 29 + .../sascha-willems/debugmarker/postprocess.frag | 43 + .../sascha-willems/debugmarker/postprocess.vert | 18 + tests/glsl/sascha-willems/debugmarker/toon.frag | 40 + tests/glsl/sascha-willems/debugmarker/toon.vert | 42 + tests/glsl/sascha-willems/deferred/debug.frag | 27 + tests/glsl/sascha-willems/deferred/debug.vert | 28 + tests/glsl/sascha-willems/deferred/deferred.frag | 76 + tests/glsl/sascha-willems/deferred/deferred.vert | 18 + tests/glsl/sascha-willems/deferred/mrt.frag | 34 + tests/glsl/sascha-willems/deferred/mrt.vert | 53 + .../deferredmultisampling/debug.frag | 56 + .../deferredmultisampling/debug.vert | 24 + .../deferredmultisampling/deferred.frag | 104 + .../deferredmultisampling/deferred.vert | 24 + .../sascha-willems/deferredmultisampling/mrt.frag | 34 + .../sascha-willems/deferredmultisampling/mrt.vert | 53 + .../glsl/sascha-willems/deferredshadows/debug.frag | 30 + .../glsl/sascha-willems/deferredshadows/debug.vert | 30 + .../sascha-willems/deferredshadows/deferred.frag | 147 + .../sascha-willems/deferredshadows/deferred.vert | 27 + tests/glsl/sascha-willems/deferredshadows/mrt.frag | 33 + tests/glsl/sascha-willems/deferredshadows/mrt.vert | 51 + .../sascha-willems/deferredshadows/shadow.frag | 12 + .../sascha-willems/deferredshadows/shadow.geom | 36 + .../sascha-willems/deferredshadows/shadow.vert | 20 + tests/glsl/sascha-willems/displacement/base.frag | 30 + tests/glsl/sascha-willems/displacement/base.vert | 19 + .../sascha-willems/displacement/displacement.tesc | 33 + .../sascha-willems/displacement/displacement.tese | 40 + .../sascha-willems/distancefieldfonts/bitmap.frag | 16 + .../sascha-willems/distancefieldfonts/bitmap.vert | 22 + .../sascha-willems/distancefieldfonts/sdf.frag | 36 + .../sascha-willems/distancefieldfonts/sdf.vert | 22 + .../sascha-willems/dynamicuniformbuffer/base.frag | 14 + .../sascha-willems/dynamicuniformbuffer/base.vert | 34 + tests/glsl/sascha-willems/gears/gears.frag | 25 + tests/glsl/sascha-willems/gears/gears.vert | 35 + tests/glsl/sascha-willems/geometryshader/base.frag | 14 + tests/glsl/sascha-willems/geometryshader/base.vert | 21 + tests/glsl/sascha-willems/geometryshader/mesh.frag | 24 + tests/glsl/sascha-willems/geometryshader/mesh.vert | 39 + .../sascha-willems/geometryshader/normaldebug.geom | 38 + tests/glsl/sascha-willems/hdr/bloom.frag | 67 + tests/glsl/sascha-willems/hdr/bloom.vert | 18 + tests/glsl/sascha-willems/hdr/composition.frag | 17 + tests/glsl/sascha-willems/hdr/composition.vert | 18 + tests/glsl/sascha-willems/hdr/gbuffer.frag | 95 + tests/glsl/sascha-willems/hdr/gbuffer.vert | 51 + tests/glsl/sascha-willems/imgui/scene.frag | 23 + tests/glsl/sascha-willems/imgui/scene.vert | 39 + tests/glsl/sascha-willems/imgui/ui.frag | 14 + tests/glsl/sascha-willems/imgui/ui.vert | 26 + tests/glsl/sascha-willems/indirectdraw/ground.frag | 29 + tests/glsl/sascha-willems/indirectdraw/ground.vert | 44 + .../sascha-willems/indirectdraw/indirectdraw.frag | 31 + .../sascha-willems/indirectdraw/indirectdraw.vert | 83 + .../sascha-willems/indirectdraw/skysphere.frag | 18 + .../sascha-willems/indirectdraw/skysphere.vert | 29 + .../glsl/sascha-willems/instancing/instancing.frag | 27 + .../glsl/sascha-willems/instancing/instancing.vert | 85 + tests/glsl/sascha-willems/instancing/planet.frag | 27 + tests/glsl/sascha-willems/instancing/planet.vert | 36 + .../glsl/sascha-willems/instancing/starfield.frag | 35 + .../glsl/sascha-willems/instancing/starfield.vert | 10 + tests/glsl/sascha-willems/mesh/mesh.frag | 28 + tests/glsl/sascha-willems/mesh/mesh.vert | 42 + .../glsl/sascha-willems/multithreading/phong.frag | 24 + .../glsl/sascha-willems/multithreading/phong.vert | 43 + .../sascha-willems/multithreading/starsphere.frag | 43 + .../sascha-willems/multithreading/starsphere.vert | 20 + tests/glsl/sascha-willems/occlusionquery/mesh.frag | 32 + tests/glsl/sascha-willems/occlusionquery/mesh.vert | 42 + .../sascha-willems/occlusionquery/occluder.frag | 14 + .../sascha-willems/occlusionquery/occluder.vert | 29 + .../glsl/sascha-willems/occlusionquery/simple.frag | 14 + .../glsl/sascha-willems/occlusionquery/simple.vert | 26 + tests/glsl/sascha-willems/offscreen/mirror.frag | 44 + tests/glsl/sascha-willems/offscreen/mirror.vert | 29 + tests/glsl/sascha-willems/offscreen/phong.frag | 30 + tests/glsl/sascha-willems/offscreen/phong.vert | 40 + tests/glsl/sascha-willems/offscreen/quad.frag | 16 + tests/glsl/sascha-willems/offscreen/quad.vert | 27 + tests/glsl/sascha-willems/parallax/parallax.frag | 144 + tests/glsl/sascha-willems/parallax/parallax.vert | 38 + .../sascha-willems/particlefire/normalmap.frag | 45 + .../sascha-willems/particlefire/normalmap.vert | 60 + .../glsl/sascha-willems/particlefire/particle.frag | 47 + .../glsl/sascha-willems/particlefire/particle.vert | 50 + tests/glsl/sascha-willems/pbrbasic/pbr.frag | 128 + tests/glsl/sascha-willems/pbrbasic/pbr.vert | 39 + tests/glsl/sascha-willems/pbribl/filtercube.vert | 20 + tests/glsl/sascha-willems/pbribl/genbrdflut.frag | 91 + tests/glsl/sascha-willems/pbribl/genbrdflut.vert | 10 + .../glsl/sascha-willems/pbribl/irradiancecube.frag | 38 + tests/glsl/sascha-willems/pbribl/pbribl.frag | 163 + tests/glsl/sascha-willems/pbribl/pbribl.vert | 40 + .../sascha-willems/pbribl/prefilterenvmap.frag | 106 + tests/glsl/sascha-willems/pbribl/skybox.frag | 40 + tests/glsl/sascha-willems/pbribl/skybox.vert | 28 + .../glsl/sascha-willems/pbrtexture/filtercube.vert | 20 + .../glsl/sascha-willems/pbrtexture/genbrdflut.frag | 91 + .../glsl/sascha-willems/pbrtexture/genbrdflut.vert | 10 + .../sascha-willems/pbrtexture/irradiancecube.frag | 38 + .../glsl/sascha-willems/pbrtexture/pbrtexture.frag | 179 + .../glsl/sascha-willems/pbrtexture/pbrtexture.vert | 36 + .../sascha-willems/pbrtexture/prefilterenvmap.frag | 106 + tests/glsl/sascha-willems/pbrtexture/skybox.frag | 40 + tests/glsl/sascha-willems/pbrtexture/skybox.vert | 28 + tests/glsl/sascha-willems/pipelines/phong.frag | 31 + tests/glsl/sascha-willems/pipelines/phong.vert | 42 + tests/glsl/sascha-willems/pipelines/toon.frag | 40 + tests/glsl/sascha-willems/pipelines/toon.vert | 42 + tests/glsl/sascha-willems/pipelines/wireframe.frag | 14 + tests/glsl/sascha-willems/pipelines/wireframe.vert | 29 + .../glsl/sascha-willems/pushconstants/lights.frag | 41 + .../glsl/sascha-willems/pushconstants/lights.vert | 48 + .../glsl/sascha-willems/radialblur/colorpass.frag | 25 + .../glsl/sascha-willems/radialblur/colorpass.vert | 30 + .../glsl/sascha-willems/radialblur/phongpass.frag | 37 + .../glsl/sascha-willems/radialblur/phongpass.vert | 38 + .../glsl/sascha-willems/radialblur/radialblur.frag | 39 + .../glsl/sascha-willems/radialblur/radialblur.vert | 18 + .../glsl/sascha-willems/raytracing/raytracing.comp | 258 + tests/glsl/sascha-willems/raytracing/texture.frag | 16 + tests/glsl/sascha-willems/raytracing/texture.vert | 18 + .../glsl/sascha-willems/scenerendering/scene.frag | 35 + .../glsl/sascha-willems/scenerendering/scene.vert | 46 + tests/glsl/sascha-willems/screenshot/mesh.frag | 24 + tests/glsl/sascha-willems/screenshot/mesh.vert | 40 + .../shadowmapomni/cubemapdisplay.frag | 17 + .../shadowmapomni/cubemapdisplay.vert | 28 + .../sascha-willems/shadowmapomni/offscreen.frag | 17 + .../sascha-willems/shadowmapomni/offscreen.vert | 36 + tests/glsl/sascha-willems/shadowmapomni/scene.frag | 44 + tests/glsl/sascha-willems/shadowmapomni/scene.vert | 43 + .../sascha-willems/shadowmapping/offscreen.frag | 14 + .../sascha-willems/shadowmapping/offscreen.vert | 23 + tests/glsl/sascha-willems/shadowmapping/quad.frag | 25 + tests/glsl/sascha-willems/shadowmapping/quad.vert | 28 + tests/glsl/sascha-willems/shadowmapping/scene.frag | 72 + tests/glsl/sascha-willems/shadowmapping/scene.vert | 52 + .../sascha-willems/skeletalanimation/mesh.frag | 28 + .../sascha-willems/skeletalanimation/mesh.vert | 53 + .../sascha-willems/skeletalanimation/texture.frag | 32 + .../sascha-willems/skeletalanimation/texture.vert | 40 + .../specializationconstants/uber.frag | 75 + .../specializationconstants/uber.vert | 42 + .../sascha-willems/sphericalenvmapping/sem.frag | 23 + .../sascha-willems/sphericalenvmapping/sem.vert | 35 + tests/glsl/sascha-willems/ssao/blur.frag | 29 + tests/glsl/sascha-willems/ssao/composition.frag | 56 + tests/glsl/sascha-willems/ssao/fullscreen.vert | 18 + tests/glsl/sascha-willems/ssao/gbuffer.frag | 30 + tests/glsl/sascha-willems/ssao/gbuffer.vert | 43 + tests/glsl/sascha-willems/ssao/ssao.frag | 73 + .../glsl/sascha-willems/subpasses/composition.frag | 82 + .../glsl/sascha-willems/subpasses/composition.vert | 18 + tests/glsl/sascha-willems/subpasses/gbuffer.frag | 43 + tests/glsl/sascha-willems/subpasses/gbuffer.vert | 43 + .../glsl/sascha-willems/subpasses/transparent.frag | 34 + .../glsl/sascha-willems/subpasses/transparent.vert | 28 + .../terraintessellation/skysphere.frag | 14 + .../terraintessellation/skysphere.vert | 24 + .../terraintessellation/terrain.frag | 65 + .../terraintessellation/terrain.tesc | 120 + .../terraintessellation/terrain.tese | 58 + .../terraintessellation/terrain.vert | 24 + tests/glsl/sascha-willems/tessellation/base.frag | 22 + tests/glsl/sascha-willems/tessellation/base.vert | 24 + .../sascha-willems/tessellation/passthrough.tesc | 28 + .../sascha-willems/tessellation/passthrough.tese | 31 + .../sascha-willems/tessellation/pntriangles.tesc | 87 + .../sascha-willems/tessellation/pntriangles.tese | 92 + .../sascha-willems/textoverlay/background.frag | 16 + .../sascha-willems/textoverlay/background.vert | 18 + tests/glsl/sascha-willems/textoverlay/mesh.frag | 27 + tests/glsl/sascha-willems/textoverlay/mesh.vert | 39 + tests/glsl/sascha-willems/textoverlay/text.frag | 14 + tests/glsl/sascha-willems/textoverlay/text.vert | 18 + tests/glsl/sascha-willems/texture/texture.frag | 29 + tests/glsl/sascha-willems/texture/texture.vert | 45 + tests/glsl/sascha-willems/texture3d/texture3d.frag | 29 + tests/glsl/sascha-willems/texture3d/texture3d.vert | 44 + .../sascha-willems/texturearray/instancing.frag | 16 + .../sascha-willems/texturearray/instancing.vert | 30 + .../sascha-willems/texturemipmapgen/texture.frag | 30 + .../sascha-willems/texturemipmapgen/texture.vert | 47 + .../texturesparseresidency/sparseresidency.frag | 48 + .../texturesparseresidency/sparseresidency.vert | 43 + tests/glsl/sascha-willems/triangle/triangle.frag | 14 + tests/glsl/sascha-willems/triangle/triangle.vert | 29 + .../sascha-willems/viewportarray/multiview.geom | 46 + tests/glsl/sascha-willems/viewportarray/scene.frag | 21 + tests/glsl/sascha-willems/viewportarray/scene.vert | 21 + tests/glsl/sascha-willems/vulkanscene/logo.frag | 23 + tests/glsl/sascha-willems/vulkanscene/logo.vert | 38 + tests/glsl/sascha-willems/vulkanscene/mesh.frag | 45 + tests/glsl/sascha-willems/vulkanscene/mesh.vert | 38 + tests/glsl/sascha-willems/vulkanscene/skybox.frag | 16 + tests/glsl/sascha-willems/vulkanscene/skybox.vert | 21 + .../dxsdk/AdaptiveTessellationCS40/Render.hlsl | 58 + .../dxsdk/AdaptiveTessellationCS40/ScanCS.hlsl | 109 + .../TessellatorCS40_EdgeFactorCS.hlsl | 217 + .../TessellatorCS40_NumVerticesIndicesCS.hlsl | 56 + .../TessellatorCS40_ScatterIDCS.hlsl | 45 + .../TessellatorCS40_TessellateIndicesCS.hlsl | 628 + .../TessellatorCS40_TessellateVerticesCS.hlsl | 206 + .../TessellatorCS40_common.hlsl | 411 + .../TessellatorCS40_defines.h | 9 + .../dxsdk/BC6HBC7EncoderCS/Shaders/BC6HEncode.hlsl | 2567 ++++ .../dxsdk/BC6HBC7EncoderCS/Shaders/BC7Encode.hlsl | 1908 +++ .../hlsl/dxsdk/BasicCompute11/BasicCompute11.hlsl | 72 + tests/hlsl/dxsdk/BasicHLSL11/BasicHLSL.fx | 158 + tests/hlsl/dxsdk/BasicHLSL11/BasicHLSL11_PS.hlsl | 51 + tests/hlsl/dxsdk/BasicHLSL11/BasicHLSL11_VS.hlsl | 49 + tests/hlsl/dxsdk/BasicHLSLFX11/BasicHLSLFX11.fx | 181 + .../CascadedShadowMaps11/RenderCascadeScene.hlsl | 506 + .../CascadedShadowMaps11/RenderCascadeShadow.hlsl | 53 + .../ComputeShaderSort11/ComputeShaderSort11.hlsl | 75 + .../Direct3D11Tutorials/Tutorial02/Tutorial02.fx | 23 + .../Tutorial02/Tutorial02_PS.hlsl | 3 + .../Tutorial02/Tutorial02_VS.hlsl | 3 + .../Direct3D11Tutorials/Tutorial03/Tutorial03.fx | 23 + .../Tutorial03/Tutorial03_PS.hlsl | 3 + .../Tutorial03/Tutorial03_VS.hlsl | 3 + .../Direct3D11Tutorials/Tutorial04/Tutorial04.fx | 46 + .../Tutorial04/Tutorial04_PS.hlsl | 3 + .../Tutorial04/Tutorial04_VS.hlsl | 3 + .../Direct3D11Tutorials/Tutorial05/Tutorial05.fx | 54 + .../Tutorial05/Tutorial05_PS.hlsl | 3 + .../Tutorial05/Tutorial05_VS.hlsl | 3 + .../Direct3D11Tutorials/Tutorial06/Tutorial06.fx | 76 + .../Tutorial06/Tutorial06_PS.hlsl | 3 + .../Tutorial06/Tutorial06_VS.hlsl | 3 + .../Direct3D11Tutorials/Tutorial07/Tutorial07.fx | 67 + .../Tutorial07/Tutorial07_PS.hlsl | 3 + .../Tutorial07/Tutorial07_VS.hlsl | 3 + .../Tutorial08/Tutorial08.fx | 56 + .../Tutorial09/Tutorial09.fx | 69 + .../Tutorial10/Tutorial10.fx | 73 + .../Tutorial11/Tutorial11.fx | 117 + .../Tutorial12/Tutorial12.fx | 129 + .../Tutorial13/Tutorial13.fx | 191 + .../Tutorial14/Tutorial14.fx | 294 + .../DynamicShaderLinkage11_LightPSH.h | 84 + .../DynamicShaderLinkage11_MaterialPSH.h | 103 + .../DynamicShaderLinkage11_PS.hlsl | 84 + .../DynamicShaderLinkage11_PSBuffers.h | 129 + .../DynamicShaderLinkage11_VS.hlsl | 66 + .../DynamicShaderLinkageFX11.fx | 192 + .../DynamicShaderLinkageFX11_LightPSH.h | 82 + .../DynamicShaderLinkageFX11_MaterialPSH.h | 103 + .../DynamicShaderLinkageFX11_PSBuffers.h | 152 + .../DynamicShaderLinkageFX11_ps.hlsl | 113 + .../DynamicShaderLinkageFX11_vs.hlsl | 65 + tests/hlsl/dxsdk/FixedFuncEMUFX11/FixedFuncEMU.fx | 468 + .../hlsl/dxsdk/FluidCS11/ComputeShaderSort11.hlsl | 75 + tests/hlsl/dxsdk/FluidCS11/FluidCS11.hlsl | 529 + tests/hlsl/dxsdk/FluidCS11/FluidRender.hlsl | 112 + .../BrightPassAndHorizFilterCS.hlsl | 64 + .../dxsdk/HDRToneMappingCS11/DumpToTexture.hlsl | 29 + tests/hlsl/dxsdk/HDRToneMappingCS11/FilterCS.hlsl | 73 + tests/hlsl/dxsdk/HDRToneMappingCS11/FinalPass.hlsl | 79 + .../hlsl/dxsdk/HDRToneMappingCS11/PSApproach.hlsl | 129 + .../dxsdk/HDRToneMappingCS11/ReduceTo1DCS.hlsl | 72 + .../dxsdk/HDRToneMappingCS11/ReduceToSingleCS.hlsl | 63 + tests/hlsl/dxsdk/HDRToneMappingCS11/skybox11.hlsl | 44 + tests/hlsl/dxsdk/InstancingFX11/Instancing.fx | 591 + .../MultithreadedRendering11_PS.hlsl | 202 + .../MultithreadedRendering11_VS.hlsl | 75 + .../dxsdk/NBodyGravityCS11/NBodyGravityCS11.hlsl | 103 + .../hlsl/dxsdk/NBodyGravityCS11/ParticleDraw.hlsl | 128 + tests/hlsl/dxsdk/OIT11/OIT_CS.hlsl | 277 + tests/hlsl/dxsdk/OIT11/OIT_PS.hlsl | 56 + tests/hlsl/dxsdk/OIT11/SceneVS.hlsl | 36 + tests/hlsl/dxsdk/README.md | 5 + .../hlsl/dxsdk/SimpleBezier11/SimpleBezier11.hlsl | 230 + tests/hlsl/dxsdk/SimpleSample11/SimpleSample.fx | 112 + tests/hlsl/dxsdk/SimpleSample11/SimpleSample.hlsl | 86 + tests/hlsl/dxsdk/SubD11/SubD11.hlsl | 1238 ++ .../dxsdk/VarianceShadows11/2DQuadShaders.hlsl | 211 + .../VarianceShadows11/RenderVarianceScene.hlsl | 412 + .../VarianceShadows11/RenderVarianceShadow.hlsl | 45 + tests/hlsl/simple/compute-numthreads.hlsl | 11 + tests/preprocessor/define-function-like.spire | 19 + .../define-function-like.spire.expected | 7 + tests/preprocessor/define-simple.spire | 14 + tests/preprocessor/if.spire | 15 + tests/preprocessor/ifdef.spire | 16 + tests/preprocessor/include-a.spireh | 3 + tests/preprocessor/include.spire | 8 + tests/reflection/arrays.hlsl | 27 + tests/reflection/arrays.hlsl.expected | 103 + tests/reflection/global-uniforms.hlsl | 21 + tests/reflection/global-uniforms.hlsl.expected | 72 + tests/reflection/multi-file-extra.hlsl | 63 + tests/reflection/multi-file.hlsl | 56 + tests/reflection/multi-file.hlsl.expected | 238 + tests/reflection/reflection0.hlsl | 19 + tests/reflection/reflection0.hlsl.expected | 44 + tests/reflection/resource-in-cbuffer.hlsl | 21 + tests/reflection/resource-in-cbuffer.hlsl.expected | 60 + tests/render/cross-compile0.hlsl | 76 + tests/render/render0.hlsl | 74 + tests/rewriter/error0.hlsl | 19 + tools/glslang/glslang.cpp | 175 + tools/glslang/glslang.h | 23 + tools/glslang/glslang.vcxproj | 237 + tools/glslang/glslang.vcxproj.filters | 253 + tools/render-test/README.md | 4 + tools/render-test/main.cpp | 369 + tools/render-test/options.cpp | 95 + tools/render-test/options.h | 41 + tools/render-test/render-d3d11.cpp | 900 ++ tools/render-test/render-d3d11.h | 10 + tools/render-test/render-gl.cpp | 242 + tools/render-test/render-gl.h | 10 + tools/render-test/render-test.vcxproj | 170 + tools/render-test/render-test.vcxproj.filters | 54 + tools/render-test/render.h | 118 + tools/render-test/slang-support.cpp | 84 + tools/render-test/slang-support.h | 12 + tools/render-test/window.h | 10 + tools/slang-test/main.cpp | 1030 ++ tools/slang-test/os.cpp | 370 + tools/slang-test/os.h | 160 + tools/slang-test/slang-test.vcxproj | 277 + tools/slang-test/slang-test.vcxproj.filters | 30 + 501 files changed, 91369 insertions(+), 3 deletions(-) create mode 100644 .gitignore create mode 100644 build/slang-build.props create mode 100644 examples/hello/README.md create mode 100644 examples/hello/hello.cpp create mode 100644 examples/hello/hello.slang create mode 100644 examples/hello/hello.sln create mode 100644 examples/hello/hello.vcxproj create mode 100644 examples/hello/hello.vcxproj.filters create mode 100644 external/glext.h create mode 100644 external/stb/stb_image.h create mode 100644 external/stb/stb_image_write.h create mode 100644 slang.h create mode 100644 slang.sln create mode 100644 source/core/allocator.h create mode 100644 source/core/array-view.h create mode 100644 source/core/array.h create mode 100644 source/core/basic.h create mode 100644 source/core/common.h create mode 100644 source/core/core.natvis create mode 100644 source/core/core.vcxproj create mode 100644 source/core/dictionary.h create mode 100644 source/core/exception.h create mode 100644 source/core/func.h create mode 100644 source/core/hash.h create mode 100644 source/core/int-set.h create mode 100644 source/core/link.h create mode 100644 source/core/linq.h create mode 100644 source/core/list.h create mode 100644 source/core/memory-pool.cpp create mode 100644 source/core/memory-pool.h create mode 100644 source/core/secure-crt.h create mode 100644 source/core/slang-io.cpp create mode 100644 source/core/slang-io.h create mode 100644 source/core/slang-math.cpp create mode 100644 source/core/slang-math.h create mode 100644 source/core/slang-string.cpp create mode 100644 source/core/slang-string.h create mode 100644 source/core/smart-pointer.h create mode 100644 source/core/stream.cpp create mode 100644 source/core/stream.h create mode 100644 source/core/text-io.cpp create mode 100644 source/core/text-io.h create mode 100644 source/core/type-traits.h create mode 100644 source/slang/check.cpp create mode 100644 source/slang/compiled-program.h create mode 100644 source/slang/compiler.cpp create mode 100644 source/slang/compiler.h create mode 100644 source/slang/diagnostic-defs.h create mode 100644 source/slang/diagnostics.cpp create mode 100644 source/slang/diagnostics.h create mode 100644 source/slang/emit.cpp create mode 100644 source/slang/emit.h create mode 100644 source/slang/intrinsic-defs.h create mode 100644 source/slang/lexer.cpp create mode 100644 source/slang/lexer.h create mode 100644 source/slang/lookup.cpp create mode 100644 source/slang/lookup.h create mode 100644 source/slang/parameter-binding.cpp create mode 100644 source/slang/parameter-binding.h create mode 100644 source/slang/parser.cpp create mode 100644 source/slang/parser.h create mode 100644 source/slang/preprocessor.cpp create mode 100644 source/slang/preprocessor.h create mode 100644 source/slang/profile-defs.h create mode 100644 source/slang/profile.cpp create mode 100644 source/slang/profile.h create mode 100644 source/slang/reflection.cpp create mode 100644 source/slang/reflection.h create mode 100644 source/slang/slang-stdlib.cpp create mode 100644 source/slang/slang-stdlib.h create mode 100644 source/slang/slang.cpp create mode 100644 source/slang/slang.natvis create mode 100644 source/slang/slang.vcxproj create mode 100644 source/slang/slang.vcxproj.filters create mode 100644 source/slang/source-loc.h create mode 100644 source/slang/syntax-visitors.h create mode 100644 source/slang/syntax.cpp create mode 100644 source/slang/syntax.h create mode 100644 source/slang/token-defs.h create mode 100644 source/slang/token.cpp create mode 100644 source/slang/token.h create mode 100644 source/slang/type-layout.cpp create mode 100644 source/slang/type-layout.h create mode 100644 source/slangc/main.cpp create mode 100644 source/slangc/slangc.vcxproj create mode 100644 source/slangc/slangc.vcxproj.filters create mode 100644 test.bat create mode 100644 tests/bindings/README.md create mode 100644 tests/bindings/binding0.hlsl create mode 100644 tests/bindings/binding1.hlsl create mode 100644 tests/bindings/explicit-binding.hlsl create mode 100644 tests/bindings/multi-file-extra.hlsl create mode 100644 tests/bindings/multi-file.hlsl create mode 100644 tests/bindings/packoffset.hlsl create mode 100644 tests/bindings/resources-in-cbuffer.hlsl create mode 100644 tests/bindings/resources-in-structs.hlsl.disabled create mode 100644 tests/bindings/targets-and-uavs-structure.hlsl create mode 100644 tests/bindings/targets-and-uavs.hlsl create mode 100644 tests/diagnostics/break-outside-loop.spire create mode 100644 tests/diagnostics/break-outside-loop.spire.expected create mode 100644 tests/diagnostics/call-argument-type.spire create mode 100644 tests/diagnostics/call-argument-type.spire.expected create mode 100644 tests/diagnostics/continue-outside-loop.spire create mode 100644 tests/diagnostics/continue-outside-loop.spire.expected create mode 100644 tests/diagnostics/expected-token-eof.spire create mode 100644 tests/diagnostics/expected-token-eof.spire.expected create mode 100644 tests/diagnostics/expected-token.spire create mode 100644 tests/diagnostics/expected-token.spire.expected create mode 100644 tests/diagnostics/function-redefinition.spire.disabled create mode 100644 tests/diagnostics/function-redefinition.spire.expected create mode 100644 tests/diagnostics/hull-shader-invalid-domain.spire.disabled create mode 100644 tests/diagnostics/hull-shader-invalid-domain.spire.expected create mode 100644 tests/diagnostics/hull-shader-no-domain.spire.disabled create mode 100644 tests/diagnostics/hull-shader-no-domain.spire.expected create mode 100644 tests/diagnostics/illegal-character.spire create mode 100644 tests/diagnostics/illegal-character.spire.expected create mode 100644 tests/diagnostics/missing-file.spire.disabled create mode 100644 tests/diagnostics/missing-file.spire.expected create mode 100644 tests/diagnostics/missing-include-file.spire create mode 100644 tests/diagnostics/missing-include-file.spire.expected create mode 100644 tests/diagnostics/parameter-already-defined.spire create mode 100644 tests/diagnostics/parameter-already-defined.spire.expected create mode 100644 tests/diagnostics/undefined-identifier.spire create mode 100644 tests/diagnostics/undefined-identifier.spire.expected create mode 100644 tests/diagnostics/variable-void-type.spire create mode 100644 tests/diagnostics/variable-void-type.spire.expected create mode 100644 tests/diagnostics/while-predicate-type.spire create mode 100644 tests/diagnostics/while-predicate-type.spire.expected create mode 100644 tests/front-end/lexer-comments.spire create mode 100644 tests/front-end/parser-decls.spire create mode 100644 tests/front-end/parser-empty.spire create mode 100644 tests/front-end/parser-error-unclosed-curly.spire create mode 100644 tests/front-end/parser-error-unclosed-curly.spire.expected create mode 100644 tests/front-end/parser-using-file-a.spireh create mode 100644 tests/front-end/parser-using-file.spire.disabled create mode 100644 tests/front-end/pipeline-simple.spireh create mode 100644 tests/front-end/struct.spire create mode 100644 tests/front-end/typedef.spire create mode 100644 tests/glsl/sascha-willems/LICENSE.md create mode 100644 tests/glsl/sascha-willems/README.md create mode 100644 tests/glsl/sascha-willems/base/textoverlay.frag create mode 100644 tests/glsl/sascha-willems/base/textoverlay.vert create mode 100644 tests/glsl/sascha-willems/bloom/colorpass.frag create mode 100644 tests/glsl/sascha-willems/bloom/colorpass.vert create mode 100644 tests/glsl/sascha-willems/bloom/gaussblur.frag create mode 100644 tests/glsl/sascha-willems/bloom/gaussblur.vert create mode 100644 tests/glsl/sascha-willems/bloom/phongpass.frag create mode 100644 tests/glsl/sascha-willems/bloom/phongpass.vert create mode 100644 tests/glsl/sascha-willems/bloom/skybox.frag create mode 100644 tests/glsl/sascha-willems/bloom/skybox.vert create mode 100644 tests/glsl/sascha-willems/computecullandlod/cull.comp create mode 100644 tests/glsl/sascha-willems/computecullandlod/indirectdraw.frag create mode 100644 tests/glsl/sascha-willems/computecullandlod/indirectdraw.vert create mode 100644 tests/glsl/sascha-willems/computenbody/particle.frag create mode 100644 tests/glsl/sascha-willems/computenbody/particle.vert create mode 100644 tests/glsl/sascha-willems/computenbody/particle_calculate.comp create mode 100644 tests/glsl/sascha-willems/computenbody/particle_integrate.comp create mode 100644 tests/glsl/sascha-willems/computeparticles/particle.comp create mode 100644 tests/glsl/sascha-willems/computeparticles/particle.frag create mode 100644 tests/glsl/sascha-willems/computeparticles/particle.vert create mode 100644 tests/glsl/sascha-willems/computeshader/edgedetect.comp create mode 100644 tests/glsl/sascha-willems/computeshader/emboss.comp create mode 100644 tests/glsl/sascha-willems/computeshader/sharpen.comp create mode 100644 tests/glsl/sascha-willems/computeshader/texture.frag create mode 100644 tests/glsl/sascha-willems/computeshader/texture.vert create mode 100644 tests/glsl/sascha-willems/cubemap/reflect.frag create mode 100644 tests/glsl/sascha-willems/cubemap/reflect.vert create mode 100644 tests/glsl/sascha-willems/cubemap/skybox.frag create mode 100644 tests/glsl/sascha-willems/cubemap/skybox.vert create mode 100644 tests/glsl/sascha-willems/debugmarker/colorpass.frag create mode 100644 tests/glsl/sascha-willems/debugmarker/colorpass.vert create mode 100644 tests/glsl/sascha-willems/debugmarker/postprocess.frag create mode 100644 tests/glsl/sascha-willems/debugmarker/postprocess.vert create mode 100644 tests/glsl/sascha-willems/debugmarker/toon.frag create mode 100644 tests/glsl/sascha-willems/debugmarker/toon.vert create mode 100644 tests/glsl/sascha-willems/deferred/debug.frag create mode 100644 tests/glsl/sascha-willems/deferred/debug.vert create mode 100644 tests/glsl/sascha-willems/deferred/deferred.frag create mode 100644 tests/glsl/sascha-willems/deferred/deferred.vert create mode 100644 tests/glsl/sascha-willems/deferred/mrt.frag create mode 100644 tests/glsl/sascha-willems/deferred/mrt.vert create mode 100644 tests/glsl/sascha-willems/deferredmultisampling/debug.frag create mode 100644 tests/glsl/sascha-willems/deferredmultisampling/debug.vert create mode 100644 tests/glsl/sascha-willems/deferredmultisampling/deferred.frag create mode 100644 tests/glsl/sascha-willems/deferredmultisampling/deferred.vert create mode 100644 tests/glsl/sascha-willems/deferredmultisampling/mrt.frag create mode 100644 tests/glsl/sascha-willems/deferredmultisampling/mrt.vert create mode 100644 tests/glsl/sascha-willems/deferredshadows/debug.frag create mode 100644 tests/glsl/sascha-willems/deferredshadows/debug.vert create mode 100644 tests/glsl/sascha-willems/deferredshadows/deferred.frag create mode 100644 tests/glsl/sascha-willems/deferredshadows/deferred.vert create mode 100644 tests/glsl/sascha-willems/deferredshadows/mrt.frag create mode 100644 tests/glsl/sascha-willems/deferredshadows/mrt.vert create mode 100644 tests/glsl/sascha-willems/deferredshadows/shadow.frag create mode 100644 tests/glsl/sascha-willems/deferredshadows/shadow.geom create mode 100644 tests/glsl/sascha-willems/deferredshadows/shadow.vert create mode 100644 tests/glsl/sascha-willems/displacement/base.frag create mode 100644 tests/glsl/sascha-willems/displacement/base.vert create mode 100644 tests/glsl/sascha-willems/displacement/displacement.tesc create mode 100644 tests/glsl/sascha-willems/displacement/displacement.tese create mode 100644 tests/glsl/sascha-willems/distancefieldfonts/bitmap.frag create mode 100644 tests/glsl/sascha-willems/distancefieldfonts/bitmap.vert create mode 100644 tests/glsl/sascha-willems/distancefieldfonts/sdf.frag create mode 100644 tests/glsl/sascha-willems/distancefieldfonts/sdf.vert create mode 100644 tests/glsl/sascha-willems/dynamicuniformbuffer/base.frag create mode 100644 tests/glsl/sascha-willems/dynamicuniformbuffer/base.vert create mode 100644 tests/glsl/sascha-willems/gears/gears.frag create mode 100644 tests/glsl/sascha-willems/gears/gears.vert create mode 100644 tests/glsl/sascha-willems/geometryshader/base.frag create mode 100644 tests/glsl/sascha-willems/geometryshader/base.vert create mode 100644 tests/glsl/sascha-willems/geometryshader/mesh.frag create mode 100644 tests/glsl/sascha-willems/geometryshader/mesh.vert create mode 100644 tests/glsl/sascha-willems/geometryshader/normaldebug.geom create mode 100644 tests/glsl/sascha-willems/hdr/bloom.frag create mode 100644 tests/glsl/sascha-willems/hdr/bloom.vert create mode 100644 tests/glsl/sascha-willems/hdr/composition.frag create mode 100644 tests/glsl/sascha-willems/hdr/composition.vert create mode 100644 tests/glsl/sascha-willems/hdr/gbuffer.frag create mode 100644 tests/glsl/sascha-willems/hdr/gbuffer.vert create mode 100644 tests/glsl/sascha-willems/imgui/scene.frag create mode 100644 tests/glsl/sascha-willems/imgui/scene.vert create mode 100644 tests/glsl/sascha-willems/imgui/ui.frag create mode 100644 tests/glsl/sascha-willems/imgui/ui.vert create mode 100644 tests/glsl/sascha-willems/indirectdraw/ground.frag create mode 100644 tests/glsl/sascha-willems/indirectdraw/ground.vert create mode 100644 tests/glsl/sascha-willems/indirectdraw/indirectdraw.frag create mode 100644 tests/glsl/sascha-willems/indirectdraw/indirectdraw.vert create mode 100644 tests/glsl/sascha-willems/indirectdraw/skysphere.frag create mode 100644 tests/glsl/sascha-willems/indirectdraw/skysphere.vert create mode 100644 tests/glsl/sascha-willems/instancing/instancing.frag create mode 100644 tests/glsl/sascha-willems/instancing/instancing.vert create mode 100644 tests/glsl/sascha-willems/instancing/planet.frag create mode 100644 tests/glsl/sascha-willems/instancing/planet.vert create mode 100644 tests/glsl/sascha-willems/instancing/starfield.frag create mode 100644 tests/glsl/sascha-willems/instancing/starfield.vert create mode 100644 tests/glsl/sascha-willems/mesh/mesh.frag create mode 100644 tests/glsl/sascha-willems/mesh/mesh.vert create mode 100644 tests/glsl/sascha-willems/multithreading/phong.frag create mode 100644 tests/glsl/sascha-willems/multithreading/phong.vert create mode 100644 tests/glsl/sascha-willems/multithreading/starsphere.frag create mode 100644 tests/glsl/sascha-willems/multithreading/starsphere.vert create mode 100644 tests/glsl/sascha-willems/occlusionquery/mesh.frag create mode 100644 tests/glsl/sascha-willems/occlusionquery/mesh.vert create mode 100644 tests/glsl/sascha-willems/occlusionquery/occluder.frag create mode 100644 tests/glsl/sascha-willems/occlusionquery/occluder.vert create mode 100644 tests/glsl/sascha-willems/occlusionquery/simple.frag create mode 100644 tests/glsl/sascha-willems/occlusionquery/simple.vert create mode 100644 tests/glsl/sascha-willems/offscreen/mirror.frag create mode 100644 tests/glsl/sascha-willems/offscreen/mirror.vert create mode 100644 tests/glsl/sascha-willems/offscreen/phong.frag create mode 100644 tests/glsl/sascha-willems/offscreen/phong.vert create mode 100644 tests/glsl/sascha-willems/offscreen/quad.frag create mode 100644 tests/glsl/sascha-willems/offscreen/quad.vert create mode 100644 tests/glsl/sascha-willems/parallax/parallax.frag create mode 100644 tests/glsl/sascha-willems/parallax/parallax.vert create mode 100644 tests/glsl/sascha-willems/particlefire/normalmap.frag create mode 100644 tests/glsl/sascha-willems/particlefire/normalmap.vert create mode 100644 tests/glsl/sascha-willems/particlefire/particle.frag create mode 100644 tests/glsl/sascha-willems/particlefire/particle.vert create mode 100644 tests/glsl/sascha-willems/pbrbasic/pbr.frag create mode 100644 tests/glsl/sascha-willems/pbrbasic/pbr.vert create mode 100644 tests/glsl/sascha-willems/pbribl/filtercube.vert create mode 100644 tests/glsl/sascha-willems/pbribl/genbrdflut.frag create mode 100644 tests/glsl/sascha-willems/pbribl/genbrdflut.vert create mode 100644 tests/glsl/sascha-willems/pbribl/irradiancecube.frag create mode 100644 tests/glsl/sascha-willems/pbribl/pbribl.frag create mode 100644 tests/glsl/sascha-willems/pbribl/pbribl.vert create mode 100644 tests/glsl/sascha-willems/pbribl/prefilterenvmap.frag create mode 100644 tests/glsl/sascha-willems/pbribl/skybox.frag create mode 100644 tests/glsl/sascha-willems/pbribl/skybox.vert create mode 100644 tests/glsl/sascha-willems/pbrtexture/filtercube.vert create mode 100644 tests/glsl/sascha-willems/pbrtexture/genbrdflut.frag create mode 100644 tests/glsl/sascha-willems/pbrtexture/genbrdflut.vert create mode 100644 tests/glsl/sascha-willems/pbrtexture/irradiancecube.frag create mode 100644 tests/glsl/sascha-willems/pbrtexture/pbrtexture.frag create mode 100644 tests/glsl/sascha-willems/pbrtexture/pbrtexture.vert create mode 100644 tests/glsl/sascha-willems/pbrtexture/prefilterenvmap.frag create mode 100644 tests/glsl/sascha-willems/pbrtexture/skybox.frag create mode 100644 tests/glsl/sascha-willems/pbrtexture/skybox.vert create mode 100644 tests/glsl/sascha-willems/pipelines/phong.frag create mode 100644 tests/glsl/sascha-willems/pipelines/phong.vert create mode 100644 tests/glsl/sascha-willems/pipelines/toon.frag create mode 100644 tests/glsl/sascha-willems/pipelines/toon.vert create mode 100644 tests/glsl/sascha-willems/pipelines/wireframe.frag create mode 100644 tests/glsl/sascha-willems/pipelines/wireframe.vert create mode 100644 tests/glsl/sascha-willems/pushconstants/lights.frag create mode 100644 tests/glsl/sascha-willems/pushconstants/lights.vert create mode 100644 tests/glsl/sascha-willems/radialblur/colorpass.frag create mode 100644 tests/glsl/sascha-willems/radialblur/colorpass.vert create mode 100644 tests/glsl/sascha-willems/radialblur/phongpass.frag create mode 100644 tests/glsl/sascha-willems/radialblur/phongpass.vert create mode 100644 tests/glsl/sascha-willems/radialblur/radialblur.frag create mode 100644 tests/glsl/sascha-willems/radialblur/radialblur.vert create mode 100644 tests/glsl/sascha-willems/raytracing/raytracing.comp create mode 100644 tests/glsl/sascha-willems/raytracing/texture.frag create mode 100644 tests/glsl/sascha-willems/raytracing/texture.vert create mode 100644 tests/glsl/sascha-willems/scenerendering/scene.frag create mode 100644 tests/glsl/sascha-willems/scenerendering/scene.vert create mode 100644 tests/glsl/sascha-willems/screenshot/mesh.frag create mode 100644 tests/glsl/sascha-willems/screenshot/mesh.vert create mode 100644 tests/glsl/sascha-willems/shadowmapomni/cubemapdisplay.frag create mode 100644 tests/glsl/sascha-willems/shadowmapomni/cubemapdisplay.vert create mode 100644 tests/glsl/sascha-willems/shadowmapomni/offscreen.frag create mode 100644 tests/glsl/sascha-willems/shadowmapomni/offscreen.vert create mode 100644 tests/glsl/sascha-willems/shadowmapomni/scene.frag create mode 100644 tests/glsl/sascha-willems/shadowmapomni/scene.vert create mode 100644 tests/glsl/sascha-willems/shadowmapping/offscreen.frag create mode 100644 tests/glsl/sascha-willems/shadowmapping/offscreen.vert create mode 100644 tests/glsl/sascha-willems/shadowmapping/quad.frag create mode 100644 tests/glsl/sascha-willems/shadowmapping/quad.vert create mode 100644 tests/glsl/sascha-willems/shadowmapping/scene.frag create mode 100644 tests/glsl/sascha-willems/shadowmapping/scene.vert create mode 100644 tests/glsl/sascha-willems/skeletalanimation/mesh.frag create mode 100644 tests/glsl/sascha-willems/skeletalanimation/mesh.vert create mode 100644 tests/glsl/sascha-willems/skeletalanimation/texture.frag create mode 100644 tests/glsl/sascha-willems/skeletalanimation/texture.vert create mode 100644 tests/glsl/sascha-willems/specializationconstants/uber.frag create mode 100644 tests/glsl/sascha-willems/specializationconstants/uber.vert create mode 100644 tests/glsl/sascha-willems/sphericalenvmapping/sem.frag create mode 100644 tests/glsl/sascha-willems/sphericalenvmapping/sem.vert create mode 100644 tests/glsl/sascha-willems/ssao/blur.frag create mode 100644 tests/glsl/sascha-willems/ssao/composition.frag create mode 100644 tests/glsl/sascha-willems/ssao/fullscreen.vert create mode 100644 tests/glsl/sascha-willems/ssao/gbuffer.frag create mode 100644 tests/glsl/sascha-willems/ssao/gbuffer.vert create mode 100644 tests/glsl/sascha-willems/ssao/ssao.frag create mode 100644 tests/glsl/sascha-willems/subpasses/composition.frag create mode 100644 tests/glsl/sascha-willems/subpasses/composition.vert create mode 100644 tests/glsl/sascha-willems/subpasses/gbuffer.frag create mode 100644 tests/glsl/sascha-willems/subpasses/gbuffer.vert create mode 100644 tests/glsl/sascha-willems/subpasses/transparent.frag create mode 100644 tests/glsl/sascha-willems/subpasses/transparent.vert create mode 100644 tests/glsl/sascha-willems/terraintessellation/skysphere.frag create mode 100644 tests/glsl/sascha-willems/terraintessellation/skysphere.vert create mode 100644 tests/glsl/sascha-willems/terraintessellation/terrain.frag create mode 100644 tests/glsl/sascha-willems/terraintessellation/terrain.tesc create mode 100644 tests/glsl/sascha-willems/terraintessellation/terrain.tese create mode 100644 tests/glsl/sascha-willems/terraintessellation/terrain.vert create mode 100644 tests/glsl/sascha-willems/tessellation/base.frag create mode 100644 tests/glsl/sascha-willems/tessellation/base.vert create mode 100644 tests/glsl/sascha-willems/tessellation/passthrough.tesc create mode 100644 tests/glsl/sascha-willems/tessellation/passthrough.tese create mode 100644 tests/glsl/sascha-willems/tessellation/pntriangles.tesc create mode 100644 tests/glsl/sascha-willems/tessellation/pntriangles.tese create mode 100644 tests/glsl/sascha-willems/textoverlay/background.frag create mode 100644 tests/glsl/sascha-willems/textoverlay/background.vert create mode 100644 tests/glsl/sascha-willems/textoverlay/mesh.frag create mode 100644 tests/glsl/sascha-willems/textoverlay/mesh.vert create mode 100644 tests/glsl/sascha-willems/textoverlay/text.frag create mode 100644 tests/glsl/sascha-willems/textoverlay/text.vert create mode 100644 tests/glsl/sascha-willems/texture/texture.frag create mode 100644 tests/glsl/sascha-willems/texture/texture.vert create mode 100644 tests/glsl/sascha-willems/texture3d/texture3d.frag create mode 100644 tests/glsl/sascha-willems/texture3d/texture3d.vert create mode 100644 tests/glsl/sascha-willems/texturearray/instancing.frag create mode 100644 tests/glsl/sascha-willems/texturearray/instancing.vert create mode 100644 tests/glsl/sascha-willems/texturemipmapgen/texture.frag create mode 100644 tests/glsl/sascha-willems/texturemipmapgen/texture.vert create mode 100644 tests/glsl/sascha-willems/texturesparseresidency/sparseresidency.frag create mode 100644 tests/glsl/sascha-willems/texturesparseresidency/sparseresidency.vert create mode 100644 tests/glsl/sascha-willems/triangle/triangle.frag create mode 100644 tests/glsl/sascha-willems/triangle/triangle.vert create mode 100644 tests/glsl/sascha-willems/viewportarray/multiview.geom create mode 100644 tests/glsl/sascha-willems/viewportarray/scene.frag create mode 100644 tests/glsl/sascha-willems/viewportarray/scene.vert create mode 100644 tests/glsl/sascha-willems/vulkanscene/logo.frag create mode 100644 tests/glsl/sascha-willems/vulkanscene/logo.vert create mode 100644 tests/glsl/sascha-willems/vulkanscene/mesh.frag create mode 100644 tests/glsl/sascha-willems/vulkanscene/mesh.vert create mode 100644 tests/glsl/sascha-willems/vulkanscene/skybox.frag create mode 100644 tests/glsl/sascha-willems/vulkanscene/skybox.vert create mode 100644 tests/hlsl/dxsdk/AdaptiveTessellationCS40/Render.hlsl create mode 100644 tests/hlsl/dxsdk/AdaptiveTessellationCS40/ScanCS.hlsl create mode 100644 tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_EdgeFactorCS.hlsl create mode 100644 tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_NumVerticesIndicesCS.hlsl create mode 100644 tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_ScatterIDCS.hlsl create mode 100644 tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_TessellateIndicesCS.hlsl create mode 100644 tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_TessellateVerticesCS.hlsl create mode 100644 tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_common.hlsl create mode 100644 tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_defines.h create mode 100644 tests/hlsl/dxsdk/BC6HBC7EncoderCS/Shaders/BC6HEncode.hlsl create mode 100644 tests/hlsl/dxsdk/BC6HBC7EncoderCS/Shaders/BC7Encode.hlsl create mode 100644 tests/hlsl/dxsdk/BasicCompute11/BasicCompute11.hlsl create mode 100644 tests/hlsl/dxsdk/BasicHLSL11/BasicHLSL.fx create mode 100644 tests/hlsl/dxsdk/BasicHLSL11/BasicHLSL11_PS.hlsl create mode 100644 tests/hlsl/dxsdk/BasicHLSL11/BasicHLSL11_VS.hlsl create mode 100644 tests/hlsl/dxsdk/BasicHLSLFX11/BasicHLSLFX11.fx create mode 100644 tests/hlsl/dxsdk/CascadedShadowMaps11/RenderCascadeScene.hlsl create mode 100644 tests/hlsl/dxsdk/CascadedShadowMaps11/RenderCascadeShadow.hlsl create mode 100644 tests/hlsl/dxsdk/ComputeShaderSort11/ComputeShaderSort11.hlsl create mode 100644 tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial02/Tutorial02.fx create mode 100644 tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial02/Tutorial02_PS.hlsl create mode 100644 tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial02/Tutorial02_VS.hlsl create mode 100644 tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial03/Tutorial03.fx create mode 100644 tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial03/Tutorial03_PS.hlsl create mode 100644 tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial03/Tutorial03_VS.hlsl create mode 100644 tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial04/Tutorial04.fx create mode 100644 tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial04/Tutorial04_PS.hlsl create mode 100644 tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial04/Tutorial04_VS.hlsl create mode 100644 tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial05/Tutorial05.fx create mode 100644 tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial05/Tutorial05_PS.hlsl create mode 100644 tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial05/Tutorial05_VS.hlsl create mode 100644 tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial06/Tutorial06.fx create mode 100644 tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial06/Tutorial06_PS.hlsl create mode 100644 tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial06/Tutorial06_VS.hlsl create mode 100644 tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial07/Tutorial07.fx create mode 100644 tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial07/Tutorial07_PS.hlsl create mode 100644 tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial07/Tutorial07_VS.hlsl create mode 100644 tests/hlsl/dxsdk/Direct3D11TutorialsDXUT/Tutorial08/Tutorial08.fx create mode 100644 tests/hlsl/dxsdk/Direct3D11TutorialsDXUT/Tutorial09/Tutorial09.fx create mode 100644 tests/hlsl/dxsdk/Direct3D11TutorialsDXUT/Tutorial10/Tutorial10.fx create mode 100644 tests/hlsl/dxsdk/Direct3D11TutorialsFX11/Tutorial11/Tutorial11.fx create mode 100644 tests/hlsl/dxsdk/Direct3D11TutorialsFX11/Tutorial12/Tutorial12.fx create mode 100644 tests/hlsl/dxsdk/Direct3D11TutorialsFX11/Tutorial13/Tutorial13.fx create mode 100644 tests/hlsl/dxsdk/Direct3D11TutorialsFX11/Tutorial14/Tutorial14.fx create mode 100644 tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_LightPSH.h create mode 100644 tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_MaterialPSH.h create mode 100644 tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_PS.hlsl create mode 100644 tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_PSBuffers.h create mode 100644 tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_VS.hlsl create mode 100644 tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11.fx create mode 100644 tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_LightPSH.h create mode 100644 tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_MaterialPSH.h create mode 100644 tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_PSBuffers.h create mode 100644 tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_ps.hlsl create mode 100644 tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_vs.hlsl create mode 100644 tests/hlsl/dxsdk/FixedFuncEMUFX11/FixedFuncEMU.fx create mode 100644 tests/hlsl/dxsdk/FluidCS11/ComputeShaderSort11.hlsl create mode 100644 tests/hlsl/dxsdk/FluidCS11/FluidCS11.hlsl create mode 100644 tests/hlsl/dxsdk/FluidCS11/FluidRender.hlsl create mode 100644 tests/hlsl/dxsdk/HDRToneMappingCS11/BrightPassAndHorizFilterCS.hlsl create mode 100644 tests/hlsl/dxsdk/HDRToneMappingCS11/DumpToTexture.hlsl create mode 100644 tests/hlsl/dxsdk/HDRToneMappingCS11/FilterCS.hlsl create mode 100644 tests/hlsl/dxsdk/HDRToneMappingCS11/FinalPass.hlsl create mode 100644 tests/hlsl/dxsdk/HDRToneMappingCS11/PSApproach.hlsl create mode 100644 tests/hlsl/dxsdk/HDRToneMappingCS11/ReduceTo1DCS.hlsl create mode 100644 tests/hlsl/dxsdk/HDRToneMappingCS11/ReduceToSingleCS.hlsl create mode 100644 tests/hlsl/dxsdk/HDRToneMappingCS11/skybox11.hlsl create mode 100644 tests/hlsl/dxsdk/InstancingFX11/Instancing.fx create mode 100644 tests/hlsl/dxsdk/MultithreadedRendering11/MultithreadedRendering11_PS.hlsl create mode 100644 tests/hlsl/dxsdk/MultithreadedRendering11/MultithreadedRendering11_VS.hlsl create mode 100644 tests/hlsl/dxsdk/NBodyGravityCS11/NBodyGravityCS11.hlsl create mode 100644 tests/hlsl/dxsdk/NBodyGravityCS11/ParticleDraw.hlsl create mode 100644 tests/hlsl/dxsdk/OIT11/OIT_CS.hlsl create mode 100644 tests/hlsl/dxsdk/OIT11/OIT_PS.hlsl create mode 100644 tests/hlsl/dxsdk/OIT11/SceneVS.hlsl create mode 100644 tests/hlsl/dxsdk/README.md create mode 100644 tests/hlsl/dxsdk/SimpleBezier11/SimpleBezier11.hlsl create mode 100644 tests/hlsl/dxsdk/SimpleSample11/SimpleSample.fx create mode 100644 tests/hlsl/dxsdk/SimpleSample11/SimpleSample.hlsl create mode 100644 tests/hlsl/dxsdk/SubD11/SubD11.hlsl create mode 100644 tests/hlsl/dxsdk/VarianceShadows11/2DQuadShaders.hlsl create mode 100644 tests/hlsl/dxsdk/VarianceShadows11/RenderVarianceScene.hlsl create mode 100644 tests/hlsl/dxsdk/VarianceShadows11/RenderVarianceShadow.hlsl create mode 100644 tests/hlsl/simple/compute-numthreads.hlsl create mode 100644 tests/preprocessor/define-function-like.spire create mode 100644 tests/preprocessor/define-function-like.spire.expected create mode 100644 tests/preprocessor/define-simple.spire create mode 100644 tests/preprocessor/if.spire create mode 100644 tests/preprocessor/ifdef.spire create mode 100644 tests/preprocessor/include-a.spireh create mode 100644 tests/preprocessor/include.spire create mode 100644 tests/reflection/arrays.hlsl create mode 100644 tests/reflection/arrays.hlsl.expected create mode 100644 tests/reflection/global-uniforms.hlsl create mode 100644 tests/reflection/global-uniforms.hlsl.expected create mode 100644 tests/reflection/multi-file-extra.hlsl create mode 100644 tests/reflection/multi-file.hlsl create mode 100644 tests/reflection/multi-file.hlsl.expected create mode 100644 tests/reflection/reflection0.hlsl create mode 100644 tests/reflection/reflection0.hlsl.expected create mode 100644 tests/reflection/resource-in-cbuffer.hlsl create mode 100644 tests/reflection/resource-in-cbuffer.hlsl.expected create mode 100644 tests/render/cross-compile0.hlsl create mode 100644 tests/render/render0.hlsl create mode 100644 tests/rewriter/error0.hlsl create mode 100644 tools/glslang/glslang.cpp create mode 100644 tools/glslang/glslang.h create mode 100644 tools/glslang/glslang.vcxproj create mode 100644 tools/glslang/glslang.vcxproj.filters create mode 100644 tools/render-test/README.md create mode 100644 tools/render-test/main.cpp create mode 100644 tools/render-test/options.cpp create mode 100644 tools/render-test/options.h create mode 100644 tools/render-test/render-d3d11.cpp create mode 100644 tools/render-test/render-d3d11.h create mode 100644 tools/render-test/render-gl.cpp create mode 100644 tools/render-test/render-gl.h create mode 100644 tools/render-test/render-test.vcxproj create mode 100644 tools/render-test/render-test.vcxproj.filters create mode 100644 tools/render-test/render.h create mode 100644 tools/render-test/slang-support.cpp create mode 100644 tools/render-test/slang-support.h create mode 100644 tools/render-test/window.h create mode 100644 tools/slang-test/main.cpp create mode 100644 tools/slang-test/os.cpp create mode 100644 tools/slang-test/os.h create mode 100644 tools/slang-test/slang-test.vcxproj create mode 100644 tools/slang-test/slang-test.vcxproj.filters diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..a0a57b5aa --- /dev/null +++ b/.gitignore @@ -0,0 +1,26 @@ +*.exe +*.pdb +.vs +*.VC.opendb +*.VC.db +*.vcxproj.user +*.sdf +bin/ +intermediate/ + +# files generated by test runner +*.actual +*.hlsl.expected +*.fx.expected +*.glsl.expected +*.vert.expected +*.frag.expected +*.geom.expected +*.tesc.expected +*.tese.expected +*.comp.expected +*.expected.png +*.actual.png + +# files generated by other shader compilers +*.spv diff --git a/LICENSE b/LICENSE index 6a710e318..23054ae34 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2017 shader-slang +Copyright (c) 2016, Carnegie Mellon University and NVIDIA Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index a6414ad85..66c753bb0 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,38 @@ -# slang -Making it easier to work with shaders +# Slang + +Slang is a library for compiling real-time shader code. +It can be used with either existing HLSL or GLSL code, or with code written directly in Slang. +The library provides a variety of services that application developers can use to put together the shader compilation workflow they want. + +Services provided by the Slang library include: + +* Slang can scan ordinary HLSL or GLSL code that neglects to include `register` or `layout` bindings and "rewrite" that code to include explicit bindings for all shader parameters. This lets you write simple and clean code, but still get deterministic binding locations. + +* Slang provides a full reflection API for shader parameters, with a uniform interface across HLSL, GLSL, and Slang. The reflection system does not silently drop unused/"dead" parameters, and it can even be used on libraries of shader code without compiling any entry points. + +* *Work in progress:* Slang supports cross-compilation of either HLSL or Slang code to GLSL. + +* You can directly get HLSL or GLSL source code as output from Slang, or you can let the library invoke lower-level code generation for you to get back DXBC or SPIR-V (DXIL support to come). + +## Documentation + +TODO + +## Getting Started + +TODO + +## Testing + +TODO + +## Contributing + +TODO + +## Contributors + +* Yong He +* Haomin Long +* Teguh Hofstee +* Tim Foley diff --git a/build/slang-build.props b/build/slang-build.props new file mode 100644 index 000000000..bb7b68930 --- /dev/null +++ b/build/slang-build.props @@ -0,0 +1,11 @@ + + + + + + $(SolutionDir)bin\$(PlatformShortName)\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformShortName)\$(Configuration)\$(ProjectName)\ + + + + \ No newline at end of file diff --git a/examples/hello/README.md b/examples/hello/README.md new file mode 100644 index 000000000..410bbd7bb --- /dev/null +++ b/examples/hello/README.md @@ -0,0 +1,9 @@ +Spire "Hello World" Example +=========================== + +The goal of this example is to demonstrate an almost minimal application that uses Spire for shading, and D3D11 for rendering. + +The `hello.spire` file contains a simple declaration of a Spire *shader module*, along with a *pipeline declaration* that will be used for mapping shader code to the capabilities of the "engine" (in this case, just vertex and fragment shaders). +The `hello.cpp` file contains the C++ application code, showing how to use the Spire C API to load and compile the shader code, and construct a (trivial) executable shader from Spire modules. + +Note that this example is not intended to demonstrate good practices for integrating Spire into a production engine; the goal is merely to use the minimum amount of code possible to demonstrate a complete applicaiton that uses Spire. diff --git a/examples/hello/hello.cpp b/examples/hello/hello.cpp new file mode 100644 index 000000000..c9121b790 --- /dev/null +++ b/examples/hello/hello.cpp @@ -0,0 +1,589 @@ +// hello.cpp + +// In order to use the Slang API, we need to include its header + +#define SLANG_INCLUDE_IMPLEMENTATION +#include + +// We will be rendering with Direct3D 11, so we need to include +// the Windows and D3D11 headers + +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#undef WIN32_LEAN_AND_MEAN +#undef NOMINMAX + +#include +#include + +// We will use the C standard library just for printing error messages. +#include + +#ifdef _MSC_VER +#include +#if (_MSC_VER < 1900) +#define snprintf sprintf_s +#endif +#endif +// + +static int gWindowWidth = 1024; +static int gWindowHeight = 768; + +// + +// +// For the purposes of a small example, we will define the vertex data for a +// single triangle directly in the source file. It should be easy to extend +// this example to load data from an external source, if desired. +// + +struct Vertex +{ + float position[3]; + float color[3]; +}; + +static const int kVertexCount = 3; +static const Vertex kVertexData[kVertexCount] = { + { { 0, 0, 0.5 }, {1, 0, 0} }, + { { 0, 1, 0.5 }, {0, 0, 1} }, + { { 1, 0, 0.5 }, {0, 1, 0} }, +}; + +// + +// Global variabels for the various D3D11 API objects to be used for rendering +ID3D11Buffer* dxConstantBuffer; +ID3D11InputLayout* dxInputLayout; +ID3D11Buffer* dxVertexBuffer; +ID3D11VertexShader* dxVertexShader; +ID3D11PixelShader* dxPixelShader; + +// The Slang compiler currently generates HLSL source, so we'll need a utility +// routine (defined later) to translate that into D3D11 shader bytecode. +ID3DBlob* compileHLSLShader( + char const* source, + char const* entryPointName, + char const* dxProfileName); + +// +// At initialization time, we are going to load and compile our Slang shader +// code, and then create the D3D11 API objects we need for rendering. +// +HRESULT initialize( ID3D11Device* dxDevice ) +{ +#if 1 + // + // First, we will load and compile our Slang source code. + // + + // The argument here is an optional directory where the Slang compiler + // can cache files to speed up compilation of many kernels. + SlangSession* slangSession = spCreateSession(NULL); + + // A compile request represents a single invocation of the compiler, + // to process some inputs and produce outputs (or errors). + SlangCompileRequest* slangRequest = spCreateCompileRequest(slangSession); + + // Instruct Slang to generate code as HLSL + spSetCodeGenTarget(slangRequest, SLANG_HLSL); + + int translationUnitIndex = spAddTranslationUnit(slangRequest, SLANG_SOURCE_LANGUAGE_SLANG, nullptr); + + spAddTranslationUnitSourceFile(slangRequest, translationUnitIndex, "hello.slang"); + + char const* vertexEntryPointName = "vertexMain"; + char const* fragmentEntryPointName = "fragmentMain"; + + char const* vertexProfileName = "vs_4_0"; + char const* fragmentProfileName = "ps_4_0"; + + spAddTranslationUnitEntryPoint(slangRequest, translationUnitIndex, vertexEntryPointName, spFindProfile(slangSession, vertexProfileName)); + spAddTranslationUnitEntryPoint(slangRequest, translationUnitIndex, fragmentEntryPointName, spFindProfile(slangSession, fragmentProfileName)); + + int compileErr = spCompile(slangRequest); + if(auto diagnostics = spGetDiagnosticOutput(slangRequest)) + { + OutputDebugStringA(diagnostics); + fprintf(stderr, "%s", diagnostics); + } + if(compileErr) + { + return E_FAIL; + } + + char const* translatedCode = spGetTranslationUnitSource(slangRequest, translationUnitIndex); + + + // TODO(tfoley): Query the required constant-buffer size + int constantBufferSize = 16 * sizeof(float); + + // Compile the generated HLSL code + ID3DBlob* dxVertexShaderBlob = compileHLSLShader(translatedCode, vertexEntryPointName, vertexProfileName); + if(!dxVertexShaderBlob) return E_FAIL; + + ID3DBlob* dxPixelShaderBlob = compileHLSLShader(translatedCode, fragmentEntryPointName, fragmentProfileName); + if(!dxPixelShaderBlob) return E_FAIL; + + HRESULT hr = S_OK; + + + D3D11_BUFFER_DESC dxConstantBufferDesc = { 0 }; + dxConstantBufferDesc.ByteWidth = constantBufferSize; + dxConstantBufferDesc.Usage = D3D11_USAGE_DYNAMIC; + dxConstantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + dxConstantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + + hr = dxDevice->CreateBuffer( + &dxConstantBufferDesc, + NULL, + &dxConstantBuffer); + if(FAILED(hr)) return hr; + + // We clean up the Slang compilation context and result *after* + // we have done the HLSL-to-bytecode compilation, because Slang + // owns the memory allocation for the generated HLSL, and will + // free it when we destroy the compilation result. + spDestroyCompileRequest(slangRequest); + spDestroySession(slangSession); + + // Input Assembler (IA) + + // In Slang-generated HLSL, all vertex shader inputs have a semantic + // like: `A0`, `A1`, `A2`, etc., rather than trying to do by-name + // matching. The user is thus responsibile for ensuring that the + // order of their "input element descs" here matches the order + // in which inputs are declared in the shader code. + D3D11_INPUT_ELEMENT_DESC dxInputElements[] = { + {"A", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(Vertex, position), D3D11_INPUT_PER_VERTEX_DATA, 0 }, + {"A", 1, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(Vertex, color), D3D11_INPUT_PER_VERTEX_DATA, 0 }, + }; + hr = dxDevice->CreateInputLayout( + &dxInputElements[0], + 2, + dxVertexShaderBlob->GetBufferPointer(), + dxVertexShaderBlob->GetBufferSize(), + &dxInputLayout); + if(FAILED(hr)) return hr; + + D3D11_BUFFER_DESC dxVertexBufferDesc = { 0 }; + dxVertexBufferDesc.ByteWidth = kVertexCount * sizeof(Vertex); + dxVertexBufferDesc.Usage = D3D11_USAGE_IMMUTABLE; + dxVertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + + D3D11_SUBRESOURCE_DATA dxVertexBufferInitData = { 0 }; + dxVertexBufferInitData.pSysMem = &kVertexData[0]; + + hr = dxDevice->CreateBuffer( + &dxVertexBufferDesc, + &dxVertexBufferInitData, + &dxVertexBuffer); + if(FAILED(hr)) return hr; + + // Vertex Shader (VS) + + hr = dxDevice->CreateVertexShader( + dxVertexShaderBlob->GetBufferPointer(), + dxVertexShaderBlob->GetBufferSize(), + NULL, + &dxVertexShader); + dxVertexShaderBlob->Release(); + if(FAILED(hr)) return hr; + + // Pixel Shader (PS) + + hr = dxDevice->CreatePixelShader( + dxPixelShaderBlob->GetBufferPointer(), + dxPixelShaderBlob->GetBufferSize(), + NULL, + &dxPixelShader); + dxPixelShaderBlob->Release(); + if(FAILED(hr)) return hr; +#endif + + return S_OK; +} + +void renderFrame(ID3D11DeviceContext* dxContext) +{ + // We update our constant buffer per-frame, just for the purposes + // of the example, but we don't actually load different data + // per-frame (we always use an identity projection). + D3D11_MAPPED_SUBRESOURCE mapped; + HRESULT hr = dxContext->Map(dxConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped); + if(!FAILED(hr)) + { + float* data = (float*) mapped.pData; + + static const float kIdentity[] = + { 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 }; + memcpy(data, kIdentity, sizeof(kIdentity)); + + dxContext->Unmap(dxConstantBuffer, 0); + } + + // Input Assembler (IA) + + dxContext->IASetInputLayout(dxInputLayout); + dxContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + + UINT dxVertexStride = sizeof(Vertex); + UINT dxVertexBufferOffset = 0; + dxContext->IASetVertexBuffers(0, 1, &dxVertexBuffer, &dxVertexStride, &dxVertexBufferOffset); + + // Vertex Shader (VS) + + dxContext->VSSetShader(dxVertexShader, NULL, 0); + dxContext->VSSetConstantBuffers(0, 1, &dxConstantBuffer); + + // Pixel Shader (PS) + + dxContext->PSSetShader(dxPixelShader, NULL, 0); + dxContext->VSSetConstantBuffers(0, 1, &dxConstantBuffer); + + // + + dxContext->Draw(3, 0); +} + +void finalize() +{ +} + +// +// Definition of the HLSL-to-bytecode compilation logic. +// +ID3DBlob* compileHLSLShader( + char const* source, + char const* entryPointName, + char const* dxProfileName ) +{ + // Rather than statically link against the `d3dcompile` library, we + // dynamically load it. + // + // Note: A more realistic application would compile from HLSL text to D3D + // shader bytecode as part of an offline process, rather than doing it + // on-the-fly like this + // + static pD3DCompile D3DCompile_ = nullptr; + if( !D3DCompile_ ) + { + // TODO(tfoley): maybe want to search for one of a few versions of the DLL + HMODULE d3dcompiler = LoadLibraryA("d3dcompiler_47.dll"); + if(!d3dcompiler) + { + fprintf(stderr, "error: failed load 'd3dcompiler_47.dll'\n"); + exit(1); + } + + D3DCompile_ = (pD3DCompile)GetProcAddress(d3dcompiler, "D3DCompile"); + if( !D3DCompile_ ) + { + fprintf(stderr, "error: failed load symbol 'D3DCompile'\n"); + exit(1); + } + } + + // For this example, we turn on debug output, and turn off all + // optimization. A real application would only use these flags + // when shader debugging is needed. + UINT flags = 0; + flags |= D3DCOMPILE_DEBUG; + flags |= D3DCOMPILE_OPTIMIZATION_LEVEL0 | D3DCOMPILE_SKIP_OPTIMIZATION; + + // The `D3DCompile` entry point takes a bunch of parameters, but we + // don't really need most of them for Slang-generated code. + ID3DBlob* dxShaderBlob = nullptr; + ID3DBlob* dxErrorBlob = nullptr; + HRESULT hr = D3DCompile_( + source, + strlen(source), + "slangGeneratedCode", // TODO: proper path for error messages + nullptr, + nullptr, + entryPointName, + dxProfileName, + flags, + 0, + &dxShaderBlob, + &dxErrorBlob); + + // If the HLSL-to-bytecode compilation produced any diagnostic messages + // then we will print them out (whether or not the compilation failed). + if( dxErrorBlob ) + { + OutputDebugStringA( + (char const*)dxErrorBlob->GetBufferPointer()); + dxErrorBlob->Release(); + } + + if( FAILED(hr) ) + { + return nullptr; + } + + return dxShaderBlob; +} + + +// +// We use a bare-minimum window procedure to get things up and running. +// + +static LRESULT CALLBACK windowProc( + HWND windowHandle, + UINT message, + WPARAM wParam, + LPARAM lParam) +{ + switch (message) + { + case WM_CLOSE: + PostQuitMessage(0); + return 0; + } + + return DefWindowProcW(windowHandle, message, wParam, lParam); +} + +// +// Our `WinMain` handles the basic task of getting a window and rendering +// context up and running. There should be nothing suprising or interesting +// here. +// + +int WINAPI WinMain( + HINSTANCE instance, + HINSTANCE /* prevInstance */, + LPSTR /* commandLine */, + int showCommand) +{ + // First we register a window class. + + WNDCLASSEXW windowClassDesc; + windowClassDesc.cbSize = sizeof(windowClassDesc); + windowClassDesc.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW; + windowClassDesc.lpfnWndProc = &windowProc; + windowClassDesc.cbClsExtra = 0; + windowClassDesc.cbWndExtra = 0; + windowClassDesc.hInstance = instance; + windowClassDesc.hIcon = 0; + windowClassDesc.hCursor = 0; + windowClassDesc.hbrBackground = 0; + windowClassDesc.lpszMenuName = 0; + windowClassDesc.lpszClassName = L"HelloWorld"; + windowClassDesc.hIconSm = 0; + ATOM windowClassAtom = RegisterClassExW(&windowClassDesc); + if(!windowClassAtom) + { + fprintf(stderr, "error: failed to register window class\n"); + return 1; + } + + // Next, we create a window using that window class. + + DWORD windowExtendedStyle = 0; + DWORD windowStyle = 0; + LPWSTR windowName = L"Slang Hello World"; + HWND windowHandle = CreateWindowExW( + windowExtendedStyle, + (LPWSTR)windowClassAtom, + windowName, + windowStyle, + 0, 0, // x, y + gWindowWidth, gWindowHeight, + NULL, // parent + NULL, // menu + instance, + NULL); + if(!windowHandle) + { + fprintf(stderr, "error: failed to create window\n"); + return 1; + } + + + // Rather than statically link against D3D, we load it dynamically. + + HMODULE d3d11 = LoadLibraryA("d3d11.dll"); + if(!d3d11) + { + fprintf(stderr, "error: failed load 'd3d11.dll'\n"); + return 1; + } + + PFN_D3D11_CREATE_DEVICE_AND_SWAP_CHAIN D3D11CreateDeviceAndSwapChain_ = + (PFN_D3D11_CREATE_DEVICE_AND_SWAP_CHAIN)GetProcAddress( + d3d11, + "D3D11CreateDeviceAndSwapChain"); + if(!D3D11CreateDeviceAndSwapChain_) + { + fprintf(stderr, + "error: failed load symbol 'D3D11CreateDeviceAndSwapChain'\n"); + return 1; + } + + // We create our device in debug mode, just so that we can check that the + // example doesn't trigger warnings. + UINT deviceFlags = 0; + deviceFlags |= D3D11_CREATE_DEVICE_DEBUG; + + // We will ask for the highest feature level that can be supported. + + D3D_FEATURE_LEVEL featureLevels[] = { + D3D_FEATURE_LEVEL_11_1, + D3D_FEATURE_LEVEL_11_0, + D3D_FEATURE_LEVEL_10_1, + D3D_FEATURE_LEVEL_10_0, + D3D_FEATURE_LEVEL_9_3, + D3D_FEATURE_LEVEL_9_2, + D3D_FEATURE_LEVEL_9_1, + }; + D3D_FEATURE_LEVEL dxFeatureLevel = D3D_FEATURE_LEVEL_9_1; + + // Our swap chain uses RGBA8 with sRGB, with double buffering. + + DXGI_SWAP_CHAIN_DESC dxSwapChainDesc = { 0 }; + dxSwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + dxSwapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; + dxSwapChainDesc.SampleDesc.Count = 1; + dxSwapChainDesc.SampleDesc.Quality = 0; + dxSwapChainDesc.BufferCount = 2; + dxSwapChainDesc.OutputWindow = windowHandle; + dxSwapChainDesc.Windowed = TRUE; + dxSwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; + dxSwapChainDesc.Flags = 0; + + // On a machine that does not have an up-to-date version of D3D installed, + // the `D3D11CreateDeviceAndSwapChain` call will fail with `E_INVALIDARG` + // if you ask for featuer level 11_1. The workaround is to call + // `D3D11CreateDeviceAndSwapChain` up to twice: the first time with 11_1 + // at the start of the list of requested feature levels, and the second + // time without it. + + IDXGISwapChain* dxSwapChain = NULL; + ID3D11Device* dxDevice = NULL; + ID3D11DeviceContext* dxImmediateContext = NULL; + HRESULT hr = S_OK; + for( int ii = 0; ii < 2; ++ii ) + { + hr = D3D11CreateDeviceAndSwapChain_( + NULL, // adapter (use default) + D3D_DRIVER_TYPE_HARDWARE, + NULL, // software + deviceFlags, + &featureLevels[ii], + (sizeof(featureLevels) / sizeof(featureLevels[0])) - 1, + D3D11_SDK_VERSION, + &dxSwapChainDesc, + &dxSwapChain, + &dxDevice, + &dxFeatureLevel, + &dxImmediateContext); + + // Failures with `E_INVALIDARG` might be due to feature level 11_1 + // not being supported. Other failures are real, though. + if( hr != E_INVALIDARG ) + break; + } + if( FAILED(hr) ) + { + return 1; + } + + // After we've created the swap chain, we can request a pointer to the + // back buffer as a D3D11 texture, and create a render-target view from it. + + ID3D11Texture2D* dxBackBufferTexture = NULL; + static const IID kIID_ID3D11Texture2D = { + 0x6f15aaf2, 0xd208, 0x4e89, 0x9a, 0xb4, 0x48, + 0x95, 0x35, 0xd3, 0x4f, 0x9c }; + dxSwapChain->GetBuffer( + 0, + kIID_ID3D11Texture2D, + (void**)&dxBackBufferTexture); + + ID3D11RenderTargetView* dxBackBufferRTV = NULL; + dxDevice->CreateRenderTargetView( + dxBackBufferTexture, + NULL, + &dxBackBufferRTV); + + // We immediately bind the back-buffer render target view, and we aren't + // going to switch. We don't bother with a depth buffer. + dxImmediateContext->OMSetRenderTargets( + 1, + &dxBackBufferRTV, + NULL); + + // Similarly, we are going to set up a viewport once, and then never + // switch, since this is a simple test app. + D3D11_VIEWPORT dxViewport; + dxViewport.TopLeftX = 0; + dxViewport.TopLeftY = 0; + dxViewport.Width = (float) gWindowWidth; + dxViewport.Height = (float) gWindowHeight; + dxViewport.MaxDepth = 1; // TODO(tfoley): use reversed depth + dxViewport.MinDepth = 0; + dxImmediateContext->RSSetViewports(1, &dxViewport); + + // Once we've done the general-purpose initialization, we + // initialize anything specific to the "hello world" application + hr = initialize( dxDevice ); + if( FAILED(hr) ) + { + exit(1); + } + + // Once initialization is all complete, we show the window... + ShowWindow(windowHandle, showCommand); + + // ... and enter the event loop: + for(;;) + { + MSG message; + + int result = PeekMessageW(&message, NULL, 0, 0, PM_REMOVE); + if (result != 0) + { + if (message.message == WM_QUIT) + { + return (int)message.wParam; + } + + TranslateMessage(&message); + DispatchMessageW(&message); + } + else + { + // Whenver we don't have Windows events to process, + // we render a frame. + + static const float kClearColor[] = { 0.25, 0.25, 0.25, 1.0 }; + dxImmediateContext->ClearRenderTargetView( + dxBackBufferRTV, + kClearColor); + + renderFrame( dxImmediateContext ); + + dxSwapChain->Present(0, 0); + } + } + + return 0; +} + + +// +// In order to actually use Slang in our application, we need to link in its +// implementation. The easiest way to accomplish this is by directly inlcuding +// the (concatenated) Slang source code into our app. +// + +#define SLANG_INCLUDE_IMPLEMENTATION +#include diff --git a/examples/hello/hello.slang b/examples/hello/hello.slang new file mode 100644 index 000000000..d563aab88 --- /dev/null +++ b/examples/hello/hello.slang @@ -0,0 +1,73 @@ +// shaders.spire + +cbuffer Uniforms +{ + float4x4 modelViewProjection; +} + +struct AssembledVertex +{ + float3 position; + float3 color; +}; + +struct CoarseVertex +{ + float3 color; +}; + +struct Fragment +{ + float4 color; +}; + + +// Vertex Shader + +struct VertexStageInput +{ + AssembledVertex assembledVertex : A; +}; + +struct VertexStageOutput +{ + CoarseVertex coarseVertex : CoarseVertex; + float4 sv_position : SV_Position; +}; + +VertexStageOutput vertexMain(VertexStageInput input) +{ + VertexStageOutput output; + + float3 position = input.assembledVertex.position; + float3 color = input.assembledVertex.color; + + output.coarseVertex.color = color; + output.sv_position = mul(modelViewProjection, float4(position, 1.0)); + + return output; +} + +// Fragment Shader + +struct FragmentStageInput +{ + CoarseVertex coarseVertex : CoarseVertex; +}; + +struct FragmentStageOutput +{ + Fragment fragment : SV_Target; +}; + +FragmentStageOutput fragmentMain(FragmentStageInput input) +{ + FragmentStageOutput output; + + float3 color = input.coarseVertex.color; + + output.fragment.color = float4(color, 1.0); + + return output; +} + diff --git a/examples/hello/hello.sln b/examples/hello/hello.sln new file mode 100644 index 000000000..3ddf262df --- /dev/null +++ b/examples/hello/hello.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "hello", "hello.vcxproj", "{E6385042-1649-4803-9EBD-168F8B7EF131}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {E6385042-1649-4803-9EBD-168F8B7EF131}.Debug|x64.ActiveCfg = Debug|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Debug|x64.Build.0 = Debug|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Debug|x86.ActiveCfg = Debug|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Debug|x86.Build.0 = Debug|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Release|x64.ActiveCfg = Release|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Release|x64.Build.0 = Release|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Release|x86.ActiveCfg = Release|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/examples/hello/hello.vcxproj b/examples/hello/hello.vcxproj new file mode 100644 index 000000000..7060da5dc --- /dev/null +++ b/examples/hello/hello.vcxproj @@ -0,0 +1,296 @@ + + + + + Debug_VS2013 + Win32 + + + Debug_VS2013 + x64 + + + Debug + Win32 + + + Release_VS2013 + Win32 + + + Release_VS2013 + x64 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + {E6385042-1649-4803-9EBD-168F8B7EF131} + Win32Proj + hello + 8.1 + + + + Application + true + v140 + Unicode + + + Application + true + v140 + Unicode + + + Application + false + v140 + true + Unicode + + + Application + false + v140 + true + Unicode + + + Application + true + v140 + Unicode + + + Application + true + v120 + Unicode + + + Application + false + v140 + true + Unicode + + + Application + false + v120 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + $(SolutionDir);$(IncludePath) + + + true + $(SolutionDir);$(IncludePath) + + + true + $(SolutionDir);$(IncludePath) + + + true + $(SolutionDir);$(IncludePath) + + + false + $(SolutionDir);$(IncludePath) + + + false + $(SolutionDir);$(IncludePath) + + + false + $(SolutionDir);$(IncludePath) + + + false + $(SolutionDir);$(IncludePath) + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + + + Windows + true + + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + + + Windows + true + + + + + + + Level3 + Disabled + _DEBUG;_WINDOWS;%(PreprocessorDefinitions) + + + Windows + true + + + + + + + Level3 + Disabled + _DEBUG;_WINDOWS;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Windows + true + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + + + Windows + true + true + true + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + + + Windows + true + true + true + + + + + Level3 + + + MaxSpeed + true + true + NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + + + Windows + true + true + true + + + + + Level3 + + + MaxSpeed + true + true + NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + + + Windows + true + true + true + + + + + + + + + + + + \ No newline at end of file diff --git a/examples/hello/hello.vcxproj.filters b/examples/hello/hello.vcxproj.filters new file mode 100644 index 000000000..cedbc9831 --- /dev/null +++ b/examples/hello/hello.vcxproj.filters @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/external/glext.h b/external/glext.h new file mode 100644 index 000000000..1c49e143d --- /dev/null +++ b/external/glext.h @@ -0,0 +1,12261 @@ +#ifndef __glext_h_ +#define __glext_h_ 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* +** Copyright (c) 2013-2017 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a +** copy of this software and/or associated documentation files (the +** "Materials"), to deal in the Materials without restriction, including +** without limitation the rights to use, copy, modify, merge, publish, +** distribute, sublicense, and/or sell copies of the Materials, and to +** permit persons to whom the Materials are 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 Materials. +** +** THE MATERIALS ARE 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 +** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +*/ +/* +** This header is generated from the Khronos OpenGL / OpenGL ES XML +** API Registry. The current version of the Registry, generator scripts +** used to make the header, and the header can be found at +** https://github.com/KhronosGroup/OpenGL-Registry +*/ + +#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN 1 +#endif +#include +#endif + +#ifndef APIENTRY +#define APIENTRY +#endif +#ifndef APIENTRYP +#define APIENTRYP APIENTRY * +#endif +#ifndef GLAPI +#define GLAPI extern +#endif + +#define GL_GLEXT_VERSION 20170531 + +/* Generated C header for: + * API: gl + * Profile: compatibility + * Versions considered: .* + * Versions emitted: 1\.[2-9]|[234]\.[0-9] + * Default extensions included: gl + * Additional extensions included: _nomatch_^ + * Extensions removed: _nomatch_^ + */ + +#ifndef GL_VERSION_1_2 +#define GL_VERSION_1_2 1 +#define GL_UNSIGNED_BYTE_3_3_2 0x8032 +#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 +#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 +#define GL_UNSIGNED_INT_8_8_8_8 0x8035 +#define GL_UNSIGNED_INT_10_10_10_2 0x8036 +#define GL_TEXTURE_BINDING_3D 0x806A +#define GL_PACK_SKIP_IMAGES 0x806B +#define GL_PACK_IMAGE_HEIGHT 0x806C +#define GL_UNPACK_SKIP_IMAGES 0x806D +#define GL_UNPACK_IMAGE_HEIGHT 0x806E +#define GL_TEXTURE_3D 0x806F +#define GL_PROXY_TEXTURE_3D 0x8070 +#define GL_TEXTURE_DEPTH 0x8071 +#define GL_TEXTURE_WRAP_R 0x8072 +#define GL_MAX_3D_TEXTURE_SIZE 0x8073 +#define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 +#define GL_UNSIGNED_SHORT_5_6_5 0x8363 +#define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 +#define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 +#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 +#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 +#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 +#define GL_BGR 0x80E0 +#define GL_BGRA 0x80E1 +#define GL_MAX_ELEMENTS_VERTICES 0x80E8 +#define GL_MAX_ELEMENTS_INDICES 0x80E9 +#define GL_CLAMP_TO_EDGE 0x812F +#define GL_TEXTURE_MIN_LOD 0x813A +#define GL_TEXTURE_MAX_LOD 0x813B +#define GL_TEXTURE_BASE_LEVEL 0x813C +#define GL_TEXTURE_MAX_LEVEL 0x813D +#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 +#define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 +#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 +#define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 +#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E +#define GL_RESCALE_NORMAL 0x803A +#define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8 +#define GL_SINGLE_COLOR 0x81F9 +#define GL_SEPARATE_SPECULAR_COLOR 0x81FA +#define GL_ALIASED_POINT_SIZE_RANGE 0x846D +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); +typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawRangeElements (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); +GLAPI void APIENTRY glTexImage3D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glCopyTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +#endif +#endif /* GL_VERSION_1_2 */ + +#ifndef GL_VERSION_1_3 +#define GL_VERSION_1_3 1 +#define GL_TEXTURE0 0x84C0 +#define GL_TEXTURE1 0x84C1 +#define GL_TEXTURE2 0x84C2 +#define GL_TEXTURE3 0x84C3 +#define GL_TEXTURE4 0x84C4 +#define GL_TEXTURE5 0x84C5 +#define GL_TEXTURE6 0x84C6 +#define GL_TEXTURE7 0x84C7 +#define GL_TEXTURE8 0x84C8 +#define GL_TEXTURE9 0x84C9 +#define GL_TEXTURE10 0x84CA +#define GL_TEXTURE11 0x84CB +#define GL_TEXTURE12 0x84CC +#define GL_TEXTURE13 0x84CD +#define GL_TEXTURE14 0x84CE +#define GL_TEXTURE15 0x84CF +#define GL_TEXTURE16 0x84D0 +#define GL_TEXTURE17 0x84D1 +#define GL_TEXTURE18 0x84D2 +#define GL_TEXTURE19 0x84D3 +#define GL_TEXTURE20 0x84D4 +#define GL_TEXTURE21 0x84D5 +#define GL_TEXTURE22 0x84D6 +#define GL_TEXTURE23 0x84D7 +#define GL_TEXTURE24 0x84D8 +#define GL_TEXTURE25 0x84D9 +#define GL_TEXTURE26 0x84DA +#define GL_TEXTURE27 0x84DB +#define GL_TEXTURE28 0x84DC +#define GL_TEXTURE29 0x84DD +#define GL_TEXTURE30 0x84DE +#define GL_TEXTURE31 0x84DF +#define GL_ACTIVE_TEXTURE 0x84E0 +#define GL_MULTISAMPLE 0x809D +#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE 0x809F +#define GL_SAMPLE_COVERAGE 0x80A0 +#define GL_SAMPLE_BUFFERS 0x80A8 +#define GL_SAMPLES 0x80A9 +#define GL_SAMPLE_COVERAGE_VALUE 0x80AA +#define GL_SAMPLE_COVERAGE_INVERT 0x80AB +#define GL_TEXTURE_CUBE_MAP 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A +#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C +#define GL_COMPRESSED_RGB 0x84ED +#define GL_COMPRESSED_RGBA 0x84EE +#define GL_TEXTURE_COMPRESSION_HINT 0x84EF +#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 +#define GL_TEXTURE_COMPRESSED 0x86A1 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 +#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 +#define GL_CLAMP_TO_BORDER 0x812D +#define GL_CLIENT_ACTIVE_TEXTURE 0x84E1 +#define GL_MAX_TEXTURE_UNITS 0x84E2 +#define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3 +#define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4 +#define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5 +#define GL_TRANSPOSE_COLOR_MATRIX 0x84E6 +#define GL_MULTISAMPLE_BIT 0x20000000 +#define GL_NORMAL_MAP 0x8511 +#define GL_REFLECTION_MAP 0x8512 +#define GL_COMPRESSED_ALPHA 0x84E9 +#define GL_COMPRESSED_LUMINANCE 0x84EA +#define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB +#define GL_COMPRESSED_INTENSITY 0x84EC +#define GL_COMBINE 0x8570 +#define GL_COMBINE_RGB 0x8571 +#define GL_COMBINE_ALPHA 0x8572 +#define GL_SOURCE0_RGB 0x8580 +#define GL_SOURCE1_RGB 0x8581 +#define GL_SOURCE2_RGB 0x8582 +#define GL_SOURCE0_ALPHA 0x8588 +#define GL_SOURCE1_ALPHA 0x8589 +#define GL_SOURCE2_ALPHA 0x858A +#define GL_OPERAND0_RGB 0x8590 +#define GL_OPERAND1_RGB 0x8591 +#define GL_OPERAND2_RGB 0x8592 +#define GL_OPERAND0_ALPHA 0x8598 +#define GL_OPERAND1_ALPHA 0x8599 +#define GL_OPERAND2_ALPHA 0x859A +#define GL_RGB_SCALE 0x8573 +#define GL_ADD_SIGNED 0x8574 +#define GL_INTERPOLATE 0x8575 +#define GL_SUBTRACT 0x84E7 +#define GL_CONSTANT 0x8576 +#define GL_PRIMARY_COLOR 0x8577 +#define GL_PREVIOUS 0x8578 +#define GL_DOT3_RGB 0x86AE +#define GL_DOT3_RGBA 0x86AF +typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLfloat value, GLboolean invert); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint level, void *img); +typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC) (GLenum target, GLdouble s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FPROC) (GLenum target, GLfloat s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IPROC) (GLenum target, GLint s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SPROC) (GLenum target, GLshort s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DPROC) (GLenum target, GLdouble s, GLdouble t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FPROC) (GLenum target, GLfloat s, GLfloat t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IPROC) (GLenum target, GLint s, GLint t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SPROC) (GLenum target, GLshort s, GLshort t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IPROC) (GLenum target, GLint s, GLint t, GLint r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SPROC) (GLenum target, GLshort s, GLshort t, GLshort r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFPROC) (const GLfloat *m); +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDPROC) (const GLdouble *m); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFPROC) (const GLfloat *m); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDPROC) (const GLdouble *m); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glActiveTexture (GLenum texture); +GLAPI void APIENTRY glSampleCoverage (GLfloat value, GLboolean invert); +GLAPI void APIENTRY glCompressedTexImage3D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexImage1D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexSubImage1D (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glGetCompressedTexImage (GLenum target, GLint level, void *img); +GLAPI void APIENTRY glClientActiveTexture (GLenum texture); +GLAPI void APIENTRY glMultiTexCoord1d (GLenum target, GLdouble s); +GLAPI void APIENTRY glMultiTexCoord1dv (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord1f (GLenum target, GLfloat s); +GLAPI void APIENTRY glMultiTexCoord1fv (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord1i (GLenum target, GLint s); +GLAPI void APIENTRY glMultiTexCoord1iv (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord1s (GLenum target, GLshort s); +GLAPI void APIENTRY glMultiTexCoord1sv (GLenum target, const GLshort *v); +GLAPI void APIENTRY glMultiTexCoord2d (GLenum target, GLdouble s, GLdouble t); +GLAPI void APIENTRY glMultiTexCoord2dv (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord2f (GLenum target, GLfloat s, GLfloat t); +GLAPI void APIENTRY glMultiTexCoord2fv (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord2i (GLenum target, GLint s, GLint t); +GLAPI void APIENTRY glMultiTexCoord2iv (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord2s (GLenum target, GLshort s, GLshort t); +GLAPI void APIENTRY glMultiTexCoord2sv (GLenum target, const GLshort *v); +GLAPI void APIENTRY glMultiTexCoord3d (GLenum target, GLdouble s, GLdouble t, GLdouble r); +GLAPI void APIENTRY glMultiTexCoord3dv (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord3f (GLenum target, GLfloat s, GLfloat t, GLfloat r); +GLAPI void APIENTRY glMultiTexCoord3fv (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord3i (GLenum target, GLint s, GLint t, GLint r); +GLAPI void APIENTRY glMultiTexCoord3iv (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord3s (GLenum target, GLshort s, GLshort t, GLshort r); +GLAPI void APIENTRY glMultiTexCoord3sv (GLenum target, const GLshort *v); +GLAPI void APIENTRY glMultiTexCoord4d (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +GLAPI void APIENTRY glMultiTexCoord4dv (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord4f (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +GLAPI void APIENTRY glMultiTexCoord4fv (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord4i (GLenum target, GLint s, GLint t, GLint r, GLint q); +GLAPI void APIENTRY glMultiTexCoord4iv (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord4s (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +GLAPI void APIENTRY glMultiTexCoord4sv (GLenum target, const GLshort *v); +GLAPI void APIENTRY glLoadTransposeMatrixf (const GLfloat *m); +GLAPI void APIENTRY glLoadTransposeMatrixd (const GLdouble *m); +GLAPI void APIENTRY glMultTransposeMatrixf (const GLfloat *m); +GLAPI void APIENTRY glMultTransposeMatrixd (const GLdouble *m); +#endif +#endif /* GL_VERSION_1_3 */ + +#ifndef GL_VERSION_1_4 +#define GL_VERSION_1_4 1 +#define GL_BLEND_DST_RGB 0x80C8 +#define GL_BLEND_SRC_RGB 0x80C9 +#define GL_BLEND_DST_ALPHA 0x80CA +#define GL_BLEND_SRC_ALPHA 0x80CB +#define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 +#define GL_DEPTH_COMPONENT16 0x81A5 +#define GL_DEPTH_COMPONENT24 0x81A6 +#define GL_DEPTH_COMPONENT32 0x81A7 +#define GL_MIRRORED_REPEAT 0x8370 +#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD +#define GL_TEXTURE_LOD_BIAS 0x8501 +#define GL_INCR_WRAP 0x8507 +#define GL_DECR_WRAP 0x8508 +#define GL_TEXTURE_DEPTH_SIZE 0x884A +#define GL_TEXTURE_COMPARE_MODE 0x884C +#define GL_TEXTURE_COMPARE_FUNC 0x884D +#define GL_POINT_SIZE_MIN 0x8126 +#define GL_POINT_SIZE_MAX 0x8127 +#define GL_POINT_DISTANCE_ATTENUATION 0x8129 +#define GL_GENERATE_MIPMAP 0x8191 +#define GL_GENERATE_MIPMAP_HINT 0x8192 +#define GL_FOG_COORDINATE_SOURCE 0x8450 +#define GL_FOG_COORDINATE 0x8451 +#define GL_FRAGMENT_DEPTH 0x8452 +#define GL_CURRENT_FOG_COORDINATE 0x8453 +#define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454 +#define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455 +#define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456 +#define GL_FOG_COORDINATE_ARRAY 0x8457 +#define GL_COLOR_SUM 0x8458 +#define GL_CURRENT_SECONDARY_COLOR 0x8459 +#define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A +#define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B +#define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C +#define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D +#define GL_SECONDARY_COLOR_ARRAY 0x845E +#define GL_TEXTURE_FILTER_CONTROL 0x8500 +#define GL_DEPTH_TEXTURE_MODE 0x884B +#define GL_COMPARE_R_TO_TEXTURE 0x884E +#define GL_FUNC_ADD 0x8006 +#define GL_FUNC_SUBTRACT 0x800A +#define GL_FUNC_REVERSE_SUBTRACT 0x800B +#define GL_MIN 0x8007 +#define GL_MAX 0x8008 +#define GL_CONSTANT_COLOR 0x8001 +#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 +#define GL_CONSTANT_ALPHA 0x8003 +#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei drawcount); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC) (GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLFOGCOORDFPROC) (GLfloat coord); +typedef void (APIENTRYP PFNGLFOGCOORDFVPROC) (const GLfloat *coord); +typedef void (APIENTRYP PFNGLFOGCOORDDPROC) (GLdouble coord); +typedef void (APIENTRYP PFNGLFOGCOORDDVPROC) (const GLdouble *coord); +typedef void (APIENTRYP PFNGLFOGCOORDPOINTERPROC) (GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BPROC) (GLbyte red, GLbyte green, GLbyte blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVPROC) (const GLbyte *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DPROC) (GLdouble red, GLdouble green, GLdouble blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FPROC) (GLfloat red, GLfloat green, GLfloat blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IPROC) (GLint red, GLint green, GLint blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SPROC) (GLshort red, GLshort green, GLshort blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBPROC) (GLubyte red, GLubyte green, GLubyte blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVPROC) (const GLubyte *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIPROC) (GLuint red, GLuint green, GLuint blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVPROC) (const GLuint *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USPROC) (GLushort red, GLushort green, GLushort blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVPROC) (const GLushort *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLWINDOWPOS2DPROC) (GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLWINDOWPOS2DVPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2FPROC) (GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLWINDOWPOS2FVPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2IPROC) (GLint x, GLint y); +typedef void (APIENTRYP PFNGLWINDOWPOS2IVPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2SPROC) (GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLWINDOWPOS2SVPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3DPROC) (GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLWINDOWPOS3DVPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3FPROC) (GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLWINDOWPOS3FVPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3IPROC) (GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLWINDOWPOS3IVPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3SPROC) (GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLBLENDCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +GLAPI void APIENTRY glMultiDrawArrays (GLenum mode, const GLint *first, const GLsizei *count, GLsizei drawcount); +GLAPI void APIENTRY glMultiDrawElements (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount); +GLAPI void APIENTRY glPointParameterf (GLenum pname, GLfloat param); +GLAPI void APIENTRY glPointParameterfv (GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glPointParameteri (GLenum pname, GLint param); +GLAPI void APIENTRY glPointParameteriv (GLenum pname, const GLint *params); +GLAPI void APIENTRY glFogCoordf (GLfloat coord); +GLAPI void APIENTRY glFogCoordfv (const GLfloat *coord); +GLAPI void APIENTRY glFogCoordd (GLdouble coord); +GLAPI void APIENTRY glFogCoorddv (const GLdouble *coord); +GLAPI void APIENTRY glFogCoordPointer (GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glSecondaryColor3b (GLbyte red, GLbyte green, GLbyte blue); +GLAPI void APIENTRY glSecondaryColor3bv (const GLbyte *v); +GLAPI void APIENTRY glSecondaryColor3d (GLdouble red, GLdouble green, GLdouble blue); +GLAPI void APIENTRY glSecondaryColor3dv (const GLdouble *v); +GLAPI void APIENTRY glSecondaryColor3f (GLfloat red, GLfloat green, GLfloat blue); +GLAPI void APIENTRY glSecondaryColor3fv (const GLfloat *v); +GLAPI void APIENTRY glSecondaryColor3i (GLint red, GLint green, GLint blue); +GLAPI void APIENTRY glSecondaryColor3iv (const GLint *v); +GLAPI void APIENTRY glSecondaryColor3s (GLshort red, GLshort green, GLshort blue); +GLAPI void APIENTRY glSecondaryColor3sv (const GLshort *v); +GLAPI void APIENTRY glSecondaryColor3ub (GLubyte red, GLubyte green, GLubyte blue); +GLAPI void APIENTRY glSecondaryColor3ubv (const GLubyte *v); +GLAPI void APIENTRY glSecondaryColor3ui (GLuint red, GLuint green, GLuint blue); +GLAPI void APIENTRY glSecondaryColor3uiv (const GLuint *v); +GLAPI void APIENTRY glSecondaryColor3us (GLushort red, GLushort green, GLushort blue); +GLAPI void APIENTRY glSecondaryColor3usv (const GLushort *v); +GLAPI void APIENTRY glSecondaryColorPointer (GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glWindowPos2d (GLdouble x, GLdouble y); +GLAPI void APIENTRY glWindowPos2dv (const GLdouble *v); +GLAPI void APIENTRY glWindowPos2f (GLfloat x, GLfloat y); +GLAPI void APIENTRY glWindowPos2fv (const GLfloat *v); +GLAPI void APIENTRY glWindowPos2i (GLint x, GLint y); +GLAPI void APIENTRY glWindowPos2iv (const GLint *v); +GLAPI void APIENTRY glWindowPos2s (GLshort x, GLshort y); +GLAPI void APIENTRY glWindowPos2sv (const GLshort *v); +GLAPI void APIENTRY glWindowPos3d (GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glWindowPos3dv (const GLdouble *v); +GLAPI void APIENTRY glWindowPos3f (GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glWindowPos3fv (const GLfloat *v); +GLAPI void APIENTRY glWindowPos3i (GLint x, GLint y, GLint z); +GLAPI void APIENTRY glWindowPos3iv (const GLint *v); +GLAPI void APIENTRY glWindowPos3s (GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glWindowPos3sv (const GLshort *v); +GLAPI void APIENTRY glBlendColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +GLAPI void APIENTRY glBlendEquation (GLenum mode); +#endif +#endif /* GL_VERSION_1_4 */ + +#ifndef GL_VERSION_1_5 +#define GL_VERSION_1_5 1 +#include +typedef ptrdiff_t GLsizeiptr; +typedef ptrdiff_t GLintptr; +#define GL_BUFFER_SIZE 0x8764 +#define GL_BUFFER_USAGE 0x8765 +#define GL_QUERY_COUNTER_BITS 0x8864 +#define GL_CURRENT_QUERY 0x8865 +#define GL_QUERY_RESULT 0x8866 +#define GL_QUERY_RESULT_AVAILABLE 0x8867 +#define GL_ARRAY_BUFFER 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 +#define GL_ARRAY_BUFFER_BINDING 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 +#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F +#define GL_READ_ONLY 0x88B8 +#define GL_WRITE_ONLY 0x88B9 +#define GL_READ_WRITE 0x88BA +#define GL_BUFFER_ACCESS 0x88BB +#define GL_BUFFER_MAPPED 0x88BC +#define GL_BUFFER_MAP_POINTER 0x88BD +#define GL_STREAM_DRAW 0x88E0 +#define GL_STREAM_READ 0x88E1 +#define GL_STREAM_COPY 0x88E2 +#define GL_STATIC_DRAW 0x88E4 +#define GL_STATIC_READ 0x88E5 +#define GL_STATIC_COPY 0x88E6 +#define GL_DYNAMIC_DRAW 0x88E8 +#define GL_DYNAMIC_READ 0x88E9 +#define GL_DYNAMIC_COPY 0x88EA +#define GL_SAMPLES_PASSED 0x8914 +#define GL_SRC1_ALPHA 0x8589 +#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 +#define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 +#define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 +#define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899 +#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A +#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B +#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C +#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D +#define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E +#define GL_FOG_COORD_SRC 0x8450 +#define GL_FOG_COORD 0x8451 +#define GL_CURRENT_FOG_COORD 0x8453 +#define GL_FOG_COORD_ARRAY_TYPE 0x8454 +#define GL_FOG_COORD_ARRAY_STRIDE 0x8455 +#define GL_FOG_COORD_ARRAY_POINTER 0x8456 +#define GL_FOG_COORD_ARRAY 0x8457 +#define GL_FOG_COORD_ARRAY_BUFFER_BINDING 0x889D +#define GL_SRC0_RGB 0x8580 +#define GL_SRC1_RGB 0x8581 +#define GL_SRC2_RGB 0x8582 +#define GL_SRC0_ALPHA 0x8588 +#define GL_SRC2_ALPHA 0x858A +typedef void (APIENTRYP PFNGLGENQUERIESPROC) (GLsizei n, GLuint *ids); +typedef void (APIENTRYP PFNGLDELETEQUERIESPROC) (GLsizei n, const GLuint *ids); +typedef GLboolean (APIENTRYP PFNGLISQUERYPROC) (GLuint id); +typedef void (APIENTRYP PFNGLBEGINQUERYPROC) (GLenum target, GLuint id); +typedef void (APIENTRYP PFNGLENDQUERYPROC) (GLenum target); +typedef void (APIENTRYP PFNGLGETQUERYIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC) (GLuint id, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC) (GLuint id, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer); +typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers); +typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers); +typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage); +typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); +typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, void *data); +typedef void *(APIENTRYP PFNGLMAPBUFFERPROC) (GLenum target, GLenum access); +typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC) (GLenum target); +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC) (GLenum target, GLenum pname, void **params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenQueries (GLsizei n, GLuint *ids); +GLAPI void APIENTRY glDeleteQueries (GLsizei n, const GLuint *ids); +GLAPI GLboolean APIENTRY glIsQuery (GLuint id); +GLAPI void APIENTRY glBeginQuery (GLenum target, GLuint id); +GLAPI void APIENTRY glEndQuery (GLenum target); +GLAPI void APIENTRY glGetQueryiv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetQueryObjectiv (GLuint id, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetQueryObjectuiv (GLuint id, GLenum pname, GLuint *params); +GLAPI void APIENTRY glBindBuffer (GLenum target, GLuint buffer); +GLAPI void APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers); +GLAPI void APIENTRY glGenBuffers (GLsizei n, GLuint *buffers); +GLAPI GLboolean APIENTRY glIsBuffer (GLuint buffer); +GLAPI void APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage); +GLAPI void APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); +GLAPI void APIENTRY glGetBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, void *data); +GLAPI void *APIENTRY glMapBuffer (GLenum target, GLenum access); +GLAPI GLboolean APIENTRY glUnmapBuffer (GLenum target); +GLAPI void APIENTRY glGetBufferParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetBufferPointerv (GLenum target, GLenum pname, void **params); +#endif +#endif /* GL_VERSION_1_5 */ + +#ifndef GL_VERSION_2_0 +#define GL_VERSION_2_0 1 +typedef char GLchar; +#define GL_BLEND_EQUATION_RGB 0x8009 +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 +#define GL_CURRENT_VERTEX_ATTRIB 0x8626 +#define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642 +#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 +#define GL_STENCIL_BACK_FUNC 0x8800 +#define GL_STENCIL_BACK_FAIL 0x8801 +#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 +#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 +#define GL_MAX_DRAW_BUFFERS 0x8824 +#define GL_DRAW_BUFFER0 0x8825 +#define GL_DRAW_BUFFER1 0x8826 +#define GL_DRAW_BUFFER2 0x8827 +#define GL_DRAW_BUFFER3 0x8828 +#define GL_DRAW_BUFFER4 0x8829 +#define GL_DRAW_BUFFER5 0x882A +#define GL_DRAW_BUFFER6 0x882B +#define GL_DRAW_BUFFER7 0x882C +#define GL_DRAW_BUFFER8 0x882D +#define GL_DRAW_BUFFER9 0x882E +#define GL_DRAW_BUFFER10 0x882F +#define GL_DRAW_BUFFER11 0x8830 +#define GL_DRAW_BUFFER12 0x8831 +#define GL_DRAW_BUFFER13 0x8832 +#define GL_DRAW_BUFFER14 0x8833 +#define GL_DRAW_BUFFER15 0x8834 +#define GL_BLEND_EQUATION_ALPHA 0x883D +#define GL_MAX_VERTEX_ATTRIBS 0x8869 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A +#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 +#define GL_FRAGMENT_SHADER 0x8B30 +#define GL_VERTEX_SHADER 0x8B31 +#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 +#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A +#define GL_MAX_VARYING_FLOATS 0x8B4B +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C +#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D +#define GL_SHADER_TYPE 0x8B4F +#define GL_FLOAT_VEC2 0x8B50 +#define GL_FLOAT_VEC3 0x8B51 +#define GL_FLOAT_VEC4 0x8B52 +#define GL_INT_VEC2 0x8B53 +#define GL_INT_VEC3 0x8B54 +#define GL_INT_VEC4 0x8B55 +#define GL_BOOL 0x8B56 +#define GL_BOOL_VEC2 0x8B57 +#define GL_BOOL_VEC3 0x8B58 +#define GL_BOOL_VEC4 0x8B59 +#define GL_FLOAT_MAT2 0x8B5A +#define GL_FLOAT_MAT3 0x8B5B +#define GL_FLOAT_MAT4 0x8B5C +#define GL_SAMPLER_1D 0x8B5D +#define GL_SAMPLER_2D 0x8B5E +#define GL_SAMPLER_3D 0x8B5F +#define GL_SAMPLER_CUBE 0x8B60 +#define GL_SAMPLER_1D_SHADOW 0x8B61 +#define GL_SAMPLER_2D_SHADOW 0x8B62 +#define GL_DELETE_STATUS 0x8B80 +#define GL_COMPILE_STATUS 0x8B81 +#define GL_LINK_STATUS 0x8B82 +#define GL_VALIDATE_STATUS 0x8B83 +#define GL_INFO_LOG_LENGTH 0x8B84 +#define GL_ATTACHED_SHADERS 0x8B85 +#define GL_ACTIVE_UNIFORMS 0x8B86 +#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 +#define GL_SHADER_SOURCE_LENGTH 0x8B88 +#define GL_ACTIVE_ATTRIBUTES 0x8B89 +#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B +#define GL_SHADING_LANGUAGE_VERSION 0x8B8C +#define GL_CURRENT_PROGRAM 0x8B8D +#define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0 +#define GL_LOWER_LEFT 0x8CA1 +#define GL_UPPER_LEFT 0x8CA2 +#define GL_STENCIL_BACK_REF 0x8CA3 +#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 +#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 +#define GL_VERTEX_PROGRAM_TWO_SIDE 0x8643 +#define GL_POINT_SPRITE 0x8861 +#define GL_COORD_REPLACE 0x8862 +#define GL_MAX_TEXTURE_COORDS 0x8871 +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha); +typedef void (APIENTRYP PFNGLDRAWBUFFERSPROC) (GLsizei n, const GLenum *bufs); +typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC) (GLenum face, GLenum func, GLint ref, GLuint mask); +typedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC) (GLenum face, GLuint mask); +typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); +typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC) (GLuint program, GLuint index, const GLchar *name); +typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader); +typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void); +typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type); +typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader); +typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader); +typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index); +typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index); +typedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +typedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC) (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); +typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); +typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLGETUNIFORMFVPROC) (GLuint program, GLint location, GLfloat *params); +typedef void (APIENTRYP PFNGLGETUNIFORMIVPROC) (GLuint program, GLint location, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC) (GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC) (GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer); +typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program); +typedef GLboolean (APIENTRYP PFNGLISSHADERPROC) (GLuint shader); +typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); +typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0); +typedef void (APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1); +typedef void (APIENTRYP PFNGLUNIFORM3FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +typedef void (APIENTRYP PFNGLUNIFORM4FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0); +typedef void (APIENTRYP PFNGLUNIFORM2IPROC) (GLint location, GLint v0, GLint v1); +typedef void (APIENTRYP PFNGLUNIFORM3IPROC) (GLint location, GLint v0, GLint v1, GLint v2); +typedef void (APIENTRYP PFNGLUNIFORM4IPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +typedef void (APIENTRYP PFNGLUNIFORM1FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM2FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM3FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM4FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM1IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM2IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM3IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM4IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC) (GLuint index, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC) (GLuint index, GLfloat x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC) (GLuint index, GLshort x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC) (GLuint index, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC) (GLuint index, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC) (GLuint index, GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC) (GLuint index, GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha); +GLAPI void APIENTRY glDrawBuffers (GLsizei n, const GLenum *bufs); +GLAPI void APIENTRY glStencilOpSeparate (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +GLAPI void APIENTRY glStencilFuncSeparate (GLenum face, GLenum func, GLint ref, GLuint mask); +GLAPI void APIENTRY glStencilMaskSeparate (GLenum face, GLuint mask); +GLAPI void APIENTRY glAttachShader (GLuint program, GLuint shader); +GLAPI void APIENTRY glBindAttribLocation (GLuint program, GLuint index, const GLchar *name); +GLAPI void APIENTRY glCompileShader (GLuint shader); +GLAPI GLuint APIENTRY glCreateProgram (void); +GLAPI GLuint APIENTRY glCreateShader (GLenum type); +GLAPI void APIENTRY glDeleteProgram (GLuint program); +GLAPI void APIENTRY glDeleteShader (GLuint shader); +GLAPI void APIENTRY glDetachShader (GLuint program, GLuint shader); +GLAPI void APIENTRY glDisableVertexAttribArray (GLuint index); +GLAPI void APIENTRY glEnableVertexAttribArray (GLuint index); +GLAPI void APIENTRY glGetActiveAttrib (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +GLAPI void APIENTRY glGetActiveUniform (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +GLAPI void APIENTRY glGetAttachedShaders (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); +GLAPI GLint APIENTRY glGetAttribLocation (GLuint program, const GLchar *name); +GLAPI void APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GLAPI void APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GLAPI void APIENTRY glGetShaderSource (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); +GLAPI GLint APIENTRY glGetUniformLocation (GLuint program, const GLchar *name); +GLAPI void APIENTRY glGetUniformfv (GLuint program, GLint location, GLfloat *params); +GLAPI void APIENTRY glGetUniformiv (GLuint program, GLint location, GLint *params); +GLAPI void APIENTRY glGetVertexAttribdv (GLuint index, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glGetVertexAttribfv (GLuint index, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void **pointer); +GLAPI GLboolean APIENTRY glIsProgram (GLuint program); +GLAPI GLboolean APIENTRY glIsShader (GLuint shader); +GLAPI void APIENTRY glLinkProgram (GLuint program); +GLAPI void APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); +GLAPI void APIENTRY glUseProgram (GLuint program); +GLAPI void APIENTRY glUniform1f (GLint location, GLfloat v0); +GLAPI void APIENTRY glUniform2f (GLint location, GLfloat v0, GLfloat v1); +GLAPI void APIENTRY glUniform3f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +GLAPI void APIENTRY glUniform4f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +GLAPI void APIENTRY glUniform1i (GLint location, GLint v0); +GLAPI void APIENTRY glUniform2i (GLint location, GLint v0, GLint v1); +GLAPI void APIENTRY glUniform3i (GLint location, GLint v0, GLint v1, GLint v2); +GLAPI void APIENTRY glUniform4i (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +GLAPI void APIENTRY glUniform1fv (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform2fv (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform3fv (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform4fv (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform1iv (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniform2iv (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniform3iv (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniform4iv (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniformMatrix2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glValidateProgram (GLuint program); +GLAPI void APIENTRY glVertexAttrib1d (GLuint index, GLdouble x); +GLAPI void APIENTRY glVertexAttrib1dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib1f (GLuint index, GLfloat x); +GLAPI void APIENTRY glVertexAttrib1fv (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib1s (GLuint index, GLshort x); +GLAPI void APIENTRY glVertexAttrib1sv (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib2d (GLuint index, GLdouble x, GLdouble y); +GLAPI void APIENTRY glVertexAttrib2dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib2f (GLuint index, GLfloat x, GLfloat y); +GLAPI void APIENTRY glVertexAttrib2fv (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib2s (GLuint index, GLshort x, GLshort y); +GLAPI void APIENTRY glVertexAttrib2sv (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib3d (GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glVertexAttrib3dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib3f (GLuint index, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glVertexAttrib3fv (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib3s (GLuint index, GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glVertexAttrib3sv (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4Nbv (GLuint index, const GLbyte *v); +GLAPI void APIENTRY glVertexAttrib4Niv (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttrib4Nsv (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4Nub (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +GLAPI void APIENTRY glVertexAttrib4Nubv (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttrib4Nuiv (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttrib4Nusv (GLuint index, const GLushort *v); +GLAPI void APIENTRY glVertexAttrib4bv (GLuint index, const GLbyte *v); +GLAPI void APIENTRY glVertexAttrib4d (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glVertexAttrib4dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib4f (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glVertexAttrib4fv (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib4iv (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttrib4s (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI void APIENTRY glVertexAttrib4sv (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4ubv (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttrib4uiv (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttrib4usv (GLuint index, const GLushort *v); +GLAPI void APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +#endif +#endif /* GL_VERSION_2_0 */ + +#ifndef GL_VERSION_2_1 +#define GL_VERSION_2_1 1 +#define GL_PIXEL_PACK_BUFFER 0x88EB +#define GL_PIXEL_UNPACK_BUFFER 0x88EC +#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED +#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF +#define GL_FLOAT_MAT2x3 0x8B65 +#define GL_FLOAT_MAT2x4 0x8B66 +#define GL_FLOAT_MAT3x2 0x8B67 +#define GL_FLOAT_MAT3x4 0x8B68 +#define GL_FLOAT_MAT4x2 0x8B69 +#define GL_FLOAT_MAT4x3 0x8B6A +#define GL_SRGB 0x8C40 +#define GL_SRGB8 0x8C41 +#define GL_SRGB_ALPHA 0x8C42 +#define GL_SRGB8_ALPHA8 0x8C43 +#define GL_COMPRESSED_SRGB 0x8C48 +#define GL_COMPRESSED_SRGB_ALPHA 0x8C49 +#define GL_CURRENT_RASTER_SECONDARY_COLOR 0x845F +#define GL_SLUMINANCE_ALPHA 0x8C44 +#define GL_SLUMINANCE8_ALPHA8 0x8C45 +#define GL_SLUMINANCE 0x8C46 +#define GL_SLUMINANCE8 0x8C47 +#define GL_COMPRESSED_SLUMINANCE 0x8C4A +#define GL_COMPRESSED_SLUMINANCE_ALPHA 0x8C4B +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glUniformMatrix2x3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix3x2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix2x4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix4x2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix3x4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix4x3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +#endif +#endif /* GL_VERSION_2_1 */ + +#ifndef GL_VERSION_3_0 +#define GL_VERSION_3_0 1 +typedef unsigned short GLhalf; +#define GL_COMPARE_REF_TO_TEXTURE 0x884E +#define GL_CLIP_DISTANCE0 0x3000 +#define GL_CLIP_DISTANCE1 0x3001 +#define GL_CLIP_DISTANCE2 0x3002 +#define GL_CLIP_DISTANCE3 0x3003 +#define GL_CLIP_DISTANCE4 0x3004 +#define GL_CLIP_DISTANCE5 0x3005 +#define GL_CLIP_DISTANCE6 0x3006 +#define GL_CLIP_DISTANCE7 0x3007 +#define GL_MAX_CLIP_DISTANCES 0x0D32 +#define GL_MAJOR_VERSION 0x821B +#define GL_MINOR_VERSION 0x821C +#define GL_NUM_EXTENSIONS 0x821D +#define GL_CONTEXT_FLAGS 0x821E +#define GL_COMPRESSED_RED 0x8225 +#define GL_COMPRESSED_RG 0x8226 +#define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x00000001 +#define GL_RGBA32F 0x8814 +#define GL_RGB32F 0x8815 +#define GL_RGBA16F 0x881A +#define GL_RGB16F 0x881B +#define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD +#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF +#define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 +#define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 +#define GL_CLAMP_READ_COLOR 0x891C +#define GL_FIXED_ONLY 0x891D +#define GL_MAX_VARYING_COMPONENTS 0x8B4B +#define GL_TEXTURE_1D_ARRAY 0x8C18 +#define GL_PROXY_TEXTURE_1D_ARRAY 0x8C19 +#define GL_TEXTURE_2D_ARRAY 0x8C1A +#define GL_PROXY_TEXTURE_2D_ARRAY 0x8C1B +#define GL_TEXTURE_BINDING_1D_ARRAY 0x8C1C +#define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D +#define GL_R11F_G11F_B10F 0x8C3A +#define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B +#define GL_RGB9_E5 0x8C3D +#define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E +#define GL_TEXTURE_SHARED_SIZE 0x8C3F +#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 +#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 +#define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 +#define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 +#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 +#define GL_PRIMITIVES_GENERATED 0x8C87 +#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 +#define GL_RASTERIZER_DISCARD 0x8C89 +#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B +#define GL_INTERLEAVED_ATTRIBS 0x8C8C +#define GL_SEPARATE_ATTRIBS 0x8C8D +#define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E +#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F +#define GL_RGBA32UI 0x8D70 +#define GL_RGB32UI 0x8D71 +#define GL_RGBA16UI 0x8D76 +#define GL_RGB16UI 0x8D77 +#define GL_RGBA8UI 0x8D7C +#define GL_RGB8UI 0x8D7D +#define GL_RGBA32I 0x8D82 +#define GL_RGB32I 0x8D83 +#define GL_RGBA16I 0x8D88 +#define GL_RGB16I 0x8D89 +#define GL_RGBA8I 0x8D8E +#define GL_RGB8I 0x8D8F +#define GL_RED_INTEGER 0x8D94 +#define GL_GREEN_INTEGER 0x8D95 +#define GL_BLUE_INTEGER 0x8D96 +#define GL_RGB_INTEGER 0x8D98 +#define GL_RGBA_INTEGER 0x8D99 +#define GL_BGR_INTEGER 0x8D9A +#define GL_BGRA_INTEGER 0x8D9B +#define GL_SAMPLER_1D_ARRAY 0x8DC0 +#define GL_SAMPLER_2D_ARRAY 0x8DC1 +#define GL_SAMPLER_1D_ARRAY_SHADOW 0x8DC3 +#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 +#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 +#define GL_UNSIGNED_INT_VEC2 0x8DC6 +#define GL_UNSIGNED_INT_VEC3 0x8DC7 +#define GL_UNSIGNED_INT_VEC4 0x8DC8 +#define GL_INT_SAMPLER_1D 0x8DC9 +#define GL_INT_SAMPLER_2D 0x8DCA +#define GL_INT_SAMPLER_3D 0x8DCB +#define GL_INT_SAMPLER_CUBE 0x8DCC +#define GL_INT_SAMPLER_1D_ARRAY 0x8DCE +#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF +#define GL_UNSIGNED_INT_SAMPLER_1D 0x8DD1 +#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 +#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 +#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 +#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY 0x8DD6 +#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 +#define GL_QUERY_WAIT 0x8E13 +#define GL_QUERY_NO_WAIT 0x8E14 +#define GL_QUERY_BY_REGION_WAIT 0x8E15 +#define GL_QUERY_BY_REGION_NO_WAIT 0x8E16 +#define GL_BUFFER_ACCESS_FLAGS 0x911F +#define GL_BUFFER_MAP_LENGTH 0x9120 +#define GL_BUFFER_MAP_OFFSET 0x9121 +#define GL_DEPTH_COMPONENT32F 0x8CAC +#define GL_DEPTH32F_STENCIL8 0x8CAD +#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD +#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 +#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 +#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 +#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 +#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 +#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 +#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 +#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 +#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 +#define GL_FRAMEBUFFER_DEFAULT 0x8218 +#define GL_FRAMEBUFFER_UNDEFINED 0x8219 +#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A +#define GL_MAX_RENDERBUFFER_SIZE 0x84E8 +#define GL_DEPTH_STENCIL 0x84F9 +#define GL_UNSIGNED_INT_24_8 0x84FA +#define GL_DEPTH24_STENCIL8 0x88F0 +#define GL_TEXTURE_STENCIL_SIZE 0x88F1 +#define GL_TEXTURE_RED_TYPE 0x8C10 +#define GL_TEXTURE_GREEN_TYPE 0x8C11 +#define GL_TEXTURE_BLUE_TYPE 0x8C12 +#define GL_TEXTURE_ALPHA_TYPE 0x8C13 +#define GL_TEXTURE_DEPTH_TYPE 0x8C16 +#define GL_UNSIGNED_NORMALIZED 0x8C17 +#define GL_FRAMEBUFFER_BINDING 0x8CA6 +#define GL_DRAW_FRAMEBUFFER_BINDING 0x8CA6 +#define GL_RENDERBUFFER_BINDING 0x8CA7 +#define GL_READ_FRAMEBUFFER 0x8CA8 +#define GL_DRAW_FRAMEBUFFER 0x8CA9 +#define GL_READ_FRAMEBUFFER_BINDING 0x8CAA +#define GL_RENDERBUFFER_SAMPLES 0x8CAB +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 +#define GL_FRAMEBUFFER_COMPLETE 0x8CD5 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER 0x8CDB +#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER 0x8CDC +#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD +#define GL_MAX_COLOR_ATTACHMENTS 0x8CDF +#define GL_COLOR_ATTACHMENT0 0x8CE0 +#define GL_COLOR_ATTACHMENT1 0x8CE1 +#define GL_COLOR_ATTACHMENT2 0x8CE2 +#define GL_COLOR_ATTACHMENT3 0x8CE3 +#define GL_COLOR_ATTACHMENT4 0x8CE4 +#define GL_COLOR_ATTACHMENT5 0x8CE5 +#define GL_COLOR_ATTACHMENT6 0x8CE6 +#define GL_COLOR_ATTACHMENT7 0x8CE7 +#define GL_COLOR_ATTACHMENT8 0x8CE8 +#define GL_COLOR_ATTACHMENT9 0x8CE9 +#define GL_COLOR_ATTACHMENT10 0x8CEA +#define GL_COLOR_ATTACHMENT11 0x8CEB +#define GL_COLOR_ATTACHMENT12 0x8CEC +#define GL_COLOR_ATTACHMENT13 0x8CED +#define GL_COLOR_ATTACHMENT14 0x8CEE +#define GL_COLOR_ATTACHMENT15 0x8CEF +#define GL_COLOR_ATTACHMENT16 0x8CF0 +#define GL_COLOR_ATTACHMENT17 0x8CF1 +#define GL_COLOR_ATTACHMENT18 0x8CF2 +#define GL_COLOR_ATTACHMENT19 0x8CF3 +#define GL_COLOR_ATTACHMENT20 0x8CF4 +#define GL_COLOR_ATTACHMENT21 0x8CF5 +#define GL_COLOR_ATTACHMENT22 0x8CF6 +#define GL_COLOR_ATTACHMENT23 0x8CF7 +#define GL_COLOR_ATTACHMENT24 0x8CF8 +#define GL_COLOR_ATTACHMENT25 0x8CF9 +#define GL_COLOR_ATTACHMENT26 0x8CFA +#define GL_COLOR_ATTACHMENT27 0x8CFB +#define GL_COLOR_ATTACHMENT28 0x8CFC +#define GL_COLOR_ATTACHMENT29 0x8CFD +#define GL_COLOR_ATTACHMENT30 0x8CFE +#define GL_COLOR_ATTACHMENT31 0x8CFF +#define GL_DEPTH_ATTACHMENT 0x8D00 +#define GL_STENCIL_ATTACHMENT 0x8D20 +#define GL_FRAMEBUFFER 0x8D40 +#define GL_RENDERBUFFER 0x8D41 +#define GL_RENDERBUFFER_WIDTH 0x8D42 +#define GL_RENDERBUFFER_HEIGHT 0x8D43 +#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 +#define GL_STENCIL_INDEX1 0x8D46 +#define GL_STENCIL_INDEX4 0x8D47 +#define GL_STENCIL_INDEX8 0x8D48 +#define GL_STENCIL_INDEX16 0x8D49 +#define GL_RENDERBUFFER_RED_SIZE 0x8D50 +#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 +#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 +#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 +#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 +#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 +#define GL_MAX_SAMPLES 0x8D57 +#define GL_INDEX 0x8222 +#define GL_TEXTURE_LUMINANCE_TYPE 0x8C14 +#define GL_TEXTURE_INTENSITY_TYPE 0x8C15 +#define GL_FRAMEBUFFER_SRGB 0x8DB9 +#define GL_HALF_FLOAT 0x140B +#define GL_MAP_READ_BIT 0x0001 +#define GL_MAP_WRITE_BIT 0x0002 +#define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 +#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 +#define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 +#define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 +#define GL_COMPRESSED_RED_RGTC1 0x8DBB +#define GL_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC +#define GL_COMPRESSED_RG_RGTC2 0x8DBD +#define GL_COMPRESSED_SIGNED_RG_RGTC2 0x8DBE +#define GL_RG 0x8227 +#define GL_RG_INTEGER 0x8228 +#define GL_R8 0x8229 +#define GL_R16 0x822A +#define GL_RG8 0x822B +#define GL_RG16 0x822C +#define GL_R16F 0x822D +#define GL_R32F 0x822E +#define GL_RG16F 0x822F +#define GL_RG32F 0x8230 +#define GL_R8I 0x8231 +#define GL_R8UI 0x8232 +#define GL_R16I 0x8233 +#define GL_R16UI 0x8234 +#define GL_R32I 0x8235 +#define GL_R32UI 0x8236 +#define GL_RG8I 0x8237 +#define GL_RG8UI 0x8238 +#define GL_RG16I 0x8239 +#define GL_RG16UI 0x823A +#define GL_RG32I 0x823B +#define GL_RG32UI 0x823C +#define GL_VERTEX_ARRAY_BINDING 0x85B5 +#define GL_CLAMP_VERTEX_COLOR 0x891A +#define GL_CLAMP_FRAGMENT_COLOR 0x891B +#define GL_ALPHA_INTEGER 0x8D97 +typedef void (APIENTRYP PFNGLCOLORMASKIPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC) (GLenum target, GLuint index, GLboolean *data); +typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC) (GLenum target, GLuint index, GLint *data); +typedef void (APIENTRYP PFNGLENABLEIPROC) (GLenum target, GLuint index); +typedef void (APIENTRYP PFNGLDISABLEIPROC) (GLenum target, GLuint index); +typedef GLboolean (APIENTRYP PFNGLISENABLEDIPROC) (GLenum target, GLuint index); +typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKPROC) (GLenum primitiveMode); +typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKPROC) (void); +typedef void (APIENTRYP PFNGLBINDBUFFERRANGEPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLBINDBUFFERBASEPROC) (GLenum target, GLuint index, GLuint buffer); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSPROC) (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +typedef void (APIENTRYP PFNGLCLAMPCOLORPROC) (GLenum target, GLenum clamp); +typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERPROC) (GLuint id, GLenum mode); +typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERPROC) (void); +typedef void (APIENTRYP PFNGLVERTEXATTRIBIPOINTERPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIIVPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIUIVPROC) (GLuint index, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IPROC) (GLuint index, GLint x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IPROC) (GLuint index, GLint x, GLint y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IPROC) (GLuint index, GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IPROC) (GLuint index, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIPROC) (GLuint index, GLuint x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIPROC) (GLuint index, GLuint x, GLuint y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIPROC) (GLuint index, GLuint x, GLuint y, GLuint z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIPROC) (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4BVPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UBVPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4USVPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLGETUNIFORMUIVPROC) (GLuint program, GLint location, GLuint *params); +typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONPROC) (GLuint program, GLuint color, const GLchar *name); +typedef GLint (APIENTRYP PFNGLGETFRAGDATALOCATIONPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLUNIFORM1UIPROC) (GLint location, GLuint v0); +typedef void (APIENTRYP PFNGLUNIFORM2UIPROC) (GLint location, GLuint v0, GLuint v1); +typedef void (APIENTRYP PFNGLUNIFORM3UIPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2); +typedef void (APIENTRYP PFNGLUNIFORM4UIPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +typedef void (APIENTRYP PFNGLUNIFORM1UIVPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLUNIFORM2UIVPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLUNIFORM3UIVPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLUNIFORM4UIVPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLTEXPARAMETERIIVPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLTEXPARAMETERIUIVPROC) (GLenum target, GLenum pname, const GLuint *params); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIUIVPROC) (GLenum target, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLCLEARBUFFERIVPROC) (GLenum buffer, GLint drawbuffer, const GLint *value); +typedef void (APIENTRYP PFNGLCLEARBUFFERUIVPROC) (GLenum buffer, GLint drawbuffer, const GLuint *value); +typedef void (APIENTRYP PFNGLCLEARBUFFERFVPROC) (GLenum buffer, GLint drawbuffer, const GLfloat *value); +typedef void (APIENTRYP PFNGLCLEARBUFFERFIPROC) (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); +typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGIPROC) (GLenum name, GLuint index); +typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFERPROC) (GLuint renderbuffer); +typedef void (APIENTRYP PFNGLBINDRENDERBUFFERPROC) (GLenum target, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSPROC) (GLsizei n, const GLuint *renderbuffers); +typedef void (APIENTRYP PFNGLGENRENDERBUFFERSPROC) (GLsizei n, GLuint *renderbuffers); +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFERPROC) (GLuint framebuffer); +typedef void (APIENTRYP PFNGLBINDFRAMEBUFFERPROC) (GLenum target, GLuint framebuffer); +typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSPROC) (GLsizei n, const GLuint *framebuffers); +typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSPROC) (GLsizei n, GLuint *framebuffers); +typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSPROC) (GLenum target); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFERPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGENERATEMIPMAPPROC) (GLenum target); +typedef void (APIENTRYP PFNGLBLITFRAMEBUFFERPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +typedef void *(APIENTRYP PFNGLMAPBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); +typedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length); +typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC) (GLuint array); +typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays); +typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays); +typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYPROC) (GLuint array); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorMaski (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +GLAPI void APIENTRY glGetBooleani_v (GLenum target, GLuint index, GLboolean *data); +GLAPI void APIENTRY glGetIntegeri_v (GLenum target, GLuint index, GLint *data); +GLAPI void APIENTRY glEnablei (GLenum target, GLuint index); +GLAPI void APIENTRY glDisablei (GLenum target, GLuint index); +GLAPI GLboolean APIENTRY glIsEnabledi (GLenum target, GLuint index); +GLAPI void APIENTRY glBeginTransformFeedback (GLenum primitiveMode); +GLAPI void APIENTRY glEndTransformFeedback (void); +GLAPI void APIENTRY glBindBufferRange (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glBindBufferBase (GLenum target, GLuint index, GLuint buffer); +GLAPI void APIENTRY glTransformFeedbackVaryings (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); +GLAPI void APIENTRY glGetTransformFeedbackVarying (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +GLAPI void APIENTRY glClampColor (GLenum target, GLenum clamp); +GLAPI void APIENTRY glBeginConditionalRender (GLuint id, GLenum mode); +GLAPI void APIENTRY glEndConditionalRender (void); +GLAPI void APIENTRY glVertexAttribIPointer (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glGetVertexAttribIiv (GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribIuiv (GLuint index, GLenum pname, GLuint *params); +GLAPI void APIENTRY glVertexAttribI1i (GLuint index, GLint x); +GLAPI void APIENTRY glVertexAttribI2i (GLuint index, GLint x, GLint y); +GLAPI void APIENTRY glVertexAttribI3i (GLuint index, GLint x, GLint y, GLint z); +GLAPI void APIENTRY glVertexAttribI4i (GLuint index, GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glVertexAttribI1ui (GLuint index, GLuint x); +GLAPI void APIENTRY glVertexAttribI2ui (GLuint index, GLuint x, GLuint y); +GLAPI void APIENTRY glVertexAttribI3ui (GLuint index, GLuint x, GLuint y, GLuint z); +GLAPI void APIENTRY glVertexAttribI4ui (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +GLAPI void APIENTRY glVertexAttribI1iv (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI2iv (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI3iv (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI4iv (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI1uiv (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI2uiv (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI3uiv (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI4uiv (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI4bv (GLuint index, const GLbyte *v); +GLAPI void APIENTRY glVertexAttribI4sv (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttribI4ubv (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttribI4usv (GLuint index, const GLushort *v); +GLAPI void APIENTRY glGetUniformuiv (GLuint program, GLint location, GLuint *params); +GLAPI void APIENTRY glBindFragDataLocation (GLuint program, GLuint color, const GLchar *name); +GLAPI GLint APIENTRY glGetFragDataLocation (GLuint program, const GLchar *name); +GLAPI void APIENTRY glUniform1ui (GLint location, GLuint v0); +GLAPI void APIENTRY glUniform2ui (GLint location, GLuint v0, GLuint v1); +GLAPI void APIENTRY glUniform3ui (GLint location, GLuint v0, GLuint v1, GLuint v2); +GLAPI void APIENTRY glUniform4ui (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +GLAPI void APIENTRY glUniform1uiv (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glUniform2uiv (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glUniform3uiv (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glUniform4uiv (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glTexParameterIiv (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glTexParameterIuiv (GLenum target, GLenum pname, const GLuint *params); +GLAPI void APIENTRY glGetTexParameterIiv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetTexParameterIuiv (GLenum target, GLenum pname, GLuint *params); +GLAPI void APIENTRY glClearBufferiv (GLenum buffer, GLint drawbuffer, const GLint *value); +GLAPI void APIENTRY glClearBufferuiv (GLenum buffer, GLint drawbuffer, const GLuint *value); +GLAPI void APIENTRY glClearBufferfv (GLenum buffer, GLint drawbuffer, const GLfloat *value); +GLAPI void APIENTRY glClearBufferfi (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); +GLAPI const GLubyte *APIENTRY glGetStringi (GLenum name, GLuint index); +GLAPI GLboolean APIENTRY glIsRenderbuffer (GLuint renderbuffer); +GLAPI void APIENTRY glBindRenderbuffer (GLenum target, GLuint renderbuffer); +GLAPI void APIENTRY glDeleteRenderbuffers (GLsizei n, const GLuint *renderbuffers); +GLAPI void APIENTRY glGenRenderbuffers (GLsizei n, GLuint *renderbuffers); +GLAPI void APIENTRY glRenderbufferStorage (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetRenderbufferParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI GLboolean APIENTRY glIsFramebuffer (GLuint framebuffer); +GLAPI void APIENTRY glBindFramebuffer (GLenum target, GLuint framebuffer); +GLAPI void APIENTRY glDeleteFramebuffers (GLsizei n, const GLuint *framebuffers); +GLAPI void APIENTRY glGenFramebuffers (GLsizei n, GLuint *framebuffers); +GLAPI GLenum APIENTRY glCheckFramebufferStatus (GLenum target); +GLAPI void APIENTRY glFramebufferTexture1D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI void APIENTRY glFramebufferTexture2D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI void APIENTRY glFramebufferTexture3D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +GLAPI void APIENTRY glFramebufferRenderbuffer (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +GLAPI void APIENTRY glGetFramebufferAttachmentParameteriv (GLenum target, GLenum attachment, GLenum pname, GLint *params); +GLAPI void APIENTRY glGenerateMipmap (GLenum target); +GLAPI void APIENTRY glBlitFramebuffer (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +GLAPI void APIENTRY glRenderbufferStorageMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glFramebufferTextureLayer (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +GLAPI void *APIENTRY glMapBufferRange (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); +GLAPI void APIENTRY glFlushMappedBufferRange (GLenum target, GLintptr offset, GLsizeiptr length); +GLAPI void APIENTRY glBindVertexArray (GLuint array); +GLAPI void APIENTRY glDeleteVertexArrays (GLsizei n, const GLuint *arrays); +GLAPI void APIENTRY glGenVertexArrays (GLsizei n, GLuint *arrays); +GLAPI GLboolean APIENTRY glIsVertexArray (GLuint array); +#endif +#endif /* GL_VERSION_3_0 */ + +#ifndef GL_VERSION_3_1 +#define GL_VERSION_3_1 1 +#define GL_SAMPLER_2D_RECT 0x8B63 +#define GL_SAMPLER_2D_RECT_SHADOW 0x8B64 +#define GL_SAMPLER_BUFFER 0x8DC2 +#define GL_INT_SAMPLER_2D_RECT 0x8DCD +#define GL_INT_SAMPLER_BUFFER 0x8DD0 +#define GL_UNSIGNED_INT_SAMPLER_2D_RECT 0x8DD5 +#define GL_UNSIGNED_INT_SAMPLER_BUFFER 0x8DD8 +#define GL_TEXTURE_BUFFER 0x8C2A +#define GL_MAX_TEXTURE_BUFFER_SIZE 0x8C2B +#define GL_TEXTURE_BINDING_BUFFER 0x8C2C +#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING 0x8C2D +#define GL_TEXTURE_RECTANGLE 0x84F5 +#define GL_TEXTURE_BINDING_RECTANGLE 0x84F6 +#define GL_PROXY_TEXTURE_RECTANGLE 0x84F7 +#define GL_MAX_RECTANGLE_TEXTURE_SIZE 0x84F8 +#define GL_R8_SNORM 0x8F94 +#define GL_RG8_SNORM 0x8F95 +#define GL_RGB8_SNORM 0x8F96 +#define GL_RGBA8_SNORM 0x8F97 +#define GL_R16_SNORM 0x8F98 +#define GL_RG16_SNORM 0x8F99 +#define GL_RGB16_SNORM 0x8F9A +#define GL_RGBA16_SNORM 0x8F9B +#define GL_SIGNED_NORMALIZED 0x8F9C +#define GL_PRIMITIVE_RESTART 0x8F9D +#define GL_PRIMITIVE_RESTART_INDEX 0x8F9E +#define GL_COPY_READ_BUFFER 0x8F36 +#define GL_COPY_WRITE_BUFFER 0x8F37 +#define GL_UNIFORM_BUFFER 0x8A11 +#define GL_UNIFORM_BUFFER_BINDING 0x8A28 +#define GL_UNIFORM_BUFFER_START 0x8A29 +#define GL_UNIFORM_BUFFER_SIZE 0x8A2A +#define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B +#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS 0x8A2C +#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D +#define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E +#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F +#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 +#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 +#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS 0x8A32 +#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 +#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 +#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 +#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 +#define GL_UNIFORM_TYPE 0x8A37 +#define GL_UNIFORM_SIZE 0x8A38 +#define GL_UNIFORM_NAME_LENGTH 0x8A39 +#define GL_UNIFORM_BLOCK_INDEX 0x8A3A +#define GL_UNIFORM_OFFSET 0x8A3B +#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C +#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D +#define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E +#define GL_UNIFORM_BLOCK_BINDING 0x8A3F +#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 +#define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 +#define GL_INVALID_INDEX 0xFFFFFFFFu +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDPROC) (GLenum mode, GLint first, GLsizei count, GLsizei instancecount); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount); +typedef void (APIENTRYP PFNGLTEXBUFFERPROC) (GLenum target, GLenum internalformat, GLuint buffer); +typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXPROC) (GLuint index); +typedef void (APIENTRYP PFNGLCOPYBUFFERSUBDATAPROC) (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLGETUNIFORMINDICESPROC) (GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMSIVPROC) (GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMNAMEPROC) (GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName); +typedef GLuint (APIENTRYP PFNGLGETUNIFORMBLOCKINDEXPROC) (GLuint program, const GLchar *uniformBlockName); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKIVPROC) (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC) (GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); +typedef void (APIENTRYP PFNGLUNIFORMBLOCKBINDINGPROC) (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawArraysInstanced (GLenum mode, GLint first, GLsizei count, GLsizei instancecount); +GLAPI void APIENTRY glDrawElementsInstanced (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount); +GLAPI void APIENTRY glTexBuffer (GLenum target, GLenum internalformat, GLuint buffer); +GLAPI void APIENTRY glPrimitiveRestartIndex (GLuint index); +GLAPI void APIENTRY glCopyBufferSubData (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +GLAPI void APIENTRY glGetUniformIndices (GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices); +GLAPI void APIENTRY glGetActiveUniformsiv (GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetActiveUniformName (GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName); +GLAPI GLuint APIENTRY glGetUniformBlockIndex (GLuint program, const GLchar *uniformBlockName); +GLAPI void APIENTRY glGetActiveUniformBlockiv (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetActiveUniformBlockName (GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); +GLAPI void APIENTRY glUniformBlockBinding (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); +#endif +#endif /* GL_VERSION_3_1 */ + +#ifndef GL_VERSION_3_2 +#define GL_VERSION_3_2 1 +typedef struct __GLsync *GLsync; +#ifndef GLEXT_64_TYPES_DEFINED +/* This code block is duplicated in glxext.h, so must be protected */ +#define GLEXT_64_TYPES_DEFINED +/* Define int32_t, int64_t, and uint64_t types for UST/MSC */ +/* (as used in the GL_EXT_timer_query extension). */ +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L +#include +#elif defined(__sun__) || defined(__digital__) +#include +#if defined(__STDC__) +#if defined(__arch64__) || defined(_LP64) +typedef long int int64_t; +typedef unsigned long int uint64_t; +#else +typedef long long int int64_t; +typedef unsigned long long int uint64_t; +#endif /* __arch64__ */ +#endif /* __STDC__ */ +#elif defined( __VMS ) || defined(__sgi) +#include +#elif defined(__SCO__) || defined(__USLC__) +#include +#elif defined(__UNIXOS2__) || defined(__SOL64__) +typedef long int int32_t; +typedef long long int int64_t; +typedef unsigned long long int uint64_t; +#elif defined(_WIN32) && defined(__GNUC__) +#include +#elif defined(_WIN32) +typedef __int32 int32_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +#else +/* Fallback if nothing above works */ +#include +#endif +#endif +typedef uint64_t GLuint64; +typedef int64_t GLint64; +#define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001 +#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 +#define GL_LINES_ADJACENCY 0x000A +#define GL_LINE_STRIP_ADJACENCY 0x000B +#define GL_TRIANGLES_ADJACENCY 0x000C +#define GL_TRIANGLE_STRIP_ADJACENCY 0x000D +#define GL_PROGRAM_POINT_SIZE 0x8642 +#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS 0x8C29 +#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED 0x8DA7 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS 0x8DA8 +#define GL_GEOMETRY_SHADER 0x8DD9 +#define GL_GEOMETRY_VERTICES_OUT 0x8916 +#define GL_GEOMETRY_INPUT_TYPE 0x8917 +#define GL_GEOMETRY_OUTPUT_TYPE 0x8918 +#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS 0x8DDF +#define GL_MAX_GEOMETRY_OUTPUT_VERTICES 0x8DE0 +#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS 0x8DE1 +#define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 +#define GL_MAX_GEOMETRY_INPUT_COMPONENTS 0x9123 +#define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS 0x9124 +#define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 +#define GL_CONTEXT_PROFILE_MASK 0x9126 +#define GL_DEPTH_CLAMP 0x864F +#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION 0x8E4C +#define GL_FIRST_VERTEX_CONVENTION 0x8E4D +#define GL_LAST_VERTEX_CONVENTION 0x8E4E +#define GL_PROVOKING_VERTEX 0x8E4F +#define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F +#define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 +#define GL_OBJECT_TYPE 0x9112 +#define GL_SYNC_CONDITION 0x9113 +#define GL_SYNC_STATUS 0x9114 +#define GL_SYNC_FLAGS 0x9115 +#define GL_SYNC_FENCE 0x9116 +#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 +#define GL_UNSIGNALED 0x9118 +#define GL_SIGNALED 0x9119 +#define GL_ALREADY_SIGNALED 0x911A +#define GL_TIMEOUT_EXPIRED 0x911B +#define GL_CONDITION_SATISFIED 0x911C +#define GL_WAIT_FAILED 0x911D +#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull +#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 +#define GL_SAMPLE_POSITION 0x8E50 +#define GL_SAMPLE_MASK 0x8E51 +#define GL_SAMPLE_MASK_VALUE 0x8E52 +#define GL_MAX_SAMPLE_MASK_WORDS 0x8E59 +#define GL_TEXTURE_2D_MULTISAMPLE 0x9100 +#define GL_PROXY_TEXTURE_2D_MULTISAMPLE 0x9101 +#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102 +#define GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9103 +#define GL_TEXTURE_BINDING_2D_MULTISAMPLE 0x9104 +#define GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY 0x9105 +#define GL_TEXTURE_SAMPLES 0x9106 +#define GL_TEXTURE_FIXED_SAMPLE_LOCATIONS 0x9107 +#define GL_SAMPLER_2D_MULTISAMPLE 0x9108 +#define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109 +#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A +#define GL_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910B +#define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910C +#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910D +#define GL_MAX_COLOR_TEXTURE_SAMPLES 0x910E +#define GL_MAX_DEPTH_TEXTURE_SAMPLES 0x910F +#define GL_MAX_INTEGER_SAMPLES 0x9110 +typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount, const GLint *basevertex); +typedef void (APIENTRYP PFNGLPROVOKINGVERTEXPROC) (GLenum mode); +typedef GLsync (APIENTRYP PFNGLFENCESYNCPROC) (GLenum condition, GLbitfield flags); +typedef GLboolean (APIENTRYP PFNGLISSYNCPROC) (GLsync sync); +typedef void (APIENTRYP PFNGLDELETESYNCPROC) (GLsync sync); +typedef GLenum (APIENTRYP PFNGLCLIENTWAITSYNCPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout); +typedef void (APIENTRYP PFNGLWAITSYNCPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout); +typedef void (APIENTRYP PFNGLGETINTEGER64VPROC) (GLenum pname, GLint64 *data); +typedef void (APIENTRYP PFNGLGETSYNCIVPROC) (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); +typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC) (GLenum target, GLuint index, GLint64 *data); +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERI64VPROC) (GLenum target, GLenum pname, GLint64 *params); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLGETMULTISAMPLEFVPROC) (GLenum pname, GLuint index, GLfloat *val); +typedef void (APIENTRYP PFNGLSAMPLEMASKIPROC) (GLuint maskNumber, GLbitfield mask); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawElementsBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); +GLAPI void APIENTRY glDrawRangeElementsBaseVertex (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); +GLAPI void APIENTRY glDrawElementsInstancedBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); +GLAPI void APIENTRY glMultiDrawElementsBaseVertex (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount, const GLint *basevertex); +GLAPI void APIENTRY glProvokingVertex (GLenum mode); +GLAPI GLsync APIENTRY glFenceSync (GLenum condition, GLbitfield flags); +GLAPI GLboolean APIENTRY glIsSync (GLsync sync); +GLAPI void APIENTRY glDeleteSync (GLsync sync); +GLAPI GLenum APIENTRY glClientWaitSync (GLsync sync, GLbitfield flags, GLuint64 timeout); +GLAPI void APIENTRY glWaitSync (GLsync sync, GLbitfield flags, GLuint64 timeout); +GLAPI void APIENTRY glGetInteger64v (GLenum pname, GLint64 *data); +GLAPI void APIENTRY glGetSynciv (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); +GLAPI void APIENTRY glGetInteger64i_v (GLenum target, GLuint index, GLint64 *data); +GLAPI void APIENTRY glGetBufferParameteri64v (GLenum target, GLenum pname, GLint64 *params); +GLAPI void APIENTRY glFramebufferTexture (GLenum target, GLenum attachment, GLuint texture, GLint level); +GLAPI void APIENTRY glTexImage2DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTexImage3DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glGetMultisamplefv (GLenum pname, GLuint index, GLfloat *val); +GLAPI void APIENTRY glSampleMaski (GLuint maskNumber, GLbitfield mask); +#endif +#endif /* GL_VERSION_3_2 */ + +#ifndef GL_VERSION_3_3 +#define GL_VERSION_3_3 1 +#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE +#define GL_SRC1_COLOR 0x88F9 +#define GL_ONE_MINUS_SRC1_COLOR 0x88FA +#define GL_ONE_MINUS_SRC1_ALPHA 0x88FB +#define GL_MAX_DUAL_SOURCE_DRAW_BUFFERS 0x88FC +#define GL_ANY_SAMPLES_PASSED 0x8C2F +#define GL_SAMPLER_BINDING 0x8919 +#define GL_RGB10_A2UI 0x906F +#define GL_TEXTURE_SWIZZLE_R 0x8E42 +#define GL_TEXTURE_SWIZZLE_G 0x8E43 +#define GL_TEXTURE_SWIZZLE_B 0x8E44 +#define GL_TEXTURE_SWIZZLE_A 0x8E45 +#define GL_TEXTURE_SWIZZLE_RGBA 0x8E46 +#define GL_TIME_ELAPSED 0x88BF +#define GL_TIMESTAMP 0x8E28 +#define GL_INT_2_10_10_10_REV 0x8D9F +typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONINDEXEDPROC) (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name); +typedef GLint (APIENTRYP PFNGLGETFRAGDATAINDEXPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLGENSAMPLERSPROC) (GLsizei count, GLuint *samplers); +typedef void (APIENTRYP PFNGLDELETESAMPLERSPROC) (GLsizei count, const GLuint *samplers); +typedef GLboolean (APIENTRYP PFNGLISSAMPLERPROC) (GLuint sampler); +typedef void (APIENTRYP PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIPROC) (GLuint sampler, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIVPROC) (GLuint sampler, GLenum pname, const GLint *param); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERFPROC) (GLuint sampler, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum pname, const GLfloat *param); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIIVPROC) (GLuint sampler, GLenum pname, const GLint *param); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIUIVPROC) (GLuint sampler, GLenum pname, const GLuint *param); +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIVPROC) (GLuint sampler, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIIVPROC) (GLuint sampler, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVPROC) (GLuint sampler, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLQUERYCOUNTERPROC) (GLuint id, GLenum target); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTI64VPROC) (GLuint id, GLenum pname, GLint64 *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUI64VPROC) (GLuint id, GLenum pname, GLuint64 *params); +typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORPROC) (GLuint index, GLuint divisor); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXP2UIPROC) (GLenum type, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXP2UIVPROC) (GLenum type, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXP3UIPROC) (GLenum type, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXP3UIVPROC) (GLenum type, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXP4UIPROC) (GLenum type, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXP4UIVPROC) (GLenum type, const GLuint *value); +typedef void (APIENTRYP PFNGLTEXCOORDP1UIPROC) (GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLTEXCOORDP1UIVPROC) (GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLTEXCOORDP2UIPROC) (GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLTEXCOORDP2UIVPROC) (GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLTEXCOORDP3UIPROC) (GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLTEXCOORDP3UIVPROC) (GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLTEXCOORDP4UIPROC) (GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLTEXCOORDP4UIVPROC) (GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP1UIPROC) (GLenum texture, GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP1UIVPROC) (GLenum texture, GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP2UIPROC) (GLenum texture, GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP2UIVPROC) (GLenum texture, GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP3UIPROC) (GLenum texture, GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP3UIVPROC) (GLenum texture, GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP4UIPROC) (GLenum texture, GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP4UIVPROC) (GLenum texture, GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLNORMALP3UIPROC) (GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLNORMALP3UIVPROC) (GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLCOLORP3UIPROC) (GLenum type, GLuint color); +typedef void (APIENTRYP PFNGLCOLORP3UIVPROC) (GLenum type, const GLuint *color); +typedef void (APIENTRYP PFNGLCOLORP4UIPROC) (GLenum type, GLuint color); +typedef void (APIENTRYP PFNGLCOLORP4UIVPROC) (GLenum type, const GLuint *color); +typedef void (APIENTRYP PFNGLSECONDARYCOLORP3UIPROC) (GLenum type, GLuint color); +typedef void (APIENTRYP PFNGLSECONDARYCOLORP3UIVPROC) (GLenum type, const GLuint *color); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindFragDataLocationIndexed (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name); +GLAPI GLint APIENTRY glGetFragDataIndex (GLuint program, const GLchar *name); +GLAPI void APIENTRY glGenSamplers (GLsizei count, GLuint *samplers); +GLAPI void APIENTRY glDeleteSamplers (GLsizei count, const GLuint *samplers); +GLAPI GLboolean APIENTRY glIsSampler (GLuint sampler); +GLAPI void APIENTRY glBindSampler (GLuint unit, GLuint sampler); +GLAPI void APIENTRY glSamplerParameteri (GLuint sampler, GLenum pname, GLint param); +GLAPI void APIENTRY glSamplerParameteriv (GLuint sampler, GLenum pname, const GLint *param); +GLAPI void APIENTRY glSamplerParameterf (GLuint sampler, GLenum pname, GLfloat param); +GLAPI void APIENTRY glSamplerParameterfv (GLuint sampler, GLenum pname, const GLfloat *param); +GLAPI void APIENTRY glSamplerParameterIiv (GLuint sampler, GLenum pname, const GLint *param); +GLAPI void APIENTRY glSamplerParameterIuiv (GLuint sampler, GLenum pname, const GLuint *param); +GLAPI void APIENTRY glGetSamplerParameteriv (GLuint sampler, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetSamplerParameterIiv (GLuint sampler, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetSamplerParameterfv (GLuint sampler, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetSamplerParameterIuiv (GLuint sampler, GLenum pname, GLuint *params); +GLAPI void APIENTRY glQueryCounter (GLuint id, GLenum target); +GLAPI void APIENTRY glGetQueryObjecti64v (GLuint id, GLenum pname, GLint64 *params); +GLAPI void APIENTRY glGetQueryObjectui64v (GLuint id, GLenum pname, GLuint64 *params); +GLAPI void APIENTRY glVertexAttribDivisor (GLuint index, GLuint divisor); +GLAPI void APIENTRY glVertexAttribP1ui (GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI void APIENTRY glVertexAttribP1uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI void APIENTRY glVertexAttribP2ui (GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI void APIENTRY glVertexAttribP2uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI void APIENTRY glVertexAttribP3ui (GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI void APIENTRY glVertexAttribP3uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI void APIENTRY glVertexAttribP4ui (GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI void APIENTRY glVertexAttribP4uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI void APIENTRY glVertexP2ui (GLenum type, GLuint value); +GLAPI void APIENTRY glVertexP2uiv (GLenum type, const GLuint *value); +GLAPI void APIENTRY glVertexP3ui (GLenum type, GLuint value); +GLAPI void APIENTRY glVertexP3uiv (GLenum type, const GLuint *value); +GLAPI void APIENTRY glVertexP4ui (GLenum type, GLuint value); +GLAPI void APIENTRY glVertexP4uiv (GLenum type, const GLuint *value); +GLAPI void APIENTRY glTexCoordP1ui (GLenum type, GLuint coords); +GLAPI void APIENTRY glTexCoordP1uiv (GLenum type, const GLuint *coords); +GLAPI void APIENTRY glTexCoordP2ui (GLenum type, GLuint coords); +GLAPI void APIENTRY glTexCoordP2uiv (GLenum type, const GLuint *coords); +GLAPI void APIENTRY glTexCoordP3ui (GLenum type, GLuint coords); +GLAPI void APIENTRY glTexCoordP3uiv (GLenum type, const GLuint *coords); +GLAPI void APIENTRY glTexCoordP4ui (GLenum type, GLuint coords); +GLAPI void APIENTRY glTexCoordP4uiv (GLenum type, const GLuint *coords); +GLAPI void APIENTRY glMultiTexCoordP1ui (GLenum texture, GLenum type, GLuint coords); +GLAPI void APIENTRY glMultiTexCoordP1uiv (GLenum texture, GLenum type, const GLuint *coords); +GLAPI void APIENTRY glMultiTexCoordP2ui (GLenum texture, GLenum type, GLuint coords); +GLAPI void APIENTRY glMultiTexCoordP2uiv (GLenum texture, GLenum type, const GLuint *coords); +GLAPI void APIENTRY glMultiTexCoordP3ui (GLenum texture, GLenum type, GLuint coords); +GLAPI void APIENTRY glMultiTexCoordP3uiv (GLenum texture, GLenum type, const GLuint *coords); +GLAPI void APIENTRY glMultiTexCoordP4ui (GLenum texture, GLenum type, GLuint coords); +GLAPI void APIENTRY glMultiTexCoordP4uiv (GLenum texture, GLenum type, const GLuint *coords); +GLAPI void APIENTRY glNormalP3ui (GLenum type, GLuint coords); +GLAPI void APIENTRY glNormalP3uiv (GLenum type, const GLuint *coords); +GLAPI void APIENTRY glColorP3ui (GLenum type, GLuint color); +GLAPI void APIENTRY glColorP3uiv (GLenum type, const GLuint *color); +GLAPI void APIENTRY glColorP4ui (GLenum type, GLuint color); +GLAPI void APIENTRY glColorP4uiv (GLenum type, const GLuint *color); +GLAPI void APIENTRY glSecondaryColorP3ui (GLenum type, GLuint color); +GLAPI void APIENTRY glSecondaryColorP3uiv (GLenum type, const GLuint *color); +#endif +#endif /* GL_VERSION_3_3 */ + +#ifndef GL_VERSION_4_0 +#define GL_VERSION_4_0 1 +#define GL_SAMPLE_SHADING 0x8C36 +#define GL_MIN_SAMPLE_SHADING_VALUE 0x8C37 +#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5E +#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5F +#define GL_TEXTURE_CUBE_MAP_ARRAY 0x9009 +#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY 0x900A +#define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY 0x900B +#define GL_SAMPLER_CUBE_MAP_ARRAY 0x900C +#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW 0x900D +#define GL_INT_SAMPLER_CUBE_MAP_ARRAY 0x900E +#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY 0x900F +#define GL_DRAW_INDIRECT_BUFFER 0x8F3F +#define GL_DRAW_INDIRECT_BUFFER_BINDING 0x8F43 +#define GL_GEOMETRY_SHADER_INVOCATIONS 0x887F +#define GL_MAX_GEOMETRY_SHADER_INVOCATIONS 0x8E5A +#define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET 0x8E5B +#define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET 0x8E5C +#define GL_FRAGMENT_INTERPOLATION_OFFSET_BITS 0x8E5D +#define GL_MAX_VERTEX_STREAMS 0x8E71 +#define GL_DOUBLE_VEC2 0x8FFC +#define GL_DOUBLE_VEC3 0x8FFD +#define GL_DOUBLE_VEC4 0x8FFE +#define GL_DOUBLE_MAT2 0x8F46 +#define GL_DOUBLE_MAT3 0x8F47 +#define GL_DOUBLE_MAT4 0x8F48 +#define GL_DOUBLE_MAT2x3 0x8F49 +#define GL_DOUBLE_MAT2x4 0x8F4A +#define GL_DOUBLE_MAT3x2 0x8F4B +#define GL_DOUBLE_MAT3x4 0x8F4C +#define GL_DOUBLE_MAT4x2 0x8F4D +#define GL_DOUBLE_MAT4x3 0x8F4E +#define GL_ACTIVE_SUBROUTINES 0x8DE5 +#define GL_ACTIVE_SUBROUTINE_UNIFORMS 0x8DE6 +#define GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS 0x8E47 +#define GL_ACTIVE_SUBROUTINE_MAX_LENGTH 0x8E48 +#define GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH 0x8E49 +#define GL_MAX_SUBROUTINES 0x8DE7 +#define GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS 0x8DE8 +#define GL_NUM_COMPATIBLE_SUBROUTINES 0x8E4A +#define GL_COMPATIBLE_SUBROUTINES 0x8E4B +#define GL_PATCHES 0x000E +#define GL_PATCH_VERTICES 0x8E72 +#define GL_PATCH_DEFAULT_INNER_LEVEL 0x8E73 +#define GL_PATCH_DEFAULT_OUTER_LEVEL 0x8E74 +#define GL_TESS_CONTROL_OUTPUT_VERTICES 0x8E75 +#define GL_TESS_GEN_MODE 0x8E76 +#define GL_TESS_GEN_SPACING 0x8E77 +#define GL_TESS_GEN_VERTEX_ORDER 0x8E78 +#define GL_TESS_GEN_POINT_MODE 0x8E79 +#define GL_ISOLINES 0x8E7A +#define GL_FRACTIONAL_ODD 0x8E7B +#define GL_FRACTIONAL_EVEN 0x8E7C +#define GL_MAX_PATCH_VERTICES 0x8E7D +#define GL_MAX_TESS_GEN_LEVEL 0x8E7E +#define GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E7F +#define GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E80 +#define GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS 0x8E81 +#define GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS 0x8E82 +#define GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS 0x8E83 +#define GL_MAX_TESS_PATCH_COMPONENTS 0x8E84 +#define GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS 0x8E85 +#define GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS 0x8E86 +#define GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS 0x8E89 +#define GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS 0x8E8A +#define GL_MAX_TESS_CONTROL_INPUT_COMPONENTS 0x886C +#define GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS 0x886D +#define GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E1E +#define GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E1F +#define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER 0x84F0 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER 0x84F1 +#define GL_TESS_EVALUATION_SHADER 0x8E87 +#define GL_TESS_CONTROL_SHADER 0x8E88 +#define GL_TRANSFORM_FEEDBACK 0x8E22 +#define GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED 0x8E23 +#define GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE 0x8E24 +#define GL_TRANSFORM_FEEDBACK_BINDING 0x8E25 +#define GL_MAX_TRANSFORM_FEEDBACK_BUFFERS 0x8E70 +typedef void (APIENTRYP PFNGLMINSAMPLESHADINGPROC) (GLfloat value); +typedef void (APIENTRYP PFNGLBLENDEQUATIONIPROC) (GLuint buf, GLenum mode); +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEIPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +typedef void (APIENTRYP PFNGLBLENDFUNCIPROC) (GLuint buf, GLenum src, GLenum dst); +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEIPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +typedef void (APIENTRYP PFNGLDRAWARRAYSINDIRECTPROC) (GLenum mode, const void *indirect); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINDIRECTPROC) (GLenum mode, GLenum type, const void *indirect); +typedef void (APIENTRYP PFNGLUNIFORM1DPROC) (GLint location, GLdouble x); +typedef void (APIENTRYP PFNGLUNIFORM2DPROC) (GLint location, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLUNIFORM3DPROC) (GLint location, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLUNIFORM4DPROC) (GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLUNIFORM1DVPROC) (GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORM2DVPROC) (GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORM3DVPROC) (GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORM4DVPROC) (GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLGETUNIFORMDVPROC) (GLuint program, GLint location, GLdouble *params); +typedef GLint (APIENTRYP PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC) (GLuint program, GLenum shadertype, const GLchar *name); +typedef GLuint (APIENTRYP PFNGLGETSUBROUTINEINDEXPROC) (GLuint program, GLenum shadertype, const GLchar *name); +typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC) (GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint *values); +typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC) (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name); +typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINENAMEPROC) (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name); +typedef void (APIENTRYP PFNGLUNIFORMSUBROUTINESUIVPROC) (GLenum shadertype, GLsizei count, const GLuint *indices); +typedef void (APIENTRYP PFNGLGETUNIFORMSUBROUTINEUIVPROC) (GLenum shadertype, GLint location, GLuint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMSTAGEIVPROC) (GLuint program, GLenum shadertype, GLenum pname, GLint *values); +typedef void (APIENTRYP PFNGLPATCHPARAMETERIPROC) (GLenum pname, GLint value); +typedef void (APIENTRYP PFNGLPATCHPARAMETERFVPROC) (GLenum pname, const GLfloat *values); +typedef void (APIENTRYP PFNGLBINDTRANSFORMFEEDBACKPROC) (GLenum target, GLuint id); +typedef void (APIENTRYP PFNGLDELETETRANSFORMFEEDBACKSPROC) (GLsizei n, const GLuint *ids); +typedef void (APIENTRYP PFNGLGENTRANSFORMFEEDBACKSPROC) (GLsizei n, GLuint *ids); +typedef GLboolean (APIENTRYP PFNGLISTRANSFORMFEEDBACKPROC) (GLuint id); +typedef void (APIENTRYP PFNGLPAUSETRANSFORMFEEDBACKPROC) (void); +typedef void (APIENTRYP PFNGLRESUMETRANSFORMFEEDBACKPROC) (void); +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKPROC) (GLenum mode, GLuint id); +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC) (GLenum mode, GLuint id, GLuint stream); +typedef void (APIENTRYP PFNGLBEGINQUERYINDEXEDPROC) (GLenum target, GLuint index, GLuint id); +typedef void (APIENTRYP PFNGLENDQUERYINDEXEDPROC) (GLenum target, GLuint index); +typedef void (APIENTRYP PFNGLGETQUERYINDEXEDIVPROC) (GLenum target, GLuint index, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMinSampleShading (GLfloat value); +GLAPI void APIENTRY glBlendEquationi (GLuint buf, GLenum mode); +GLAPI void APIENTRY glBlendEquationSeparatei (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +GLAPI void APIENTRY glBlendFunci (GLuint buf, GLenum src, GLenum dst); +GLAPI void APIENTRY glBlendFuncSeparatei (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +GLAPI void APIENTRY glDrawArraysIndirect (GLenum mode, const void *indirect); +GLAPI void APIENTRY glDrawElementsIndirect (GLenum mode, GLenum type, const void *indirect); +GLAPI void APIENTRY glUniform1d (GLint location, GLdouble x); +GLAPI void APIENTRY glUniform2d (GLint location, GLdouble x, GLdouble y); +GLAPI void APIENTRY glUniform3d (GLint location, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glUniform4d (GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glUniform1dv (GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glUniform2dv (GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glUniform3dv (GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glUniform4dv (GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix2dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix3dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix4dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix2x3dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix2x4dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix3x2dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix3x4dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix4x2dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix4x3dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glGetUniformdv (GLuint program, GLint location, GLdouble *params); +GLAPI GLint APIENTRY glGetSubroutineUniformLocation (GLuint program, GLenum shadertype, const GLchar *name); +GLAPI GLuint APIENTRY glGetSubroutineIndex (GLuint program, GLenum shadertype, const GLchar *name); +GLAPI void APIENTRY glGetActiveSubroutineUniformiv (GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint *values); +GLAPI void APIENTRY glGetActiveSubroutineUniformName (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name); +GLAPI void APIENTRY glGetActiveSubroutineName (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name); +GLAPI void APIENTRY glUniformSubroutinesuiv (GLenum shadertype, GLsizei count, const GLuint *indices); +GLAPI void APIENTRY glGetUniformSubroutineuiv (GLenum shadertype, GLint location, GLuint *params); +GLAPI void APIENTRY glGetProgramStageiv (GLuint program, GLenum shadertype, GLenum pname, GLint *values); +GLAPI void APIENTRY glPatchParameteri (GLenum pname, GLint value); +GLAPI void APIENTRY glPatchParameterfv (GLenum pname, const GLfloat *values); +GLAPI void APIENTRY glBindTransformFeedback (GLenum target, GLuint id); +GLAPI void APIENTRY glDeleteTransformFeedbacks (GLsizei n, const GLuint *ids); +GLAPI void APIENTRY glGenTransformFeedbacks (GLsizei n, GLuint *ids); +GLAPI GLboolean APIENTRY glIsTransformFeedback (GLuint id); +GLAPI void APIENTRY glPauseTransformFeedback (void); +GLAPI void APIENTRY glResumeTransformFeedback (void); +GLAPI void APIENTRY glDrawTransformFeedback (GLenum mode, GLuint id); +GLAPI void APIENTRY glDrawTransformFeedbackStream (GLenum mode, GLuint id, GLuint stream); +GLAPI void APIENTRY glBeginQueryIndexed (GLenum target, GLuint index, GLuint id); +GLAPI void APIENTRY glEndQueryIndexed (GLenum target, GLuint index); +GLAPI void APIENTRY glGetQueryIndexediv (GLenum target, GLuint index, GLenum pname, GLint *params); +#endif +#endif /* GL_VERSION_4_0 */ + +#ifndef GL_VERSION_4_1 +#define GL_VERSION_4_1 1 +#define GL_FIXED 0x140C +#define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A +#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B +#define GL_LOW_FLOAT 0x8DF0 +#define GL_MEDIUM_FLOAT 0x8DF1 +#define GL_HIGH_FLOAT 0x8DF2 +#define GL_LOW_INT 0x8DF3 +#define GL_MEDIUM_INT 0x8DF4 +#define GL_HIGH_INT 0x8DF5 +#define GL_SHADER_COMPILER 0x8DFA +#define GL_SHADER_BINARY_FORMATS 0x8DF8 +#define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9 +#define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB +#define GL_MAX_VARYING_VECTORS 0x8DFC +#define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD +#define GL_RGB565 0x8D62 +#define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0x8257 +#define GL_PROGRAM_BINARY_LENGTH 0x8741 +#define GL_NUM_PROGRAM_BINARY_FORMATS 0x87FE +#define GL_PROGRAM_BINARY_FORMATS 0x87FF +#define GL_VERTEX_SHADER_BIT 0x00000001 +#define GL_FRAGMENT_SHADER_BIT 0x00000002 +#define GL_GEOMETRY_SHADER_BIT 0x00000004 +#define GL_TESS_CONTROL_SHADER_BIT 0x00000008 +#define GL_TESS_EVALUATION_SHADER_BIT 0x00000010 +#define GL_ALL_SHADER_BITS 0xFFFFFFFF +#define GL_PROGRAM_SEPARABLE 0x8258 +#define GL_ACTIVE_PROGRAM 0x8259 +#define GL_PROGRAM_PIPELINE_BINDING 0x825A +#define GL_MAX_VIEWPORTS 0x825B +#define GL_VIEWPORT_SUBPIXEL_BITS 0x825C +#define GL_VIEWPORT_BOUNDS_RANGE 0x825D +#define GL_LAYER_PROVOKING_VERTEX 0x825E +#define GL_VIEWPORT_INDEX_PROVOKING_VERTEX 0x825F +#define GL_UNDEFINED_VERTEX 0x8260 +typedef void (APIENTRYP PFNGLRELEASESHADERCOMPILERPROC) (void); +typedef void (APIENTRYP PFNGLSHADERBINARYPROC) (GLsizei count, const GLuint *shaders, GLenum binaryformat, const void *binary, GLsizei length); +typedef void (APIENTRYP PFNGLGETSHADERPRECISIONFORMATPROC) (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); +typedef void (APIENTRYP PFNGLDEPTHRANGEFPROC) (GLfloat n, GLfloat f); +typedef void (APIENTRYP PFNGLCLEARDEPTHFPROC) (GLfloat d); +typedef void (APIENTRYP PFNGLGETPROGRAMBINARYPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); +typedef void (APIENTRYP PFNGLPROGRAMBINARYPROC) (GLuint program, GLenum binaryFormat, const void *binary, GLsizei length); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIPROC) (GLuint program, GLenum pname, GLint value); +typedef void (APIENTRYP PFNGLUSEPROGRAMSTAGESPROC) (GLuint pipeline, GLbitfield stages, GLuint program); +typedef void (APIENTRYP PFNGLACTIVESHADERPROGRAMPROC) (GLuint pipeline, GLuint program); +typedef GLuint (APIENTRYP PFNGLCREATESHADERPROGRAMVPROC) (GLenum type, GLsizei count, const GLchar *const*strings); +typedef void (APIENTRYP PFNGLBINDPROGRAMPIPELINEPROC) (GLuint pipeline); +typedef void (APIENTRYP PFNGLDELETEPROGRAMPIPELINESPROC) (GLsizei n, const GLuint *pipelines); +typedef void (APIENTRYP PFNGLGENPROGRAMPIPELINESPROC) (GLsizei n, GLuint *pipelines); +typedef GLboolean (APIENTRYP PFNGLISPROGRAMPIPELINEPROC) (GLuint pipeline); +typedef void (APIENTRYP PFNGLGETPROGRAMPIPELINEIVPROC) (GLuint pipeline, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IPROC) (GLuint program, GLint location, GLint v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FPROC) (GLuint program, GLint location, GLfloat v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DPROC) (GLuint program, GLint location, GLdouble v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIPROC) (GLuint program, GLint location, GLuint v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IPROC) (GLuint program, GLint location, GLint v0, GLint v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DPROC) (GLuint program, GLint location, GLdouble v0, GLdouble v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIPROC) (GLuint program, GLint location, GLuint v0, GLuint v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DPROC) (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DPROC) (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPIPELINEPROC) (GLuint pipeline); +typedef void (APIENTRYP PFNGLGETPROGRAMPIPELINEINFOLOGPROC) (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DPROC) (GLuint index, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DPROC) (GLuint index, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBLPOINTERPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLDVPROC) (GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLVIEWPORTARRAYVPROC) (GLuint first, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVIEWPORTINDEXEDFPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); +typedef void (APIENTRYP PFNGLVIEWPORTINDEXEDFVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLSCISSORARRAYVPROC) (GLuint first, GLsizei count, const GLint *v); +typedef void (APIENTRYP PFNGLSCISSORINDEXEDPROC) (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLSCISSORINDEXEDVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLDEPTHRANGEARRAYVPROC) (GLuint first, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLDEPTHRANGEINDEXEDPROC) (GLuint index, GLdouble n, GLdouble f); +typedef void (APIENTRYP PFNGLGETFLOATI_VPROC) (GLenum target, GLuint index, GLfloat *data); +typedef void (APIENTRYP PFNGLGETDOUBLEI_VPROC) (GLenum target, GLuint index, GLdouble *data); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glReleaseShaderCompiler (void); +GLAPI void APIENTRY glShaderBinary (GLsizei count, const GLuint *shaders, GLenum binaryformat, const void *binary, GLsizei length); +GLAPI void APIENTRY glGetShaderPrecisionFormat (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); +GLAPI void APIENTRY glDepthRangef (GLfloat n, GLfloat f); +GLAPI void APIENTRY glClearDepthf (GLfloat d); +GLAPI void APIENTRY glGetProgramBinary (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); +GLAPI void APIENTRY glProgramBinary (GLuint program, GLenum binaryFormat, const void *binary, GLsizei length); +GLAPI void APIENTRY glProgramParameteri (GLuint program, GLenum pname, GLint value); +GLAPI void APIENTRY glUseProgramStages (GLuint pipeline, GLbitfield stages, GLuint program); +GLAPI void APIENTRY glActiveShaderProgram (GLuint pipeline, GLuint program); +GLAPI GLuint APIENTRY glCreateShaderProgramv (GLenum type, GLsizei count, const GLchar *const*strings); +GLAPI void APIENTRY glBindProgramPipeline (GLuint pipeline); +GLAPI void APIENTRY glDeleteProgramPipelines (GLsizei n, const GLuint *pipelines); +GLAPI void APIENTRY glGenProgramPipelines (GLsizei n, GLuint *pipelines); +GLAPI GLboolean APIENTRY glIsProgramPipeline (GLuint pipeline); +GLAPI void APIENTRY glGetProgramPipelineiv (GLuint pipeline, GLenum pname, GLint *params); +GLAPI void APIENTRY glProgramUniform1i (GLuint program, GLint location, GLint v0); +GLAPI void APIENTRY glProgramUniform1iv (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform1f (GLuint program, GLint location, GLfloat v0); +GLAPI void APIENTRY glProgramUniform1fv (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform1d (GLuint program, GLint location, GLdouble v0); +GLAPI void APIENTRY glProgramUniform1dv (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform1ui (GLuint program, GLint location, GLuint v0); +GLAPI void APIENTRY glProgramUniform1uiv (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniform2i (GLuint program, GLint location, GLint v0, GLint v1); +GLAPI void APIENTRY glProgramUniform2iv (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform2f (GLuint program, GLint location, GLfloat v0, GLfloat v1); +GLAPI void APIENTRY glProgramUniform2fv (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform2d (GLuint program, GLint location, GLdouble v0, GLdouble v1); +GLAPI void APIENTRY glProgramUniform2dv (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform2ui (GLuint program, GLint location, GLuint v0, GLuint v1); +GLAPI void APIENTRY glProgramUniform2uiv (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniform3i (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); +GLAPI void APIENTRY glProgramUniform3iv (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform3f (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +GLAPI void APIENTRY glProgramUniform3fv (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform3d (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2); +GLAPI void APIENTRY glProgramUniform3dv (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform3ui (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); +GLAPI void APIENTRY glProgramUniform3uiv (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniform4i (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +GLAPI void APIENTRY glProgramUniform4iv (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform4f (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +GLAPI void APIENTRY glProgramUniform4fv (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform4d (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3); +GLAPI void APIENTRY glProgramUniform4dv (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform4ui (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +GLAPI void APIENTRY glProgramUniform4uiv (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniformMatrix2fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix3fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix4fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix2dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix3dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix4dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix2x3fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix3x2fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix2x4fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix4x2fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix3x4fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix4x3fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix2x3dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix3x2dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix2x4dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix4x2dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix3x4dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix4x3dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glValidateProgramPipeline (GLuint pipeline); +GLAPI void APIENTRY glGetProgramPipelineInfoLog (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GLAPI void APIENTRY glVertexAttribL1d (GLuint index, GLdouble x); +GLAPI void APIENTRY glVertexAttribL2d (GLuint index, GLdouble x, GLdouble y); +GLAPI void APIENTRY glVertexAttribL3d (GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glVertexAttribL4d (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glVertexAttribL1dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribL2dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribL3dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribL4dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribLPointer (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glGetVertexAttribLdv (GLuint index, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glViewportArrayv (GLuint first, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glViewportIndexedf (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); +GLAPI void APIENTRY glViewportIndexedfv (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glScissorArrayv (GLuint first, GLsizei count, const GLint *v); +GLAPI void APIENTRY glScissorIndexed (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height); +GLAPI void APIENTRY glScissorIndexedv (GLuint index, const GLint *v); +GLAPI void APIENTRY glDepthRangeArrayv (GLuint first, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glDepthRangeIndexed (GLuint index, GLdouble n, GLdouble f); +GLAPI void APIENTRY glGetFloati_v (GLenum target, GLuint index, GLfloat *data); +GLAPI void APIENTRY glGetDoublei_v (GLenum target, GLuint index, GLdouble *data); +#endif +#endif /* GL_VERSION_4_1 */ + +#ifndef GL_VERSION_4_2 +#define GL_VERSION_4_2 1 +#define GL_COPY_READ_BUFFER_BINDING 0x8F36 +#define GL_COPY_WRITE_BUFFER_BINDING 0x8F37 +#define GL_TRANSFORM_FEEDBACK_ACTIVE 0x8E24 +#define GL_TRANSFORM_FEEDBACK_PAUSED 0x8E23 +#define GL_UNPACK_COMPRESSED_BLOCK_WIDTH 0x9127 +#define GL_UNPACK_COMPRESSED_BLOCK_HEIGHT 0x9128 +#define GL_UNPACK_COMPRESSED_BLOCK_DEPTH 0x9129 +#define GL_UNPACK_COMPRESSED_BLOCK_SIZE 0x912A +#define GL_PACK_COMPRESSED_BLOCK_WIDTH 0x912B +#define GL_PACK_COMPRESSED_BLOCK_HEIGHT 0x912C +#define GL_PACK_COMPRESSED_BLOCK_DEPTH 0x912D +#define GL_PACK_COMPRESSED_BLOCK_SIZE 0x912E +#define GL_NUM_SAMPLE_COUNTS 0x9380 +#define GL_MIN_MAP_BUFFER_ALIGNMENT 0x90BC +#define GL_ATOMIC_COUNTER_BUFFER 0x92C0 +#define GL_ATOMIC_COUNTER_BUFFER_BINDING 0x92C1 +#define GL_ATOMIC_COUNTER_BUFFER_START 0x92C2 +#define GL_ATOMIC_COUNTER_BUFFER_SIZE 0x92C3 +#define GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE 0x92C4 +#define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS 0x92C5 +#define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES 0x92C6 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER 0x92C7 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER 0x92C8 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER 0x92C9 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER 0x92CA +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER 0x92CB +#define GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS 0x92CC +#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS 0x92CD +#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS 0x92CE +#define GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS 0x92CF +#define GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS 0x92D0 +#define GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS 0x92D1 +#define GL_MAX_VERTEX_ATOMIC_COUNTERS 0x92D2 +#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS 0x92D3 +#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS 0x92D4 +#define GL_MAX_GEOMETRY_ATOMIC_COUNTERS 0x92D5 +#define GL_MAX_FRAGMENT_ATOMIC_COUNTERS 0x92D6 +#define GL_MAX_COMBINED_ATOMIC_COUNTERS 0x92D7 +#define GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE 0x92D8 +#define GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS 0x92DC +#define GL_ACTIVE_ATOMIC_COUNTER_BUFFERS 0x92D9 +#define GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX 0x92DA +#define GL_UNSIGNED_INT_ATOMIC_COUNTER 0x92DB +#define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001 +#define GL_ELEMENT_ARRAY_BARRIER_BIT 0x00000002 +#define GL_UNIFORM_BARRIER_BIT 0x00000004 +#define GL_TEXTURE_FETCH_BARRIER_BIT 0x00000008 +#define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020 +#define GL_COMMAND_BARRIER_BIT 0x00000040 +#define GL_PIXEL_BUFFER_BARRIER_BIT 0x00000080 +#define GL_TEXTURE_UPDATE_BARRIER_BIT 0x00000100 +#define GL_BUFFER_UPDATE_BARRIER_BIT 0x00000200 +#define GL_FRAMEBUFFER_BARRIER_BIT 0x00000400 +#define GL_TRANSFORM_FEEDBACK_BARRIER_BIT 0x00000800 +#define GL_ATOMIC_COUNTER_BARRIER_BIT 0x00001000 +#define GL_ALL_BARRIER_BITS 0xFFFFFFFF +#define GL_MAX_IMAGE_UNITS 0x8F38 +#define GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS 0x8F39 +#define GL_IMAGE_BINDING_NAME 0x8F3A +#define GL_IMAGE_BINDING_LEVEL 0x8F3B +#define GL_IMAGE_BINDING_LAYERED 0x8F3C +#define GL_IMAGE_BINDING_LAYER 0x8F3D +#define GL_IMAGE_BINDING_ACCESS 0x8F3E +#define GL_IMAGE_1D 0x904C +#define GL_IMAGE_2D 0x904D +#define GL_IMAGE_3D 0x904E +#define GL_IMAGE_2D_RECT 0x904F +#define GL_IMAGE_CUBE 0x9050 +#define GL_IMAGE_BUFFER 0x9051 +#define GL_IMAGE_1D_ARRAY 0x9052 +#define GL_IMAGE_2D_ARRAY 0x9053 +#define GL_IMAGE_CUBE_MAP_ARRAY 0x9054 +#define GL_IMAGE_2D_MULTISAMPLE 0x9055 +#define GL_IMAGE_2D_MULTISAMPLE_ARRAY 0x9056 +#define GL_INT_IMAGE_1D 0x9057 +#define GL_INT_IMAGE_2D 0x9058 +#define GL_INT_IMAGE_3D 0x9059 +#define GL_INT_IMAGE_2D_RECT 0x905A +#define GL_INT_IMAGE_CUBE 0x905B +#define GL_INT_IMAGE_BUFFER 0x905C +#define GL_INT_IMAGE_1D_ARRAY 0x905D +#define GL_INT_IMAGE_2D_ARRAY 0x905E +#define GL_INT_IMAGE_CUBE_MAP_ARRAY 0x905F +#define GL_INT_IMAGE_2D_MULTISAMPLE 0x9060 +#define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x9061 +#define GL_UNSIGNED_INT_IMAGE_1D 0x9062 +#define GL_UNSIGNED_INT_IMAGE_2D 0x9063 +#define GL_UNSIGNED_INT_IMAGE_3D 0x9064 +#define GL_UNSIGNED_INT_IMAGE_2D_RECT 0x9065 +#define GL_UNSIGNED_INT_IMAGE_CUBE 0x9066 +#define GL_UNSIGNED_INT_IMAGE_BUFFER 0x9067 +#define GL_UNSIGNED_INT_IMAGE_1D_ARRAY 0x9068 +#define GL_UNSIGNED_INT_IMAGE_2D_ARRAY 0x9069 +#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY 0x906A +#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE 0x906B +#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x906C +#define GL_MAX_IMAGE_SAMPLES 0x906D +#define GL_IMAGE_BINDING_FORMAT 0x906E +#define GL_IMAGE_FORMAT_COMPATIBILITY_TYPE 0x90C7 +#define GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE 0x90C8 +#define GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS 0x90C9 +#define GL_MAX_VERTEX_IMAGE_UNIFORMS 0x90CA +#define GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS 0x90CB +#define GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS 0x90CC +#define GL_MAX_GEOMETRY_IMAGE_UNIFORMS 0x90CD +#define GL_MAX_FRAGMENT_IMAGE_UNIFORMS 0x90CE +#define GL_MAX_COMBINED_IMAGE_UNIFORMS 0x90CF +#define GL_COMPRESSED_RGBA_BPTC_UNORM 0x8E8C +#define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM 0x8E8D +#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT 0x8E8E +#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT 0x8E8F +#define GL_TEXTURE_IMMUTABLE_FORMAT 0x912F +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC) (GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance); +typedef void (APIENTRYP PFNGLGETINTERNALFORMATIVPROC) (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params); +typedef void (APIENTRYP PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC) (GLuint program, GLuint bufferIndex, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLBINDIMAGETEXTUREPROC) (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format); +typedef void (APIENTRYP PFNGLMEMORYBARRIERPROC) (GLbitfield barriers); +typedef void (APIENTRYP PFNGLTEXSTORAGE1DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +typedef void (APIENTRYP PFNGLTEXSTORAGE2DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLTEXSTORAGE3DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC) (GLenum mode, GLuint id, GLsizei instancecount); +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC) (GLenum mode, GLuint id, GLuint stream, GLsizei instancecount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawArraysInstancedBaseInstance (GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance); +GLAPI void APIENTRY glDrawElementsInstancedBaseInstance (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance); +GLAPI void APIENTRY glDrawElementsInstancedBaseVertexBaseInstance (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance); +GLAPI void APIENTRY glGetInternalformativ (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params); +GLAPI void APIENTRY glGetActiveAtomicCounterBufferiv (GLuint program, GLuint bufferIndex, GLenum pname, GLint *params); +GLAPI void APIENTRY glBindImageTexture (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format); +GLAPI void APIENTRY glMemoryBarrier (GLbitfield barriers); +GLAPI void APIENTRY glTexStorage1D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +GLAPI void APIENTRY glTexStorage2D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glTexStorage3D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +GLAPI void APIENTRY glDrawTransformFeedbackInstanced (GLenum mode, GLuint id, GLsizei instancecount); +GLAPI void APIENTRY glDrawTransformFeedbackStreamInstanced (GLenum mode, GLuint id, GLuint stream, GLsizei instancecount); +#endif +#endif /* GL_VERSION_4_2 */ + +#ifndef GL_VERSION_4_3 +#define GL_VERSION_4_3 1 +typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +#define GL_NUM_SHADING_LANGUAGE_VERSIONS 0x82E9 +#define GL_VERTEX_ATTRIB_ARRAY_LONG 0x874E +#define GL_COMPRESSED_RGB8_ETC2 0x9274 +#define GL_COMPRESSED_SRGB8_ETC2 0x9275 +#define GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276 +#define GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9277 +#define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 +#define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279 +#define GL_COMPRESSED_R11_EAC 0x9270 +#define GL_COMPRESSED_SIGNED_R11_EAC 0x9271 +#define GL_COMPRESSED_RG11_EAC 0x9272 +#define GL_COMPRESSED_SIGNED_RG11_EAC 0x9273 +#define GL_PRIMITIVE_RESTART_FIXED_INDEX 0x8D69 +#define GL_ANY_SAMPLES_PASSED_CONSERVATIVE 0x8D6A +#define GL_MAX_ELEMENT_INDEX 0x8D6B +#define GL_COMPUTE_SHADER 0x91B9 +#define GL_MAX_COMPUTE_UNIFORM_BLOCKS 0x91BB +#define GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS 0x91BC +#define GL_MAX_COMPUTE_IMAGE_UNIFORMS 0x91BD +#define GL_MAX_COMPUTE_SHARED_MEMORY_SIZE 0x8262 +#define GL_MAX_COMPUTE_UNIFORM_COMPONENTS 0x8263 +#define GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS 0x8264 +#define GL_MAX_COMPUTE_ATOMIC_COUNTERS 0x8265 +#define GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS 0x8266 +#define GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS 0x90EB +#define GL_MAX_COMPUTE_WORK_GROUP_COUNT 0x91BE +#define GL_MAX_COMPUTE_WORK_GROUP_SIZE 0x91BF +#define GL_COMPUTE_WORK_GROUP_SIZE 0x8267 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER 0x90EC +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER 0x90ED +#define GL_DISPATCH_INDIRECT_BUFFER 0x90EE +#define GL_DISPATCH_INDIRECT_BUFFER_BINDING 0x90EF +#define GL_COMPUTE_SHADER_BIT 0x00000020 +#define GL_DEBUG_OUTPUT_SYNCHRONOUS 0x8242 +#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH 0x8243 +#define GL_DEBUG_CALLBACK_FUNCTION 0x8244 +#define GL_DEBUG_CALLBACK_USER_PARAM 0x8245 +#define GL_DEBUG_SOURCE_API 0x8246 +#define GL_DEBUG_SOURCE_WINDOW_SYSTEM 0x8247 +#define GL_DEBUG_SOURCE_SHADER_COMPILER 0x8248 +#define GL_DEBUG_SOURCE_THIRD_PARTY 0x8249 +#define GL_DEBUG_SOURCE_APPLICATION 0x824A +#define GL_DEBUG_SOURCE_OTHER 0x824B +#define GL_DEBUG_TYPE_ERROR 0x824C +#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR 0x824D +#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR 0x824E +#define GL_DEBUG_TYPE_PORTABILITY 0x824F +#define GL_DEBUG_TYPE_PERFORMANCE 0x8250 +#define GL_DEBUG_TYPE_OTHER 0x8251 +#define GL_MAX_DEBUG_MESSAGE_LENGTH 0x9143 +#define GL_MAX_DEBUG_LOGGED_MESSAGES 0x9144 +#define GL_DEBUG_LOGGED_MESSAGES 0x9145 +#define GL_DEBUG_SEVERITY_HIGH 0x9146 +#define GL_DEBUG_SEVERITY_MEDIUM 0x9147 +#define GL_DEBUG_SEVERITY_LOW 0x9148 +#define GL_DEBUG_TYPE_MARKER 0x8268 +#define GL_DEBUG_TYPE_PUSH_GROUP 0x8269 +#define GL_DEBUG_TYPE_POP_GROUP 0x826A +#define GL_DEBUG_SEVERITY_NOTIFICATION 0x826B +#define GL_MAX_DEBUG_GROUP_STACK_DEPTH 0x826C +#define GL_DEBUG_GROUP_STACK_DEPTH 0x826D +#define GL_BUFFER 0x82E0 +#define GL_SHADER 0x82E1 +#define GL_PROGRAM 0x82E2 +#define GL_QUERY 0x82E3 +#define GL_PROGRAM_PIPELINE 0x82E4 +#define GL_SAMPLER 0x82E6 +#define GL_MAX_LABEL_LENGTH 0x82E8 +#define GL_DEBUG_OUTPUT 0x92E0 +#define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002 +#define GL_MAX_UNIFORM_LOCATIONS 0x826E +#define GL_FRAMEBUFFER_DEFAULT_WIDTH 0x9310 +#define GL_FRAMEBUFFER_DEFAULT_HEIGHT 0x9311 +#define GL_FRAMEBUFFER_DEFAULT_LAYERS 0x9312 +#define GL_FRAMEBUFFER_DEFAULT_SAMPLES 0x9313 +#define GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS 0x9314 +#define GL_MAX_FRAMEBUFFER_WIDTH 0x9315 +#define GL_MAX_FRAMEBUFFER_HEIGHT 0x9316 +#define GL_MAX_FRAMEBUFFER_LAYERS 0x9317 +#define GL_MAX_FRAMEBUFFER_SAMPLES 0x9318 +#define GL_INTERNALFORMAT_SUPPORTED 0x826F +#define GL_INTERNALFORMAT_PREFERRED 0x8270 +#define GL_INTERNALFORMAT_RED_SIZE 0x8271 +#define GL_INTERNALFORMAT_GREEN_SIZE 0x8272 +#define GL_INTERNALFORMAT_BLUE_SIZE 0x8273 +#define GL_INTERNALFORMAT_ALPHA_SIZE 0x8274 +#define GL_INTERNALFORMAT_DEPTH_SIZE 0x8275 +#define GL_INTERNALFORMAT_STENCIL_SIZE 0x8276 +#define GL_INTERNALFORMAT_SHARED_SIZE 0x8277 +#define GL_INTERNALFORMAT_RED_TYPE 0x8278 +#define GL_INTERNALFORMAT_GREEN_TYPE 0x8279 +#define GL_INTERNALFORMAT_BLUE_TYPE 0x827A +#define GL_INTERNALFORMAT_ALPHA_TYPE 0x827B +#define GL_INTERNALFORMAT_DEPTH_TYPE 0x827C +#define GL_INTERNALFORMAT_STENCIL_TYPE 0x827D +#define GL_MAX_WIDTH 0x827E +#define GL_MAX_HEIGHT 0x827F +#define GL_MAX_DEPTH 0x8280 +#define GL_MAX_LAYERS 0x8281 +#define GL_MAX_COMBINED_DIMENSIONS 0x8282 +#define GL_COLOR_COMPONENTS 0x8283 +#define GL_DEPTH_COMPONENTS 0x8284 +#define GL_STENCIL_COMPONENTS 0x8285 +#define GL_COLOR_RENDERABLE 0x8286 +#define GL_DEPTH_RENDERABLE 0x8287 +#define GL_STENCIL_RENDERABLE 0x8288 +#define GL_FRAMEBUFFER_RENDERABLE 0x8289 +#define GL_FRAMEBUFFER_RENDERABLE_LAYERED 0x828A +#define GL_FRAMEBUFFER_BLEND 0x828B +#define GL_READ_PIXELS 0x828C +#define GL_READ_PIXELS_FORMAT 0x828D +#define GL_READ_PIXELS_TYPE 0x828E +#define GL_TEXTURE_IMAGE_FORMAT 0x828F +#define GL_TEXTURE_IMAGE_TYPE 0x8290 +#define GL_GET_TEXTURE_IMAGE_FORMAT 0x8291 +#define GL_GET_TEXTURE_IMAGE_TYPE 0x8292 +#define GL_MIPMAP 0x8293 +#define GL_MANUAL_GENERATE_MIPMAP 0x8294 +#define GL_AUTO_GENERATE_MIPMAP 0x8295 +#define GL_COLOR_ENCODING 0x8296 +#define GL_SRGB_READ 0x8297 +#define GL_SRGB_WRITE 0x8298 +#define GL_FILTER 0x829A +#define GL_VERTEX_TEXTURE 0x829B +#define GL_TESS_CONTROL_TEXTURE 0x829C +#define GL_TESS_EVALUATION_TEXTURE 0x829D +#define GL_GEOMETRY_TEXTURE 0x829E +#define GL_FRAGMENT_TEXTURE 0x829F +#define GL_COMPUTE_TEXTURE 0x82A0 +#define GL_TEXTURE_SHADOW 0x82A1 +#define GL_TEXTURE_GATHER 0x82A2 +#define GL_TEXTURE_GATHER_SHADOW 0x82A3 +#define GL_SHADER_IMAGE_LOAD 0x82A4 +#define GL_SHADER_IMAGE_STORE 0x82A5 +#define GL_SHADER_IMAGE_ATOMIC 0x82A6 +#define GL_IMAGE_TEXEL_SIZE 0x82A7 +#define GL_IMAGE_COMPATIBILITY_CLASS 0x82A8 +#define GL_IMAGE_PIXEL_FORMAT 0x82A9 +#define GL_IMAGE_PIXEL_TYPE 0x82AA +#define GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST 0x82AC +#define GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST 0x82AD +#define GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE 0x82AE +#define GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE 0x82AF +#define GL_TEXTURE_COMPRESSED_BLOCK_WIDTH 0x82B1 +#define GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT 0x82B2 +#define GL_TEXTURE_COMPRESSED_BLOCK_SIZE 0x82B3 +#define GL_CLEAR_BUFFER 0x82B4 +#define GL_TEXTURE_VIEW 0x82B5 +#define GL_VIEW_COMPATIBILITY_CLASS 0x82B6 +#define GL_FULL_SUPPORT 0x82B7 +#define GL_CAVEAT_SUPPORT 0x82B8 +#define GL_IMAGE_CLASS_4_X_32 0x82B9 +#define GL_IMAGE_CLASS_2_X_32 0x82BA +#define GL_IMAGE_CLASS_1_X_32 0x82BB +#define GL_IMAGE_CLASS_4_X_16 0x82BC +#define GL_IMAGE_CLASS_2_X_16 0x82BD +#define GL_IMAGE_CLASS_1_X_16 0x82BE +#define GL_IMAGE_CLASS_4_X_8 0x82BF +#define GL_IMAGE_CLASS_2_X_8 0x82C0 +#define GL_IMAGE_CLASS_1_X_8 0x82C1 +#define GL_IMAGE_CLASS_11_11_10 0x82C2 +#define GL_IMAGE_CLASS_10_10_10_2 0x82C3 +#define GL_VIEW_CLASS_128_BITS 0x82C4 +#define GL_VIEW_CLASS_96_BITS 0x82C5 +#define GL_VIEW_CLASS_64_BITS 0x82C6 +#define GL_VIEW_CLASS_48_BITS 0x82C7 +#define GL_VIEW_CLASS_32_BITS 0x82C8 +#define GL_VIEW_CLASS_24_BITS 0x82C9 +#define GL_VIEW_CLASS_16_BITS 0x82CA +#define GL_VIEW_CLASS_8_BITS 0x82CB +#define GL_VIEW_CLASS_S3TC_DXT1_RGB 0x82CC +#define GL_VIEW_CLASS_S3TC_DXT1_RGBA 0x82CD +#define GL_VIEW_CLASS_S3TC_DXT3_RGBA 0x82CE +#define GL_VIEW_CLASS_S3TC_DXT5_RGBA 0x82CF +#define GL_VIEW_CLASS_RGTC1_RED 0x82D0 +#define GL_VIEW_CLASS_RGTC2_RG 0x82D1 +#define GL_VIEW_CLASS_BPTC_UNORM 0x82D2 +#define GL_VIEW_CLASS_BPTC_FLOAT 0x82D3 +#define GL_UNIFORM 0x92E1 +#define GL_UNIFORM_BLOCK 0x92E2 +#define GL_PROGRAM_INPUT 0x92E3 +#define GL_PROGRAM_OUTPUT 0x92E4 +#define GL_BUFFER_VARIABLE 0x92E5 +#define GL_SHADER_STORAGE_BLOCK 0x92E6 +#define GL_VERTEX_SUBROUTINE 0x92E8 +#define GL_TESS_CONTROL_SUBROUTINE 0x92E9 +#define GL_TESS_EVALUATION_SUBROUTINE 0x92EA +#define GL_GEOMETRY_SUBROUTINE 0x92EB +#define GL_FRAGMENT_SUBROUTINE 0x92EC +#define GL_COMPUTE_SUBROUTINE 0x92ED +#define GL_VERTEX_SUBROUTINE_UNIFORM 0x92EE +#define GL_TESS_CONTROL_SUBROUTINE_UNIFORM 0x92EF +#define GL_TESS_EVALUATION_SUBROUTINE_UNIFORM 0x92F0 +#define GL_GEOMETRY_SUBROUTINE_UNIFORM 0x92F1 +#define GL_FRAGMENT_SUBROUTINE_UNIFORM 0x92F2 +#define GL_COMPUTE_SUBROUTINE_UNIFORM 0x92F3 +#define GL_TRANSFORM_FEEDBACK_VARYING 0x92F4 +#define GL_ACTIVE_RESOURCES 0x92F5 +#define GL_MAX_NAME_LENGTH 0x92F6 +#define GL_MAX_NUM_ACTIVE_VARIABLES 0x92F7 +#define GL_MAX_NUM_COMPATIBLE_SUBROUTINES 0x92F8 +#define GL_NAME_LENGTH 0x92F9 +#define GL_TYPE 0x92FA +#define GL_ARRAY_SIZE 0x92FB +#define GL_OFFSET 0x92FC +#define GL_BLOCK_INDEX 0x92FD +#define GL_ARRAY_STRIDE 0x92FE +#define GL_MATRIX_STRIDE 0x92FF +#define GL_IS_ROW_MAJOR 0x9300 +#define GL_ATOMIC_COUNTER_BUFFER_INDEX 0x9301 +#define GL_BUFFER_BINDING 0x9302 +#define GL_BUFFER_DATA_SIZE 0x9303 +#define GL_NUM_ACTIVE_VARIABLES 0x9304 +#define GL_ACTIVE_VARIABLES 0x9305 +#define GL_REFERENCED_BY_VERTEX_SHADER 0x9306 +#define GL_REFERENCED_BY_TESS_CONTROL_SHADER 0x9307 +#define GL_REFERENCED_BY_TESS_EVALUATION_SHADER 0x9308 +#define GL_REFERENCED_BY_GEOMETRY_SHADER 0x9309 +#define GL_REFERENCED_BY_FRAGMENT_SHADER 0x930A +#define GL_REFERENCED_BY_COMPUTE_SHADER 0x930B +#define GL_TOP_LEVEL_ARRAY_SIZE 0x930C +#define GL_TOP_LEVEL_ARRAY_STRIDE 0x930D +#define GL_LOCATION 0x930E +#define GL_LOCATION_INDEX 0x930F +#define GL_IS_PER_PATCH 0x92E7 +#define GL_SHADER_STORAGE_BUFFER 0x90D2 +#define GL_SHADER_STORAGE_BUFFER_BINDING 0x90D3 +#define GL_SHADER_STORAGE_BUFFER_START 0x90D4 +#define GL_SHADER_STORAGE_BUFFER_SIZE 0x90D5 +#define GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS 0x90D6 +#define GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS 0x90D7 +#define GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS 0x90D8 +#define GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS 0x90D9 +#define GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS 0x90DA +#define GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS 0x90DB +#define GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS 0x90DC +#define GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS 0x90DD +#define GL_MAX_SHADER_STORAGE_BLOCK_SIZE 0x90DE +#define GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT 0x90DF +#define GL_SHADER_STORAGE_BARRIER_BIT 0x00002000 +#define GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES 0x8F39 +#define GL_DEPTH_STENCIL_TEXTURE_MODE 0x90EA +#define GL_TEXTURE_BUFFER_OFFSET 0x919D +#define GL_TEXTURE_BUFFER_SIZE 0x919E +#define GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT 0x919F +#define GL_TEXTURE_VIEW_MIN_LEVEL 0x82DB +#define GL_TEXTURE_VIEW_NUM_LEVELS 0x82DC +#define GL_TEXTURE_VIEW_MIN_LAYER 0x82DD +#define GL_TEXTURE_VIEW_NUM_LAYERS 0x82DE +#define GL_TEXTURE_IMMUTABLE_LEVELS 0x82DF +#define GL_VERTEX_ATTRIB_BINDING 0x82D4 +#define GL_VERTEX_ATTRIB_RELATIVE_OFFSET 0x82D5 +#define GL_VERTEX_BINDING_DIVISOR 0x82D6 +#define GL_VERTEX_BINDING_OFFSET 0x82D7 +#define GL_VERTEX_BINDING_STRIDE 0x82D8 +#define GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET 0x82D9 +#define GL_MAX_VERTEX_ATTRIB_BINDINGS 0x82DA +#define GL_VERTEX_BINDING_BUFFER 0x8F4F +#define GL_DISPLAY_LIST 0x82E7 +typedef void (APIENTRYP PFNGLCLEARBUFFERDATAPROC) (GLenum target, GLenum internalformat, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLCLEARBUFFERSUBDATAPROC) (GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLDISPATCHCOMPUTEPROC) (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z); +typedef void (APIENTRYP PFNGLDISPATCHCOMPUTEINDIRECTPROC) (GLintptr indirect); +typedef void (APIENTRYP PFNGLCOPYIMAGESUBDATAPROC) (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); +typedef void (APIENTRYP PFNGLFRAMEBUFFERPARAMETERIPROC) (GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETINTERNALFORMATI64VPROC) (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint64 *params); +typedef void (APIENTRYP PFNGLINVALIDATETEXSUBIMAGEPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth); +typedef void (APIENTRYP PFNGLINVALIDATETEXIMAGEPROC) (GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLINVALIDATEBUFFERSUBDATAPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length); +typedef void (APIENTRYP PFNGLINVALIDATEBUFFERDATAPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLINVALIDATEFRAMEBUFFERPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments); +typedef void (APIENTRYP PFNGLINVALIDATESUBFRAMEBUFFERPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTPROC) (GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride); +typedef void (APIENTRYP PFNGLGETPROGRAMINTERFACEIVPROC) (GLuint program, GLenum programInterface, GLenum pname, GLint *params); +typedef GLuint (APIENTRYP PFNGLGETPROGRAMRESOURCEINDEXPROC) (GLuint program, GLenum programInterface, const GLchar *name); +typedef void (APIENTRYP PFNGLGETPROGRAMRESOURCENAMEPROC) (GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); +typedef void (APIENTRYP PFNGLGETPROGRAMRESOURCEIVPROC) (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLint *params); +typedef GLint (APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONPROC) (GLuint program, GLenum programInterface, const GLchar *name); +typedef GLint (APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC) (GLuint program, GLenum programInterface, const GLchar *name); +typedef void (APIENTRYP PFNGLSHADERSTORAGEBLOCKBINDINGPROC) (GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding); +typedef void (APIENTRYP PFNGLTEXBUFFERRANGEPROC) (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLTEXSTORAGE2DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXSTORAGE3DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXTUREVIEWPROC) (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); +typedef void (APIENTRYP PFNGLBINDVERTEXBUFFERPROC) (GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +typedef void (APIENTRYP PFNGLVERTEXATTRIBFORMATPROC) (GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXATTRIBIFORMATPROC) (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXATTRIBLFORMATPROC) (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXATTRIBBINDINGPROC) (GLuint attribindex, GLuint bindingindex); +typedef void (APIENTRYP PFNGLVERTEXBINDINGDIVISORPROC) (GLuint bindingindex, GLuint divisor); +typedef void (APIENTRYP PFNGLDEBUGMESSAGECONTROLPROC) (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTPROC) (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); +typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKPROC) (GLDEBUGPROC callback, const void *userParam); +typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGPROC) (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); +typedef void (APIENTRYP PFNGLPUSHDEBUGGROUPPROC) (GLenum source, GLuint id, GLsizei length, const GLchar *message); +typedef void (APIENTRYP PFNGLPOPDEBUGGROUPPROC) (void); +typedef void (APIENTRYP PFNGLOBJECTLABELPROC) (GLenum identifier, GLuint name, GLsizei length, const GLchar *label); +typedef void (APIENTRYP PFNGLGETOBJECTLABELPROC) (GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label); +typedef void (APIENTRYP PFNGLOBJECTPTRLABELPROC) (const void *ptr, GLsizei length, const GLchar *label); +typedef void (APIENTRYP PFNGLGETOBJECTPTRLABELPROC) (const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glClearBufferData (GLenum target, GLenum internalformat, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glClearBufferSubData (GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glDispatchCompute (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z); +GLAPI void APIENTRY glDispatchComputeIndirect (GLintptr indirect); +GLAPI void APIENTRY glCopyImageSubData (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); +GLAPI void APIENTRY glFramebufferParameteri (GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glGetFramebufferParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetInternalformati64v (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint64 *params); +GLAPI void APIENTRY glInvalidateTexSubImage (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth); +GLAPI void APIENTRY glInvalidateTexImage (GLuint texture, GLint level); +GLAPI void APIENTRY glInvalidateBufferSubData (GLuint buffer, GLintptr offset, GLsizeiptr length); +GLAPI void APIENTRY glInvalidateBufferData (GLuint buffer); +GLAPI void APIENTRY glInvalidateFramebuffer (GLenum target, GLsizei numAttachments, const GLenum *attachments); +GLAPI void APIENTRY glInvalidateSubFramebuffer (GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glMultiDrawArraysIndirect (GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride); +GLAPI void APIENTRY glMultiDrawElementsIndirect (GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride); +GLAPI void APIENTRY glGetProgramInterfaceiv (GLuint program, GLenum programInterface, GLenum pname, GLint *params); +GLAPI GLuint APIENTRY glGetProgramResourceIndex (GLuint program, GLenum programInterface, const GLchar *name); +GLAPI void APIENTRY glGetProgramResourceName (GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); +GLAPI void APIENTRY glGetProgramResourceiv (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLint *params); +GLAPI GLint APIENTRY glGetProgramResourceLocation (GLuint program, GLenum programInterface, const GLchar *name); +GLAPI GLint APIENTRY glGetProgramResourceLocationIndex (GLuint program, GLenum programInterface, const GLchar *name); +GLAPI void APIENTRY glShaderStorageBlockBinding (GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding); +GLAPI void APIENTRY glTexBufferRange (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glTexStorage2DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTexStorage3DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTextureView (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); +GLAPI void APIENTRY glBindVertexBuffer (GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +GLAPI void APIENTRY glVertexAttribFormat (GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +GLAPI void APIENTRY glVertexAttribIFormat (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI void APIENTRY glVertexAttribLFormat (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI void APIENTRY glVertexAttribBinding (GLuint attribindex, GLuint bindingindex); +GLAPI void APIENTRY glVertexBindingDivisor (GLuint bindingindex, GLuint divisor); +GLAPI void APIENTRY glDebugMessageControl (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +GLAPI void APIENTRY glDebugMessageInsert (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); +GLAPI void APIENTRY glDebugMessageCallback (GLDEBUGPROC callback, const void *userParam); +GLAPI GLuint APIENTRY glGetDebugMessageLog (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); +GLAPI void APIENTRY glPushDebugGroup (GLenum source, GLuint id, GLsizei length, const GLchar *message); +GLAPI void APIENTRY glPopDebugGroup (void); +GLAPI void APIENTRY glObjectLabel (GLenum identifier, GLuint name, GLsizei length, const GLchar *label); +GLAPI void APIENTRY glGetObjectLabel (GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label); +GLAPI void APIENTRY glObjectPtrLabel (const void *ptr, GLsizei length, const GLchar *label); +GLAPI void APIENTRY glGetObjectPtrLabel (const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label); +#endif +#endif /* GL_VERSION_4_3 */ + +#ifndef GL_VERSION_4_4 +#define GL_VERSION_4_4 1 +#define GL_MAX_VERTEX_ATTRIB_STRIDE 0x82E5 +#define GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED 0x8221 +#define GL_TEXTURE_BUFFER_BINDING 0x8C2A +#define GL_MAP_PERSISTENT_BIT 0x0040 +#define GL_MAP_COHERENT_BIT 0x0080 +#define GL_DYNAMIC_STORAGE_BIT 0x0100 +#define GL_CLIENT_STORAGE_BIT 0x0200 +#define GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT 0x00004000 +#define GL_BUFFER_IMMUTABLE_STORAGE 0x821F +#define GL_BUFFER_STORAGE_FLAGS 0x8220 +#define GL_CLEAR_TEXTURE 0x9365 +#define GL_LOCATION_COMPONENT 0x934A +#define GL_TRANSFORM_FEEDBACK_BUFFER_INDEX 0x934B +#define GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE 0x934C +#define GL_QUERY_BUFFER 0x9192 +#define GL_QUERY_BUFFER_BARRIER_BIT 0x00008000 +#define GL_QUERY_BUFFER_BINDING 0x9193 +#define GL_QUERY_RESULT_NO_WAIT 0x9194 +#define GL_MIRROR_CLAMP_TO_EDGE 0x8743 +typedef void (APIENTRYP PFNGLBUFFERSTORAGEPROC) (GLenum target, GLsizeiptr size, const void *data, GLbitfield flags); +typedef void (APIENTRYP PFNGLCLEARTEXIMAGEPROC) (GLuint texture, GLint level, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLCLEARTEXSUBIMAGEPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLBINDBUFFERSBASEPROC) (GLenum target, GLuint first, GLsizei count, const GLuint *buffers); +typedef void (APIENTRYP PFNGLBINDBUFFERSRANGEPROC) (GLenum target, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizeiptr *sizes); +typedef void (APIENTRYP PFNGLBINDTEXTURESPROC) (GLuint first, GLsizei count, const GLuint *textures); +typedef void (APIENTRYP PFNGLBINDSAMPLERSPROC) (GLuint first, GLsizei count, const GLuint *samplers); +typedef void (APIENTRYP PFNGLBINDIMAGETEXTURESPROC) (GLuint first, GLsizei count, const GLuint *textures); +typedef void (APIENTRYP PFNGLBINDVERTEXBUFFERSPROC) (GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBufferStorage (GLenum target, GLsizeiptr size, const void *data, GLbitfield flags); +GLAPI void APIENTRY glClearTexImage (GLuint texture, GLint level, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glClearTexSubImage (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glBindBuffersBase (GLenum target, GLuint first, GLsizei count, const GLuint *buffers); +GLAPI void APIENTRY glBindBuffersRange (GLenum target, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizeiptr *sizes); +GLAPI void APIENTRY glBindTextures (GLuint first, GLsizei count, const GLuint *textures); +GLAPI void APIENTRY glBindSamplers (GLuint first, GLsizei count, const GLuint *samplers); +GLAPI void APIENTRY glBindImageTextures (GLuint first, GLsizei count, const GLuint *textures); +GLAPI void APIENTRY glBindVertexBuffers (GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); +#endif +#endif /* GL_VERSION_4_4 */ + +#ifndef GL_VERSION_4_5 +#define GL_VERSION_4_5 1 +#define GL_CONTEXT_LOST 0x0507 +#define GL_NEGATIVE_ONE_TO_ONE 0x935E +#define GL_ZERO_TO_ONE 0x935F +#define GL_CLIP_ORIGIN 0x935C +#define GL_CLIP_DEPTH_MODE 0x935D +#define GL_QUERY_WAIT_INVERTED 0x8E17 +#define GL_QUERY_NO_WAIT_INVERTED 0x8E18 +#define GL_QUERY_BY_REGION_WAIT_INVERTED 0x8E19 +#define GL_QUERY_BY_REGION_NO_WAIT_INVERTED 0x8E1A +#define GL_MAX_CULL_DISTANCES 0x82F9 +#define GL_MAX_COMBINED_CLIP_AND_CULL_DISTANCES 0x82FA +#define GL_TEXTURE_TARGET 0x1006 +#define GL_QUERY_TARGET 0x82EA +#define GL_GUILTY_CONTEXT_RESET 0x8253 +#define GL_INNOCENT_CONTEXT_RESET 0x8254 +#define GL_UNKNOWN_CONTEXT_RESET 0x8255 +#define GL_RESET_NOTIFICATION_STRATEGY 0x8256 +#define GL_LOSE_CONTEXT_ON_RESET 0x8252 +#define GL_NO_RESET_NOTIFICATION 0x8261 +#define GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT 0x00000004 +#define GL_CONTEXT_RELEASE_BEHAVIOR 0x82FB +#define GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH 0x82FC +typedef void (APIENTRYP PFNGLCLIPCONTROLPROC) (GLenum origin, GLenum depth); +typedef void (APIENTRYP PFNGLCREATETRANSFORMFEEDBACKSPROC) (GLsizei n, GLuint *ids); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKBUFFERBASEPROC) (GLuint xfb, GLuint index, GLuint buffer); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKBUFFERRANGEPROC) (GLuint xfb, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKIVPROC) (GLuint xfb, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint *param); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI64_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint64 *param); +typedef void (APIENTRYP PFNGLCREATEBUFFERSPROC) (GLsizei n, GLuint *buffers); +typedef void (APIENTRYP PFNGLNAMEDBUFFERSTORAGEPROC) (GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags); +typedef void (APIENTRYP PFNGLNAMEDBUFFERDATAPROC) (GLuint buffer, GLsizeiptr size, const void *data, GLenum usage); +typedef void (APIENTRYP PFNGLNAMEDBUFFERSUBDATAPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); +typedef void (APIENTRYP PFNGLCOPYNAMEDBUFFERSUBDATAPROC) (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERDATAPROC) (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERSUBDATAPROC) (GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); +typedef void *(APIENTRYP PFNGLMAPNAMEDBUFFERPROC) (GLuint buffer, GLenum access); +typedef void *(APIENTRYP PFNGLMAPNAMEDBUFFERRANGEPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access); +typedef GLboolean (APIENTRYP PFNGLUNMAPNAMEDBUFFERPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERIVPROC) (GLuint buffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERI64VPROC) (GLuint buffer, GLenum pname, GLint64 *params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPOINTERVPROC) (GLuint buffer, GLenum pname, void **params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERSUBDATAPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, void *data); +typedef void (APIENTRYP PFNGLCREATEFRAMEBUFFERSPROC) (GLsizei n, GLuint *framebuffers); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERRENDERBUFFERPROC) (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERPARAMETERIPROC) (GLuint framebuffer, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTUREPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERDRAWBUFFERPROC) (GLuint framebuffer, GLenum buf); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERDRAWBUFFERSPROC) (GLuint framebuffer, GLsizei n, const GLenum *bufs); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERREADBUFFERPROC) (GLuint framebuffer, GLenum src); +typedef void (APIENTRYP PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC) (GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments); +typedef void (APIENTRYP PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC) (GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERIVPROC) (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLint *value); +typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERUIVPROC) (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLuint *value); +typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERFVPROC) (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLfloat *value); +typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERFIPROC) (GLuint framebuffer, GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); +typedef void (APIENTRYP PFNGLBLITNAMEDFRAMEBUFFERPROC) (GLuint readFramebuffer, GLuint drawFramebuffer, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +typedef GLenum (APIENTRYP PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC) (GLuint framebuffer, GLenum target); +typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVPROC) (GLuint framebuffer, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC) (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLCREATERENDERBUFFERSPROC) (GLsizei n, GLuint *renderbuffers); +typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEPROC) (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC) (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC) (GLuint renderbuffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLCREATETEXTURESPROC) (GLenum target, GLsizei n, GLuint *textures); +typedef void (APIENTRYP PFNGLTEXTUREBUFFERPROC) (GLuint texture, GLenum internalformat, GLuint buffer); +typedef void (APIENTRYP PFNGLTEXTUREBUFFERRANGEPROC) (GLuint texture, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE1DPROC) (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DPROC) (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DPROC) (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC) (GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC) (GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE1DPROC) (GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE2DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE3DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC) (GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE1DPROC) (GLuint texture, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE2DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE3DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFPROC) (GLuint texture, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFVPROC) (GLuint texture, GLenum pname, const GLfloat *param); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIPROC) (GLuint texture, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIIVPROC) (GLuint texture, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIUIVPROC) (GLuint texture, GLenum pname, const GLuint *params); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIVPROC) (GLuint texture, GLenum pname, const GLint *param); +typedef void (APIENTRYP PFNGLGENERATETEXTUREMIPMAPPROC) (GLuint texture); +typedef void (APIENTRYP PFNGLBINDTEXTUREUNITPROC) (GLuint unit, GLuint texture); +typedef void (APIENTRYP PFNGLGETTEXTUREIMAGEPROC) (GLuint texture, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTUREIMAGEPROC) (GLuint texture, GLint level, GLsizei bufSize, void *pixels); +typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERFVPROC) (GLuint texture, GLint level, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERIVPROC) (GLuint texture, GLint level, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERFVPROC) (GLuint texture, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIIVPROC) (GLuint texture, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIUIVPROC) (GLuint texture, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIVPROC) (GLuint texture, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLCREATEVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays); +typedef void (APIENTRYP PFNGLDISABLEVERTEXARRAYATTRIBPROC) (GLuint vaobj, GLuint index); +typedef void (APIENTRYP PFNGLENABLEVERTEXARRAYATTRIBPROC) (GLuint vaobj, GLuint index); +typedef void (APIENTRYP PFNGLVERTEXARRAYELEMENTBUFFERPROC) (GLuint vaobj, GLuint buffer); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXBUFFERPROC) (GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXBUFFERSPROC) (GLuint vaobj, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); +typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBBINDINGPROC) (GLuint vaobj, GLuint attribindex, GLuint bindingindex); +typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBFORMATPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBIFORMATPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBLFORMATPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXARRAYBINDINGDIVISORPROC) (GLuint vaobj, GLuint bindingindex, GLuint divisor); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYIVPROC) (GLuint vaobj, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYINDEXEDIVPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYINDEXED64IVPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint64 *param); +typedef void (APIENTRYP PFNGLCREATESAMPLERSPROC) (GLsizei n, GLuint *samplers); +typedef void (APIENTRYP PFNGLCREATEPROGRAMPIPELINESPROC) (GLsizei n, GLuint *pipelines); +typedef void (APIENTRYP PFNGLCREATEQUERIESPROC) (GLenum target, GLsizei n, GLuint *ids); +typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTI64VPROC) (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTIVPROC) (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTUI64VPROC) (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTUIVPROC) (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +typedef void (APIENTRYP PFNGLMEMORYBARRIERBYREGIONPROC) (GLbitfield barriers); +typedef void (APIENTRYP PFNGLGETTEXTURESUBIMAGEPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei bufSize, void *pixels); +typedef GLenum (APIENTRYP PFNGLGETGRAPHICSRESETSTATUSPROC) (void); +typedef void (APIENTRYP PFNGLGETNCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint lod, GLsizei bufSize, void *pixels); +typedef void (APIENTRYP PFNGLGETNTEXIMAGEPROC) (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +typedef void (APIENTRYP PFNGLGETNUNIFORMDVPROC) (GLuint program, GLint location, GLsizei bufSize, GLdouble *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMFVPROC) (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMIVPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMUIVPROC) (GLuint program, GLint location, GLsizei bufSize, GLuint *params); +typedef void (APIENTRYP PFNGLREADNPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); +typedef void (APIENTRYP PFNGLGETNMAPDVPROC) (GLenum target, GLenum query, GLsizei bufSize, GLdouble *v); +typedef void (APIENTRYP PFNGLGETNMAPFVPROC) (GLenum target, GLenum query, GLsizei bufSize, GLfloat *v); +typedef void (APIENTRYP PFNGLGETNMAPIVPROC) (GLenum target, GLenum query, GLsizei bufSize, GLint *v); +typedef void (APIENTRYP PFNGLGETNPIXELMAPFVPROC) (GLenum map, GLsizei bufSize, GLfloat *values); +typedef void (APIENTRYP PFNGLGETNPIXELMAPUIVPROC) (GLenum map, GLsizei bufSize, GLuint *values); +typedef void (APIENTRYP PFNGLGETNPIXELMAPUSVPROC) (GLenum map, GLsizei bufSize, GLushort *values); +typedef void (APIENTRYP PFNGLGETNPOLYGONSTIPPLEPROC) (GLsizei bufSize, GLubyte *pattern); +typedef void (APIENTRYP PFNGLGETNCOLORTABLEPROC) (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *table); +typedef void (APIENTRYP PFNGLGETNCONVOLUTIONFILTERPROC) (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *image); +typedef void (APIENTRYP PFNGLGETNSEPARABLEFILTERPROC) (GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span); +typedef void (APIENTRYP PFNGLGETNHISTOGRAMPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +typedef void (APIENTRYP PFNGLGETNMINMAXPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +typedef void (APIENTRYP PFNGLTEXTUREBARRIERPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glClipControl (GLenum origin, GLenum depth); +GLAPI void APIENTRY glCreateTransformFeedbacks (GLsizei n, GLuint *ids); +GLAPI void APIENTRY glTransformFeedbackBufferBase (GLuint xfb, GLuint index, GLuint buffer); +GLAPI void APIENTRY glTransformFeedbackBufferRange (GLuint xfb, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glGetTransformFeedbackiv (GLuint xfb, GLenum pname, GLint *param); +GLAPI void APIENTRY glGetTransformFeedbacki_v (GLuint xfb, GLenum pname, GLuint index, GLint *param); +GLAPI void APIENTRY glGetTransformFeedbacki64_v (GLuint xfb, GLenum pname, GLuint index, GLint64 *param); +GLAPI void APIENTRY glCreateBuffers (GLsizei n, GLuint *buffers); +GLAPI void APIENTRY glNamedBufferStorage (GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags); +GLAPI void APIENTRY glNamedBufferData (GLuint buffer, GLsizeiptr size, const void *data, GLenum usage); +GLAPI void APIENTRY glNamedBufferSubData (GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); +GLAPI void APIENTRY glCopyNamedBufferSubData (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +GLAPI void APIENTRY glClearNamedBufferData (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glClearNamedBufferSubData (GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); +GLAPI void *APIENTRY glMapNamedBuffer (GLuint buffer, GLenum access); +GLAPI void *APIENTRY glMapNamedBufferRange (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access); +GLAPI GLboolean APIENTRY glUnmapNamedBuffer (GLuint buffer); +GLAPI void APIENTRY glFlushMappedNamedBufferRange (GLuint buffer, GLintptr offset, GLsizeiptr length); +GLAPI void APIENTRY glGetNamedBufferParameteriv (GLuint buffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetNamedBufferParameteri64v (GLuint buffer, GLenum pname, GLint64 *params); +GLAPI void APIENTRY glGetNamedBufferPointerv (GLuint buffer, GLenum pname, void **params); +GLAPI void APIENTRY glGetNamedBufferSubData (GLuint buffer, GLintptr offset, GLsizeiptr size, void *data); +GLAPI void APIENTRY glCreateFramebuffers (GLsizei n, GLuint *framebuffers); +GLAPI void APIENTRY glNamedFramebufferRenderbuffer (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +GLAPI void APIENTRY glNamedFramebufferParameteri (GLuint framebuffer, GLenum pname, GLint param); +GLAPI void APIENTRY glNamedFramebufferTexture (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); +GLAPI void APIENTRY glNamedFramebufferTextureLayer (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); +GLAPI void APIENTRY glNamedFramebufferDrawBuffer (GLuint framebuffer, GLenum buf); +GLAPI void APIENTRY glNamedFramebufferDrawBuffers (GLuint framebuffer, GLsizei n, const GLenum *bufs); +GLAPI void APIENTRY glNamedFramebufferReadBuffer (GLuint framebuffer, GLenum src); +GLAPI void APIENTRY glInvalidateNamedFramebufferData (GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments); +GLAPI void APIENTRY glInvalidateNamedFramebufferSubData (GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glClearNamedFramebufferiv (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLint *value); +GLAPI void APIENTRY glClearNamedFramebufferuiv (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLuint *value); +GLAPI void APIENTRY glClearNamedFramebufferfv (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLfloat *value); +GLAPI void APIENTRY glClearNamedFramebufferfi (GLuint framebuffer, GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); +GLAPI void APIENTRY glBlitNamedFramebuffer (GLuint readFramebuffer, GLuint drawFramebuffer, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +GLAPI GLenum APIENTRY glCheckNamedFramebufferStatus (GLuint framebuffer, GLenum target); +GLAPI void APIENTRY glGetNamedFramebufferParameteriv (GLuint framebuffer, GLenum pname, GLint *param); +GLAPI void APIENTRY glGetNamedFramebufferAttachmentParameteriv (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params); +GLAPI void APIENTRY glCreateRenderbuffers (GLsizei n, GLuint *renderbuffers); +GLAPI void APIENTRY glNamedRenderbufferStorage (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glNamedRenderbufferStorageMultisample (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetNamedRenderbufferParameteriv (GLuint renderbuffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glCreateTextures (GLenum target, GLsizei n, GLuint *textures); +GLAPI void APIENTRY glTextureBuffer (GLuint texture, GLenum internalformat, GLuint buffer); +GLAPI void APIENTRY glTextureBufferRange (GLuint texture, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glTextureStorage1D (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width); +GLAPI void APIENTRY glTextureStorage2D (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glTextureStorage3D (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +GLAPI void APIENTRY glTextureStorage2DMultisample (GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTextureStorage3DMultisample (GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTextureSubImage1D (GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTextureSubImage2D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTextureSubImage3D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glCompressedTextureSubImage1D (GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTextureSubImage2D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTextureSubImage3D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCopyTextureSubImage1D (GLuint texture, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glCopyTextureSubImage2D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glCopyTextureSubImage3D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glTextureParameterf (GLuint texture, GLenum pname, GLfloat param); +GLAPI void APIENTRY glTextureParameterfv (GLuint texture, GLenum pname, const GLfloat *param); +GLAPI void APIENTRY glTextureParameteri (GLuint texture, GLenum pname, GLint param); +GLAPI void APIENTRY glTextureParameterIiv (GLuint texture, GLenum pname, const GLint *params); +GLAPI void APIENTRY glTextureParameterIuiv (GLuint texture, GLenum pname, const GLuint *params); +GLAPI void APIENTRY glTextureParameteriv (GLuint texture, GLenum pname, const GLint *param); +GLAPI void APIENTRY glGenerateTextureMipmap (GLuint texture); +GLAPI void APIENTRY glBindTextureUnit (GLuint unit, GLuint texture); +GLAPI void APIENTRY glGetTextureImage (GLuint texture, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +GLAPI void APIENTRY glGetCompressedTextureImage (GLuint texture, GLint level, GLsizei bufSize, void *pixels); +GLAPI void APIENTRY glGetTextureLevelParameterfv (GLuint texture, GLint level, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetTextureLevelParameteriv (GLuint texture, GLint level, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetTextureParameterfv (GLuint texture, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetTextureParameterIiv (GLuint texture, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetTextureParameterIuiv (GLuint texture, GLenum pname, GLuint *params); +GLAPI void APIENTRY glGetTextureParameteriv (GLuint texture, GLenum pname, GLint *params); +GLAPI void APIENTRY glCreateVertexArrays (GLsizei n, GLuint *arrays); +GLAPI void APIENTRY glDisableVertexArrayAttrib (GLuint vaobj, GLuint index); +GLAPI void APIENTRY glEnableVertexArrayAttrib (GLuint vaobj, GLuint index); +GLAPI void APIENTRY glVertexArrayElementBuffer (GLuint vaobj, GLuint buffer); +GLAPI void APIENTRY glVertexArrayVertexBuffer (GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +GLAPI void APIENTRY glVertexArrayVertexBuffers (GLuint vaobj, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); +GLAPI void APIENTRY glVertexArrayAttribBinding (GLuint vaobj, GLuint attribindex, GLuint bindingindex); +GLAPI void APIENTRY glVertexArrayAttribFormat (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +GLAPI void APIENTRY glVertexArrayAttribIFormat (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI void APIENTRY glVertexArrayAttribLFormat (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI void APIENTRY glVertexArrayBindingDivisor (GLuint vaobj, GLuint bindingindex, GLuint divisor); +GLAPI void APIENTRY glGetVertexArrayiv (GLuint vaobj, GLenum pname, GLint *param); +GLAPI void APIENTRY glGetVertexArrayIndexediv (GLuint vaobj, GLuint index, GLenum pname, GLint *param); +GLAPI void APIENTRY glGetVertexArrayIndexed64iv (GLuint vaobj, GLuint index, GLenum pname, GLint64 *param); +GLAPI void APIENTRY glCreateSamplers (GLsizei n, GLuint *samplers); +GLAPI void APIENTRY glCreateProgramPipelines (GLsizei n, GLuint *pipelines); +GLAPI void APIENTRY glCreateQueries (GLenum target, GLsizei n, GLuint *ids); +GLAPI void APIENTRY glGetQueryBufferObjecti64v (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +GLAPI void APIENTRY glGetQueryBufferObjectiv (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +GLAPI void APIENTRY glGetQueryBufferObjectui64v (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +GLAPI void APIENTRY glGetQueryBufferObjectuiv (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +GLAPI void APIENTRY glMemoryBarrierByRegion (GLbitfield barriers); +GLAPI void APIENTRY glGetTextureSubImage (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +GLAPI void APIENTRY glGetCompressedTextureSubImage (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei bufSize, void *pixels); +GLAPI GLenum APIENTRY glGetGraphicsResetStatus (void); +GLAPI void APIENTRY glGetnCompressedTexImage (GLenum target, GLint lod, GLsizei bufSize, void *pixels); +GLAPI void APIENTRY glGetnTexImage (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +GLAPI void APIENTRY glGetnUniformdv (GLuint program, GLint location, GLsizei bufSize, GLdouble *params); +GLAPI void APIENTRY glGetnUniformfv (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); +GLAPI void APIENTRY glGetnUniformiv (GLuint program, GLint location, GLsizei bufSize, GLint *params); +GLAPI void APIENTRY glGetnUniformuiv (GLuint program, GLint location, GLsizei bufSize, GLuint *params); +GLAPI void APIENTRY glReadnPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); +GLAPI void APIENTRY glGetnMapdv (GLenum target, GLenum query, GLsizei bufSize, GLdouble *v); +GLAPI void APIENTRY glGetnMapfv (GLenum target, GLenum query, GLsizei bufSize, GLfloat *v); +GLAPI void APIENTRY glGetnMapiv (GLenum target, GLenum query, GLsizei bufSize, GLint *v); +GLAPI void APIENTRY glGetnPixelMapfv (GLenum map, GLsizei bufSize, GLfloat *values); +GLAPI void APIENTRY glGetnPixelMapuiv (GLenum map, GLsizei bufSize, GLuint *values); +GLAPI void APIENTRY glGetnPixelMapusv (GLenum map, GLsizei bufSize, GLushort *values); +GLAPI void APIENTRY glGetnPolygonStipple (GLsizei bufSize, GLubyte *pattern); +GLAPI void APIENTRY glGetnColorTable (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *table); +GLAPI void APIENTRY glGetnConvolutionFilter (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *image); +GLAPI void APIENTRY glGetnSeparableFilter (GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span); +GLAPI void APIENTRY glGetnHistogram (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +GLAPI void APIENTRY glGetnMinmax (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +GLAPI void APIENTRY glTextureBarrier (void); +#endif +#endif /* GL_VERSION_4_5 */ + +#ifndef GL_ARB_ES2_compatibility +#define GL_ARB_ES2_compatibility 1 +#endif /* GL_ARB_ES2_compatibility */ + +#ifndef GL_ARB_ES3_1_compatibility +#define GL_ARB_ES3_1_compatibility 1 +#endif /* GL_ARB_ES3_1_compatibility */ + +#ifndef GL_ARB_ES3_2_compatibility +#define GL_ARB_ES3_2_compatibility 1 +#define GL_PRIMITIVE_BOUNDING_BOX_ARB 0x92BE +#define GL_MULTISAMPLE_LINE_WIDTH_RANGE_ARB 0x9381 +#define GL_MULTISAMPLE_LINE_WIDTH_GRANULARITY_ARB 0x9382 +typedef void (APIENTRYP PFNGLPRIMITIVEBOUNDINGBOXARBPROC) (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPrimitiveBoundingBoxARB (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW); +#endif +#endif /* GL_ARB_ES3_2_compatibility */ + +#ifndef GL_ARB_ES3_compatibility +#define GL_ARB_ES3_compatibility 1 +#endif /* GL_ARB_ES3_compatibility */ + +#ifndef GL_ARB_arrays_of_arrays +#define GL_ARB_arrays_of_arrays 1 +#endif /* GL_ARB_arrays_of_arrays */ + +#ifndef GL_ARB_base_instance +#define GL_ARB_base_instance 1 +#endif /* GL_ARB_base_instance */ + +#ifndef GL_ARB_bindless_texture +#define GL_ARB_bindless_texture 1 +typedef uint64_t GLuint64EXT; +#define GL_UNSIGNED_INT64_ARB 0x140F +typedef GLuint64 (APIENTRYP PFNGLGETTEXTUREHANDLEARBPROC) (GLuint texture); +typedef GLuint64 (APIENTRYP PFNGLGETTEXTURESAMPLERHANDLEARBPROC) (GLuint texture, GLuint sampler); +typedef void (APIENTRYP PFNGLMAKETEXTUREHANDLERESIDENTARBPROC) (GLuint64 handle); +typedef void (APIENTRYP PFNGLMAKETEXTUREHANDLENONRESIDENTARBPROC) (GLuint64 handle); +typedef GLuint64 (APIENTRYP PFNGLGETIMAGEHANDLEARBPROC) (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); +typedef void (APIENTRYP PFNGLMAKEIMAGEHANDLERESIDENTARBPROC) (GLuint64 handle, GLenum access); +typedef void (APIENTRYP PFNGLMAKEIMAGEHANDLENONRESIDENTARBPROC) (GLuint64 handle); +typedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64ARBPROC) (GLint location, GLuint64 value); +typedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64VARBPROC) (GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64ARBPROC) (GLuint program, GLint location, GLuint64 value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *values); +typedef GLboolean (APIENTRYP PFNGLISTEXTUREHANDLERESIDENTARBPROC) (GLuint64 handle); +typedef GLboolean (APIENTRYP PFNGLISIMAGEHANDLERESIDENTARBPROC) (GLuint64 handle); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64ARBPROC) (GLuint index, GLuint64EXT x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64VARBPROC) (GLuint index, const GLuint64EXT *v); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLUI64VARBPROC) (GLuint index, GLenum pname, GLuint64EXT *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLuint64 APIENTRY glGetTextureHandleARB (GLuint texture); +GLAPI GLuint64 APIENTRY glGetTextureSamplerHandleARB (GLuint texture, GLuint sampler); +GLAPI void APIENTRY glMakeTextureHandleResidentARB (GLuint64 handle); +GLAPI void APIENTRY glMakeTextureHandleNonResidentARB (GLuint64 handle); +GLAPI GLuint64 APIENTRY glGetImageHandleARB (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); +GLAPI void APIENTRY glMakeImageHandleResidentARB (GLuint64 handle, GLenum access); +GLAPI void APIENTRY glMakeImageHandleNonResidentARB (GLuint64 handle); +GLAPI void APIENTRY glUniformHandleui64ARB (GLint location, GLuint64 value); +GLAPI void APIENTRY glUniformHandleui64vARB (GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glProgramUniformHandleui64ARB (GLuint program, GLint location, GLuint64 value); +GLAPI void APIENTRY glProgramUniformHandleui64vARB (GLuint program, GLint location, GLsizei count, const GLuint64 *values); +GLAPI GLboolean APIENTRY glIsTextureHandleResidentARB (GLuint64 handle); +GLAPI GLboolean APIENTRY glIsImageHandleResidentARB (GLuint64 handle); +GLAPI void APIENTRY glVertexAttribL1ui64ARB (GLuint index, GLuint64EXT x); +GLAPI void APIENTRY glVertexAttribL1ui64vARB (GLuint index, const GLuint64EXT *v); +GLAPI void APIENTRY glGetVertexAttribLui64vARB (GLuint index, GLenum pname, GLuint64EXT *params); +#endif +#endif /* GL_ARB_bindless_texture */ + +#ifndef GL_ARB_blend_func_extended +#define GL_ARB_blend_func_extended 1 +#endif /* GL_ARB_blend_func_extended */ + +#ifndef GL_ARB_buffer_storage +#define GL_ARB_buffer_storage 1 +#endif /* GL_ARB_buffer_storage */ + +#ifndef GL_ARB_cl_event +#define GL_ARB_cl_event 1 +struct _cl_context; +struct _cl_event; +#define GL_SYNC_CL_EVENT_ARB 0x8240 +#define GL_SYNC_CL_EVENT_COMPLETE_ARB 0x8241 +typedef GLsync (APIENTRYP PFNGLCREATESYNCFROMCLEVENTARBPROC) (struct _cl_context *context, struct _cl_event *event, GLbitfield flags); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLsync APIENTRY glCreateSyncFromCLeventARB (struct _cl_context *context, struct _cl_event *event, GLbitfield flags); +#endif +#endif /* GL_ARB_cl_event */ + +#ifndef GL_ARB_clear_buffer_object +#define GL_ARB_clear_buffer_object 1 +#endif /* GL_ARB_clear_buffer_object */ + +#ifndef GL_ARB_clear_texture +#define GL_ARB_clear_texture 1 +#endif /* GL_ARB_clear_texture */ + +#ifndef GL_ARB_clip_control +#define GL_ARB_clip_control 1 +#endif /* GL_ARB_clip_control */ + +#ifndef GL_ARB_color_buffer_float +#define GL_ARB_color_buffer_float 1 +#define GL_RGBA_FLOAT_MODE_ARB 0x8820 +#define GL_CLAMP_VERTEX_COLOR_ARB 0x891A +#define GL_CLAMP_FRAGMENT_COLOR_ARB 0x891B +#define GL_CLAMP_READ_COLOR_ARB 0x891C +#define GL_FIXED_ONLY_ARB 0x891D +typedef void (APIENTRYP PFNGLCLAMPCOLORARBPROC) (GLenum target, GLenum clamp); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glClampColorARB (GLenum target, GLenum clamp); +#endif +#endif /* GL_ARB_color_buffer_float */ + +#ifndef GL_ARB_compatibility +#define GL_ARB_compatibility 1 +#endif /* GL_ARB_compatibility */ + +#ifndef GL_ARB_compressed_texture_pixel_storage +#define GL_ARB_compressed_texture_pixel_storage 1 +#endif /* GL_ARB_compressed_texture_pixel_storage */ + +#ifndef GL_ARB_compute_shader +#define GL_ARB_compute_shader 1 +#endif /* GL_ARB_compute_shader */ + +#ifndef GL_ARB_compute_variable_group_size +#define GL_ARB_compute_variable_group_size 1 +#define GL_MAX_COMPUTE_VARIABLE_GROUP_INVOCATIONS_ARB 0x9344 +#define GL_MAX_COMPUTE_FIXED_GROUP_INVOCATIONS_ARB 0x90EB +#define GL_MAX_COMPUTE_VARIABLE_GROUP_SIZE_ARB 0x9345 +#define GL_MAX_COMPUTE_FIXED_GROUP_SIZE_ARB 0x91BF +typedef void (APIENTRYP PFNGLDISPATCHCOMPUTEGROUPSIZEARBPROC) (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z, GLuint group_size_x, GLuint group_size_y, GLuint group_size_z); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDispatchComputeGroupSizeARB (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z, GLuint group_size_x, GLuint group_size_y, GLuint group_size_z); +#endif +#endif /* GL_ARB_compute_variable_group_size */ + +#ifndef GL_ARB_conditional_render_inverted +#define GL_ARB_conditional_render_inverted 1 +#endif /* GL_ARB_conditional_render_inverted */ + +#ifndef GL_ARB_conservative_depth +#define GL_ARB_conservative_depth 1 +#endif /* GL_ARB_conservative_depth */ + +#ifndef GL_ARB_copy_buffer +#define GL_ARB_copy_buffer 1 +#endif /* GL_ARB_copy_buffer */ + +#ifndef GL_ARB_copy_image +#define GL_ARB_copy_image 1 +#endif /* GL_ARB_copy_image */ + +#ifndef GL_ARB_cull_distance +#define GL_ARB_cull_distance 1 +#endif /* GL_ARB_cull_distance */ + +#ifndef GL_ARB_debug_output +#define GL_ARB_debug_output 1 +typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +#define GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB 0x8242 +#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_ARB 0x8243 +#define GL_DEBUG_CALLBACK_FUNCTION_ARB 0x8244 +#define GL_DEBUG_CALLBACK_USER_PARAM_ARB 0x8245 +#define GL_DEBUG_SOURCE_API_ARB 0x8246 +#define GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB 0x8247 +#define GL_DEBUG_SOURCE_SHADER_COMPILER_ARB 0x8248 +#define GL_DEBUG_SOURCE_THIRD_PARTY_ARB 0x8249 +#define GL_DEBUG_SOURCE_APPLICATION_ARB 0x824A +#define GL_DEBUG_SOURCE_OTHER_ARB 0x824B +#define GL_DEBUG_TYPE_ERROR_ARB 0x824C +#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB 0x824D +#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB 0x824E +#define GL_DEBUG_TYPE_PORTABILITY_ARB 0x824F +#define GL_DEBUG_TYPE_PERFORMANCE_ARB 0x8250 +#define GL_DEBUG_TYPE_OTHER_ARB 0x8251 +#define GL_MAX_DEBUG_MESSAGE_LENGTH_ARB 0x9143 +#define GL_MAX_DEBUG_LOGGED_MESSAGES_ARB 0x9144 +#define GL_DEBUG_LOGGED_MESSAGES_ARB 0x9145 +#define GL_DEBUG_SEVERITY_HIGH_ARB 0x9146 +#define GL_DEBUG_SEVERITY_MEDIUM_ARB 0x9147 +#define GL_DEBUG_SEVERITY_LOW_ARB 0x9148 +typedef void (APIENTRYP PFNGLDEBUGMESSAGECONTROLARBPROC) (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTARBPROC) (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); +typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKARBPROC) (GLDEBUGPROCARB callback, const void *userParam); +typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGARBPROC) (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDebugMessageControlARB (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +GLAPI void APIENTRY glDebugMessageInsertARB (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); +GLAPI void APIENTRY glDebugMessageCallbackARB (GLDEBUGPROCARB callback, const void *userParam); +GLAPI GLuint APIENTRY glGetDebugMessageLogARB (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); +#endif +#endif /* GL_ARB_debug_output */ + +#ifndef GL_ARB_depth_buffer_float +#define GL_ARB_depth_buffer_float 1 +#endif /* GL_ARB_depth_buffer_float */ + +#ifndef GL_ARB_depth_clamp +#define GL_ARB_depth_clamp 1 +#endif /* GL_ARB_depth_clamp */ + +#ifndef GL_ARB_depth_texture +#define GL_ARB_depth_texture 1 +#define GL_DEPTH_COMPONENT16_ARB 0x81A5 +#define GL_DEPTH_COMPONENT24_ARB 0x81A6 +#define GL_DEPTH_COMPONENT32_ARB 0x81A7 +#define GL_TEXTURE_DEPTH_SIZE_ARB 0x884A +#define GL_DEPTH_TEXTURE_MODE_ARB 0x884B +#endif /* GL_ARB_depth_texture */ + +#ifndef GL_ARB_derivative_control +#define GL_ARB_derivative_control 1 +#endif /* GL_ARB_derivative_control */ + +#ifndef GL_ARB_direct_state_access +#define GL_ARB_direct_state_access 1 +#endif /* GL_ARB_direct_state_access */ + +#ifndef GL_ARB_draw_buffers +#define GL_ARB_draw_buffers 1 +#define GL_MAX_DRAW_BUFFERS_ARB 0x8824 +#define GL_DRAW_BUFFER0_ARB 0x8825 +#define GL_DRAW_BUFFER1_ARB 0x8826 +#define GL_DRAW_BUFFER2_ARB 0x8827 +#define GL_DRAW_BUFFER3_ARB 0x8828 +#define GL_DRAW_BUFFER4_ARB 0x8829 +#define GL_DRAW_BUFFER5_ARB 0x882A +#define GL_DRAW_BUFFER6_ARB 0x882B +#define GL_DRAW_BUFFER7_ARB 0x882C +#define GL_DRAW_BUFFER8_ARB 0x882D +#define GL_DRAW_BUFFER9_ARB 0x882E +#define GL_DRAW_BUFFER10_ARB 0x882F +#define GL_DRAW_BUFFER11_ARB 0x8830 +#define GL_DRAW_BUFFER12_ARB 0x8831 +#define GL_DRAW_BUFFER13_ARB 0x8832 +#define GL_DRAW_BUFFER14_ARB 0x8833 +#define GL_DRAW_BUFFER15_ARB 0x8834 +typedef void (APIENTRYP PFNGLDRAWBUFFERSARBPROC) (GLsizei n, const GLenum *bufs); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawBuffersARB (GLsizei n, const GLenum *bufs); +#endif +#endif /* GL_ARB_draw_buffers */ + +#ifndef GL_ARB_draw_buffers_blend +#define GL_ARB_draw_buffers_blend 1 +typedef void (APIENTRYP PFNGLBLENDEQUATIONIARBPROC) (GLuint buf, GLenum mode); +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEIARBPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +typedef void (APIENTRYP PFNGLBLENDFUNCIARBPROC) (GLuint buf, GLenum src, GLenum dst); +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEIARBPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendEquationiARB (GLuint buf, GLenum mode); +GLAPI void APIENTRY glBlendEquationSeparateiARB (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +GLAPI void APIENTRY glBlendFunciARB (GLuint buf, GLenum src, GLenum dst); +GLAPI void APIENTRY glBlendFuncSeparateiARB (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +#endif +#endif /* GL_ARB_draw_buffers_blend */ + +#ifndef GL_ARB_draw_elements_base_vertex +#define GL_ARB_draw_elements_base_vertex 1 +#endif /* GL_ARB_draw_elements_base_vertex */ + +#ifndef GL_ARB_draw_indirect +#define GL_ARB_draw_indirect 1 +#endif /* GL_ARB_draw_indirect */ + +#ifndef GL_ARB_draw_instanced +#define GL_ARB_draw_instanced 1 +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDARBPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDARBPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawArraysInstancedARB (GLenum mode, GLint first, GLsizei count, GLsizei primcount); +GLAPI void APIENTRY glDrawElementsInstancedARB (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); +#endif +#endif /* GL_ARB_draw_instanced */ + +#ifndef GL_ARB_enhanced_layouts +#define GL_ARB_enhanced_layouts 1 +#endif /* GL_ARB_enhanced_layouts */ + +#ifndef GL_ARB_explicit_attrib_location +#define GL_ARB_explicit_attrib_location 1 +#endif /* GL_ARB_explicit_attrib_location */ + +#ifndef GL_ARB_explicit_uniform_location +#define GL_ARB_explicit_uniform_location 1 +#endif /* GL_ARB_explicit_uniform_location */ + +#ifndef GL_ARB_fragment_coord_conventions +#define GL_ARB_fragment_coord_conventions 1 +#endif /* GL_ARB_fragment_coord_conventions */ + +#ifndef GL_ARB_fragment_layer_viewport +#define GL_ARB_fragment_layer_viewport 1 +#endif /* GL_ARB_fragment_layer_viewport */ + +#ifndef GL_ARB_fragment_program +#define GL_ARB_fragment_program 1 +#define GL_FRAGMENT_PROGRAM_ARB 0x8804 +#define GL_PROGRAM_FORMAT_ASCII_ARB 0x8875 +#define GL_PROGRAM_LENGTH_ARB 0x8627 +#define GL_PROGRAM_FORMAT_ARB 0x8876 +#define GL_PROGRAM_BINDING_ARB 0x8677 +#define GL_PROGRAM_INSTRUCTIONS_ARB 0x88A0 +#define GL_MAX_PROGRAM_INSTRUCTIONS_ARB 0x88A1 +#define GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A2 +#define GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A3 +#define GL_PROGRAM_TEMPORARIES_ARB 0x88A4 +#define GL_MAX_PROGRAM_TEMPORARIES_ARB 0x88A5 +#define GL_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A6 +#define GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A7 +#define GL_PROGRAM_PARAMETERS_ARB 0x88A8 +#define GL_MAX_PROGRAM_PARAMETERS_ARB 0x88A9 +#define GL_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AA +#define GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AB +#define GL_PROGRAM_ATTRIBS_ARB 0x88AC +#define GL_MAX_PROGRAM_ATTRIBS_ARB 0x88AD +#define GL_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AE +#define GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AF +#define GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB 0x88B4 +#define GL_MAX_PROGRAM_ENV_PARAMETERS_ARB 0x88B5 +#define GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB 0x88B6 +#define GL_PROGRAM_ALU_INSTRUCTIONS_ARB 0x8805 +#define GL_PROGRAM_TEX_INSTRUCTIONS_ARB 0x8806 +#define GL_PROGRAM_TEX_INDIRECTIONS_ARB 0x8807 +#define GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x8808 +#define GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x8809 +#define GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x880A +#define GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB 0x880B +#define GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB 0x880C +#define GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB 0x880D +#define GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x880E +#define GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x880F +#define GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x8810 +#define GL_PROGRAM_STRING_ARB 0x8628 +#define GL_PROGRAM_ERROR_POSITION_ARB 0x864B +#define GL_CURRENT_MATRIX_ARB 0x8641 +#define GL_TRANSPOSE_CURRENT_MATRIX_ARB 0x88B7 +#define GL_CURRENT_MATRIX_STACK_DEPTH_ARB 0x8640 +#define GL_MAX_PROGRAM_MATRICES_ARB 0x862F +#define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB 0x862E +#define GL_MAX_TEXTURE_COORDS_ARB 0x8871 +#define GL_MAX_TEXTURE_IMAGE_UNITS_ARB 0x8872 +#define GL_PROGRAM_ERROR_STRING_ARB 0x8874 +#define GL_MATRIX0_ARB 0x88C0 +#define GL_MATRIX1_ARB 0x88C1 +#define GL_MATRIX2_ARB 0x88C2 +#define GL_MATRIX3_ARB 0x88C3 +#define GL_MATRIX4_ARB 0x88C4 +#define GL_MATRIX5_ARB 0x88C5 +#define GL_MATRIX6_ARB 0x88C6 +#define GL_MATRIX7_ARB 0x88C7 +#define GL_MATRIX8_ARB 0x88C8 +#define GL_MATRIX9_ARB 0x88C9 +#define GL_MATRIX10_ARB 0x88CA +#define GL_MATRIX11_ARB 0x88CB +#define GL_MATRIX12_ARB 0x88CC +#define GL_MATRIX13_ARB 0x88CD +#define GL_MATRIX14_ARB 0x88CE +#define GL_MATRIX15_ARB 0x88CF +#define GL_MATRIX16_ARB 0x88D0 +#define GL_MATRIX17_ARB 0x88D1 +#define GL_MATRIX18_ARB 0x88D2 +#define GL_MATRIX19_ARB 0x88D3 +#define GL_MATRIX20_ARB 0x88D4 +#define GL_MATRIX21_ARB 0x88D5 +#define GL_MATRIX22_ARB 0x88D6 +#define GL_MATRIX23_ARB 0x88D7 +#define GL_MATRIX24_ARB 0x88D8 +#define GL_MATRIX25_ARB 0x88D9 +#define GL_MATRIX26_ARB 0x88DA +#define GL_MATRIX27_ARB 0x88DB +#define GL_MATRIX28_ARB 0x88DC +#define GL_MATRIX29_ARB 0x88DD +#define GL_MATRIX30_ARB 0x88DE +#define GL_MATRIX31_ARB 0x88DF +typedef void (APIENTRYP PFNGLPROGRAMSTRINGARBPROC) (GLenum target, GLenum format, GLsizei len, const void *string); +typedef void (APIENTRYP PFNGLBINDPROGRAMARBPROC) (GLenum target, GLuint program); +typedef void (APIENTRYP PFNGLDELETEPROGRAMSARBPROC) (GLsizei n, const GLuint *programs); +typedef void (APIENTRYP PFNGLGENPROGRAMSARBPROC) (GLsizei n, GLuint *programs); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params); +typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params); +typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMIVARBPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGARBPROC) (GLenum target, GLenum pname, void *string); +typedef GLboolean (APIENTRYP PFNGLISPROGRAMARBPROC) (GLuint program); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramStringARB (GLenum target, GLenum format, GLsizei len, const void *string); +GLAPI void APIENTRY glBindProgramARB (GLenum target, GLuint program); +GLAPI void APIENTRY glDeleteProgramsARB (GLsizei n, const GLuint *programs); +GLAPI void APIENTRY glGenProgramsARB (GLsizei n, GLuint *programs); +GLAPI void APIENTRY glProgramEnvParameter4dARB (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glProgramEnvParameter4dvARB (GLenum target, GLuint index, const GLdouble *params); +GLAPI void APIENTRY glProgramEnvParameter4fARB (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glProgramEnvParameter4fvARB (GLenum target, GLuint index, const GLfloat *params); +GLAPI void APIENTRY glProgramLocalParameter4dARB (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glProgramLocalParameter4dvARB (GLenum target, GLuint index, const GLdouble *params); +GLAPI void APIENTRY glProgramLocalParameter4fARB (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glProgramLocalParameter4fvARB (GLenum target, GLuint index, const GLfloat *params); +GLAPI void APIENTRY glGetProgramEnvParameterdvARB (GLenum target, GLuint index, GLdouble *params); +GLAPI void APIENTRY glGetProgramEnvParameterfvARB (GLenum target, GLuint index, GLfloat *params); +GLAPI void APIENTRY glGetProgramLocalParameterdvARB (GLenum target, GLuint index, GLdouble *params); +GLAPI void APIENTRY glGetProgramLocalParameterfvARB (GLenum target, GLuint index, GLfloat *params); +GLAPI void APIENTRY glGetProgramivARB (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetProgramStringARB (GLenum target, GLenum pname, void *string); +GLAPI GLboolean APIENTRY glIsProgramARB (GLuint program); +#endif +#endif /* GL_ARB_fragment_program */ + +#ifndef GL_ARB_fragment_program_shadow +#define GL_ARB_fragment_program_shadow 1 +#endif /* GL_ARB_fragment_program_shadow */ + +#ifndef GL_ARB_fragment_shader +#define GL_ARB_fragment_shader 1 +#define GL_FRAGMENT_SHADER_ARB 0x8B30 +#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB 0x8B49 +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB 0x8B8B +#endif /* GL_ARB_fragment_shader */ + +#ifndef GL_ARB_fragment_shader_interlock +#define GL_ARB_fragment_shader_interlock 1 +#endif /* GL_ARB_fragment_shader_interlock */ + +#ifndef GL_ARB_framebuffer_no_attachments +#define GL_ARB_framebuffer_no_attachments 1 +#endif /* GL_ARB_framebuffer_no_attachments */ + +#ifndef GL_ARB_framebuffer_object +#define GL_ARB_framebuffer_object 1 +#endif /* GL_ARB_framebuffer_object */ + +#ifndef GL_ARB_framebuffer_sRGB +#define GL_ARB_framebuffer_sRGB 1 +#endif /* GL_ARB_framebuffer_sRGB */ + +#ifndef GL_ARB_geometry_shader4 +#define GL_ARB_geometry_shader4 1 +#define GL_LINES_ADJACENCY_ARB 0x000A +#define GL_LINE_STRIP_ADJACENCY_ARB 0x000B +#define GL_TRIANGLES_ADJACENCY_ARB 0x000C +#define GL_TRIANGLE_STRIP_ADJACENCY_ARB 0x000D +#define GL_PROGRAM_POINT_SIZE_ARB 0x8642 +#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_ARB 0x8C29 +#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_ARB 0x8DA7 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_ARB 0x8DA8 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_ARB 0x8DA9 +#define GL_GEOMETRY_SHADER_ARB 0x8DD9 +#define GL_GEOMETRY_VERTICES_OUT_ARB 0x8DDA +#define GL_GEOMETRY_INPUT_TYPE_ARB 0x8DDB +#define GL_GEOMETRY_OUTPUT_TYPE_ARB 0x8DDC +#define GL_MAX_GEOMETRY_VARYING_COMPONENTS_ARB 0x8DDD +#define GL_MAX_VERTEX_VARYING_COMPONENTS_ARB 0x8DDE +#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_ARB 0x8DDF +#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_ARB 0x8DE0 +#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_ARB 0x8DE1 +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIARBPROC) (GLuint program, GLenum pname, GLint value); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREFACEARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramParameteriARB (GLuint program, GLenum pname, GLint value); +GLAPI void APIENTRY glFramebufferTextureARB (GLenum target, GLenum attachment, GLuint texture, GLint level); +GLAPI void APIENTRY glFramebufferTextureLayerARB (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +GLAPI void APIENTRY glFramebufferTextureFaceARB (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); +#endif +#endif /* GL_ARB_geometry_shader4 */ + +#ifndef GL_ARB_get_program_binary +#define GL_ARB_get_program_binary 1 +#endif /* GL_ARB_get_program_binary */ + +#ifndef GL_ARB_get_texture_sub_image +#define GL_ARB_get_texture_sub_image 1 +#endif /* GL_ARB_get_texture_sub_image */ + +#ifndef GL_ARB_gl_spirv +#define GL_ARB_gl_spirv 1 +#define GL_SHADER_BINARY_FORMAT_SPIR_V_ARB 0x9551 +#define GL_SPIR_V_BINARY_ARB 0x9552 +typedef void (APIENTRYP PFNGLSPECIALIZESHADERARBPROC) (GLuint shader, const GLchar *pEntryPoint, GLuint numSpecializationConstants, const GLuint *pConstantIndex, const GLuint *pConstantValue); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSpecializeShaderARB (GLuint shader, const GLchar *pEntryPoint, GLuint numSpecializationConstants, const GLuint *pConstantIndex, const GLuint *pConstantValue); +#endif +#endif /* GL_ARB_gl_spirv */ + +#ifndef GL_ARB_gpu_shader5 +#define GL_ARB_gpu_shader5 1 +#endif /* GL_ARB_gpu_shader5 */ + +#ifndef GL_ARB_gpu_shader_fp64 +#define GL_ARB_gpu_shader_fp64 1 +#endif /* GL_ARB_gpu_shader_fp64 */ + +#ifndef GL_ARB_gpu_shader_int64 +#define GL_ARB_gpu_shader_int64 1 +#define GL_INT64_ARB 0x140E +#define GL_INT64_VEC2_ARB 0x8FE9 +#define GL_INT64_VEC3_ARB 0x8FEA +#define GL_INT64_VEC4_ARB 0x8FEB +#define GL_UNSIGNED_INT64_VEC2_ARB 0x8FF5 +#define GL_UNSIGNED_INT64_VEC3_ARB 0x8FF6 +#define GL_UNSIGNED_INT64_VEC4_ARB 0x8FF7 +typedef void (APIENTRYP PFNGLUNIFORM1I64ARBPROC) (GLint location, GLint64 x); +typedef void (APIENTRYP PFNGLUNIFORM2I64ARBPROC) (GLint location, GLint64 x, GLint64 y); +typedef void (APIENTRYP PFNGLUNIFORM3I64ARBPROC) (GLint location, GLint64 x, GLint64 y, GLint64 z); +typedef void (APIENTRYP PFNGLUNIFORM4I64ARBPROC) (GLint location, GLint64 x, GLint64 y, GLint64 z, GLint64 w); +typedef void (APIENTRYP PFNGLUNIFORM1I64VARBPROC) (GLint location, GLsizei count, const GLint64 *value); +typedef void (APIENTRYP PFNGLUNIFORM2I64VARBPROC) (GLint location, GLsizei count, const GLint64 *value); +typedef void (APIENTRYP PFNGLUNIFORM3I64VARBPROC) (GLint location, GLsizei count, const GLint64 *value); +typedef void (APIENTRYP PFNGLUNIFORM4I64VARBPROC) (GLint location, GLsizei count, const GLint64 *value); +typedef void (APIENTRYP PFNGLUNIFORM1UI64ARBPROC) (GLint location, GLuint64 x); +typedef void (APIENTRYP PFNGLUNIFORM2UI64ARBPROC) (GLint location, GLuint64 x, GLuint64 y); +typedef void (APIENTRYP PFNGLUNIFORM3UI64ARBPROC) (GLint location, GLuint64 x, GLuint64 y, GLuint64 z); +typedef void (APIENTRYP PFNGLUNIFORM4UI64ARBPROC) (GLint location, GLuint64 x, GLuint64 y, GLuint64 z, GLuint64 w); +typedef void (APIENTRYP PFNGLUNIFORM1UI64VARBPROC) (GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLUNIFORM2UI64VARBPROC) (GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLUNIFORM3UI64VARBPROC) (GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLUNIFORM4UI64VARBPROC) (GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLGETUNIFORMI64VARBPROC) (GLuint program, GLint location, GLint64 *params); +typedef void (APIENTRYP PFNGLGETUNIFORMUI64VARBPROC) (GLuint program, GLint location, GLuint64 *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMI64VARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLint64 *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMUI64VARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLuint64 *params); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1I64ARBPROC) (GLuint program, GLint location, GLint64 x); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2I64ARBPROC) (GLuint program, GLint location, GLint64 x, GLint64 y); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3I64ARBPROC) (GLuint program, GLint location, GLint64 x, GLint64 y, GLint64 z); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4I64ARBPROC) (GLuint program, GLint location, GLint64 x, GLint64 y, GLint64 z, GLint64 w); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1I64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2I64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3I64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4I64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UI64ARBPROC) (GLuint program, GLint location, GLuint64 x); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UI64ARBPROC) (GLuint program, GLint location, GLuint64 x, GLuint64 y); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UI64ARBPROC) (GLuint program, GLint location, GLuint64 x, GLuint64 y, GLuint64 z); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UI64ARBPROC) (GLuint program, GLint location, GLuint64 x, GLuint64 y, GLuint64 z, GLuint64 w); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UI64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UI64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UI64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UI64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glUniform1i64ARB (GLint location, GLint64 x); +GLAPI void APIENTRY glUniform2i64ARB (GLint location, GLint64 x, GLint64 y); +GLAPI void APIENTRY glUniform3i64ARB (GLint location, GLint64 x, GLint64 y, GLint64 z); +GLAPI void APIENTRY glUniform4i64ARB (GLint location, GLint64 x, GLint64 y, GLint64 z, GLint64 w); +GLAPI void APIENTRY glUniform1i64vARB (GLint location, GLsizei count, const GLint64 *value); +GLAPI void APIENTRY glUniform2i64vARB (GLint location, GLsizei count, const GLint64 *value); +GLAPI void APIENTRY glUniform3i64vARB (GLint location, GLsizei count, const GLint64 *value); +GLAPI void APIENTRY glUniform4i64vARB (GLint location, GLsizei count, const GLint64 *value); +GLAPI void APIENTRY glUniform1ui64ARB (GLint location, GLuint64 x); +GLAPI void APIENTRY glUniform2ui64ARB (GLint location, GLuint64 x, GLuint64 y); +GLAPI void APIENTRY glUniform3ui64ARB (GLint location, GLuint64 x, GLuint64 y, GLuint64 z); +GLAPI void APIENTRY glUniform4ui64ARB (GLint location, GLuint64 x, GLuint64 y, GLuint64 z, GLuint64 w); +GLAPI void APIENTRY glUniform1ui64vARB (GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glUniform2ui64vARB (GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glUniform3ui64vARB (GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glUniform4ui64vARB (GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glGetUniformi64vARB (GLuint program, GLint location, GLint64 *params); +GLAPI void APIENTRY glGetUniformui64vARB (GLuint program, GLint location, GLuint64 *params); +GLAPI void APIENTRY glGetnUniformi64vARB (GLuint program, GLint location, GLsizei bufSize, GLint64 *params); +GLAPI void APIENTRY glGetnUniformui64vARB (GLuint program, GLint location, GLsizei bufSize, GLuint64 *params); +GLAPI void APIENTRY glProgramUniform1i64ARB (GLuint program, GLint location, GLint64 x); +GLAPI void APIENTRY glProgramUniform2i64ARB (GLuint program, GLint location, GLint64 x, GLint64 y); +GLAPI void APIENTRY glProgramUniform3i64ARB (GLuint program, GLint location, GLint64 x, GLint64 y, GLint64 z); +GLAPI void APIENTRY glProgramUniform4i64ARB (GLuint program, GLint location, GLint64 x, GLint64 y, GLint64 z, GLint64 w); +GLAPI void APIENTRY glProgramUniform1i64vARB (GLuint program, GLint location, GLsizei count, const GLint64 *value); +GLAPI void APIENTRY glProgramUniform2i64vARB (GLuint program, GLint location, GLsizei count, const GLint64 *value); +GLAPI void APIENTRY glProgramUniform3i64vARB (GLuint program, GLint location, GLsizei count, const GLint64 *value); +GLAPI void APIENTRY glProgramUniform4i64vARB (GLuint program, GLint location, GLsizei count, const GLint64 *value); +GLAPI void APIENTRY glProgramUniform1ui64ARB (GLuint program, GLint location, GLuint64 x); +GLAPI void APIENTRY glProgramUniform2ui64ARB (GLuint program, GLint location, GLuint64 x, GLuint64 y); +GLAPI void APIENTRY glProgramUniform3ui64ARB (GLuint program, GLint location, GLuint64 x, GLuint64 y, GLuint64 z); +GLAPI void APIENTRY glProgramUniform4ui64ARB (GLuint program, GLint location, GLuint64 x, GLuint64 y, GLuint64 z, GLuint64 w); +GLAPI void APIENTRY glProgramUniform1ui64vARB (GLuint program, GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glProgramUniform2ui64vARB (GLuint program, GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glProgramUniform3ui64vARB (GLuint program, GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glProgramUniform4ui64vARB (GLuint program, GLint location, GLsizei count, const GLuint64 *value); +#endif +#endif /* GL_ARB_gpu_shader_int64 */ + +#ifndef GL_ARB_half_float_pixel +#define GL_ARB_half_float_pixel 1 +typedef unsigned short GLhalfARB; +#define GL_HALF_FLOAT_ARB 0x140B +#endif /* GL_ARB_half_float_pixel */ + +#ifndef GL_ARB_half_float_vertex +#define GL_ARB_half_float_vertex 1 +#endif /* GL_ARB_half_float_vertex */ + +#ifndef GL_ARB_imaging +#define GL_ARB_imaging 1 +#define GL_BLEND_COLOR 0x8005 +#define GL_BLEND_EQUATION 0x8009 +#define GL_CONVOLUTION_1D 0x8010 +#define GL_CONVOLUTION_2D 0x8011 +#define GL_SEPARABLE_2D 0x8012 +#define GL_CONVOLUTION_BORDER_MODE 0x8013 +#define GL_CONVOLUTION_FILTER_SCALE 0x8014 +#define GL_CONVOLUTION_FILTER_BIAS 0x8015 +#define GL_REDUCE 0x8016 +#define GL_CONVOLUTION_FORMAT 0x8017 +#define GL_CONVOLUTION_WIDTH 0x8018 +#define GL_CONVOLUTION_HEIGHT 0x8019 +#define GL_MAX_CONVOLUTION_WIDTH 0x801A +#define GL_MAX_CONVOLUTION_HEIGHT 0x801B +#define GL_POST_CONVOLUTION_RED_SCALE 0x801C +#define GL_POST_CONVOLUTION_GREEN_SCALE 0x801D +#define GL_POST_CONVOLUTION_BLUE_SCALE 0x801E +#define GL_POST_CONVOLUTION_ALPHA_SCALE 0x801F +#define GL_POST_CONVOLUTION_RED_BIAS 0x8020 +#define GL_POST_CONVOLUTION_GREEN_BIAS 0x8021 +#define GL_POST_CONVOLUTION_BLUE_BIAS 0x8022 +#define GL_POST_CONVOLUTION_ALPHA_BIAS 0x8023 +#define GL_HISTOGRAM 0x8024 +#define GL_PROXY_HISTOGRAM 0x8025 +#define GL_HISTOGRAM_WIDTH 0x8026 +#define GL_HISTOGRAM_FORMAT 0x8027 +#define GL_HISTOGRAM_RED_SIZE 0x8028 +#define GL_HISTOGRAM_GREEN_SIZE 0x8029 +#define GL_HISTOGRAM_BLUE_SIZE 0x802A +#define GL_HISTOGRAM_ALPHA_SIZE 0x802B +#define GL_HISTOGRAM_LUMINANCE_SIZE 0x802C +#define GL_HISTOGRAM_SINK 0x802D +#define GL_MINMAX 0x802E +#define GL_MINMAX_FORMAT 0x802F +#define GL_MINMAX_SINK 0x8030 +#define GL_TABLE_TOO_LARGE 0x8031 +#define GL_COLOR_MATRIX 0x80B1 +#define GL_COLOR_MATRIX_STACK_DEPTH 0x80B2 +#define GL_MAX_COLOR_MATRIX_STACK_DEPTH 0x80B3 +#define GL_POST_COLOR_MATRIX_RED_SCALE 0x80B4 +#define GL_POST_COLOR_MATRIX_GREEN_SCALE 0x80B5 +#define GL_POST_COLOR_MATRIX_BLUE_SCALE 0x80B6 +#define GL_POST_COLOR_MATRIX_ALPHA_SCALE 0x80B7 +#define GL_POST_COLOR_MATRIX_RED_BIAS 0x80B8 +#define GL_POST_COLOR_MATRIX_GREEN_BIAS 0x80B9 +#define GL_POST_COLOR_MATRIX_BLUE_BIAS 0x80BA +#define GL_POST_COLOR_MATRIX_ALPHA_BIAS 0x80BB +#define GL_COLOR_TABLE 0x80D0 +#define GL_POST_CONVOLUTION_COLOR_TABLE 0x80D1 +#define GL_POST_COLOR_MATRIX_COLOR_TABLE 0x80D2 +#define GL_PROXY_COLOR_TABLE 0x80D3 +#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE 0x80D4 +#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE 0x80D5 +#define GL_COLOR_TABLE_SCALE 0x80D6 +#define GL_COLOR_TABLE_BIAS 0x80D7 +#define GL_COLOR_TABLE_FORMAT 0x80D8 +#define GL_COLOR_TABLE_WIDTH 0x80D9 +#define GL_COLOR_TABLE_RED_SIZE 0x80DA +#define GL_COLOR_TABLE_GREEN_SIZE 0x80DB +#define GL_COLOR_TABLE_BLUE_SIZE 0x80DC +#define GL_COLOR_TABLE_ALPHA_SIZE 0x80DD +#define GL_COLOR_TABLE_LUMINANCE_SIZE 0x80DE +#define GL_COLOR_TABLE_INTENSITY_SIZE 0x80DF +#define GL_CONSTANT_BORDER 0x8151 +#define GL_REPLICATE_BORDER 0x8153 +#define GL_CONVOLUTION_BORDER_COLOR 0x8154 +typedef void (APIENTRYP PFNGLCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *table); +typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOPYCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPROC) (GLenum target, GLenum format, GLenum type, void *table); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *image); +typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *image); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFPROC) (GLenum target, GLenum pname, GLfloat params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIPROC) (GLenum target, GLenum pname, GLint params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTERPROC) (GLenum target, GLenum format, GLenum type, void *image); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSEPARABLEFILTERPROC) (GLenum target, GLenum format, GLenum type, void *row, void *column, void *span); +typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *row, const void *column); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMINMAXPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLHISTOGRAMPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink); +typedef void (APIENTRYP PFNGLMINMAXPROC) (GLenum target, GLenum internalformat, GLboolean sink); +typedef void (APIENTRYP PFNGLRESETHISTOGRAMPROC) (GLenum target); +typedef void (APIENTRYP PFNGLRESETMINMAXPROC) (GLenum target); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorTable (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *table); +GLAPI void APIENTRY glColorTableParameterfv (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glColorTableParameteriv (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glCopyColorTable (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glGetColorTable (GLenum target, GLenum format, GLenum type, void *table); +GLAPI void APIENTRY glGetColorTableParameterfv (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetColorTableParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glColorSubTable (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glCopyColorSubTable (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glConvolutionFilter1D (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *image); +GLAPI void APIENTRY glConvolutionFilter2D (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *image); +GLAPI void APIENTRY glConvolutionParameterf (GLenum target, GLenum pname, GLfloat params); +GLAPI void APIENTRY glConvolutionParameterfv (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glConvolutionParameteri (GLenum target, GLenum pname, GLint params); +GLAPI void APIENTRY glConvolutionParameteriv (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glCopyConvolutionFilter1D (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glCopyConvolutionFilter2D (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetConvolutionFilter (GLenum target, GLenum format, GLenum type, void *image); +GLAPI void APIENTRY glGetConvolutionParameterfv (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetConvolutionParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetSeparableFilter (GLenum target, GLenum format, GLenum type, void *row, void *column, void *span); +GLAPI void APIENTRY glSeparableFilter2D (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *row, const void *column); +GLAPI void APIENTRY glGetHistogram (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +GLAPI void APIENTRY glGetHistogramParameterfv (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetHistogramParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMinmax (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +GLAPI void APIENTRY glGetMinmaxParameterfv (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMinmaxParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glHistogram (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink); +GLAPI void APIENTRY glMinmax (GLenum target, GLenum internalformat, GLboolean sink); +GLAPI void APIENTRY glResetHistogram (GLenum target); +GLAPI void APIENTRY glResetMinmax (GLenum target); +#endif +#endif /* GL_ARB_imaging */ + +#ifndef GL_ARB_indirect_parameters +#define GL_ARB_indirect_parameters 1 +#define GL_PARAMETER_BUFFER_ARB 0x80EE +#define GL_PARAMETER_BUFFER_BINDING_ARB 0x80EF +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTCOUNTARBPROC) (GLenum mode, GLintptr indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTARBPROC) (GLenum mode, GLenum type, GLintptr indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiDrawArraysIndirectCountARB (GLenum mode, GLintptr indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +GLAPI void APIENTRY glMultiDrawElementsIndirectCountARB (GLenum mode, GLenum type, GLintptr indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +#endif +#endif /* GL_ARB_indirect_parameters */ + +#ifndef GL_ARB_instanced_arrays +#define GL_ARB_instanced_arrays 1 +#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ARB 0x88FE +typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORARBPROC) (GLuint index, GLuint divisor); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribDivisorARB (GLuint index, GLuint divisor); +#endif +#endif /* GL_ARB_instanced_arrays */ + +#ifndef GL_ARB_internalformat_query +#define GL_ARB_internalformat_query 1 +#endif /* GL_ARB_internalformat_query */ + +#ifndef GL_ARB_internalformat_query2 +#define GL_ARB_internalformat_query2 1 +#define GL_SRGB_DECODE_ARB 0x8299 +#endif /* GL_ARB_internalformat_query2 */ + +#ifndef GL_ARB_invalidate_subdata +#define GL_ARB_invalidate_subdata 1 +#endif /* GL_ARB_invalidate_subdata */ + +#ifndef GL_ARB_map_buffer_alignment +#define GL_ARB_map_buffer_alignment 1 +#endif /* GL_ARB_map_buffer_alignment */ + +#ifndef GL_ARB_map_buffer_range +#define GL_ARB_map_buffer_range 1 +#endif /* GL_ARB_map_buffer_range */ + +#ifndef GL_ARB_matrix_palette +#define GL_ARB_matrix_palette 1 +#define GL_MATRIX_PALETTE_ARB 0x8840 +#define GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB 0x8841 +#define GL_MAX_PALETTE_MATRICES_ARB 0x8842 +#define GL_CURRENT_PALETTE_MATRIX_ARB 0x8843 +#define GL_MATRIX_INDEX_ARRAY_ARB 0x8844 +#define GL_CURRENT_MATRIX_INDEX_ARB 0x8845 +#define GL_MATRIX_INDEX_ARRAY_SIZE_ARB 0x8846 +#define GL_MATRIX_INDEX_ARRAY_TYPE_ARB 0x8847 +#define GL_MATRIX_INDEX_ARRAY_STRIDE_ARB 0x8848 +#define GL_MATRIX_INDEX_ARRAY_POINTER_ARB 0x8849 +typedef void (APIENTRYP PFNGLCURRENTPALETTEMATRIXARBPROC) (GLint index); +typedef void (APIENTRYP PFNGLMATRIXINDEXUBVARBPROC) (GLint size, const GLubyte *indices); +typedef void (APIENTRYP PFNGLMATRIXINDEXUSVARBPROC) (GLint size, const GLushort *indices); +typedef void (APIENTRYP PFNGLMATRIXINDEXUIVARBPROC) (GLint size, const GLuint *indices); +typedef void (APIENTRYP PFNGLMATRIXINDEXPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCurrentPaletteMatrixARB (GLint index); +GLAPI void APIENTRY glMatrixIndexubvARB (GLint size, const GLubyte *indices); +GLAPI void APIENTRY glMatrixIndexusvARB (GLint size, const GLushort *indices); +GLAPI void APIENTRY glMatrixIndexuivARB (GLint size, const GLuint *indices); +GLAPI void APIENTRY glMatrixIndexPointerARB (GLint size, GLenum type, GLsizei stride, const void *pointer); +#endif +#endif /* GL_ARB_matrix_palette */ + +#ifndef GL_ARB_multi_bind +#define GL_ARB_multi_bind 1 +#endif /* GL_ARB_multi_bind */ + +#ifndef GL_ARB_multi_draw_indirect +#define GL_ARB_multi_draw_indirect 1 +#endif /* GL_ARB_multi_draw_indirect */ + +#ifndef GL_ARB_multisample +#define GL_ARB_multisample 1 +#define GL_MULTISAMPLE_ARB 0x809D +#define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE_ARB 0x809F +#define GL_SAMPLE_COVERAGE_ARB 0x80A0 +#define GL_SAMPLE_BUFFERS_ARB 0x80A8 +#define GL_SAMPLES_ARB 0x80A9 +#define GL_SAMPLE_COVERAGE_VALUE_ARB 0x80AA +#define GL_SAMPLE_COVERAGE_INVERT_ARB 0x80AB +#define GL_MULTISAMPLE_BIT_ARB 0x20000000 +typedef void (APIENTRYP PFNGLSAMPLECOVERAGEARBPROC) (GLfloat value, GLboolean invert); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSampleCoverageARB (GLfloat value, GLboolean invert); +#endif +#endif /* GL_ARB_multisample */ + +#ifndef GL_ARB_multitexture +#define GL_ARB_multitexture 1 +#define GL_TEXTURE0_ARB 0x84C0 +#define GL_TEXTURE1_ARB 0x84C1 +#define GL_TEXTURE2_ARB 0x84C2 +#define GL_TEXTURE3_ARB 0x84C3 +#define GL_TEXTURE4_ARB 0x84C4 +#define GL_TEXTURE5_ARB 0x84C5 +#define GL_TEXTURE6_ARB 0x84C6 +#define GL_TEXTURE7_ARB 0x84C7 +#define GL_TEXTURE8_ARB 0x84C8 +#define GL_TEXTURE9_ARB 0x84C9 +#define GL_TEXTURE10_ARB 0x84CA +#define GL_TEXTURE11_ARB 0x84CB +#define GL_TEXTURE12_ARB 0x84CC +#define GL_TEXTURE13_ARB 0x84CD +#define GL_TEXTURE14_ARB 0x84CE +#define GL_TEXTURE15_ARB 0x84CF +#define GL_TEXTURE16_ARB 0x84D0 +#define GL_TEXTURE17_ARB 0x84D1 +#define GL_TEXTURE18_ARB 0x84D2 +#define GL_TEXTURE19_ARB 0x84D3 +#define GL_TEXTURE20_ARB 0x84D4 +#define GL_TEXTURE21_ARB 0x84D5 +#define GL_TEXTURE22_ARB 0x84D6 +#define GL_TEXTURE23_ARB 0x84D7 +#define GL_TEXTURE24_ARB 0x84D8 +#define GL_TEXTURE25_ARB 0x84D9 +#define GL_TEXTURE26_ARB 0x84DA +#define GL_TEXTURE27_ARB 0x84DB +#define GL_TEXTURE28_ARB 0x84DC +#define GL_TEXTURE29_ARB 0x84DD +#define GL_TEXTURE30_ARB 0x84DE +#define GL_TEXTURE31_ARB 0x84DF +#define GL_ACTIVE_TEXTURE_ARB 0x84E0 +#define GL_CLIENT_ACTIVE_TEXTURE_ARB 0x84E1 +#define GL_MAX_TEXTURE_UNITS_ARB 0x84E2 +typedef void (APIENTRYP PFNGLACTIVETEXTUREARBPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DARBPROC) (GLenum target, GLdouble s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FARBPROC) (GLenum target, GLfloat s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IARBPROC) (GLenum target, GLint s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SARBPROC) (GLenum target, GLshort s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVARBPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DARBPROC) (GLenum target, GLdouble s, GLdouble t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FARBPROC) (GLenum target, GLfloat s, GLfloat t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IARBPROC) (GLenum target, GLint s, GLint t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SARBPROC) (GLenum target, GLshort s, GLshort t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVARBPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IARBPROC) (GLenum target, GLint s, GLint t, GLint r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVARBPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IARBPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVARBPROC) (GLenum target, const GLshort *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glActiveTextureARB (GLenum texture); +GLAPI void APIENTRY glClientActiveTextureARB (GLenum texture); +GLAPI void APIENTRY glMultiTexCoord1dARB (GLenum target, GLdouble s); +GLAPI void APIENTRY glMultiTexCoord1dvARB (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord1fARB (GLenum target, GLfloat s); +GLAPI void APIENTRY glMultiTexCoord1fvARB (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord1iARB (GLenum target, GLint s); +GLAPI void APIENTRY glMultiTexCoord1ivARB (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord1sARB (GLenum target, GLshort s); +GLAPI void APIENTRY glMultiTexCoord1svARB (GLenum target, const GLshort *v); +GLAPI void APIENTRY glMultiTexCoord2dARB (GLenum target, GLdouble s, GLdouble t); +GLAPI void APIENTRY glMultiTexCoord2dvARB (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord2fARB (GLenum target, GLfloat s, GLfloat t); +GLAPI void APIENTRY glMultiTexCoord2fvARB (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord2iARB (GLenum target, GLint s, GLint t); +GLAPI void APIENTRY glMultiTexCoord2ivARB (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord2sARB (GLenum target, GLshort s, GLshort t); +GLAPI void APIENTRY glMultiTexCoord2svARB (GLenum target, const GLshort *v); +GLAPI void APIENTRY glMultiTexCoord3dARB (GLenum target, GLdouble s, GLdouble t, GLdouble r); +GLAPI void APIENTRY glMultiTexCoord3dvARB (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord3fARB (GLenum target, GLfloat s, GLfloat t, GLfloat r); +GLAPI void APIENTRY glMultiTexCoord3fvARB (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord3iARB (GLenum target, GLint s, GLint t, GLint r); +GLAPI void APIENTRY glMultiTexCoord3ivARB (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord3sARB (GLenum target, GLshort s, GLshort t, GLshort r); +GLAPI void APIENTRY glMultiTexCoord3svARB (GLenum target, const GLshort *v); +GLAPI void APIENTRY glMultiTexCoord4dARB (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +GLAPI void APIENTRY glMultiTexCoord4dvARB (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord4fARB (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +GLAPI void APIENTRY glMultiTexCoord4fvARB (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord4iARB (GLenum target, GLint s, GLint t, GLint r, GLint q); +GLAPI void APIENTRY glMultiTexCoord4ivARB (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord4sARB (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +GLAPI void APIENTRY glMultiTexCoord4svARB (GLenum target, const GLshort *v); +#endif +#endif /* GL_ARB_multitexture */ + +#ifndef GL_ARB_occlusion_query +#define GL_ARB_occlusion_query 1 +#define GL_QUERY_COUNTER_BITS_ARB 0x8864 +#define GL_CURRENT_QUERY_ARB 0x8865 +#define GL_QUERY_RESULT_ARB 0x8866 +#define GL_QUERY_RESULT_AVAILABLE_ARB 0x8867 +#define GL_SAMPLES_PASSED_ARB 0x8914 +typedef void (APIENTRYP PFNGLGENQUERIESARBPROC) (GLsizei n, GLuint *ids); +typedef void (APIENTRYP PFNGLDELETEQUERIESARBPROC) (GLsizei n, const GLuint *ids); +typedef GLboolean (APIENTRYP PFNGLISQUERYARBPROC) (GLuint id); +typedef void (APIENTRYP PFNGLBEGINQUERYARBPROC) (GLenum target, GLuint id); +typedef void (APIENTRYP PFNGLENDQUERYARBPROC) (GLenum target); +typedef void (APIENTRYP PFNGLGETQUERYIVARBPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVARBPROC) (GLuint id, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVARBPROC) (GLuint id, GLenum pname, GLuint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenQueriesARB (GLsizei n, GLuint *ids); +GLAPI void APIENTRY glDeleteQueriesARB (GLsizei n, const GLuint *ids); +GLAPI GLboolean APIENTRY glIsQueryARB (GLuint id); +GLAPI void APIENTRY glBeginQueryARB (GLenum target, GLuint id); +GLAPI void APIENTRY glEndQueryARB (GLenum target); +GLAPI void APIENTRY glGetQueryivARB (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetQueryObjectivARB (GLuint id, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetQueryObjectuivARB (GLuint id, GLenum pname, GLuint *params); +#endif +#endif /* GL_ARB_occlusion_query */ + +#ifndef GL_ARB_occlusion_query2 +#define GL_ARB_occlusion_query2 1 +#endif /* GL_ARB_occlusion_query2 */ + +#ifndef GL_ARB_parallel_shader_compile +#define GL_ARB_parallel_shader_compile 1 +#define GL_MAX_SHADER_COMPILER_THREADS_ARB 0x91B0 +#define GL_COMPLETION_STATUS_ARB 0x91B1 +typedef void (APIENTRYP PFNGLMAXSHADERCOMPILERTHREADSARBPROC) (GLuint count); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMaxShaderCompilerThreadsARB (GLuint count); +#endif +#endif /* GL_ARB_parallel_shader_compile */ + +#ifndef GL_ARB_pipeline_statistics_query +#define GL_ARB_pipeline_statistics_query 1 +#define GL_VERTICES_SUBMITTED_ARB 0x82EE +#define GL_PRIMITIVES_SUBMITTED_ARB 0x82EF +#define GL_VERTEX_SHADER_INVOCATIONS_ARB 0x82F0 +#define GL_TESS_CONTROL_SHADER_PATCHES_ARB 0x82F1 +#define GL_TESS_EVALUATION_SHADER_INVOCATIONS_ARB 0x82F2 +#define GL_GEOMETRY_SHADER_PRIMITIVES_EMITTED_ARB 0x82F3 +#define GL_FRAGMENT_SHADER_INVOCATIONS_ARB 0x82F4 +#define GL_COMPUTE_SHADER_INVOCATIONS_ARB 0x82F5 +#define GL_CLIPPING_INPUT_PRIMITIVES_ARB 0x82F6 +#define GL_CLIPPING_OUTPUT_PRIMITIVES_ARB 0x82F7 +#endif /* GL_ARB_pipeline_statistics_query */ + +#ifndef GL_ARB_pixel_buffer_object +#define GL_ARB_pixel_buffer_object 1 +#define GL_PIXEL_PACK_BUFFER_ARB 0x88EB +#define GL_PIXEL_UNPACK_BUFFER_ARB 0x88EC +#define GL_PIXEL_PACK_BUFFER_BINDING_ARB 0x88ED +#define GL_PIXEL_UNPACK_BUFFER_BINDING_ARB 0x88EF +#endif /* GL_ARB_pixel_buffer_object */ + +#ifndef GL_ARB_point_parameters +#define GL_ARB_point_parameters 1 +#define GL_POINT_SIZE_MIN_ARB 0x8126 +#define GL_POINT_SIZE_MAX_ARB 0x8127 +#define GL_POINT_FADE_THRESHOLD_SIZE_ARB 0x8128 +#define GL_POINT_DISTANCE_ATTENUATION_ARB 0x8129 +typedef void (APIENTRYP PFNGLPOINTPARAMETERFARBPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVARBPROC) (GLenum pname, const GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPointParameterfARB (GLenum pname, GLfloat param); +GLAPI void APIENTRY glPointParameterfvARB (GLenum pname, const GLfloat *params); +#endif +#endif /* GL_ARB_point_parameters */ + +#ifndef GL_ARB_point_sprite +#define GL_ARB_point_sprite 1 +#define GL_POINT_SPRITE_ARB 0x8861 +#define GL_COORD_REPLACE_ARB 0x8862 +#endif /* GL_ARB_point_sprite */ + +#ifndef GL_ARB_post_depth_coverage +#define GL_ARB_post_depth_coverage 1 +#endif /* GL_ARB_post_depth_coverage */ + +#ifndef GL_ARB_program_interface_query +#define GL_ARB_program_interface_query 1 +#endif /* GL_ARB_program_interface_query */ + +#ifndef GL_ARB_provoking_vertex +#define GL_ARB_provoking_vertex 1 +#endif /* GL_ARB_provoking_vertex */ + +#ifndef GL_ARB_query_buffer_object +#define GL_ARB_query_buffer_object 1 +#endif /* GL_ARB_query_buffer_object */ + +#ifndef GL_ARB_robust_buffer_access_behavior +#define GL_ARB_robust_buffer_access_behavior 1 +#endif /* GL_ARB_robust_buffer_access_behavior */ + +#ifndef GL_ARB_robustness +#define GL_ARB_robustness 1 +#define GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB 0x00000004 +#define GL_LOSE_CONTEXT_ON_RESET_ARB 0x8252 +#define GL_GUILTY_CONTEXT_RESET_ARB 0x8253 +#define GL_INNOCENT_CONTEXT_RESET_ARB 0x8254 +#define GL_UNKNOWN_CONTEXT_RESET_ARB 0x8255 +#define GL_RESET_NOTIFICATION_STRATEGY_ARB 0x8256 +#define GL_NO_RESET_NOTIFICATION_ARB 0x8261 +typedef GLenum (APIENTRYP PFNGLGETGRAPHICSRESETSTATUSARBPROC) (void); +typedef void (APIENTRYP PFNGLGETNTEXIMAGEARBPROC) (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *img); +typedef void (APIENTRYP PFNGLREADNPIXELSARBPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); +typedef void (APIENTRYP PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint lod, GLsizei bufSize, void *img); +typedef void (APIENTRYP PFNGLGETNUNIFORMFVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMIVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMUIVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLuint *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMDVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLdouble *params); +typedef void (APIENTRYP PFNGLGETNMAPDVARBPROC) (GLenum target, GLenum query, GLsizei bufSize, GLdouble *v); +typedef void (APIENTRYP PFNGLGETNMAPFVARBPROC) (GLenum target, GLenum query, GLsizei bufSize, GLfloat *v); +typedef void (APIENTRYP PFNGLGETNMAPIVARBPROC) (GLenum target, GLenum query, GLsizei bufSize, GLint *v); +typedef void (APIENTRYP PFNGLGETNPIXELMAPFVARBPROC) (GLenum map, GLsizei bufSize, GLfloat *values); +typedef void (APIENTRYP PFNGLGETNPIXELMAPUIVARBPROC) (GLenum map, GLsizei bufSize, GLuint *values); +typedef void (APIENTRYP PFNGLGETNPIXELMAPUSVARBPROC) (GLenum map, GLsizei bufSize, GLushort *values); +typedef void (APIENTRYP PFNGLGETNPOLYGONSTIPPLEARBPROC) (GLsizei bufSize, GLubyte *pattern); +typedef void (APIENTRYP PFNGLGETNCOLORTABLEARBPROC) (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *table); +typedef void (APIENTRYP PFNGLGETNCONVOLUTIONFILTERARBPROC) (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *image); +typedef void (APIENTRYP PFNGLGETNSEPARABLEFILTERARBPROC) (GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span); +typedef void (APIENTRYP PFNGLGETNHISTOGRAMARBPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +typedef void (APIENTRYP PFNGLGETNMINMAXARBPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLenum APIENTRY glGetGraphicsResetStatusARB (void); +GLAPI void APIENTRY glGetnTexImageARB (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *img); +GLAPI void APIENTRY glReadnPixelsARB (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); +GLAPI void APIENTRY glGetnCompressedTexImageARB (GLenum target, GLint lod, GLsizei bufSize, void *img); +GLAPI void APIENTRY glGetnUniformfvARB (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); +GLAPI void APIENTRY glGetnUniformivARB (GLuint program, GLint location, GLsizei bufSize, GLint *params); +GLAPI void APIENTRY glGetnUniformuivARB (GLuint program, GLint location, GLsizei bufSize, GLuint *params); +GLAPI void APIENTRY glGetnUniformdvARB (GLuint program, GLint location, GLsizei bufSize, GLdouble *params); +GLAPI void APIENTRY glGetnMapdvARB (GLenum target, GLenum query, GLsizei bufSize, GLdouble *v); +GLAPI void APIENTRY glGetnMapfvARB (GLenum target, GLenum query, GLsizei bufSize, GLfloat *v); +GLAPI void APIENTRY glGetnMapivARB (GLenum target, GLenum query, GLsizei bufSize, GLint *v); +GLAPI void APIENTRY glGetnPixelMapfvARB (GLenum map, GLsizei bufSize, GLfloat *values); +GLAPI void APIENTRY glGetnPixelMapuivARB (GLenum map, GLsizei bufSize, GLuint *values); +GLAPI void APIENTRY glGetnPixelMapusvARB (GLenum map, GLsizei bufSize, GLushort *values); +GLAPI void APIENTRY glGetnPolygonStippleARB (GLsizei bufSize, GLubyte *pattern); +GLAPI void APIENTRY glGetnColorTableARB (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *table); +GLAPI void APIENTRY glGetnConvolutionFilterARB (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *image); +GLAPI void APIENTRY glGetnSeparableFilterARB (GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span); +GLAPI void APIENTRY glGetnHistogramARB (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +GLAPI void APIENTRY glGetnMinmaxARB (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +#endif +#endif /* GL_ARB_robustness */ + +#ifndef GL_ARB_robustness_isolation +#define GL_ARB_robustness_isolation 1 +#endif /* GL_ARB_robustness_isolation */ + +#ifndef GL_ARB_sample_locations +#define GL_ARB_sample_locations 1 +#define GL_SAMPLE_LOCATION_SUBPIXEL_BITS_ARB 0x933D +#define GL_SAMPLE_LOCATION_PIXEL_GRID_WIDTH_ARB 0x933E +#define GL_SAMPLE_LOCATION_PIXEL_GRID_HEIGHT_ARB 0x933F +#define GL_PROGRAMMABLE_SAMPLE_LOCATION_TABLE_SIZE_ARB 0x9340 +#define GL_SAMPLE_LOCATION_ARB 0x8E50 +#define GL_PROGRAMMABLE_SAMPLE_LOCATION_ARB 0x9341 +#define GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_ARB 0x9342 +#define GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_ARB 0x9343 +typedef void (APIENTRYP PFNGLFRAMEBUFFERSAMPLELOCATIONSFVARBPROC) (GLenum target, GLuint start, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVARBPROC) (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLEVALUATEDEPTHVALUESARBPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFramebufferSampleLocationsfvARB (GLenum target, GLuint start, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glNamedFramebufferSampleLocationsfvARB (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glEvaluateDepthValuesARB (void); +#endif +#endif /* GL_ARB_sample_locations */ + +#ifndef GL_ARB_sample_shading +#define GL_ARB_sample_shading 1 +#define GL_SAMPLE_SHADING_ARB 0x8C36 +#define GL_MIN_SAMPLE_SHADING_VALUE_ARB 0x8C37 +typedef void (APIENTRYP PFNGLMINSAMPLESHADINGARBPROC) (GLfloat value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMinSampleShadingARB (GLfloat value); +#endif +#endif /* GL_ARB_sample_shading */ + +#ifndef GL_ARB_sampler_objects +#define GL_ARB_sampler_objects 1 +#endif /* GL_ARB_sampler_objects */ + +#ifndef GL_ARB_seamless_cube_map +#define GL_ARB_seamless_cube_map 1 +#endif /* GL_ARB_seamless_cube_map */ + +#ifndef GL_ARB_seamless_cubemap_per_texture +#define GL_ARB_seamless_cubemap_per_texture 1 +#endif /* GL_ARB_seamless_cubemap_per_texture */ + +#ifndef GL_ARB_separate_shader_objects +#define GL_ARB_separate_shader_objects 1 +#endif /* GL_ARB_separate_shader_objects */ + +#ifndef GL_ARB_shader_atomic_counter_ops +#define GL_ARB_shader_atomic_counter_ops 1 +#endif /* GL_ARB_shader_atomic_counter_ops */ + +#ifndef GL_ARB_shader_atomic_counters +#define GL_ARB_shader_atomic_counters 1 +#endif /* GL_ARB_shader_atomic_counters */ + +#ifndef GL_ARB_shader_ballot +#define GL_ARB_shader_ballot 1 +#endif /* GL_ARB_shader_ballot */ + +#ifndef GL_ARB_shader_bit_encoding +#define GL_ARB_shader_bit_encoding 1 +#endif /* GL_ARB_shader_bit_encoding */ + +#ifndef GL_ARB_shader_clock +#define GL_ARB_shader_clock 1 +#endif /* GL_ARB_shader_clock */ + +#ifndef GL_ARB_shader_draw_parameters +#define GL_ARB_shader_draw_parameters 1 +#endif /* GL_ARB_shader_draw_parameters */ + +#ifndef GL_ARB_shader_group_vote +#define GL_ARB_shader_group_vote 1 +#endif /* GL_ARB_shader_group_vote */ + +#ifndef GL_ARB_shader_image_load_store +#define GL_ARB_shader_image_load_store 1 +#endif /* GL_ARB_shader_image_load_store */ + +#ifndef GL_ARB_shader_image_size +#define GL_ARB_shader_image_size 1 +#endif /* GL_ARB_shader_image_size */ + +#ifndef GL_ARB_shader_objects +#define GL_ARB_shader_objects 1 +#ifdef __APPLE__ +typedef void *GLhandleARB; +#else +typedef unsigned int GLhandleARB; +#endif +typedef char GLcharARB; +#define GL_PROGRAM_OBJECT_ARB 0x8B40 +#define GL_SHADER_OBJECT_ARB 0x8B48 +#define GL_OBJECT_TYPE_ARB 0x8B4E +#define GL_OBJECT_SUBTYPE_ARB 0x8B4F +#define GL_FLOAT_VEC2_ARB 0x8B50 +#define GL_FLOAT_VEC3_ARB 0x8B51 +#define GL_FLOAT_VEC4_ARB 0x8B52 +#define GL_INT_VEC2_ARB 0x8B53 +#define GL_INT_VEC3_ARB 0x8B54 +#define GL_INT_VEC4_ARB 0x8B55 +#define GL_BOOL_ARB 0x8B56 +#define GL_BOOL_VEC2_ARB 0x8B57 +#define GL_BOOL_VEC3_ARB 0x8B58 +#define GL_BOOL_VEC4_ARB 0x8B59 +#define GL_FLOAT_MAT2_ARB 0x8B5A +#define GL_FLOAT_MAT3_ARB 0x8B5B +#define GL_FLOAT_MAT4_ARB 0x8B5C +#define GL_SAMPLER_1D_ARB 0x8B5D +#define GL_SAMPLER_2D_ARB 0x8B5E +#define GL_SAMPLER_3D_ARB 0x8B5F +#define GL_SAMPLER_CUBE_ARB 0x8B60 +#define GL_SAMPLER_1D_SHADOW_ARB 0x8B61 +#define GL_SAMPLER_2D_SHADOW_ARB 0x8B62 +#define GL_SAMPLER_2D_RECT_ARB 0x8B63 +#define GL_SAMPLER_2D_RECT_SHADOW_ARB 0x8B64 +#define GL_OBJECT_DELETE_STATUS_ARB 0x8B80 +#define GL_OBJECT_COMPILE_STATUS_ARB 0x8B81 +#define GL_OBJECT_LINK_STATUS_ARB 0x8B82 +#define GL_OBJECT_VALIDATE_STATUS_ARB 0x8B83 +#define GL_OBJECT_INFO_LOG_LENGTH_ARB 0x8B84 +#define GL_OBJECT_ATTACHED_OBJECTS_ARB 0x8B85 +#define GL_OBJECT_ACTIVE_UNIFORMS_ARB 0x8B86 +#define GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB 0x8B87 +#define GL_OBJECT_SHADER_SOURCE_LENGTH_ARB 0x8B88 +typedef void (APIENTRYP PFNGLDELETEOBJECTARBPROC) (GLhandleARB obj); +typedef GLhandleARB (APIENTRYP PFNGLGETHANDLEARBPROC) (GLenum pname); +typedef void (APIENTRYP PFNGLDETACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB attachedObj); +typedef GLhandleARB (APIENTRYP PFNGLCREATESHADEROBJECTARBPROC) (GLenum shaderType); +typedef void (APIENTRYP PFNGLSHADERSOURCEARBPROC) (GLhandleARB shaderObj, GLsizei count, const GLcharARB **string, const GLint *length); +typedef void (APIENTRYP PFNGLCOMPILESHADERARBPROC) (GLhandleARB shaderObj); +typedef GLhandleARB (APIENTRYP PFNGLCREATEPROGRAMOBJECTARBPROC) (void); +typedef void (APIENTRYP PFNGLATTACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB obj); +typedef void (APIENTRYP PFNGLLINKPROGRAMARBPROC) (GLhandleARB programObj); +typedef void (APIENTRYP PFNGLUSEPROGRAMOBJECTARBPROC) (GLhandleARB programObj); +typedef void (APIENTRYP PFNGLVALIDATEPROGRAMARBPROC) (GLhandleARB programObj); +typedef void (APIENTRYP PFNGLUNIFORM1FARBPROC) (GLint location, GLfloat v0); +typedef void (APIENTRYP PFNGLUNIFORM2FARBPROC) (GLint location, GLfloat v0, GLfloat v1); +typedef void (APIENTRYP PFNGLUNIFORM3FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +typedef void (APIENTRYP PFNGLUNIFORM4FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (APIENTRYP PFNGLUNIFORM1IARBPROC) (GLint location, GLint v0); +typedef void (APIENTRYP PFNGLUNIFORM2IARBPROC) (GLint location, GLint v0, GLint v1); +typedef void (APIENTRYP PFNGLUNIFORM3IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2); +typedef void (APIENTRYP PFNGLUNIFORM4IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +typedef void (APIENTRYP PFNGLUNIFORM1FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM2FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM3FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM4FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM1IVARBPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM2IVARBPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM3IVARBPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM4IVARBPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERFVARBPROC) (GLhandleARB obj, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERIVARBPROC) (GLhandleARB obj, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETINFOLOGARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog); +typedef void (APIENTRYP PFNGLGETATTACHEDOBJECTSARBPROC) (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj); +typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); +typedef void (APIENTRYP PFNGLGETUNIFORMFVARBPROC) (GLhandleARB programObj, GLint location, GLfloat *params); +typedef void (APIENTRYP PFNGLGETUNIFORMIVARBPROC) (GLhandleARB programObj, GLint location, GLint *params); +typedef void (APIENTRYP PFNGLGETSHADERSOURCEARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDeleteObjectARB (GLhandleARB obj); +GLAPI GLhandleARB APIENTRY glGetHandleARB (GLenum pname); +GLAPI void APIENTRY glDetachObjectARB (GLhandleARB containerObj, GLhandleARB attachedObj); +GLAPI GLhandleARB APIENTRY glCreateShaderObjectARB (GLenum shaderType); +GLAPI void APIENTRY glShaderSourceARB (GLhandleARB shaderObj, GLsizei count, const GLcharARB **string, const GLint *length); +GLAPI void APIENTRY glCompileShaderARB (GLhandleARB shaderObj); +GLAPI GLhandleARB APIENTRY glCreateProgramObjectARB (void); +GLAPI void APIENTRY glAttachObjectARB (GLhandleARB containerObj, GLhandleARB obj); +GLAPI void APIENTRY glLinkProgramARB (GLhandleARB programObj); +GLAPI void APIENTRY glUseProgramObjectARB (GLhandleARB programObj); +GLAPI void APIENTRY glValidateProgramARB (GLhandleARB programObj); +GLAPI void APIENTRY glUniform1fARB (GLint location, GLfloat v0); +GLAPI void APIENTRY glUniform2fARB (GLint location, GLfloat v0, GLfloat v1); +GLAPI void APIENTRY glUniform3fARB (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +GLAPI void APIENTRY glUniform4fARB (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +GLAPI void APIENTRY glUniform1iARB (GLint location, GLint v0); +GLAPI void APIENTRY glUniform2iARB (GLint location, GLint v0, GLint v1); +GLAPI void APIENTRY glUniform3iARB (GLint location, GLint v0, GLint v1, GLint v2); +GLAPI void APIENTRY glUniform4iARB (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +GLAPI void APIENTRY glUniform1fvARB (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform2fvARB (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform3fvARB (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform4fvARB (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform1ivARB (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniform2ivARB (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniform3ivARB (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniform4ivARB (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniformMatrix2fvARB (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix3fvARB (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix4fvARB (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glGetObjectParameterfvARB (GLhandleARB obj, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetObjectParameterivARB (GLhandleARB obj, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetInfoLogARB (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog); +GLAPI void APIENTRY glGetAttachedObjectsARB (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj); +GLAPI GLint APIENTRY glGetUniformLocationARB (GLhandleARB programObj, const GLcharARB *name); +GLAPI void APIENTRY glGetActiveUniformARB (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); +GLAPI void APIENTRY glGetUniformfvARB (GLhandleARB programObj, GLint location, GLfloat *params); +GLAPI void APIENTRY glGetUniformivARB (GLhandleARB programObj, GLint location, GLint *params); +GLAPI void APIENTRY glGetShaderSourceARB (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source); +#endif +#endif /* GL_ARB_shader_objects */ + +#ifndef GL_ARB_shader_precision +#define GL_ARB_shader_precision 1 +#endif /* GL_ARB_shader_precision */ + +#ifndef GL_ARB_shader_stencil_export +#define GL_ARB_shader_stencil_export 1 +#endif /* GL_ARB_shader_stencil_export */ + +#ifndef GL_ARB_shader_storage_buffer_object +#define GL_ARB_shader_storage_buffer_object 1 +#endif /* GL_ARB_shader_storage_buffer_object */ + +#ifndef GL_ARB_shader_subroutine +#define GL_ARB_shader_subroutine 1 +#endif /* GL_ARB_shader_subroutine */ + +#ifndef GL_ARB_shader_texture_image_samples +#define GL_ARB_shader_texture_image_samples 1 +#endif /* GL_ARB_shader_texture_image_samples */ + +#ifndef GL_ARB_shader_texture_lod +#define GL_ARB_shader_texture_lod 1 +#endif /* GL_ARB_shader_texture_lod */ + +#ifndef GL_ARB_shader_viewport_layer_array +#define GL_ARB_shader_viewport_layer_array 1 +#endif /* GL_ARB_shader_viewport_layer_array */ + +#ifndef GL_ARB_shading_language_100 +#define GL_ARB_shading_language_100 1 +#define GL_SHADING_LANGUAGE_VERSION_ARB 0x8B8C +#endif /* GL_ARB_shading_language_100 */ + +#ifndef GL_ARB_shading_language_420pack +#define GL_ARB_shading_language_420pack 1 +#endif /* GL_ARB_shading_language_420pack */ + +#ifndef GL_ARB_shading_language_include +#define GL_ARB_shading_language_include 1 +#define GL_SHADER_INCLUDE_ARB 0x8DAE +#define GL_NAMED_STRING_LENGTH_ARB 0x8DE9 +#define GL_NAMED_STRING_TYPE_ARB 0x8DEA +typedef void (APIENTRYP PFNGLNAMEDSTRINGARBPROC) (GLenum type, GLint namelen, const GLchar *name, GLint stringlen, const GLchar *string); +typedef void (APIENTRYP PFNGLDELETENAMEDSTRINGARBPROC) (GLint namelen, const GLchar *name); +typedef void (APIENTRYP PFNGLCOMPILESHADERINCLUDEARBPROC) (GLuint shader, GLsizei count, const GLchar *const*path, const GLint *length); +typedef GLboolean (APIENTRYP PFNGLISNAMEDSTRINGARBPROC) (GLint namelen, const GLchar *name); +typedef void (APIENTRYP PFNGLGETNAMEDSTRINGARBPROC) (GLint namelen, const GLchar *name, GLsizei bufSize, GLint *stringlen, GLchar *string); +typedef void (APIENTRYP PFNGLGETNAMEDSTRINGIVARBPROC) (GLint namelen, const GLchar *name, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glNamedStringARB (GLenum type, GLint namelen, const GLchar *name, GLint stringlen, const GLchar *string); +GLAPI void APIENTRY glDeleteNamedStringARB (GLint namelen, const GLchar *name); +GLAPI void APIENTRY glCompileShaderIncludeARB (GLuint shader, GLsizei count, const GLchar *const*path, const GLint *length); +GLAPI GLboolean APIENTRY glIsNamedStringARB (GLint namelen, const GLchar *name); +GLAPI void APIENTRY glGetNamedStringARB (GLint namelen, const GLchar *name, GLsizei bufSize, GLint *stringlen, GLchar *string); +GLAPI void APIENTRY glGetNamedStringivARB (GLint namelen, const GLchar *name, GLenum pname, GLint *params); +#endif +#endif /* GL_ARB_shading_language_include */ + +#ifndef GL_ARB_shading_language_packing +#define GL_ARB_shading_language_packing 1 +#endif /* GL_ARB_shading_language_packing */ + +#ifndef GL_ARB_shadow +#define GL_ARB_shadow 1 +#define GL_TEXTURE_COMPARE_MODE_ARB 0x884C +#define GL_TEXTURE_COMPARE_FUNC_ARB 0x884D +#define GL_COMPARE_R_TO_TEXTURE_ARB 0x884E +#endif /* GL_ARB_shadow */ + +#ifndef GL_ARB_shadow_ambient +#define GL_ARB_shadow_ambient 1 +#define GL_TEXTURE_COMPARE_FAIL_VALUE_ARB 0x80BF +#endif /* GL_ARB_shadow_ambient */ + +#ifndef GL_ARB_sparse_buffer +#define GL_ARB_sparse_buffer 1 +#define GL_SPARSE_STORAGE_BIT_ARB 0x0400 +#define GL_SPARSE_BUFFER_PAGE_SIZE_ARB 0x82F8 +typedef void (APIENTRYP PFNGLBUFFERPAGECOMMITMENTARBPROC) (GLenum target, GLintptr offset, GLsizeiptr size, GLboolean commit); +typedef void (APIENTRYP PFNGLNAMEDBUFFERPAGECOMMITMENTEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, GLboolean commit); +typedef void (APIENTRYP PFNGLNAMEDBUFFERPAGECOMMITMENTARBPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, GLboolean commit); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBufferPageCommitmentARB (GLenum target, GLintptr offset, GLsizeiptr size, GLboolean commit); +GLAPI void APIENTRY glNamedBufferPageCommitmentEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, GLboolean commit); +GLAPI void APIENTRY glNamedBufferPageCommitmentARB (GLuint buffer, GLintptr offset, GLsizeiptr size, GLboolean commit); +#endif +#endif /* GL_ARB_sparse_buffer */ + +#ifndef GL_ARB_sparse_texture +#define GL_ARB_sparse_texture 1 +#define GL_TEXTURE_SPARSE_ARB 0x91A6 +#define GL_VIRTUAL_PAGE_SIZE_INDEX_ARB 0x91A7 +#define GL_NUM_SPARSE_LEVELS_ARB 0x91AA +#define GL_NUM_VIRTUAL_PAGE_SIZES_ARB 0x91A8 +#define GL_VIRTUAL_PAGE_SIZE_X_ARB 0x9195 +#define GL_VIRTUAL_PAGE_SIZE_Y_ARB 0x9196 +#define GL_VIRTUAL_PAGE_SIZE_Z_ARB 0x9197 +#define GL_MAX_SPARSE_TEXTURE_SIZE_ARB 0x9198 +#define GL_MAX_SPARSE_3D_TEXTURE_SIZE_ARB 0x9199 +#define GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS_ARB 0x919A +#define GL_SPARSE_TEXTURE_FULL_ARRAY_CUBE_MIPMAPS_ARB 0x91A9 +typedef void (APIENTRYP PFNGLTEXPAGECOMMITMENTARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexPageCommitmentARB (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit); +#endif +#endif /* GL_ARB_sparse_texture */ + +#ifndef GL_ARB_sparse_texture2 +#define GL_ARB_sparse_texture2 1 +#endif /* GL_ARB_sparse_texture2 */ + +#ifndef GL_ARB_sparse_texture_clamp +#define GL_ARB_sparse_texture_clamp 1 +#endif /* GL_ARB_sparse_texture_clamp */ + +#ifndef GL_ARB_stencil_texturing +#define GL_ARB_stencil_texturing 1 +#endif /* GL_ARB_stencil_texturing */ + +#ifndef GL_ARB_sync +#define GL_ARB_sync 1 +#endif /* GL_ARB_sync */ + +#ifndef GL_ARB_tessellation_shader +#define GL_ARB_tessellation_shader 1 +#endif /* GL_ARB_tessellation_shader */ + +#ifndef GL_ARB_texture_barrier +#define GL_ARB_texture_barrier 1 +#endif /* GL_ARB_texture_barrier */ + +#ifndef GL_ARB_texture_border_clamp +#define GL_ARB_texture_border_clamp 1 +#define GL_CLAMP_TO_BORDER_ARB 0x812D +#endif /* GL_ARB_texture_border_clamp */ + +#ifndef GL_ARB_texture_buffer_object +#define GL_ARB_texture_buffer_object 1 +#define GL_TEXTURE_BUFFER_ARB 0x8C2A +#define GL_MAX_TEXTURE_BUFFER_SIZE_ARB 0x8C2B +#define GL_TEXTURE_BINDING_BUFFER_ARB 0x8C2C +#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING_ARB 0x8C2D +#define GL_TEXTURE_BUFFER_FORMAT_ARB 0x8C2E +typedef void (APIENTRYP PFNGLTEXBUFFERARBPROC) (GLenum target, GLenum internalformat, GLuint buffer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexBufferARB (GLenum target, GLenum internalformat, GLuint buffer); +#endif +#endif /* GL_ARB_texture_buffer_object */ + +#ifndef GL_ARB_texture_buffer_object_rgb32 +#define GL_ARB_texture_buffer_object_rgb32 1 +#endif /* GL_ARB_texture_buffer_object_rgb32 */ + +#ifndef GL_ARB_texture_buffer_range +#define GL_ARB_texture_buffer_range 1 +#endif /* GL_ARB_texture_buffer_range */ + +#ifndef GL_ARB_texture_compression +#define GL_ARB_texture_compression 1 +#define GL_COMPRESSED_ALPHA_ARB 0x84E9 +#define GL_COMPRESSED_LUMINANCE_ARB 0x84EA +#define GL_COMPRESSED_LUMINANCE_ALPHA_ARB 0x84EB +#define GL_COMPRESSED_INTENSITY_ARB 0x84EC +#define GL_COMPRESSED_RGB_ARB 0x84ED +#define GL_COMPRESSED_RGBA_ARB 0x84EE +#define GL_TEXTURE_COMPRESSION_HINT_ARB 0x84EF +#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB 0x86A0 +#define GL_TEXTURE_COMPRESSED_ARB 0x86A1 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A2 +#define GL_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A3 +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint level, void *img); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCompressedTexImage3DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexImage2DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexImage1DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexSubImage3DARB (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexSubImage2DARB (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexSubImage1DARB (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glGetCompressedTexImageARB (GLenum target, GLint level, void *img); +#endif +#endif /* GL_ARB_texture_compression */ + +#ifndef GL_ARB_texture_compression_bptc +#define GL_ARB_texture_compression_bptc 1 +#define GL_COMPRESSED_RGBA_BPTC_UNORM_ARB 0x8E8C +#define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB 0x8E8D +#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB 0x8E8E +#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB 0x8E8F +#endif /* GL_ARB_texture_compression_bptc */ + +#ifndef GL_ARB_texture_compression_rgtc +#define GL_ARB_texture_compression_rgtc 1 +#endif /* GL_ARB_texture_compression_rgtc */ + +#ifndef GL_ARB_texture_cube_map +#define GL_ARB_texture_cube_map 1 +#define GL_NORMAL_MAP_ARB 0x8511 +#define GL_REFLECTION_MAP_ARB 0x8512 +#define GL_TEXTURE_CUBE_MAP_ARB 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP_ARB 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x851A +#define GL_PROXY_TEXTURE_CUBE_MAP_ARB 0x851B +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB 0x851C +#endif /* GL_ARB_texture_cube_map */ + +#ifndef GL_ARB_texture_cube_map_array +#define GL_ARB_texture_cube_map_array 1 +#define GL_TEXTURE_CUBE_MAP_ARRAY_ARB 0x9009 +#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB 0x900A +#define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY_ARB 0x900B +#define GL_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900C +#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_ARB 0x900D +#define GL_INT_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900E +#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900F +#endif /* GL_ARB_texture_cube_map_array */ + +#ifndef GL_ARB_texture_env_add +#define GL_ARB_texture_env_add 1 +#endif /* GL_ARB_texture_env_add */ + +#ifndef GL_ARB_texture_env_combine +#define GL_ARB_texture_env_combine 1 +#define GL_COMBINE_ARB 0x8570 +#define GL_COMBINE_RGB_ARB 0x8571 +#define GL_COMBINE_ALPHA_ARB 0x8572 +#define GL_SOURCE0_RGB_ARB 0x8580 +#define GL_SOURCE1_RGB_ARB 0x8581 +#define GL_SOURCE2_RGB_ARB 0x8582 +#define GL_SOURCE0_ALPHA_ARB 0x8588 +#define GL_SOURCE1_ALPHA_ARB 0x8589 +#define GL_SOURCE2_ALPHA_ARB 0x858A +#define GL_OPERAND0_RGB_ARB 0x8590 +#define GL_OPERAND1_RGB_ARB 0x8591 +#define GL_OPERAND2_RGB_ARB 0x8592 +#define GL_OPERAND0_ALPHA_ARB 0x8598 +#define GL_OPERAND1_ALPHA_ARB 0x8599 +#define GL_OPERAND2_ALPHA_ARB 0x859A +#define GL_RGB_SCALE_ARB 0x8573 +#define GL_ADD_SIGNED_ARB 0x8574 +#define GL_INTERPOLATE_ARB 0x8575 +#define GL_SUBTRACT_ARB 0x84E7 +#define GL_CONSTANT_ARB 0x8576 +#define GL_PRIMARY_COLOR_ARB 0x8577 +#define GL_PREVIOUS_ARB 0x8578 +#endif /* GL_ARB_texture_env_combine */ + +#ifndef GL_ARB_texture_env_crossbar +#define GL_ARB_texture_env_crossbar 1 +#endif /* GL_ARB_texture_env_crossbar */ + +#ifndef GL_ARB_texture_env_dot3 +#define GL_ARB_texture_env_dot3 1 +#define GL_DOT3_RGB_ARB 0x86AE +#define GL_DOT3_RGBA_ARB 0x86AF +#endif /* GL_ARB_texture_env_dot3 */ + +#ifndef GL_ARB_texture_filter_minmax +#define GL_ARB_texture_filter_minmax 1 +#define GL_TEXTURE_REDUCTION_MODE_ARB 0x9366 +#define GL_WEIGHTED_AVERAGE_ARB 0x9367 +#endif /* GL_ARB_texture_filter_minmax */ + +#ifndef GL_ARB_texture_float +#define GL_ARB_texture_float 1 +#define GL_TEXTURE_RED_TYPE_ARB 0x8C10 +#define GL_TEXTURE_GREEN_TYPE_ARB 0x8C11 +#define GL_TEXTURE_BLUE_TYPE_ARB 0x8C12 +#define GL_TEXTURE_ALPHA_TYPE_ARB 0x8C13 +#define GL_TEXTURE_LUMINANCE_TYPE_ARB 0x8C14 +#define GL_TEXTURE_INTENSITY_TYPE_ARB 0x8C15 +#define GL_TEXTURE_DEPTH_TYPE_ARB 0x8C16 +#define GL_UNSIGNED_NORMALIZED_ARB 0x8C17 +#define GL_RGBA32F_ARB 0x8814 +#define GL_RGB32F_ARB 0x8815 +#define GL_ALPHA32F_ARB 0x8816 +#define GL_INTENSITY32F_ARB 0x8817 +#define GL_LUMINANCE32F_ARB 0x8818 +#define GL_LUMINANCE_ALPHA32F_ARB 0x8819 +#define GL_RGBA16F_ARB 0x881A +#define GL_RGB16F_ARB 0x881B +#define GL_ALPHA16F_ARB 0x881C +#define GL_INTENSITY16F_ARB 0x881D +#define GL_LUMINANCE16F_ARB 0x881E +#define GL_LUMINANCE_ALPHA16F_ARB 0x881F +#endif /* GL_ARB_texture_float */ + +#ifndef GL_ARB_texture_gather +#define GL_ARB_texture_gather 1 +#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5E +#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5F +#define GL_MAX_PROGRAM_TEXTURE_GATHER_COMPONENTS_ARB 0x8F9F +#endif /* GL_ARB_texture_gather */ + +#ifndef GL_ARB_texture_mirror_clamp_to_edge +#define GL_ARB_texture_mirror_clamp_to_edge 1 +#endif /* GL_ARB_texture_mirror_clamp_to_edge */ + +#ifndef GL_ARB_texture_mirrored_repeat +#define GL_ARB_texture_mirrored_repeat 1 +#define GL_MIRRORED_REPEAT_ARB 0x8370 +#endif /* GL_ARB_texture_mirrored_repeat */ + +#ifndef GL_ARB_texture_multisample +#define GL_ARB_texture_multisample 1 +#endif /* GL_ARB_texture_multisample */ + +#ifndef GL_ARB_texture_non_power_of_two +#define GL_ARB_texture_non_power_of_two 1 +#endif /* GL_ARB_texture_non_power_of_two */ + +#ifndef GL_ARB_texture_query_levels +#define GL_ARB_texture_query_levels 1 +#endif /* GL_ARB_texture_query_levels */ + +#ifndef GL_ARB_texture_query_lod +#define GL_ARB_texture_query_lod 1 +#endif /* GL_ARB_texture_query_lod */ + +#ifndef GL_ARB_texture_rectangle +#define GL_ARB_texture_rectangle 1 +#define GL_TEXTURE_RECTANGLE_ARB 0x84F5 +#define GL_TEXTURE_BINDING_RECTANGLE_ARB 0x84F6 +#define GL_PROXY_TEXTURE_RECTANGLE_ARB 0x84F7 +#define GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB 0x84F8 +#endif /* GL_ARB_texture_rectangle */ + +#ifndef GL_ARB_texture_rg +#define GL_ARB_texture_rg 1 +#endif /* GL_ARB_texture_rg */ + +#ifndef GL_ARB_texture_rgb10_a2ui +#define GL_ARB_texture_rgb10_a2ui 1 +#endif /* GL_ARB_texture_rgb10_a2ui */ + +#ifndef GL_ARB_texture_stencil8 +#define GL_ARB_texture_stencil8 1 +#endif /* GL_ARB_texture_stencil8 */ + +#ifndef GL_ARB_texture_storage +#define GL_ARB_texture_storage 1 +#endif /* GL_ARB_texture_storage */ + +#ifndef GL_ARB_texture_storage_multisample +#define GL_ARB_texture_storage_multisample 1 +#endif /* GL_ARB_texture_storage_multisample */ + +#ifndef GL_ARB_texture_swizzle +#define GL_ARB_texture_swizzle 1 +#endif /* GL_ARB_texture_swizzle */ + +#ifndef GL_ARB_texture_view +#define GL_ARB_texture_view 1 +#endif /* GL_ARB_texture_view */ + +#ifndef GL_ARB_timer_query +#define GL_ARB_timer_query 1 +#endif /* GL_ARB_timer_query */ + +#ifndef GL_ARB_transform_feedback2 +#define GL_ARB_transform_feedback2 1 +#endif /* GL_ARB_transform_feedback2 */ + +#ifndef GL_ARB_transform_feedback3 +#define GL_ARB_transform_feedback3 1 +#endif /* GL_ARB_transform_feedback3 */ + +#ifndef GL_ARB_transform_feedback_instanced +#define GL_ARB_transform_feedback_instanced 1 +#endif /* GL_ARB_transform_feedback_instanced */ + +#ifndef GL_ARB_transform_feedback_overflow_query +#define GL_ARB_transform_feedback_overflow_query 1 +#define GL_TRANSFORM_FEEDBACK_OVERFLOW_ARB 0x82EC +#define GL_TRANSFORM_FEEDBACK_STREAM_OVERFLOW_ARB 0x82ED +#endif /* GL_ARB_transform_feedback_overflow_query */ + +#ifndef GL_ARB_transpose_matrix +#define GL_ARB_transpose_matrix 1 +#define GL_TRANSPOSE_MODELVIEW_MATRIX_ARB 0x84E3 +#define GL_TRANSPOSE_PROJECTION_MATRIX_ARB 0x84E4 +#define GL_TRANSPOSE_TEXTURE_MATRIX_ARB 0x84E5 +#define GL_TRANSPOSE_COLOR_MATRIX_ARB 0x84E6 +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFARBPROC) (const GLfloat *m); +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDARBPROC) (const GLdouble *m); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFARBPROC) (const GLfloat *m); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDARBPROC) (const GLdouble *m); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glLoadTransposeMatrixfARB (const GLfloat *m); +GLAPI void APIENTRY glLoadTransposeMatrixdARB (const GLdouble *m); +GLAPI void APIENTRY glMultTransposeMatrixfARB (const GLfloat *m); +GLAPI void APIENTRY glMultTransposeMatrixdARB (const GLdouble *m); +#endif +#endif /* GL_ARB_transpose_matrix */ + +#ifndef GL_ARB_uniform_buffer_object +#define GL_ARB_uniform_buffer_object 1 +#endif /* GL_ARB_uniform_buffer_object */ + +#ifndef GL_ARB_vertex_array_bgra +#define GL_ARB_vertex_array_bgra 1 +#endif /* GL_ARB_vertex_array_bgra */ + +#ifndef GL_ARB_vertex_array_object +#define GL_ARB_vertex_array_object 1 +#endif /* GL_ARB_vertex_array_object */ + +#ifndef GL_ARB_vertex_attrib_64bit +#define GL_ARB_vertex_attrib_64bit 1 +#endif /* GL_ARB_vertex_attrib_64bit */ + +#ifndef GL_ARB_vertex_attrib_binding +#define GL_ARB_vertex_attrib_binding 1 +#endif /* GL_ARB_vertex_attrib_binding */ + +#ifndef GL_ARB_vertex_blend +#define GL_ARB_vertex_blend 1 +#define GL_MAX_VERTEX_UNITS_ARB 0x86A4 +#define GL_ACTIVE_VERTEX_UNITS_ARB 0x86A5 +#define GL_WEIGHT_SUM_UNITY_ARB 0x86A6 +#define GL_VERTEX_BLEND_ARB 0x86A7 +#define GL_CURRENT_WEIGHT_ARB 0x86A8 +#define GL_WEIGHT_ARRAY_TYPE_ARB 0x86A9 +#define GL_WEIGHT_ARRAY_STRIDE_ARB 0x86AA +#define GL_WEIGHT_ARRAY_SIZE_ARB 0x86AB +#define GL_WEIGHT_ARRAY_POINTER_ARB 0x86AC +#define GL_WEIGHT_ARRAY_ARB 0x86AD +#define GL_MODELVIEW0_ARB 0x1700 +#define GL_MODELVIEW1_ARB 0x850A +#define GL_MODELVIEW2_ARB 0x8722 +#define GL_MODELVIEW3_ARB 0x8723 +#define GL_MODELVIEW4_ARB 0x8724 +#define GL_MODELVIEW5_ARB 0x8725 +#define GL_MODELVIEW6_ARB 0x8726 +#define GL_MODELVIEW7_ARB 0x8727 +#define GL_MODELVIEW8_ARB 0x8728 +#define GL_MODELVIEW9_ARB 0x8729 +#define GL_MODELVIEW10_ARB 0x872A +#define GL_MODELVIEW11_ARB 0x872B +#define GL_MODELVIEW12_ARB 0x872C +#define GL_MODELVIEW13_ARB 0x872D +#define GL_MODELVIEW14_ARB 0x872E +#define GL_MODELVIEW15_ARB 0x872F +#define GL_MODELVIEW16_ARB 0x8730 +#define GL_MODELVIEW17_ARB 0x8731 +#define GL_MODELVIEW18_ARB 0x8732 +#define GL_MODELVIEW19_ARB 0x8733 +#define GL_MODELVIEW20_ARB 0x8734 +#define GL_MODELVIEW21_ARB 0x8735 +#define GL_MODELVIEW22_ARB 0x8736 +#define GL_MODELVIEW23_ARB 0x8737 +#define GL_MODELVIEW24_ARB 0x8738 +#define GL_MODELVIEW25_ARB 0x8739 +#define GL_MODELVIEW26_ARB 0x873A +#define GL_MODELVIEW27_ARB 0x873B +#define GL_MODELVIEW28_ARB 0x873C +#define GL_MODELVIEW29_ARB 0x873D +#define GL_MODELVIEW30_ARB 0x873E +#define GL_MODELVIEW31_ARB 0x873F +typedef void (APIENTRYP PFNGLWEIGHTBVARBPROC) (GLint size, const GLbyte *weights); +typedef void (APIENTRYP PFNGLWEIGHTSVARBPROC) (GLint size, const GLshort *weights); +typedef void (APIENTRYP PFNGLWEIGHTIVARBPROC) (GLint size, const GLint *weights); +typedef void (APIENTRYP PFNGLWEIGHTFVARBPROC) (GLint size, const GLfloat *weights); +typedef void (APIENTRYP PFNGLWEIGHTDVARBPROC) (GLint size, const GLdouble *weights); +typedef void (APIENTRYP PFNGLWEIGHTUBVARBPROC) (GLint size, const GLubyte *weights); +typedef void (APIENTRYP PFNGLWEIGHTUSVARBPROC) (GLint size, const GLushort *weights); +typedef void (APIENTRYP PFNGLWEIGHTUIVARBPROC) (GLint size, const GLuint *weights); +typedef void (APIENTRYP PFNGLWEIGHTPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLVERTEXBLENDARBPROC) (GLint count); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glWeightbvARB (GLint size, const GLbyte *weights); +GLAPI void APIENTRY glWeightsvARB (GLint size, const GLshort *weights); +GLAPI void APIENTRY glWeightivARB (GLint size, const GLint *weights); +GLAPI void APIENTRY glWeightfvARB (GLint size, const GLfloat *weights); +GLAPI void APIENTRY glWeightdvARB (GLint size, const GLdouble *weights); +GLAPI void APIENTRY glWeightubvARB (GLint size, const GLubyte *weights); +GLAPI void APIENTRY glWeightusvARB (GLint size, const GLushort *weights); +GLAPI void APIENTRY glWeightuivARB (GLint size, const GLuint *weights); +GLAPI void APIENTRY glWeightPointerARB (GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glVertexBlendARB (GLint count); +#endif +#endif /* GL_ARB_vertex_blend */ + +#ifndef GL_ARB_vertex_buffer_object +#define GL_ARB_vertex_buffer_object 1 +typedef ptrdiff_t GLsizeiptrARB; +typedef ptrdiff_t GLintptrARB; +#define GL_BUFFER_SIZE_ARB 0x8764 +#define GL_BUFFER_USAGE_ARB 0x8765 +#define GL_ARRAY_BUFFER_ARB 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER_ARB 0x8893 +#define GL_ARRAY_BUFFER_BINDING_ARB 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB 0x8895 +#define GL_VERTEX_ARRAY_BUFFER_BINDING_ARB 0x8896 +#define GL_NORMAL_ARRAY_BUFFER_BINDING_ARB 0x8897 +#define GL_COLOR_ARRAY_BUFFER_BINDING_ARB 0x8898 +#define GL_INDEX_ARRAY_BUFFER_BINDING_ARB 0x8899 +#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB 0x889A +#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB 0x889B +#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB 0x889C +#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB 0x889D +#define GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB 0x889E +#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB 0x889F +#define GL_READ_ONLY_ARB 0x88B8 +#define GL_WRITE_ONLY_ARB 0x88B9 +#define GL_READ_WRITE_ARB 0x88BA +#define GL_BUFFER_ACCESS_ARB 0x88BB +#define GL_BUFFER_MAPPED_ARB 0x88BC +#define GL_BUFFER_MAP_POINTER_ARB 0x88BD +#define GL_STREAM_DRAW_ARB 0x88E0 +#define GL_STREAM_READ_ARB 0x88E1 +#define GL_STREAM_COPY_ARB 0x88E2 +#define GL_STATIC_DRAW_ARB 0x88E4 +#define GL_STATIC_READ_ARB 0x88E5 +#define GL_STATIC_COPY_ARB 0x88E6 +#define GL_DYNAMIC_DRAW_ARB 0x88E8 +#define GL_DYNAMIC_READ_ARB 0x88E9 +#define GL_DYNAMIC_COPY_ARB 0x88EA +typedef void (APIENTRYP PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer); +typedef void (APIENTRYP PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers); +typedef void (APIENTRYP PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers); +typedef GLboolean (APIENTRYP PFNGLISBUFFERARBPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLBUFFERDATAARBPROC) (GLenum target, GLsizeiptrARB size, const void *data, GLenum usage); +typedef void (APIENTRYP PFNGLBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const void *data); +typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, void *data); +typedef void *(APIENTRYP PFNGLMAPBUFFERARBPROC) (GLenum target, GLenum access); +typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERARBPROC) (GLenum target); +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVARBPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVARBPROC) (GLenum target, GLenum pname, void **params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindBufferARB (GLenum target, GLuint buffer); +GLAPI void APIENTRY glDeleteBuffersARB (GLsizei n, const GLuint *buffers); +GLAPI void APIENTRY glGenBuffersARB (GLsizei n, GLuint *buffers); +GLAPI GLboolean APIENTRY glIsBufferARB (GLuint buffer); +GLAPI void APIENTRY glBufferDataARB (GLenum target, GLsizeiptrARB size, const void *data, GLenum usage); +GLAPI void APIENTRY glBufferSubDataARB (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const void *data); +GLAPI void APIENTRY glGetBufferSubDataARB (GLenum target, GLintptrARB offset, GLsizeiptrARB size, void *data); +GLAPI void *APIENTRY glMapBufferARB (GLenum target, GLenum access); +GLAPI GLboolean APIENTRY glUnmapBufferARB (GLenum target); +GLAPI void APIENTRY glGetBufferParameterivARB (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetBufferPointervARB (GLenum target, GLenum pname, void **params); +#endif +#endif /* GL_ARB_vertex_buffer_object */ + +#ifndef GL_ARB_vertex_program +#define GL_ARB_vertex_program 1 +#define GL_COLOR_SUM_ARB 0x8458 +#define GL_VERTEX_PROGRAM_ARB 0x8620 +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB 0x8625 +#define GL_CURRENT_VERTEX_ATTRIB_ARB 0x8626 +#define GL_VERTEX_PROGRAM_POINT_SIZE_ARB 0x8642 +#define GL_VERTEX_PROGRAM_TWO_SIDE_ARB 0x8643 +#define GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB 0x8645 +#define GL_MAX_VERTEX_ATTRIBS_ARB 0x8869 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB 0x886A +#define GL_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B0 +#define GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B1 +#define GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B2 +#define GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B3 +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DARBPROC) (GLuint index, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVARBPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FARBPROC) (GLuint index, GLfloat x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVARBPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SARBPROC) (GLuint index, GLshort x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DARBPROC) (GLuint index, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVARBPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FARBPROC) (GLuint index, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVARBPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SARBPROC) (GLuint index, GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVARBPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVARBPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVARBPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVARBPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBARBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVARBPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVARBPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVARBPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVARBPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVARBPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVARBPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVARBPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVARBPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVARBPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVARBPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERARBPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYARBPROC) (GLuint index); +typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYARBPROC) (GLuint index); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVARBPROC) (GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVARBPROC) (GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVARBPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVARBPROC) (GLuint index, GLenum pname, void **pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttrib1dARB (GLuint index, GLdouble x); +GLAPI void APIENTRY glVertexAttrib1dvARB (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib1fARB (GLuint index, GLfloat x); +GLAPI void APIENTRY glVertexAttrib1fvARB (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib1sARB (GLuint index, GLshort x); +GLAPI void APIENTRY glVertexAttrib1svARB (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib2dARB (GLuint index, GLdouble x, GLdouble y); +GLAPI void APIENTRY glVertexAttrib2dvARB (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib2fARB (GLuint index, GLfloat x, GLfloat y); +GLAPI void APIENTRY glVertexAttrib2fvARB (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib2sARB (GLuint index, GLshort x, GLshort y); +GLAPI void APIENTRY glVertexAttrib2svARB (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib3dARB (GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glVertexAttrib3dvARB (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib3fARB (GLuint index, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glVertexAttrib3fvARB (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib3sARB (GLuint index, GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glVertexAttrib3svARB (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4NbvARB (GLuint index, const GLbyte *v); +GLAPI void APIENTRY glVertexAttrib4NivARB (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttrib4NsvARB (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4NubARB (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +GLAPI void APIENTRY glVertexAttrib4NubvARB (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttrib4NuivARB (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttrib4NusvARB (GLuint index, const GLushort *v); +GLAPI void APIENTRY glVertexAttrib4bvARB (GLuint index, const GLbyte *v); +GLAPI void APIENTRY glVertexAttrib4dARB (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glVertexAttrib4dvARB (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib4fARB (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glVertexAttrib4fvARB (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib4ivARB (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttrib4sARB (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI void APIENTRY glVertexAttrib4svARB (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4ubvARB (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttrib4uivARB (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttrib4usvARB (GLuint index, const GLushort *v); +GLAPI void APIENTRY glVertexAttribPointerARB (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glEnableVertexAttribArrayARB (GLuint index); +GLAPI void APIENTRY glDisableVertexAttribArrayARB (GLuint index); +GLAPI void APIENTRY glGetVertexAttribdvARB (GLuint index, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glGetVertexAttribfvARB (GLuint index, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetVertexAttribivARB (GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribPointervARB (GLuint index, GLenum pname, void **pointer); +#endif +#endif /* GL_ARB_vertex_program */ + +#ifndef GL_ARB_vertex_shader +#define GL_ARB_vertex_shader 1 +#define GL_VERTEX_SHADER_ARB 0x8B31 +#define GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB 0x8B4A +#define GL_MAX_VARYING_FLOATS_ARB 0x8B4B +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB 0x8B4C +#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB 0x8B4D +#define GL_OBJECT_ACTIVE_ATTRIBUTES_ARB 0x8B89 +#define GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB 0x8B8A +typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONARBPROC) (GLhandleARB programObj, GLuint index, const GLcharARB *name); +typedef void (APIENTRYP PFNGLGETACTIVEATTRIBARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); +typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindAttribLocationARB (GLhandleARB programObj, GLuint index, const GLcharARB *name); +GLAPI void APIENTRY glGetActiveAttribARB (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); +GLAPI GLint APIENTRY glGetAttribLocationARB (GLhandleARB programObj, const GLcharARB *name); +#endif +#endif /* GL_ARB_vertex_shader */ + +#ifndef GL_ARB_vertex_type_10f_11f_11f_rev +#define GL_ARB_vertex_type_10f_11f_11f_rev 1 +#endif /* GL_ARB_vertex_type_10f_11f_11f_rev */ + +#ifndef GL_ARB_vertex_type_2_10_10_10_rev +#define GL_ARB_vertex_type_2_10_10_10_rev 1 +#endif /* GL_ARB_vertex_type_2_10_10_10_rev */ + +#ifndef GL_ARB_viewport_array +#define GL_ARB_viewport_array 1 +#endif /* GL_ARB_viewport_array */ + +#ifndef GL_ARB_window_pos +#define GL_ARB_window_pos 1 +typedef void (APIENTRYP PFNGLWINDOWPOS2DARBPROC) (GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLWINDOWPOS2DVARBPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2FARBPROC) (GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLWINDOWPOS2FVARBPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2IARBPROC) (GLint x, GLint y); +typedef void (APIENTRYP PFNGLWINDOWPOS2IVARBPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2SARBPROC) (GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLWINDOWPOS2SVARBPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3DARBPROC) (GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLWINDOWPOS3DVARBPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3FARBPROC) (GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLWINDOWPOS3FVARBPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3IARBPROC) (GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLWINDOWPOS3IVARBPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3SARBPROC) (GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLWINDOWPOS3SVARBPROC) (const GLshort *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glWindowPos2dARB (GLdouble x, GLdouble y); +GLAPI void APIENTRY glWindowPos2dvARB (const GLdouble *v); +GLAPI void APIENTRY glWindowPos2fARB (GLfloat x, GLfloat y); +GLAPI void APIENTRY glWindowPos2fvARB (const GLfloat *v); +GLAPI void APIENTRY glWindowPos2iARB (GLint x, GLint y); +GLAPI void APIENTRY glWindowPos2ivARB (const GLint *v); +GLAPI void APIENTRY glWindowPos2sARB (GLshort x, GLshort y); +GLAPI void APIENTRY glWindowPos2svARB (const GLshort *v); +GLAPI void APIENTRY glWindowPos3dARB (GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glWindowPos3dvARB (const GLdouble *v); +GLAPI void APIENTRY glWindowPos3fARB (GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glWindowPos3fvARB (const GLfloat *v); +GLAPI void APIENTRY glWindowPos3iARB (GLint x, GLint y, GLint z); +GLAPI void APIENTRY glWindowPos3ivARB (const GLint *v); +GLAPI void APIENTRY glWindowPos3sARB (GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glWindowPos3svARB (const GLshort *v); +#endif +#endif /* GL_ARB_window_pos */ + +#ifndef GL_KHR_blend_equation_advanced +#define GL_KHR_blend_equation_advanced 1 +#define GL_MULTIPLY_KHR 0x9294 +#define GL_SCREEN_KHR 0x9295 +#define GL_OVERLAY_KHR 0x9296 +#define GL_DARKEN_KHR 0x9297 +#define GL_LIGHTEN_KHR 0x9298 +#define GL_COLORDODGE_KHR 0x9299 +#define GL_COLORBURN_KHR 0x929A +#define GL_HARDLIGHT_KHR 0x929B +#define GL_SOFTLIGHT_KHR 0x929C +#define GL_DIFFERENCE_KHR 0x929E +#define GL_EXCLUSION_KHR 0x92A0 +#define GL_HSL_HUE_KHR 0x92AD +#define GL_HSL_SATURATION_KHR 0x92AE +#define GL_HSL_COLOR_KHR 0x92AF +#define GL_HSL_LUMINOSITY_KHR 0x92B0 +typedef void (APIENTRYP PFNGLBLENDBARRIERKHRPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendBarrierKHR (void); +#endif +#endif /* GL_KHR_blend_equation_advanced */ + +#ifndef GL_KHR_blend_equation_advanced_coherent +#define GL_KHR_blend_equation_advanced_coherent 1 +#define GL_BLEND_ADVANCED_COHERENT_KHR 0x9285 +#endif /* GL_KHR_blend_equation_advanced_coherent */ + +#ifndef GL_KHR_context_flush_control +#define GL_KHR_context_flush_control 1 +#endif /* GL_KHR_context_flush_control */ + +#ifndef GL_KHR_debug +#define GL_KHR_debug 1 +#endif /* GL_KHR_debug */ + +#ifndef GL_KHR_no_error +#define GL_KHR_no_error 1 +#define GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR 0x00000008 +#endif /* GL_KHR_no_error */ + +#ifndef GL_KHR_robust_buffer_access_behavior +#define GL_KHR_robust_buffer_access_behavior 1 +#endif /* GL_KHR_robust_buffer_access_behavior */ + +#ifndef GL_KHR_robustness +#define GL_KHR_robustness 1 +#define GL_CONTEXT_ROBUST_ACCESS 0x90F3 +#endif /* GL_KHR_robustness */ + +#ifndef GL_KHR_texture_compression_astc_hdr +#define GL_KHR_texture_compression_astc_hdr 1 +#define GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93B0 +#define GL_COMPRESSED_RGBA_ASTC_5x4_KHR 0x93B1 +#define GL_COMPRESSED_RGBA_ASTC_5x5_KHR 0x93B2 +#define GL_COMPRESSED_RGBA_ASTC_6x5_KHR 0x93B3 +#define GL_COMPRESSED_RGBA_ASTC_6x6_KHR 0x93B4 +#define GL_COMPRESSED_RGBA_ASTC_8x5_KHR 0x93B5 +#define GL_COMPRESSED_RGBA_ASTC_8x6_KHR 0x93B6 +#define GL_COMPRESSED_RGBA_ASTC_8x8_KHR 0x93B7 +#define GL_COMPRESSED_RGBA_ASTC_10x5_KHR 0x93B8 +#define GL_COMPRESSED_RGBA_ASTC_10x6_KHR 0x93B9 +#define GL_COMPRESSED_RGBA_ASTC_10x8_KHR 0x93BA +#define GL_COMPRESSED_RGBA_ASTC_10x10_KHR 0x93BB +#define GL_COMPRESSED_RGBA_ASTC_12x10_KHR 0x93BC +#define GL_COMPRESSED_RGBA_ASTC_12x12_KHR 0x93BD +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR 0x93D0 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR 0x93D1 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR 0x93D2 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR 0x93D3 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR 0x93D4 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR 0x93D5 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR 0x93D6 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR 0x93D7 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR 0x93D8 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR 0x93D9 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR 0x93DA +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR 0x93DB +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR 0x93DC +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR 0x93DD +#endif /* GL_KHR_texture_compression_astc_hdr */ + +#ifndef GL_KHR_texture_compression_astc_ldr +#define GL_KHR_texture_compression_astc_ldr 1 +#endif /* GL_KHR_texture_compression_astc_ldr */ + +#ifndef GL_KHR_texture_compression_astc_sliced_3d +#define GL_KHR_texture_compression_astc_sliced_3d 1 +#endif /* GL_KHR_texture_compression_astc_sliced_3d */ + +#ifndef GL_OES_byte_coordinates +#define GL_OES_byte_coordinates 1 +typedef void (APIENTRYP PFNGLMULTITEXCOORD1BOESPROC) (GLenum texture, GLbyte s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1BVOESPROC) (GLenum texture, const GLbyte *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2BOESPROC) (GLenum texture, GLbyte s, GLbyte t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2BVOESPROC) (GLenum texture, const GLbyte *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3BOESPROC) (GLenum texture, GLbyte s, GLbyte t, GLbyte r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3BVOESPROC) (GLenum texture, const GLbyte *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4BOESPROC) (GLenum texture, GLbyte s, GLbyte t, GLbyte r, GLbyte q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4BVOESPROC) (GLenum texture, const GLbyte *coords); +typedef void (APIENTRYP PFNGLTEXCOORD1BOESPROC) (GLbyte s); +typedef void (APIENTRYP PFNGLTEXCOORD1BVOESPROC) (const GLbyte *coords); +typedef void (APIENTRYP PFNGLTEXCOORD2BOESPROC) (GLbyte s, GLbyte t); +typedef void (APIENTRYP PFNGLTEXCOORD2BVOESPROC) (const GLbyte *coords); +typedef void (APIENTRYP PFNGLTEXCOORD3BOESPROC) (GLbyte s, GLbyte t, GLbyte r); +typedef void (APIENTRYP PFNGLTEXCOORD3BVOESPROC) (const GLbyte *coords); +typedef void (APIENTRYP PFNGLTEXCOORD4BOESPROC) (GLbyte s, GLbyte t, GLbyte r, GLbyte q); +typedef void (APIENTRYP PFNGLTEXCOORD4BVOESPROC) (const GLbyte *coords); +typedef void (APIENTRYP PFNGLVERTEX2BOESPROC) (GLbyte x, GLbyte y); +typedef void (APIENTRYP PFNGLVERTEX2BVOESPROC) (const GLbyte *coords); +typedef void (APIENTRYP PFNGLVERTEX3BOESPROC) (GLbyte x, GLbyte y, GLbyte z); +typedef void (APIENTRYP PFNGLVERTEX3BVOESPROC) (const GLbyte *coords); +typedef void (APIENTRYP PFNGLVERTEX4BOESPROC) (GLbyte x, GLbyte y, GLbyte z, GLbyte w); +typedef void (APIENTRYP PFNGLVERTEX4BVOESPROC) (const GLbyte *coords); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiTexCoord1bOES (GLenum texture, GLbyte s); +GLAPI void APIENTRY glMultiTexCoord1bvOES (GLenum texture, const GLbyte *coords); +GLAPI void APIENTRY glMultiTexCoord2bOES (GLenum texture, GLbyte s, GLbyte t); +GLAPI void APIENTRY glMultiTexCoord2bvOES (GLenum texture, const GLbyte *coords); +GLAPI void APIENTRY glMultiTexCoord3bOES (GLenum texture, GLbyte s, GLbyte t, GLbyte r); +GLAPI void APIENTRY glMultiTexCoord3bvOES (GLenum texture, const GLbyte *coords); +GLAPI void APIENTRY glMultiTexCoord4bOES (GLenum texture, GLbyte s, GLbyte t, GLbyte r, GLbyte q); +GLAPI void APIENTRY glMultiTexCoord4bvOES (GLenum texture, const GLbyte *coords); +GLAPI void APIENTRY glTexCoord1bOES (GLbyte s); +GLAPI void APIENTRY glTexCoord1bvOES (const GLbyte *coords); +GLAPI void APIENTRY glTexCoord2bOES (GLbyte s, GLbyte t); +GLAPI void APIENTRY glTexCoord2bvOES (const GLbyte *coords); +GLAPI void APIENTRY glTexCoord3bOES (GLbyte s, GLbyte t, GLbyte r); +GLAPI void APIENTRY glTexCoord3bvOES (const GLbyte *coords); +GLAPI void APIENTRY glTexCoord4bOES (GLbyte s, GLbyte t, GLbyte r, GLbyte q); +GLAPI void APIENTRY glTexCoord4bvOES (const GLbyte *coords); +GLAPI void APIENTRY glVertex2bOES (GLbyte x, GLbyte y); +GLAPI void APIENTRY glVertex2bvOES (const GLbyte *coords); +GLAPI void APIENTRY glVertex3bOES (GLbyte x, GLbyte y, GLbyte z); +GLAPI void APIENTRY glVertex3bvOES (const GLbyte *coords); +GLAPI void APIENTRY glVertex4bOES (GLbyte x, GLbyte y, GLbyte z, GLbyte w); +GLAPI void APIENTRY glVertex4bvOES (const GLbyte *coords); +#endif +#endif /* GL_OES_byte_coordinates */ + +#ifndef GL_OES_compressed_paletted_texture +#define GL_OES_compressed_paletted_texture 1 +#define GL_PALETTE4_RGB8_OES 0x8B90 +#define GL_PALETTE4_RGBA8_OES 0x8B91 +#define GL_PALETTE4_R5_G6_B5_OES 0x8B92 +#define GL_PALETTE4_RGBA4_OES 0x8B93 +#define GL_PALETTE4_RGB5_A1_OES 0x8B94 +#define GL_PALETTE8_RGB8_OES 0x8B95 +#define GL_PALETTE8_RGBA8_OES 0x8B96 +#define GL_PALETTE8_R5_G6_B5_OES 0x8B97 +#define GL_PALETTE8_RGBA4_OES 0x8B98 +#define GL_PALETTE8_RGB5_A1_OES 0x8B99 +#endif /* GL_OES_compressed_paletted_texture */ + +#ifndef GL_OES_fixed_point +#define GL_OES_fixed_point 1 +typedef GLint GLfixed; +#define GL_FIXED_OES 0x140C +typedef void (APIENTRYP PFNGLALPHAFUNCXOESPROC) (GLenum func, GLfixed ref); +typedef void (APIENTRYP PFNGLCLEARCOLORXOESPROC) (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +typedef void (APIENTRYP PFNGLCLEARDEPTHXOESPROC) (GLfixed depth); +typedef void (APIENTRYP PFNGLCLIPPLANEXOESPROC) (GLenum plane, const GLfixed *equation); +typedef void (APIENTRYP PFNGLCOLOR4XOESPROC) (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +typedef void (APIENTRYP PFNGLDEPTHRANGEXOESPROC) (GLfixed n, GLfixed f); +typedef void (APIENTRYP PFNGLFOGXOESPROC) (GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLFOGXVOESPROC) (GLenum pname, const GLfixed *param); +typedef void (APIENTRYP PFNGLFRUSTUMXOESPROC) (GLfixed l, GLfixed r, GLfixed b, GLfixed t, GLfixed n, GLfixed f); +typedef void (APIENTRYP PFNGLGETCLIPPLANEXOESPROC) (GLenum plane, GLfixed *equation); +typedef void (APIENTRYP PFNGLGETFIXEDVOESPROC) (GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLGETTEXENVXVOESPROC) (GLenum target, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERXVOESPROC) (GLenum target, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLLIGHTMODELXOESPROC) (GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLLIGHTMODELXVOESPROC) (GLenum pname, const GLfixed *param); +typedef void (APIENTRYP PFNGLLIGHTXOESPROC) (GLenum light, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLLIGHTXVOESPROC) (GLenum light, GLenum pname, const GLfixed *params); +typedef void (APIENTRYP PFNGLLINEWIDTHXOESPROC) (GLfixed width); +typedef void (APIENTRYP PFNGLLOADMATRIXXOESPROC) (const GLfixed *m); +typedef void (APIENTRYP PFNGLMATERIALXOESPROC) (GLenum face, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLMATERIALXVOESPROC) (GLenum face, GLenum pname, const GLfixed *param); +typedef void (APIENTRYP PFNGLMULTMATRIXXOESPROC) (const GLfixed *m); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4XOESPROC) (GLenum texture, GLfixed s, GLfixed t, GLfixed r, GLfixed q); +typedef void (APIENTRYP PFNGLNORMAL3XOESPROC) (GLfixed nx, GLfixed ny, GLfixed nz); +typedef void (APIENTRYP PFNGLORTHOXOESPROC) (GLfixed l, GLfixed r, GLfixed b, GLfixed t, GLfixed n, GLfixed f); +typedef void (APIENTRYP PFNGLPOINTPARAMETERXVOESPROC) (GLenum pname, const GLfixed *params); +typedef void (APIENTRYP PFNGLPOINTSIZEXOESPROC) (GLfixed size); +typedef void (APIENTRYP PFNGLPOLYGONOFFSETXOESPROC) (GLfixed factor, GLfixed units); +typedef void (APIENTRYP PFNGLROTATEXOESPROC) (GLfixed angle, GLfixed x, GLfixed y, GLfixed z); +typedef void (APIENTRYP PFNGLSCALEXOESPROC) (GLfixed x, GLfixed y, GLfixed z); +typedef void (APIENTRYP PFNGLTEXENVXOESPROC) (GLenum target, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLTEXENVXVOESPROC) (GLenum target, GLenum pname, const GLfixed *params); +typedef void (APIENTRYP PFNGLTEXPARAMETERXOESPROC) (GLenum target, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLTEXPARAMETERXVOESPROC) (GLenum target, GLenum pname, const GLfixed *params); +typedef void (APIENTRYP PFNGLTRANSLATEXOESPROC) (GLfixed x, GLfixed y, GLfixed z); +typedef void (APIENTRYP PFNGLACCUMXOESPROC) (GLenum op, GLfixed value); +typedef void (APIENTRYP PFNGLBITMAPXOESPROC) (GLsizei width, GLsizei height, GLfixed xorig, GLfixed yorig, GLfixed xmove, GLfixed ymove, const GLubyte *bitmap); +typedef void (APIENTRYP PFNGLBLENDCOLORXOESPROC) (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +typedef void (APIENTRYP PFNGLCLEARACCUMXOESPROC) (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +typedef void (APIENTRYP PFNGLCOLOR3XOESPROC) (GLfixed red, GLfixed green, GLfixed blue); +typedef void (APIENTRYP PFNGLCOLOR3XVOESPROC) (const GLfixed *components); +typedef void (APIENTRYP PFNGLCOLOR4XVOESPROC) (const GLfixed *components); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERXOESPROC) (GLenum target, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERXVOESPROC) (GLenum target, GLenum pname, const GLfixed *params); +typedef void (APIENTRYP PFNGLEVALCOORD1XOESPROC) (GLfixed u); +typedef void (APIENTRYP PFNGLEVALCOORD1XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLEVALCOORD2XOESPROC) (GLfixed u, GLfixed v); +typedef void (APIENTRYP PFNGLEVALCOORD2XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLFEEDBACKBUFFERXOESPROC) (GLsizei n, GLenum type, const GLfixed *buffer); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERXVOESPROC) (GLenum target, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERXVOESPROC) (GLenum target, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLGETLIGHTXOESPROC) (GLenum light, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLGETMAPXVOESPROC) (GLenum target, GLenum query, GLfixed *v); +typedef void (APIENTRYP PFNGLGETMATERIALXOESPROC) (GLenum face, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLGETPIXELMAPXVPROC) (GLenum map, GLint size, GLfixed *values); +typedef void (APIENTRYP PFNGLGETTEXGENXVOESPROC) (GLenum coord, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERXVOESPROC) (GLenum target, GLint level, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLINDEXXOESPROC) (GLfixed component); +typedef void (APIENTRYP PFNGLINDEXXVOESPROC) (const GLfixed *component); +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXXOESPROC) (const GLfixed *m); +typedef void (APIENTRYP PFNGLMAP1XOESPROC) (GLenum target, GLfixed u1, GLfixed u2, GLint stride, GLint order, GLfixed points); +typedef void (APIENTRYP PFNGLMAP2XOESPROC) (GLenum target, GLfixed u1, GLfixed u2, GLint ustride, GLint uorder, GLfixed v1, GLfixed v2, GLint vstride, GLint vorder, GLfixed points); +typedef void (APIENTRYP PFNGLMAPGRID1XOESPROC) (GLint n, GLfixed u1, GLfixed u2); +typedef void (APIENTRYP PFNGLMAPGRID2XOESPROC) (GLint n, GLfixed u1, GLfixed u2, GLfixed v1, GLfixed v2); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXXOESPROC) (const GLfixed *m); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1XOESPROC) (GLenum texture, GLfixed s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1XVOESPROC) (GLenum texture, const GLfixed *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2XOESPROC) (GLenum texture, GLfixed s, GLfixed t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2XVOESPROC) (GLenum texture, const GLfixed *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3XOESPROC) (GLenum texture, GLfixed s, GLfixed t, GLfixed r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3XVOESPROC) (GLenum texture, const GLfixed *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4XVOESPROC) (GLenum texture, const GLfixed *coords); +typedef void (APIENTRYP PFNGLNORMAL3XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLPASSTHROUGHXOESPROC) (GLfixed token); +typedef void (APIENTRYP PFNGLPIXELMAPXPROC) (GLenum map, GLint size, const GLfixed *values); +typedef void (APIENTRYP PFNGLPIXELSTOREXPROC) (GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLPIXELTRANSFERXOESPROC) (GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLPIXELZOOMXOESPROC) (GLfixed xfactor, GLfixed yfactor); +typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESXOESPROC) (GLsizei n, const GLuint *textures, const GLfixed *priorities); +typedef void (APIENTRYP PFNGLRASTERPOS2XOESPROC) (GLfixed x, GLfixed y); +typedef void (APIENTRYP PFNGLRASTERPOS2XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLRASTERPOS3XOESPROC) (GLfixed x, GLfixed y, GLfixed z); +typedef void (APIENTRYP PFNGLRASTERPOS3XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLRASTERPOS4XOESPROC) (GLfixed x, GLfixed y, GLfixed z, GLfixed w); +typedef void (APIENTRYP PFNGLRASTERPOS4XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLRECTXOESPROC) (GLfixed x1, GLfixed y1, GLfixed x2, GLfixed y2); +typedef void (APIENTRYP PFNGLRECTXVOESPROC) (const GLfixed *v1, const GLfixed *v2); +typedef void (APIENTRYP PFNGLTEXCOORD1XOESPROC) (GLfixed s); +typedef void (APIENTRYP PFNGLTEXCOORD1XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLTEXCOORD2XOESPROC) (GLfixed s, GLfixed t); +typedef void (APIENTRYP PFNGLTEXCOORD2XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLTEXCOORD3XOESPROC) (GLfixed s, GLfixed t, GLfixed r); +typedef void (APIENTRYP PFNGLTEXCOORD3XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLTEXCOORD4XOESPROC) (GLfixed s, GLfixed t, GLfixed r, GLfixed q); +typedef void (APIENTRYP PFNGLTEXCOORD4XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLTEXGENXOESPROC) (GLenum coord, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLTEXGENXVOESPROC) (GLenum coord, GLenum pname, const GLfixed *params); +typedef void (APIENTRYP PFNGLVERTEX2XOESPROC) (GLfixed x); +typedef void (APIENTRYP PFNGLVERTEX2XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLVERTEX3XOESPROC) (GLfixed x, GLfixed y); +typedef void (APIENTRYP PFNGLVERTEX3XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLVERTEX4XOESPROC) (GLfixed x, GLfixed y, GLfixed z); +typedef void (APIENTRYP PFNGLVERTEX4XVOESPROC) (const GLfixed *coords); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glAlphaFuncxOES (GLenum func, GLfixed ref); +GLAPI void APIENTRY glClearColorxOES (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +GLAPI void APIENTRY glClearDepthxOES (GLfixed depth); +GLAPI void APIENTRY glClipPlanexOES (GLenum plane, const GLfixed *equation); +GLAPI void APIENTRY glColor4xOES (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +GLAPI void APIENTRY glDepthRangexOES (GLfixed n, GLfixed f); +GLAPI void APIENTRY glFogxOES (GLenum pname, GLfixed param); +GLAPI void APIENTRY glFogxvOES (GLenum pname, const GLfixed *param); +GLAPI void APIENTRY glFrustumxOES (GLfixed l, GLfixed r, GLfixed b, GLfixed t, GLfixed n, GLfixed f); +GLAPI void APIENTRY glGetClipPlanexOES (GLenum plane, GLfixed *equation); +GLAPI void APIENTRY glGetFixedvOES (GLenum pname, GLfixed *params); +GLAPI void APIENTRY glGetTexEnvxvOES (GLenum target, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glGetTexParameterxvOES (GLenum target, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glLightModelxOES (GLenum pname, GLfixed param); +GLAPI void APIENTRY glLightModelxvOES (GLenum pname, const GLfixed *param); +GLAPI void APIENTRY glLightxOES (GLenum light, GLenum pname, GLfixed param); +GLAPI void APIENTRY glLightxvOES (GLenum light, GLenum pname, const GLfixed *params); +GLAPI void APIENTRY glLineWidthxOES (GLfixed width); +GLAPI void APIENTRY glLoadMatrixxOES (const GLfixed *m); +GLAPI void APIENTRY glMaterialxOES (GLenum face, GLenum pname, GLfixed param); +GLAPI void APIENTRY glMaterialxvOES (GLenum face, GLenum pname, const GLfixed *param); +GLAPI void APIENTRY glMultMatrixxOES (const GLfixed *m); +GLAPI void APIENTRY glMultiTexCoord4xOES (GLenum texture, GLfixed s, GLfixed t, GLfixed r, GLfixed q); +GLAPI void APIENTRY glNormal3xOES (GLfixed nx, GLfixed ny, GLfixed nz); +GLAPI void APIENTRY glOrthoxOES (GLfixed l, GLfixed r, GLfixed b, GLfixed t, GLfixed n, GLfixed f); +GLAPI void APIENTRY glPointParameterxvOES (GLenum pname, const GLfixed *params); +GLAPI void APIENTRY glPointSizexOES (GLfixed size); +GLAPI void APIENTRY glPolygonOffsetxOES (GLfixed factor, GLfixed units); +GLAPI void APIENTRY glRotatexOES (GLfixed angle, GLfixed x, GLfixed y, GLfixed z); +GLAPI void APIENTRY glScalexOES (GLfixed x, GLfixed y, GLfixed z); +GLAPI void APIENTRY glTexEnvxOES (GLenum target, GLenum pname, GLfixed param); +GLAPI void APIENTRY glTexEnvxvOES (GLenum target, GLenum pname, const GLfixed *params); +GLAPI void APIENTRY glTexParameterxOES (GLenum target, GLenum pname, GLfixed param); +GLAPI void APIENTRY glTexParameterxvOES (GLenum target, GLenum pname, const GLfixed *params); +GLAPI void APIENTRY glTranslatexOES (GLfixed x, GLfixed y, GLfixed z); +GLAPI void APIENTRY glAccumxOES (GLenum op, GLfixed value); +GLAPI void APIENTRY glBitmapxOES (GLsizei width, GLsizei height, GLfixed xorig, GLfixed yorig, GLfixed xmove, GLfixed ymove, const GLubyte *bitmap); +GLAPI void APIENTRY glBlendColorxOES (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +GLAPI void APIENTRY glClearAccumxOES (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +GLAPI void APIENTRY glColor3xOES (GLfixed red, GLfixed green, GLfixed blue); +GLAPI void APIENTRY glColor3xvOES (const GLfixed *components); +GLAPI void APIENTRY glColor4xvOES (const GLfixed *components); +GLAPI void APIENTRY glConvolutionParameterxOES (GLenum target, GLenum pname, GLfixed param); +GLAPI void APIENTRY glConvolutionParameterxvOES (GLenum target, GLenum pname, const GLfixed *params); +GLAPI void APIENTRY glEvalCoord1xOES (GLfixed u); +GLAPI void APIENTRY glEvalCoord1xvOES (const GLfixed *coords); +GLAPI void APIENTRY glEvalCoord2xOES (GLfixed u, GLfixed v); +GLAPI void APIENTRY glEvalCoord2xvOES (const GLfixed *coords); +GLAPI void APIENTRY glFeedbackBufferxOES (GLsizei n, GLenum type, const GLfixed *buffer); +GLAPI void APIENTRY glGetConvolutionParameterxvOES (GLenum target, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glGetHistogramParameterxvOES (GLenum target, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glGetLightxOES (GLenum light, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glGetMapxvOES (GLenum target, GLenum query, GLfixed *v); +GLAPI void APIENTRY glGetMaterialxOES (GLenum face, GLenum pname, GLfixed param); +GLAPI void APIENTRY glGetPixelMapxv (GLenum map, GLint size, GLfixed *values); +GLAPI void APIENTRY glGetTexGenxvOES (GLenum coord, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glGetTexLevelParameterxvOES (GLenum target, GLint level, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glIndexxOES (GLfixed component); +GLAPI void APIENTRY glIndexxvOES (const GLfixed *component); +GLAPI void APIENTRY glLoadTransposeMatrixxOES (const GLfixed *m); +GLAPI void APIENTRY glMap1xOES (GLenum target, GLfixed u1, GLfixed u2, GLint stride, GLint order, GLfixed points); +GLAPI void APIENTRY glMap2xOES (GLenum target, GLfixed u1, GLfixed u2, GLint ustride, GLint uorder, GLfixed v1, GLfixed v2, GLint vstride, GLint vorder, GLfixed points); +GLAPI void APIENTRY glMapGrid1xOES (GLint n, GLfixed u1, GLfixed u2); +GLAPI void APIENTRY glMapGrid2xOES (GLint n, GLfixed u1, GLfixed u2, GLfixed v1, GLfixed v2); +GLAPI void APIENTRY glMultTransposeMatrixxOES (const GLfixed *m); +GLAPI void APIENTRY glMultiTexCoord1xOES (GLenum texture, GLfixed s); +GLAPI void APIENTRY glMultiTexCoord1xvOES (GLenum texture, const GLfixed *coords); +GLAPI void APIENTRY glMultiTexCoord2xOES (GLenum texture, GLfixed s, GLfixed t); +GLAPI void APIENTRY glMultiTexCoord2xvOES (GLenum texture, const GLfixed *coords); +GLAPI void APIENTRY glMultiTexCoord3xOES (GLenum texture, GLfixed s, GLfixed t, GLfixed r); +GLAPI void APIENTRY glMultiTexCoord3xvOES (GLenum texture, const GLfixed *coords); +GLAPI void APIENTRY glMultiTexCoord4xvOES (GLenum texture, const GLfixed *coords); +GLAPI void APIENTRY glNormal3xvOES (const GLfixed *coords); +GLAPI void APIENTRY glPassThroughxOES (GLfixed token); +GLAPI void APIENTRY glPixelMapx (GLenum map, GLint size, const GLfixed *values); +GLAPI void APIENTRY glPixelStorex (GLenum pname, GLfixed param); +GLAPI void APIENTRY glPixelTransferxOES (GLenum pname, GLfixed param); +GLAPI void APIENTRY glPixelZoomxOES (GLfixed xfactor, GLfixed yfactor); +GLAPI void APIENTRY glPrioritizeTexturesxOES (GLsizei n, const GLuint *textures, const GLfixed *priorities); +GLAPI void APIENTRY glRasterPos2xOES (GLfixed x, GLfixed y); +GLAPI void APIENTRY glRasterPos2xvOES (const GLfixed *coords); +GLAPI void APIENTRY glRasterPos3xOES (GLfixed x, GLfixed y, GLfixed z); +GLAPI void APIENTRY glRasterPos3xvOES (const GLfixed *coords); +GLAPI void APIENTRY glRasterPos4xOES (GLfixed x, GLfixed y, GLfixed z, GLfixed w); +GLAPI void APIENTRY glRasterPos4xvOES (const GLfixed *coords); +GLAPI void APIENTRY glRectxOES (GLfixed x1, GLfixed y1, GLfixed x2, GLfixed y2); +GLAPI void APIENTRY glRectxvOES (const GLfixed *v1, const GLfixed *v2); +GLAPI void APIENTRY glTexCoord1xOES (GLfixed s); +GLAPI void APIENTRY glTexCoord1xvOES (const GLfixed *coords); +GLAPI void APIENTRY glTexCoord2xOES (GLfixed s, GLfixed t); +GLAPI void APIENTRY glTexCoord2xvOES (const GLfixed *coords); +GLAPI void APIENTRY glTexCoord3xOES (GLfixed s, GLfixed t, GLfixed r); +GLAPI void APIENTRY glTexCoord3xvOES (const GLfixed *coords); +GLAPI void APIENTRY glTexCoord4xOES (GLfixed s, GLfixed t, GLfixed r, GLfixed q); +GLAPI void APIENTRY glTexCoord4xvOES (const GLfixed *coords); +GLAPI void APIENTRY glTexGenxOES (GLenum coord, GLenum pname, GLfixed param); +GLAPI void APIENTRY glTexGenxvOES (GLenum coord, GLenum pname, const GLfixed *params); +GLAPI void APIENTRY glVertex2xOES (GLfixed x); +GLAPI void APIENTRY glVertex2xvOES (const GLfixed *coords); +GLAPI void APIENTRY glVertex3xOES (GLfixed x, GLfixed y); +GLAPI void APIENTRY glVertex3xvOES (const GLfixed *coords); +GLAPI void APIENTRY glVertex4xOES (GLfixed x, GLfixed y, GLfixed z); +GLAPI void APIENTRY glVertex4xvOES (const GLfixed *coords); +#endif +#endif /* GL_OES_fixed_point */ + +#ifndef GL_OES_query_matrix +#define GL_OES_query_matrix 1 +typedef GLbitfield (APIENTRYP PFNGLQUERYMATRIXXOESPROC) (GLfixed *mantissa, GLint *exponent); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLbitfield APIENTRY glQueryMatrixxOES (GLfixed *mantissa, GLint *exponent); +#endif +#endif /* GL_OES_query_matrix */ + +#ifndef GL_OES_read_format +#define GL_OES_read_format 1 +#define GL_IMPLEMENTATION_COLOR_READ_TYPE_OES 0x8B9A +#define GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES 0x8B9B +#endif /* GL_OES_read_format */ + +#ifndef GL_OES_single_precision +#define GL_OES_single_precision 1 +typedef void (APIENTRYP PFNGLCLEARDEPTHFOESPROC) (GLclampf depth); +typedef void (APIENTRYP PFNGLCLIPPLANEFOESPROC) (GLenum plane, const GLfloat *equation); +typedef void (APIENTRYP PFNGLDEPTHRANGEFOESPROC) (GLclampf n, GLclampf f); +typedef void (APIENTRYP PFNGLFRUSTUMFOESPROC) (GLfloat l, GLfloat r, GLfloat b, GLfloat t, GLfloat n, GLfloat f); +typedef void (APIENTRYP PFNGLGETCLIPPLANEFOESPROC) (GLenum plane, GLfloat *equation); +typedef void (APIENTRYP PFNGLORTHOFOESPROC) (GLfloat l, GLfloat r, GLfloat b, GLfloat t, GLfloat n, GLfloat f); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glClearDepthfOES (GLclampf depth); +GLAPI void APIENTRY glClipPlanefOES (GLenum plane, const GLfloat *equation); +GLAPI void APIENTRY glDepthRangefOES (GLclampf n, GLclampf f); +GLAPI void APIENTRY glFrustumfOES (GLfloat l, GLfloat r, GLfloat b, GLfloat t, GLfloat n, GLfloat f); +GLAPI void APIENTRY glGetClipPlanefOES (GLenum plane, GLfloat *equation); +GLAPI void APIENTRY glOrthofOES (GLfloat l, GLfloat r, GLfloat b, GLfloat t, GLfloat n, GLfloat f); +#endif +#endif /* GL_OES_single_precision */ + +#ifndef GL_3DFX_multisample +#define GL_3DFX_multisample 1 +#define GL_MULTISAMPLE_3DFX 0x86B2 +#define GL_SAMPLE_BUFFERS_3DFX 0x86B3 +#define GL_SAMPLES_3DFX 0x86B4 +#define GL_MULTISAMPLE_BIT_3DFX 0x20000000 +#endif /* GL_3DFX_multisample */ + +#ifndef GL_3DFX_tbuffer +#define GL_3DFX_tbuffer 1 +typedef void (APIENTRYP PFNGLTBUFFERMASK3DFXPROC) (GLuint mask); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTbufferMask3DFX (GLuint mask); +#endif +#endif /* GL_3DFX_tbuffer */ + +#ifndef GL_3DFX_texture_compression_FXT1 +#define GL_3DFX_texture_compression_FXT1 1 +#define GL_COMPRESSED_RGB_FXT1_3DFX 0x86B0 +#define GL_COMPRESSED_RGBA_FXT1_3DFX 0x86B1 +#endif /* GL_3DFX_texture_compression_FXT1 */ + +#ifndef GL_AMD_blend_minmax_factor +#define GL_AMD_blend_minmax_factor 1 +#define GL_FACTOR_MIN_AMD 0x901C +#define GL_FACTOR_MAX_AMD 0x901D +#endif /* GL_AMD_blend_minmax_factor */ + +#ifndef GL_AMD_conservative_depth +#define GL_AMD_conservative_depth 1 +#endif /* GL_AMD_conservative_depth */ + +#ifndef GL_AMD_debug_output +#define GL_AMD_debug_output 1 +typedef void (APIENTRY *GLDEBUGPROCAMD)(GLuint id,GLenum category,GLenum severity,GLsizei length,const GLchar *message,void *userParam); +#define GL_MAX_DEBUG_MESSAGE_LENGTH_AMD 0x9143 +#define GL_MAX_DEBUG_LOGGED_MESSAGES_AMD 0x9144 +#define GL_DEBUG_LOGGED_MESSAGES_AMD 0x9145 +#define GL_DEBUG_SEVERITY_HIGH_AMD 0x9146 +#define GL_DEBUG_SEVERITY_MEDIUM_AMD 0x9147 +#define GL_DEBUG_SEVERITY_LOW_AMD 0x9148 +#define GL_DEBUG_CATEGORY_API_ERROR_AMD 0x9149 +#define GL_DEBUG_CATEGORY_WINDOW_SYSTEM_AMD 0x914A +#define GL_DEBUG_CATEGORY_DEPRECATION_AMD 0x914B +#define GL_DEBUG_CATEGORY_UNDEFINED_BEHAVIOR_AMD 0x914C +#define GL_DEBUG_CATEGORY_PERFORMANCE_AMD 0x914D +#define GL_DEBUG_CATEGORY_SHADER_COMPILER_AMD 0x914E +#define GL_DEBUG_CATEGORY_APPLICATION_AMD 0x914F +#define GL_DEBUG_CATEGORY_OTHER_AMD 0x9150 +typedef void (APIENTRYP PFNGLDEBUGMESSAGEENABLEAMDPROC) (GLenum category, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTAMDPROC) (GLenum category, GLenum severity, GLuint id, GLsizei length, const GLchar *buf); +typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKAMDPROC) (GLDEBUGPROCAMD callback, void *userParam); +typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGAMDPROC) (GLuint count, GLsizei bufsize, GLenum *categories, GLuint *severities, GLuint *ids, GLsizei *lengths, GLchar *message); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDebugMessageEnableAMD (GLenum category, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +GLAPI void APIENTRY glDebugMessageInsertAMD (GLenum category, GLenum severity, GLuint id, GLsizei length, const GLchar *buf); +GLAPI void APIENTRY glDebugMessageCallbackAMD (GLDEBUGPROCAMD callback, void *userParam); +GLAPI GLuint APIENTRY glGetDebugMessageLogAMD (GLuint count, GLsizei bufsize, GLenum *categories, GLuint *severities, GLuint *ids, GLsizei *lengths, GLchar *message); +#endif +#endif /* GL_AMD_debug_output */ + +#ifndef GL_AMD_depth_clamp_separate +#define GL_AMD_depth_clamp_separate 1 +#define GL_DEPTH_CLAMP_NEAR_AMD 0x901E +#define GL_DEPTH_CLAMP_FAR_AMD 0x901F +#endif /* GL_AMD_depth_clamp_separate */ + +#ifndef GL_AMD_draw_buffers_blend +#define GL_AMD_draw_buffers_blend 1 +typedef void (APIENTRYP PFNGLBLENDFUNCINDEXEDAMDPROC) (GLuint buf, GLenum src, GLenum dst); +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINDEXEDAMDPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +typedef void (APIENTRYP PFNGLBLENDEQUATIONINDEXEDAMDPROC) (GLuint buf, GLenum mode); +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEINDEXEDAMDPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendFuncIndexedAMD (GLuint buf, GLenum src, GLenum dst); +GLAPI void APIENTRY glBlendFuncSeparateIndexedAMD (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +GLAPI void APIENTRY glBlendEquationIndexedAMD (GLuint buf, GLenum mode); +GLAPI void APIENTRY glBlendEquationSeparateIndexedAMD (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +#endif +#endif /* GL_AMD_draw_buffers_blend */ + +#ifndef GL_AMD_framebuffer_sample_positions +#define GL_AMD_framebuffer_sample_positions 1 +#define GL_SUBSAMPLE_DISTANCE_AMD 0x883F +#define GL_PIXELS_PER_SAMPLE_PATTERN_X_AMD 0x91AE +#define GL_PIXELS_PER_SAMPLE_PATTERN_Y_AMD 0x91AF +#define GL_ALL_PIXELS_AMD 0xFFFFFFFF +typedef void (APIENTRYP PFNGLFRAMEBUFFERSAMPLEPOSITIONSFVAMDPROC) (GLenum target, GLuint numsamples, GLuint pixelindex, const GLfloat *values); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERSAMPLEPOSITIONSFVAMDPROC) (GLuint framebuffer, GLuint numsamples, GLuint pixelindex, const GLfloat *values); +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERFVAMDPROC) (GLenum target, GLenum pname, GLuint numsamples, GLuint pixelindex, GLsizei size, GLfloat *values); +typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERPARAMETERFVAMDPROC) (GLuint framebuffer, GLenum pname, GLuint numsamples, GLuint pixelindex, GLsizei size, GLfloat *values); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFramebufferSamplePositionsfvAMD (GLenum target, GLuint numsamples, GLuint pixelindex, const GLfloat *values); +GLAPI void APIENTRY glNamedFramebufferSamplePositionsfvAMD (GLuint framebuffer, GLuint numsamples, GLuint pixelindex, const GLfloat *values); +GLAPI void APIENTRY glGetFramebufferParameterfvAMD (GLenum target, GLenum pname, GLuint numsamples, GLuint pixelindex, GLsizei size, GLfloat *values); +GLAPI void APIENTRY glGetNamedFramebufferParameterfvAMD (GLuint framebuffer, GLenum pname, GLuint numsamples, GLuint pixelindex, GLsizei size, GLfloat *values); +#endif +#endif /* GL_AMD_framebuffer_sample_positions */ + +#ifndef GL_AMD_gcn_shader +#define GL_AMD_gcn_shader 1 +#endif /* GL_AMD_gcn_shader */ + +#ifndef GL_AMD_gpu_shader_half_float +#define GL_AMD_gpu_shader_half_float 1 +#define GL_FLOAT16_NV 0x8FF8 +#define GL_FLOAT16_VEC2_NV 0x8FF9 +#define GL_FLOAT16_VEC3_NV 0x8FFA +#define GL_FLOAT16_VEC4_NV 0x8FFB +#define GL_FLOAT16_MAT2_AMD 0x91C5 +#define GL_FLOAT16_MAT3_AMD 0x91C6 +#define GL_FLOAT16_MAT4_AMD 0x91C7 +#define GL_FLOAT16_MAT2x3_AMD 0x91C8 +#define GL_FLOAT16_MAT2x4_AMD 0x91C9 +#define GL_FLOAT16_MAT3x2_AMD 0x91CA +#define GL_FLOAT16_MAT3x4_AMD 0x91CB +#define GL_FLOAT16_MAT4x2_AMD 0x91CC +#define GL_FLOAT16_MAT4x3_AMD 0x91CD +#endif /* GL_AMD_gpu_shader_half_float */ + +#ifndef GL_AMD_gpu_shader_int64 +#define GL_AMD_gpu_shader_int64 1 +typedef int64_t GLint64EXT; +#define GL_INT64_NV 0x140E +#define GL_UNSIGNED_INT64_NV 0x140F +#define GL_INT8_NV 0x8FE0 +#define GL_INT8_VEC2_NV 0x8FE1 +#define GL_INT8_VEC3_NV 0x8FE2 +#define GL_INT8_VEC4_NV 0x8FE3 +#define GL_INT16_NV 0x8FE4 +#define GL_INT16_VEC2_NV 0x8FE5 +#define GL_INT16_VEC3_NV 0x8FE6 +#define GL_INT16_VEC4_NV 0x8FE7 +#define GL_INT64_VEC2_NV 0x8FE9 +#define GL_INT64_VEC3_NV 0x8FEA +#define GL_INT64_VEC4_NV 0x8FEB +#define GL_UNSIGNED_INT8_NV 0x8FEC +#define GL_UNSIGNED_INT8_VEC2_NV 0x8FED +#define GL_UNSIGNED_INT8_VEC3_NV 0x8FEE +#define GL_UNSIGNED_INT8_VEC4_NV 0x8FEF +#define GL_UNSIGNED_INT16_NV 0x8FF0 +#define GL_UNSIGNED_INT16_VEC2_NV 0x8FF1 +#define GL_UNSIGNED_INT16_VEC3_NV 0x8FF2 +#define GL_UNSIGNED_INT16_VEC4_NV 0x8FF3 +#define GL_UNSIGNED_INT64_VEC2_NV 0x8FF5 +#define GL_UNSIGNED_INT64_VEC3_NV 0x8FF6 +#define GL_UNSIGNED_INT64_VEC4_NV 0x8FF7 +typedef void (APIENTRYP PFNGLUNIFORM1I64NVPROC) (GLint location, GLint64EXT x); +typedef void (APIENTRYP PFNGLUNIFORM2I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y); +typedef void (APIENTRYP PFNGLUNIFORM3I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); +typedef void (APIENTRYP PFNGLUNIFORM4I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +typedef void (APIENTRYP PFNGLUNIFORM1I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM2I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM3I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM4I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM1UI64NVPROC) (GLint location, GLuint64EXT x); +typedef void (APIENTRYP PFNGLUNIFORM2UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y); +typedef void (APIENTRYP PFNGLUNIFORM3UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +typedef void (APIENTRYP PFNGLUNIFORM4UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +typedef void (APIENTRYP PFNGLUNIFORM1UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM2UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM3UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM4UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLGETUNIFORMI64VNVPROC) (GLuint program, GLint location, GLint64EXT *params); +typedef void (APIENTRYP PFNGLGETUNIFORMUI64VNVPROC) (GLuint program, GLint location, GLuint64EXT *params); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1I64NVPROC) (GLuint program, GLint location, GLint64EXT x); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glUniform1i64NV (GLint location, GLint64EXT x); +GLAPI void APIENTRY glUniform2i64NV (GLint location, GLint64EXT x, GLint64EXT y); +GLAPI void APIENTRY glUniform3i64NV (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); +GLAPI void APIENTRY glUniform4i64NV (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +GLAPI void APIENTRY glUniform1i64vNV (GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glUniform2i64vNV (GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glUniform3i64vNV (GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glUniform4i64vNV (GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glUniform1ui64NV (GLint location, GLuint64EXT x); +GLAPI void APIENTRY glUniform2ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y); +GLAPI void APIENTRY glUniform3ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +GLAPI void APIENTRY glUniform4ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +GLAPI void APIENTRY glUniform1ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glUniform2ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glUniform3ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glUniform4ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glGetUniformi64vNV (GLuint program, GLint location, GLint64EXT *params); +GLAPI void APIENTRY glGetUniformui64vNV (GLuint program, GLint location, GLuint64EXT *params); +GLAPI void APIENTRY glProgramUniform1i64NV (GLuint program, GLint location, GLint64EXT x); +GLAPI void APIENTRY glProgramUniform2i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y); +GLAPI void APIENTRY glProgramUniform3i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); +GLAPI void APIENTRY glProgramUniform4i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +GLAPI void APIENTRY glProgramUniform1i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glProgramUniform2i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glProgramUniform3i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glProgramUniform4i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glProgramUniform1ui64NV (GLuint program, GLint location, GLuint64EXT x); +GLAPI void APIENTRY glProgramUniform2ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y); +GLAPI void APIENTRY glProgramUniform3ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +GLAPI void APIENTRY glProgramUniform4ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +GLAPI void APIENTRY glProgramUniform1ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glProgramUniform2ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glProgramUniform3ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glProgramUniform4ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +#endif +#endif /* GL_AMD_gpu_shader_int64 */ + +#ifndef GL_AMD_interleaved_elements +#define GL_AMD_interleaved_elements 1 +#define GL_VERTEX_ELEMENT_SWIZZLE_AMD 0x91A4 +#define GL_VERTEX_ID_SWIZZLE_AMD 0x91A5 +typedef void (APIENTRYP PFNGLVERTEXATTRIBPARAMETERIAMDPROC) (GLuint index, GLenum pname, GLint param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribParameteriAMD (GLuint index, GLenum pname, GLint param); +#endif +#endif /* GL_AMD_interleaved_elements */ + +#ifndef GL_AMD_multi_draw_indirect +#define GL_AMD_multi_draw_indirect 1 +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTAMDPROC) (GLenum mode, const void *indirect, GLsizei primcount, GLsizei stride); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTAMDPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei primcount, GLsizei stride); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiDrawArraysIndirectAMD (GLenum mode, const void *indirect, GLsizei primcount, GLsizei stride); +GLAPI void APIENTRY glMultiDrawElementsIndirectAMD (GLenum mode, GLenum type, const void *indirect, GLsizei primcount, GLsizei stride); +#endif +#endif /* GL_AMD_multi_draw_indirect */ + +#ifndef GL_AMD_name_gen_delete +#define GL_AMD_name_gen_delete 1 +#define GL_DATA_BUFFER_AMD 0x9151 +#define GL_PERFORMANCE_MONITOR_AMD 0x9152 +#define GL_QUERY_OBJECT_AMD 0x9153 +#define GL_VERTEX_ARRAY_OBJECT_AMD 0x9154 +#define GL_SAMPLER_OBJECT_AMD 0x9155 +typedef void (APIENTRYP PFNGLGENNAMESAMDPROC) (GLenum identifier, GLuint num, GLuint *names); +typedef void (APIENTRYP PFNGLDELETENAMESAMDPROC) (GLenum identifier, GLuint num, const GLuint *names); +typedef GLboolean (APIENTRYP PFNGLISNAMEAMDPROC) (GLenum identifier, GLuint name); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenNamesAMD (GLenum identifier, GLuint num, GLuint *names); +GLAPI void APIENTRY glDeleteNamesAMD (GLenum identifier, GLuint num, const GLuint *names); +GLAPI GLboolean APIENTRY glIsNameAMD (GLenum identifier, GLuint name); +#endif +#endif /* GL_AMD_name_gen_delete */ + +#ifndef GL_AMD_occlusion_query_event +#define GL_AMD_occlusion_query_event 1 +#define GL_OCCLUSION_QUERY_EVENT_MASK_AMD 0x874F +#define GL_QUERY_DEPTH_PASS_EVENT_BIT_AMD 0x00000001 +#define GL_QUERY_DEPTH_FAIL_EVENT_BIT_AMD 0x00000002 +#define GL_QUERY_STENCIL_FAIL_EVENT_BIT_AMD 0x00000004 +#define GL_QUERY_DEPTH_BOUNDS_FAIL_EVENT_BIT_AMD 0x00000008 +#define GL_QUERY_ALL_EVENT_BITS_AMD 0xFFFFFFFF +typedef void (APIENTRYP PFNGLQUERYOBJECTPARAMETERUIAMDPROC) (GLenum target, GLuint id, GLenum pname, GLuint param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glQueryObjectParameteruiAMD (GLenum target, GLuint id, GLenum pname, GLuint param); +#endif +#endif /* GL_AMD_occlusion_query_event */ + +#ifndef GL_AMD_performance_monitor +#define GL_AMD_performance_monitor 1 +#define GL_COUNTER_TYPE_AMD 0x8BC0 +#define GL_COUNTER_RANGE_AMD 0x8BC1 +#define GL_UNSIGNED_INT64_AMD 0x8BC2 +#define GL_PERCENTAGE_AMD 0x8BC3 +#define GL_PERFMON_RESULT_AVAILABLE_AMD 0x8BC4 +#define GL_PERFMON_RESULT_SIZE_AMD 0x8BC5 +#define GL_PERFMON_RESULT_AMD 0x8BC6 +typedef void (APIENTRYP PFNGLGETPERFMONITORGROUPSAMDPROC) (GLint *numGroups, GLsizei groupsSize, GLuint *groups); +typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERSAMDPROC) (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters); +typedef void (APIENTRYP PFNGLGETPERFMONITORGROUPSTRINGAMDPROC) (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString); +typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC) (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString); +typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERINFOAMDPROC) (GLuint group, GLuint counter, GLenum pname, void *data); +typedef void (APIENTRYP PFNGLGENPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors); +typedef void (APIENTRYP PFNGLDELETEPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors); +typedef void (APIENTRYP PFNGLSELECTPERFMONITORCOUNTERSAMDPROC) (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList); +typedef void (APIENTRYP PFNGLBEGINPERFMONITORAMDPROC) (GLuint monitor); +typedef void (APIENTRYP PFNGLENDPERFMONITORAMDPROC) (GLuint monitor); +typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERDATAAMDPROC) (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetPerfMonitorGroupsAMD (GLint *numGroups, GLsizei groupsSize, GLuint *groups); +GLAPI void APIENTRY glGetPerfMonitorCountersAMD (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters); +GLAPI void APIENTRY glGetPerfMonitorGroupStringAMD (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString); +GLAPI void APIENTRY glGetPerfMonitorCounterStringAMD (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString); +GLAPI void APIENTRY glGetPerfMonitorCounterInfoAMD (GLuint group, GLuint counter, GLenum pname, void *data); +GLAPI void APIENTRY glGenPerfMonitorsAMD (GLsizei n, GLuint *monitors); +GLAPI void APIENTRY glDeletePerfMonitorsAMD (GLsizei n, GLuint *monitors); +GLAPI void APIENTRY glSelectPerfMonitorCountersAMD (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList); +GLAPI void APIENTRY glBeginPerfMonitorAMD (GLuint monitor); +GLAPI void APIENTRY glEndPerfMonitorAMD (GLuint monitor); +GLAPI void APIENTRY glGetPerfMonitorCounterDataAMD (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten); +#endif +#endif /* GL_AMD_performance_monitor */ + +#ifndef GL_AMD_pinned_memory +#define GL_AMD_pinned_memory 1 +#define GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD 0x9160 +#endif /* GL_AMD_pinned_memory */ + +#ifndef GL_AMD_query_buffer_object +#define GL_AMD_query_buffer_object 1 +#define GL_QUERY_BUFFER_AMD 0x9192 +#define GL_QUERY_BUFFER_BINDING_AMD 0x9193 +#define GL_QUERY_RESULT_NO_WAIT_AMD 0x9194 +#endif /* GL_AMD_query_buffer_object */ + +#ifndef GL_AMD_sample_positions +#define GL_AMD_sample_positions 1 +typedef void (APIENTRYP PFNGLSETMULTISAMPLEFVAMDPROC) (GLenum pname, GLuint index, const GLfloat *val); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSetMultisamplefvAMD (GLenum pname, GLuint index, const GLfloat *val); +#endif +#endif /* GL_AMD_sample_positions */ + +#ifndef GL_AMD_seamless_cubemap_per_texture +#define GL_AMD_seamless_cubemap_per_texture 1 +#endif /* GL_AMD_seamless_cubemap_per_texture */ + +#ifndef GL_AMD_shader_atomic_counter_ops +#define GL_AMD_shader_atomic_counter_ops 1 +#endif /* GL_AMD_shader_atomic_counter_ops */ + +#ifndef GL_AMD_shader_ballot +#define GL_AMD_shader_ballot 1 +#endif /* GL_AMD_shader_ballot */ + +#ifndef GL_AMD_shader_explicit_vertex_parameter +#define GL_AMD_shader_explicit_vertex_parameter 1 +#endif /* GL_AMD_shader_explicit_vertex_parameter */ + +#ifndef GL_AMD_shader_stencil_export +#define GL_AMD_shader_stencil_export 1 +#endif /* GL_AMD_shader_stencil_export */ + +#ifndef GL_AMD_shader_trinary_minmax +#define GL_AMD_shader_trinary_minmax 1 +#endif /* GL_AMD_shader_trinary_minmax */ + +#ifndef GL_AMD_sparse_texture +#define GL_AMD_sparse_texture 1 +#define GL_VIRTUAL_PAGE_SIZE_X_AMD 0x9195 +#define GL_VIRTUAL_PAGE_SIZE_Y_AMD 0x9196 +#define GL_VIRTUAL_PAGE_SIZE_Z_AMD 0x9197 +#define GL_MAX_SPARSE_TEXTURE_SIZE_AMD 0x9198 +#define GL_MAX_SPARSE_3D_TEXTURE_SIZE_AMD 0x9199 +#define GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS 0x919A +#define GL_MIN_SPARSE_LEVEL_AMD 0x919B +#define GL_MIN_LOD_WARNING_AMD 0x919C +#define GL_TEXTURE_STORAGE_SPARSE_BIT_AMD 0x00000001 +typedef void (APIENTRYP PFNGLTEXSTORAGESPARSEAMDPROC) (GLenum target, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLsizei layers, GLbitfield flags); +typedef void (APIENTRYP PFNGLTEXTURESTORAGESPARSEAMDPROC) (GLuint texture, GLenum target, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLsizei layers, GLbitfield flags); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexStorageSparseAMD (GLenum target, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLsizei layers, GLbitfield flags); +GLAPI void APIENTRY glTextureStorageSparseAMD (GLuint texture, GLenum target, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLsizei layers, GLbitfield flags); +#endif +#endif /* GL_AMD_sparse_texture */ + +#ifndef GL_AMD_stencil_operation_extended +#define GL_AMD_stencil_operation_extended 1 +#define GL_SET_AMD 0x874A +#define GL_REPLACE_VALUE_AMD 0x874B +#define GL_STENCIL_OP_VALUE_AMD 0x874C +#define GL_STENCIL_BACK_OP_VALUE_AMD 0x874D +typedef void (APIENTRYP PFNGLSTENCILOPVALUEAMDPROC) (GLenum face, GLuint value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glStencilOpValueAMD (GLenum face, GLuint value); +#endif +#endif /* GL_AMD_stencil_operation_extended */ + +#ifndef GL_AMD_texture_gather_bias_lod +#define GL_AMD_texture_gather_bias_lod 1 +#endif /* GL_AMD_texture_gather_bias_lod */ + +#ifndef GL_AMD_texture_texture4 +#define GL_AMD_texture_texture4 1 +#endif /* GL_AMD_texture_texture4 */ + +#ifndef GL_AMD_transform_feedback3_lines_triangles +#define GL_AMD_transform_feedback3_lines_triangles 1 +#endif /* GL_AMD_transform_feedback3_lines_triangles */ + +#ifndef GL_AMD_transform_feedback4 +#define GL_AMD_transform_feedback4 1 +#define GL_STREAM_RASTERIZATION_AMD 0x91A0 +#endif /* GL_AMD_transform_feedback4 */ + +#ifndef GL_AMD_vertex_shader_layer +#define GL_AMD_vertex_shader_layer 1 +#endif /* GL_AMD_vertex_shader_layer */ + +#ifndef GL_AMD_vertex_shader_tessellator +#define GL_AMD_vertex_shader_tessellator 1 +#define GL_SAMPLER_BUFFER_AMD 0x9001 +#define GL_INT_SAMPLER_BUFFER_AMD 0x9002 +#define GL_UNSIGNED_INT_SAMPLER_BUFFER_AMD 0x9003 +#define GL_TESSELLATION_MODE_AMD 0x9004 +#define GL_TESSELLATION_FACTOR_AMD 0x9005 +#define GL_DISCRETE_AMD 0x9006 +#define GL_CONTINUOUS_AMD 0x9007 +typedef void (APIENTRYP PFNGLTESSELLATIONFACTORAMDPROC) (GLfloat factor); +typedef void (APIENTRYP PFNGLTESSELLATIONMODEAMDPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTessellationFactorAMD (GLfloat factor); +GLAPI void APIENTRY glTessellationModeAMD (GLenum mode); +#endif +#endif /* GL_AMD_vertex_shader_tessellator */ + +#ifndef GL_AMD_vertex_shader_viewport_index +#define GL_AMD_vertex_shader_viewport_index 1 +#endif /* GL_AMD_vertex_shader_viewport_index */ + +#ifndef GL_APPLE_aux_depth_stencil +#define GL_APPLE_aux_depth_stencil 1 +#define GL_AUX_DEPTH_STENCIL_APPLE 0x8A14 +#endif /* GL_APPLE_aux_depth_stencil */ + +#ifndef GL_APPLE_client_storage +#define GL_APPLE_client_storage 1 +#define GL_UNPACK_CLIENT_STORAGE_APPLE 0x85B2 +#endif /* GL_APPLE_client_storage */ + +#ifndef GL_APPLE_element_array +#define GL_APPLE_element_array 1 +#define GL_ELEMENT_ARRAY_APPLE 0x8A0C +#define GL_ELEMENT_ARRAY_TYPE_APPLE 0x8A0D +#define GL_ELEMENT_ARRAY_POINTER_APPLE 0x8A0E +typedef void (APIENTRYP PFNGLELEMENTPOINTERAPPLEPROC) (GLenum type, const void *pointer); +typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, GLint first, GLsizei count); +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); +typedef void (APIENTRYP PFNGLMULTIDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glElementPointerAPPLE (GLenum type, const void *pointer); +GLAPI void APIENTRY glDrawElementArrayAPPLE (GLenum mode, GLint first, GLsizei count); +GLAPI void APIENTRY glDrawRangeElementArrayAPPLE (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count); +GLAPI void APIENTRY glMultiDrawElementArrayAPPLE (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); +GLAPI void APIENTRY glMultiDrawRangeElementArrayAPPLE (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount); +#endif +#endif /* GL_APPLE_element_array */ + +#ifndef GL_APPLE_fence +#define GL_APPLE_fence 1 +#define GL_DRAW_PIXELS_APPLE 0x8A0A +#define GL_FENCE_APPLE 0x8A0B +typedef void (APIENTRYP PFNGLGENFENCESAPPLEPROC) (GLsizei n, GLuint *fences); +typedef void (APIENTRYP PFNGLDELETEFENCESAPPLEPROC) (GLsizei n, const GLuint *fences); +typedef void (APIENTRYP PFNGLSETFENCEAPPLEPROC) (GLuint fence); +typedef GLboolean (APIENTRYP PFNGLISFENCEAPPLEPROC) (GLuint fence); +typedef GLboolean (APIENTRYP PFNGLTESTFENCEAPPLEPROC) (GLuint fence); +typedef void (APIENTRYP PFNGLFINISHFENCEAPPLEPROC) (GLuint fence); +typedef GLboolean (APIENTRYP PFNGLTESTOBJECTAPPLEPROC) (GLenum object, GLuint name); +typedef void (APIENTRYP PFNGLFINISHOBJECTAPPLEPROC) (GLenum object, GLint name); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenFencesAPPLE (GLsizei n, GLuint *fences); +GLAPI void APIENTRY glDeleteFencesAPPLE (GLsizei n, const GLuint *fences); +GLAPI void APIENTRY glSetFenceAPPLE (GLuint fence); +GLAPI GLboolean APIENTRY glIsFenceAPPLE (GLuint fence); +GLAPI GLboolean APIENTRY glTestFenceAPPLE (GLuint fence); +GLAPI void APIENTRY glFinishFenceAPPLE (GLuint fence); +GLAPI GLboolean APIENTRY glTestObjectAPPLE (GLenum object, GLuint name); +GLAPI void APIENTRY glFinishObjectAPPLE (GLenum object, GLint name); +#endif +#endif /* GL_APPLE_fence */ + +#ifndef GL_APPLE_float_pixels +#define GL_APPLE_float_pixels 1 +#define GL_HALF_APPLE 0x140B +#define GL_RGBA_FLOAT32_APPLE 0x8814 +#define GL_RGB_FLOAT32_APPLE 0x8815 +#define GL_ALPHA_FLOAT32_APPLE 0x8816 +#define GL_INTENSITY_FLOAT32_APPLE 0x8817 +#define GL_LUMINANCE_FLOAT32_APPLE 0x8818 +#define GL_LUMINANCE_ALPHA_FLOAT32_APPLE 0x8819 +#define GL_RGBA_FLOAT16_APPLE 0x881A +#define GL_RGB_FLOAT16_APPLE 0x881B +#define GL_ALPHA_FLOAT16_APPLE 0x881C +#define GL_INTENSITY_FLOAT16_APPLE 0x881D +#define GL_LUMINANCE_FLOAT16_APPLE 0x881E +#define GL_LUMINANCE_ALPHA_FLOAT16_APPLE 0x881F +#define GL_COLOR_FLOAT_APPLE 0x8A0F +#endif /* GL_APPLE_float_pixels */ + +#ifndef GL_APPLE_flush_buffer_range +#define GL_APPLE_flush_buffer_range 1 +#define GL_BUFFER_SERIALIZED_MODIFY_APPLE 0x8A12 +#define GL_BUFFER_FLUSHING_UNMAP_APPLE 0x8A13 +typedef void (APIENTRYP PFNGLBUFFERPARAMETERIAPPLEPROC) (GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEAPPLEPROC) (GLenum target, GLintptr offset, GLsizeiptr size); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBufferParameteriAPPLE (GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glFlushMappedBufferRangeAPPLE (GLenum target, GLintptr offset, GLsizeiptr size); +#endif +#endif /* GL_APPLE_flush_buffer_range */ + +#ifndef GL_APPLE_object_purgeable +#define GL_APPLE_object_purgeable 1 +#define GL_BUFFER_OBJECT_APPLE 0x85B3 +#define GL_RELEASED_APPLE 0x8A19 +#define GL_VOLATILE_APPLE 0x8A1A +#define GL_RETAINED_APPLE 0x8A1B +#define GL_UNDEFINED_APPLE 0x8A1C +#define GL_PURGEABLE_APPLE 0x8A1D +typedef GLenum (APIENTRYP PFNGLOBJECTPURGEABLEAPPLEPROC) (GLenum objectType, GLuint name, GLenum option); +typedef GLenum (APIENTRYP PFNGLOBJECTUNPURGEABLEAPPLEPROC) (GLenum objectType, GLuint name, GLenum option); +typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERIVAPPLEPROC) (GLenum objectType, GLuint name, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLenum APIENTRY glObjectPurgeableAPPLE (GLenum objectType, GLuint name, GLenum option); +GLAPI GLenum APIENTRY glObjectUnpurgeableAPPLE (GLenum objectType, GLuint name, GLenum option); +GLAPI void APIENTRY glGetObjectParameterivAPPLE (GLenum objectType, GLuint name, GLenum pname, GLint *params); +#endif +#endif /* GL_APPLE_object_purgeable */ + +#ifndef GL_APPLE_rgb_422 +#define GL_APPLE_rgb_422 1 +#define GL_RGB_422_APPLE 0x8A1F +#define GL_UNSIGNED_SHORT_8_8_APPLE 0x85BA +#define GL_UNSIGNED_SHORT_8_8_REV_APPLE 0x85BB +#define GL_RGB_RAW_422_APPLE 0x8A51 +#endif /* GL_APPLE_rgb_422 */ + +#ifndef GL_APPLE_row_bytes +#define GL_APPLE_row_bytes 1 +#define GL_PACK_ROW_BYTES_APPLE 0x8A15 +#define GL_UNPACK_ROW_BYTES_APPLE 0x8A16 +#endif /* GL_APPLE_row_bytes */ + +#ifndef GL_APPLE_specular_vector +#define GL_APPLE_specular_vector 1 +#define GL_LIGHT_MODEL_SPECULAR_VECTOR_APPLE 0x85B0 +#endif /* GL_APPLE_specular_vector */ + +#ifndef GL_APPLE_texture_range +#define GL_APPLE_texture_range 1 +#define GL_TEXTURE_RANGE_LENGTH_APPLE 0x85B7 +#define GL_TEXTURE_RANGE_POINTER_APPLE 0x85B8 +#define GL_TEXTURE_STORAGE_HINT_APPLE 0x85BC +#define GL_STORAGE_PRIVATE_APPLE 0x85BD +#define GL_STORAGE_CACHED_APPLE 0x85BE +#define GL_STORAGE_SHARED_APPLE 0x85BF +typedef void (APIENTRYP PFNGLTEXTURERANGEAPPLEPROC) (GLenum target, GLsizei length, const void *pointer); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERPOINTERVAPPLEPROC) (GLenum target, GLenum pname, void **params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTextureRangeAPPLE (GLenum target, GLsizei length, const void *pointer); +GLAPI void APIENTRY glGetTexParameterPointervAPPLE (GLenum target, GLenum pname, void **params); +#endif +#endif /* GL_APPLE_texture_range */ + +#ifndef GL_APPLE_transform_hint +#define GL_APPLE_transform_hint 1 +#define GL_TRANSFORM_HINT_APPLE 0x85B1 +#endif /* GL_APPLE_transform_hint */ + +#ifndef GL_APPLE_vertex_array_object +#define GL_APPLE_vertex_array_object 1 +#define GL_VERTEX_ARRAY_BINDING_APPLE 0x85B5 +typedef void (APIENTRYP PFNGLBINDVERTEXARRAYAPPLEPROC) (GLuint array); +typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays); +typedef void (APIENTRYP PFNGLGENVERTEXARRAYSAPPLEPROC) (GLsizei n, GLuint *arrays); +typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYAPPLEPROC) (GLuint array); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindVertexArrayAPPLE (GLuint array); +GLAPI void APIENTRY glDeleteVertexArraysAPPLE (GLsizei n, const GLuint *arrays); +GLAPI void APIENTRY glGenVertexArraysAPPLE (GLsizei n, GLuint *arrays); +GLAPI GLboolean APIENTRY glIsVertexArrayAPPLE (GLuint array); +#endif +#endif /* GL_APPLE_vertex_array_object */ + +#ifndef GL_APPLE_vertex_array_range +#define GL_APPLE_vertex_array_range 1 +#define GL_VERTEX_ARRAY_RANGE_APPLE 0x851D +#define GL_VERTEX_ARRAY_RANGE_LENGTH_APPLE 0x851E +#define GL_VERTEX_ARRAY_STORAGE_HINT_APPLE 0x851F +#define GL_VERTEX_ARRAY_RANGE_POINTER_APPLE 0x8521 +#define GL_STORAGE_CLIENT_APPLE 0x85B4 +typedef void (APIENTRYP PFNGLVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, void *pointer); +typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, void *pointer); +typedef void (APIENTRYP PFNGLVERTEXARRAYPARAMETERIAPPLEPROC) (GLenum pname, GLint param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexArrayRangeAPPLE (GLsizei length, void *pointer); +GLAPI void APIENTRY glFlushVertexArrayRangeAPPLE (GLsizei length, void *pointer); +GLAPI void APIENTRY glVertexArrayParameteriAPPLE (GLenum pname, GLint param); +#endif +#endif /* GL_APPLE_vertex_array_range */ + +#ifndef GL_APPLE_vertex_program_evaluators +#define GL_APPLE_vertex_program_evaluators 1 +#define GL_VERTEX_ATTRIB_MAP1_APPLE 0x8A00 +#define GL_VERTEX_ATTRIB_MAP2_APPLE 0x8A01 +#define GL_VERTEX_ATTRIB_MAP1_SIZE_APPLE 0x8A02 +#define GL_VERTEX_ATTRIB_MAP1_COEFF_APPLE 0x8A03 +#define GL_VERTEX_ATTRIB_MAP1_ORDER_APPLE 0x8A04 +#define GL_VERTEX_ATTRIB_MAP1_DOMAIN_APPLE 0x8A05 +#define GL_VERTEX_ATTRIB_MAP2_SIZE_APPLE 0x8A06 +#define GL_VERTEX_ATTRIB_MAP2_COEFF_APPLE 0x8A07 +#define GL_VERTEX_ATTRIB_MAP2_ORDER_APPLE 0x8A08 +#define GL_VERTEX_ATTRIB_MAP2_DOMAIN_APPLE 0x8A09 +typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBAPPLEPROC) (GLuint index, GLenum pname); +typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBAPPLEPROC) (GLuint index, GLenum pname); +typedef GLboolean (APIENTRYP PFNGLISVERTEXATTRIBENABLEDAPPLEPROC) (GLuint index, GLenum pname); +typedef void (APIENTRYP PFNGLMAPVERTEXATTRIB1DAPPLEPROC) (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points); +typedef void (APIENTRYP PFNGLMAPVERTEXATTRIB1FAPPLEPROC) (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points); +typedef void (APIENTRYP PFNGLMAPVERTEXATTRIB2DAPPLEPROC) (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points); +typedef void (APIENTRYP PFNGLMAPVERTEXATTRIB2FAPPLEPROC) (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glEnableVertexAttribAPPLE (GLuint index, GLenum pname); +GLAPI void APIENTRY glDisableVertexAttribAPPLE (GLuint index, GLenum pname); +GLAPI GLboolean APIENTRY glIsVertexAttribEnabledAPPLE (GLuint index, GLenum pname); +GLAPI void APIENTRY glMapVertexAttrib1dAPPLE (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points); +GLAPI void APIENTRY glMapVertexAttrib1fAPPLE (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points); +GLAPI void APIENTRY glMapVertexAttrib2dAPPLE (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points); +GLAPI void APIENTRY glMapVertexAttrib2fAPPLE (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points); +#endif +#endif /* GL_APPLE_vertex_program_evaluators */ + +#ifndef GL_APPLE_ycbcr_422 +#define GL_APPLE_ycbcr_422 1 +#define GL_YCBCR_422_APPLE 0x85B9 +#endif /* GL_APPLE_ycbcr_422 */ + +#ifndef GL_ATI_draw_buffers +#define GL_ATI_draw_buffers 1 +#define GL_MAX_DRAW_BUFFERS_ATI 0x8824 +#define GL_DRAW_BUFFER0_ATI 0x8825 +#define GL_DRAW_BUFFER1_ATI 0x8826 +#define GL_DRAW_BUFFER2_ATI 0x8827 +#define GL_DRAW_BUFFER3_ATI 0x8828 +#define GL_DRAW_BUFFER4_ATI 0x8829 +#define GL_DRAW_BUFFER5_ATI 0x882A +#define GL_DRAW_BUFFER6_ATI 0x882B +#define GL_DRAW_BUFFER7_ATI 0x882C +#define GL_DRAW_BUFFER8_ATI 0x882D +#define GL_DRAW_BUFFER9_ATI 0x882E +#define GL_DRAW_BUFFER10_ATI 0x882F +#define GL_DRAW_BUFFER11_ATI 0x8830 +#define GL_DRAW_BUFFER12_ATI 0x8831 +#define GL_DRAW_BUFFER13_ATI 0x8832 +#define GL_DRAW_BUFFER14_ATI 0x8833 +#define GL_DRAW_BUFFER15_ATI 0x8834 +typedef void (APIENTRYP PFNGLDRAWBUFFERSATIPROC) (GLsizei n, const GLenum *bufs); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawBuffersATI (GLsizei n, const GLenum *bufs); +#endif +#endif /* GL_ATI_draw_buffers */ + +#ifndef GL_ATI_element_array +#define GL_ATI_element_array 1 +#define GL_ELEMENT_ARRAY_ATI 0x8768 +#define GL_ELEMENT_ARRAY_TYPE_ATI 0x8769 +#define GL_ELEMENT_ARRAY_POINTER_ATI 0x876A +typedef void (APIENTRYP PFNGLELEMENTPOINTERATIPROC) (GLenum type, const void *pointer); +typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYATIPROC) (GLenum mode, GLsizei count); +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYATIPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glElementPointerATI (GLenum type, const void *pointer); +GLAPI void APIENTRY glDrawElementArrayATI (GLenum mode, GLsizei count); +GLAPI void APIENTRY glDrawRangeElementArrayATI (GLenum mode, GLuint start, GLuint end, GLsizei count); +#endif +#endif /* GL_ATI_element_array */ + +#ifndef GL_ATI_envmap_bumpmap +#define GL_ATI_envmap_bumpmap 1 +#define GL_BUMP_ROT_MATRIX_ATI 0x8775 +#define GL_BUMP_ROT_MATRIX_SIZE_ATI 0x8776 +#define GL_BUMP_NUM_TEX_UNITS_ATI 0x8777 +#define GL_BUMP_TEX_UNITS_ATI 0x8778 +#define GL_DUDV_ATI 0x8779 +#define GL_DU8DV8_ATI 0x877A +#define GL_BUMP_ENVMAP_ATI 0x877B +#define GL_BUMP_TARGET_ATI 0x877C +typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERIVATIPROC) (GLenum pname, const GLint *param); +typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERFVATIPROC) (GLenum pname, const GLfloat *param); +typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERIVATIPROC) (GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERFVATIPROC) (GLenum pname, GLfloat *param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexBumpParameterivATI (GLenum pname, const GLint *param); +GLAPI void APIENTRY glTexBumpParameterfvATI (GLenum pname, const GLfloat *param); +GLAPI void APIENTRY glGetTexBumpParameterivATI (GLenum pname, GLint *param); +GLAPI void APIENTRY glGetTexBumpParameterfvATI (GLenum pname, GLfloat *param); +#endif +#endif /* GL_ATI_envmap_bumpmap */ + +#ifndef GL_ATI_fragment_shader +#define GL_ATI_fragment_shader 1 +#define GL_FRAGMENT_SHADER_ATI 0x8920 +#define GL_REG_0_ATI 0x8921 +#define GL_REG_1_ATI 0x8922 +#define GL_REG_2_ATI 0x8923 +#define GL_REG_3_ATI 0x8924 +#define GL_REG_4_ATI 0x8925 +#define GL_REG_5_ATI 0x8926 +#define GL_REG_6_ATI 0x8927 +#define GL_REG_7_ATI 0x8928 +#define GL_REG_8_ATI 0x8929 +#define GL_REG_9_ATI 0x892A +#define GL_REG_10_ATI 0x892B +#define GL_REG_11_ATI 0x892C +#define GL_REG_12_ATI 0x892D +#define GL_REG_13_ATI 0x892E +#define GL_REG_14_ATI 0x892F +#define GL_REG_15_ATI 0x8930 +#define GL_REG_16_ATI 0x8931 +#define GL_REG_17_ATI 0x8932 +#define GL_REG_18_ATI 0x8933 +#define GL_REG_19_ATI 0x8934 +#define GL_REG_20_ATI 0x8935 +#define GL_REG_21_ATI 0x8936 +#define GL_REG_22_ATI 0x8937 +#define GL_REG_23_ATI 0x8938 +#define GL_REG_24_ATI 0x8939 +#define GL_REG_25_ATI 0x893A +#define GL_REG_26_ATI 0x893B +#define GL_REG_27_ATI 0x893C +#define GL_REG_28_ATI 0x893D +#define GL_REG_29_ATI 0x893E +#define GL_REG_30_ATI 0x893F +#define GL_REG_31_ATI 0x8940 +#define GL_CON_0_ATI 0x8941 +#define GL_CON_1_ATI 0x8942 +#define GL_CON_2_ATI 0x8943 +#define GL_CON_3_ATI 0x8944 +#define GL_CON_4_ATI 0x8945 +#define GL_CON_5_ATI 0x8946 +#define GL_CON_6_ATI 0x8947 +#define GL_CON_7_ATI 0x8948 +#define GL_CON_8_ATI 0x8949 +#define GL_CON_9_ATI 0x894A +#define GL_CON_10_ATI 0x894B +#define GL_CON_11_ATI 0x894C +#define GL_CON_12_ATI 0x894D +#define GL_CON_13_ATI 0x894E +#define GL_CON_14_ATI 0x894F +#define GL_CON_15_ATI 0x8950 +#define GL_CON_16_ATI 0x8951 +#define GL_CON_17_ATI 0x8952 +#define GL_CON_18_ATI 0x8953 +#define GL_CON_19_ATI 0x8954 +#define GL_CON_20_ATI 0x8955 +#define GL_CON_21_ATI 0x8956 +#define GL_CON_22_ATI 0x8957 +#define GL_CON_23_ATI 0x8958 +#define GL_CON_24_ATI 0x8959 +#define GL_CON_25_ATI 0x895A +#define GL_CON_26_ATI 0x895B +#define GL_CON_27_ATI 0x895C +#define GL_CON_28_ATI 0x895D +#define GL_CON_29_ATI 0x895E +#define GL_CON_30_ATI 0x895F +#define GL_CON_31_ATI 0x8960 +#define GL_MOV_ATI 0x8961 +#define GL_ADD_ATI 0x8963 +#define GL_MUL_ATI 0x8964 +#define GL_SUB_ATI 0x8965 +#define GL_DOT3_ATI 0x8966 +#define GL_DOT4_ATI 0x8967 +#define GL_MAD_ATI 0x8968 +#define GL_LERP_ATI 0x8969 +#define GL_CND_ATI 0x896A +#define GL_CND0_ATI 0x896B +#define GL_DOT2_ADD_ATI 0x896C +#define GL_SECONDARY_INTERPOLATOR_ATI 0x896D +#define GL_NUM_FRAGMENT_REGISTERS_ATI 0x896E +#define GL_NUM_FRAGMENT_CONSTANTS_ATI 0x896F +#define GL_NUM_PASSES_ATI 0x8970 +#define GL_NUM_INSTRUCTIONS_PER_PASS_ATI 0x8971 +#define GL_NUM_INSTRUCTIONS_TOTAL_ATI 0x8972 +#define GL_NUM_INPUT_INTERPOLATOR_COMPONENTS_ATI 0x8973 +#define GL_NUM_LOOPBACK_COMPONENTS_ATI 0x8974 +#define GL_COLOR_ALPHA_PAIRING_ATI 0x8975 +#define GL_SWIZZLE_STR_ATI 0x8976 +#define GL_SWIZZLE_STQ_ATI 0x8977 +#define GL_SWIZZLE_STR_DR_ATI 0x8978 +#define GL_SWIZZLE_STQ_DQ_ATI 0x8979 +#define GL_SWIZZLE_STRQ_ATI 0x897A +#define GL_SWIZZLE_STRQ_DQ_ATI 0x897B +#define GL_RED_BIT_ATI 0x00000001 +#define GL_GREEN_BIT_ATI 0x00000002 +#define GL_BLUE_BIT_ATI 0x00000004 +#define GL_2X_BIT_ATI 0x00000001 +#define GL_4X_BIT_ATI 0x00000002 +#define GL_8X_BIT_ATI 0x00000004 +#define GL_HALF_BIT_ATI 0x00000008 +#define GL_QUARTER_BIT_ATI 0x00000010 +#define GL_EIGHTH_BIT_ATI 0x00000020 +#define GL_SATURATE_BIT_ATI 0x00000040 +#define GL_COMP_BIT_ATI 0x00000002 +#define GL_NEGATE_BIT_ATI 0x00000004 +#define GL_BIAS_BIT_ATI 0x00000008 +typedef GLuint (APIENTRYP PFNGLGENFRAGMENTSHADERSATIPROC) (GLuint range); +typedef void (APIENTRYP PFNGLBINDFRAGMENTSHADERATIPROC) (GLuint id); +typedef void (APIENTRYP PFNGLDELETEFRAGMENTSHADERATIPROC) (GLuint id); +typedef void (APIENTRYP PFNGLBEGINFRAGMENTSHADERATIPROC) (void); +typedef void (APIENTRYP PFNGLENDFRAGMENTSHADERATIPROC) (void); +typedef void (APIENTRYP PFNGLPASSTEXCOORDATIPROC) (GLuint dst, GLuint coord, GLenum swizzle); +typedef void (APIENTRYP PFNGLSAMPLEMAPATIPROC) (GLuint dst, GLuint interp, GLenum swizzle); +typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod); +typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod); +typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod); +typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod); +typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod); +typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod); +typedef void (APIENTRYP PFNGLSETFRAGMENTSHADERCONSTANTATIPROC) (GLuint dst, const GLfloat *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLuint APIENTRY glGenFragmentShadersATI (GLuint range); +GLAPI void APIENTRY glBindFragmentShaderATI (GLuint id); +GLAPI void APIENTRY glDeleteFragmentShaderATI (GLuint id); +GLAPI void APIENTRY glBeginFragmentShaderATI (void); +GLAPI void APIENTRY glEndFragmentShaderATI (void); +GLAPI void APIENTRY glPassTexCoordATI (GLuint dst, GLuint coord, GLenum swizzle); +GLAPI void APIENTRY glSampleMapATI (GLuint dst, GLuint interp, GLenum swizzle); +GLAPI void APIENTRY glColorFragmentOp1ATI (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod); +GLAPI void APIENTRY glColorFragmentOp2ATI (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod); +GLAPI void APIENTRY glColorFragmentOp3ATI (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod); +GLAPI void APIENTRY glAlphaFragmentOp1ATI (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod); +GLAPI void APIENTRY glAlphaFragmentOp2ATI (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod); +GLAPI void APIENTRY glAlphaFragmentOp3ATI (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod); +GLAPI void APIENTRY glSetFragmentShaderConstantATI (GLuint dst, const GLfloat *value); +#endif +#endif /* GL_ATI_fragment_shader */ + +#ifndef GL_ATI_map_object_buffer +#define GL_ATI_map_object_buffer 1 +typedef void *(APIENTRYP PFNGLMAPOBJECTBUFFERATIPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLUNMAPOBJECTBUFFERATIPROC) (GLuint buffer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void *APIENTRY glMapObjectBufferATI (GLuint buffer); +GLAPI void APIENTRY glUnmapObjectBufferATI (GLuint buffer); +#endif +#endif /* GL_ATI_map_object_buffer */ + +#ifndef GL_ATI_meminfo +#define GL_ATI_meminfo 1 +#define GL_VBO_FREE_MEMORY_ATI 0x87FB +#define GL_TEXTURE_FREE_MEMORY_ATI 0x87FC +#define GL_RENDERBUFFER_FREE_MEMORY_ATI 0x87FD +#endif /* GL_ATI_meminfo */ + +#ifndef GL_ATI_pixel_format_float +#define GL_ATI_pixel_format_float 1 +#define GL_RGBA_FLOAT_MODE_ATI 0x8820 +#define GL_COLOR_CLEAR_UNCLAMPED_VALUE_ATI 0x8835 +#endif /* GL_ATI_pixel_format_float */ + +#ifndef GL_ATI_pn_triangles +#define GL_ATI_pn_triangles 1 +#define GL_PN_TRIANGLES_ATI 0x87F0 +#define GL_MAX_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F1 +#define GL_PN_TRIANGLES_POINT_MODE_ATI 0x87F2 +#define GL_PN_TRIANGLES_NORMAL_MODE_ATI 0x87F3 +#define GL_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F4 +#define GL_PN_TRIANGLES_POINT_MODE_LINEAR_ATI 0x87F5 +#define GL_PN_TRIANGLES_POINT_MODE_CUBIC_ATI 0x87F6 +#define GL_PN_TRIANGLES_NORMAL_MODE_LINEAR_ATI 0x87F7 +#define GL_PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATI 0x87F8 +typedef void (APIENTRYP PFNGLPNTRIANGLESIATIPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPNTRIANGLESFATIPROC) (GLenum pname, GLfloat param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPNTrianglesiATI (GLenum pname, GLint param); +GLAPI void APIENTRY glPNTrianglesfATI (GLenum pname, GLfloat param); +#endif +#endif /* GL_ATI_pn_triangles */ + +#ifndef GL_ATI_separate_stencil +#define GL_ATI_separate_stencil 1 +#define GL_STENCIL_BACK_FUNC_ATI 0x8800 +#define GL_STENCIL_BACK_FAIL_ATI 0x8801 +#define GL_STENCIL_BACK_PASS_DEPTH_FAIL_ATI 0x8802 +#define GL_STENCIL_BACK_PASS_DEPTH_PASS_ATI 0x8803 +typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEATIPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEATIPROC) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glStencilOpSeparateATI (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +GLAPI void APIENTRY glStencilFuncSeparateATI (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask); +#endif +#endif /* GL_ATI_separate_stencil */ + +#ifndef GL_ATI_text_fragment_shader +#define GL_ATI_text_fragment_shader 1 +#define GL_TEXT_FRAGMENT_SHADER_ATI 0x8200 +#endif /* GL_ATI_text_fragment_shader */ + +#ifndef GL_ATI_texture_env_combine3 +#define GL_ATI_texture_env_combine3 1 +#define GL_MODULATE_ADD_ATI 0x8744 +#define GL_MODULATE_SIGNED_ADD_ATI 0x8745 +#define GL_MODULATE_SUBTRACT_ATI 0x8746 +#endif /* GL_ATI_texture_env_combine3 */ + +#ifndef GL_ATI_texture_float +#define GL_ATI_texture_float 1 +#define GL_RGBA_FLOAT32_ATI 0x8814 +#define GL_RGB_FLOAT32_ATI 0x8815 +#define GL_ALPHA_FLOAT32_ATI 0x8816 +#define GL_INTENSITY_FLOAT32_ATI 0x8817 +#define GL_LUMINANCE_FLOAT32_ATI 0x8818 +#define GL_LUMINANCE_ALPHA_FLOAT32_ATI 0x8819 +#define GL_RGBA_FLOAT16_ATI 0x881A +#define GL_RGB_FLOAT16_ATI 0x881B +#define GL_ALPHA_FLOAT16_ATI 0x881C +#define GL_INTENSITY_FLOAT16_ATI 0x881D +#define GL_LUMINANCE_FLOAT16_ATI 0x881E +#define GL_LUMINANCE_ALPHA_FLOAT16_ATI 0x881F +#endif /* GL_ATI_texture_float */ + +#ifndef GL_ATI_texture_mirror_once +#define GL_ATI_texture_mirror_once 1 +#define GL_MIRROR_CLAMP_ATI 0x8742 +#define GL_MIRROR_CLAMP_TO_EDGE_ATI 0x8743 +#endif /* GL_ATI_texture_mirror_once */ + +#ifndef GL_ATI_vertex_array_object +#define GL_ATI_vertex_array_object 1 +#define GL_STATIC_ATI 0x8760 +#define GL_DYNAMIC_ATI 0x8761 +#define GL_PRESERVE_ATI 0x8762 +#define GL_DISCARD_ATI 0x8763 +#define GL_OBJECT_BUFFER_SIZE_ATI 0x8764 +#define GL_OBJECT_BUFFER_USAGE_ATI 0x8765 +#define GL_ARRAY_OBJECT_BUFFER_ATI 0x8766 +#define GL_ARRAY_OBJECT_OFFSET_ATI 0x8767 +typedef GLuint (APIENTRYP PFNGLNEWOBJECTBUFFERATIPROC) (GLsizei size, const void *pointer, GLenum usage); +typedef GLboolean (APIENTRYP PFNGLISOBJECTBUFFERATIPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLUPDATEOBJECTBUFFERATIPROC) (GLuint buffer, GLuint offset, GLsizei size, const void *pointer, GLenum preserve); +typedef void (APIENTRYP PFNGLGETOBJECTBUFFERFVATIPROC) (GLuint buffer, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETOBJECTBUFFERIVATIPROC) (GLuint buffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLFREEOBJECTBUFFERATIPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLARRAYOBJECTATIPROC) (GLenum array, GLint size, GLenum type, GLsizei stride, GLuint buffer, GLuint offset); +typedef void (APIENTRYP PFNGLGETARRAYOBJECTFVATIPROC) (GLenum array, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETARRAYOBJECTIVATIPROC) (GLenum array, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLVARIANTARRAYOBJECTATIPROC) (GLuint id, GLenum type, GLsizei stride, GLuint buffer, GLuint offset); +typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTFVATIPROC) (GLuint id, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTIVATIPROC) (GLuint id, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLuint APIENTRY glNewObjectBufferATI (GLsizei size, const void *pointer, GLenum usage); +GLAPI GLboolean APIENTRY glIsObjectBufferATI (GLuint buffer); +GLAPI void APIENTRY glUpdateObjectBufferATI (GLuint buffer, GLuint offset, GLsizei size, const void *pointer, GLenum preserve); +GLAPI void APIENTRY glGetObjectBufferfvATI (GLuint buffer, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetObjectBufferivATI (GLuint buffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glFreeObjectBufferATI (GLuint buffer); +GLAPI void APIENTRY glArrayObjectATI (GLenum array, GLint size, GLenum type, GLsizei stride, GLuint buffer, GLuint offset); +GLAPI void APIENTRY glGetArrayObjectfvATI (GLenum array, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetArrayObjectivATI (GLenum array, GLenum pname, GLint *params); +GLAPI void APIENTRY glVariantArrayObjectATI (GLuint id, GLenum type, GLsizei stride, GLuint buffer, GLuint offset); +GLAPI void APIENTRY glGetVariantArrayObjectfvATI (GLuint id, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetVariantArrayObjectivATI (GLuint id, GLenum pname, GLint *params); +#endif +#endif /* GL_ATI_vertex_array_object */ + +#ifndef GL_ATI_vertex_attrib_array_object +#define GL_ATI_vertex_attrib_array_object 1 +typedef void (APIENTRYP PFNGLVERTEXATTRIBARRAYOBJECTATIPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint buffer, GLuint offset); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTFVATIPROC) (GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTIVATIPROC) (GLuint index, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribArrayObjectATI (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint buffer, GLuint offset); +GLAPI void APIENTRY glGetVertexAttribArrayObjectfvATI (GLuint index, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetVertexAttribArrayObjectivATI (GLuint index, GLenum pname, GLint *params); +#endif +#endif /* GL_ATI_vertex_attrib_array_object */ + +#ifndef GL_ATI_vertex_streams +#define GL_ATI_vertex_streams 1 +#define GL_MAX_VERTEX_STREAMS_ATI 0x876B +#define GL_VERTEX_STREAM0_ATI 0x876C +#define GL_VERTEX_STREAM1_ATI 0x876D +#define GL_VERTEX_STREAM2_ATI 0x876E +#define GL_VERTEX_STREAM3_ATI 0x876F +#define GL_VERTEX_STREAM4_ATI 0x8770 +#define GL_VERTEX_STREAM5_ATI 0x8771 +#define GL_VERTEX_STREAM6_ATI 0x8772 +#define GL_VERTEX_STREAM7_ATI 0x8773 +#define GL_VERTEX_SOURCE_ATI 0x8774 +typedef void (APIENTRYP PFNGLVERTEXSTREAM1SATIPROC) (GLenum stream, GLshort x); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1IATIPROC) (GLenum stream, GLint x); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1FATIPROC) (GLenum stream, GLfloat x); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1DATIPROC) (GLenum stream, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2SATIPROC) (GLenum stream, GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2IATIPROC) (GLenum stream, GLint x, GLint y); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2FATIPROC) (GLenum stream, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2DATIPROC) (GLenum stream, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3IATIPROC) (GLenum stream, GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4IATIPROC) (GLenum stream, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3BATIPROC) (GLenum stream, GLbyte nx, GLbyte ny, GLbyte nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3BVATIPROC) (GLenum stream, const GLbyte *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3SATIPROC) (GLenum stream, GLshort nx, GLshort ny, GLshort nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3IATIPROC) (GLenum stream, GLint nx, GLint ny, GLint nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3FATIPROC) (GLenum stream, GLfloat nx, GLfloat ny, GLfloat nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3DATIPROC) (GLenum stream, GLdouble nx, GLdouble ny, GLdouble nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLCLIENTACTIVEVERTEXSTREAMATIPROC) (GLenum stream); +typedef void (APIENTRYP PFNGLVERTEXBLENDENVIATIPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLVERTEXBLENDENVFATIPROC) (GLenum pname, GLfloat param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexStream1sATI (GLenum stream, GLshort x); +GLAPI void APIENTRY glVertexStream1svATI (GLenum stream, const GLshort *coords); +GLAPI void APIENTRY glVertexStream1iATI (GLenum stream, GLint x); +GLAPI void APIENTRY glVertexStream1ivATI (GLenum stream, const GLint *coords); +GLAPI void APIENTRY glVertexStream1fATI (GLenum stream, GLfloat x); +GLAPI void APIENTRY glVertexStream1fvATI (GLenum stream, const GLfloat *coords); +GLAPI void APIENTRY glVertexStream1dATI (GLenum stream, GLdouble x); +GLAPI void APIENTRY glVertexStream1dvATI (GLenum stream, const GLdouble *coords); +GLAPI void APIENTRY glVertexStream2sATI (GLenum stream, GLshort x, GLshort y); +GLAPI void APIENTRY glVertexStream2svATI (GLenum stream, const GLshort *coords); +GLAPI void APIENTRY glVertexStream2iATI (GLenum stream, GLint x, GLint y); +GLAPI void APIENTRY glVertexStream2ivATI (GLenum stream, const GLint *coords); +GLAPI void APIENTRY glVertexStream2fATI (GLenum stream, GLfloat x, GLfloat y); +GLAPI void APIENTRY glVertexStream2fvATI (GLenum stream, const GLfloat *coords); +GLAPI void APIENTRY glVertexStream2dATI (GLenum stream, GLdouble x, GLdouble y); +GLAPI void APIENTRY glVertexStream2dvATI (GLenum stream, const GLdouble *coords); +GLAPI void APIENTRY glVertexStream3sATI (GLenum stream, GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glVertexStream3svATI (GLenum stream, const GLshort *coords); +GLAPI void APIENTRY glVertexStream3iATI (GLenum stream, GLint x, GLint y, GLint z); +GLAPI void APIENTRY glVertexStream3ivATI (GLenum stream, const GLint *coords); +GLAPI void APIENTRY glVertexStream3fATI (GLenum stream, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glVertexStream3fvATI (GLenum stream, const GLfloat *coords); +GLAPI void APIENTRY glVertexStream3dATI (GLenum stream, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glVertexStream3dvATI (GLenum stream, const GLdouble *coords); +GLAPI void APIENTRY glVertexStream4sATI (GLenum stream, GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI void APIENTRY glVertexStream4svATI (GLenum stream, const GLshort *coords); +GLAPI void APIENTRY glVertexStream4iATI (GLenum stream, GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glVertexStream4ivATI (GLenum stream, const GLint *coords); +GLAPI void APIENTRY glVertexStream4fATI (GLenum stream, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glVertexStream4fvATI (GLenum stream, const GLfloat *coords); +GLAPI void APIENTRY glVertexStream4dATI (GLenum stream, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glVertexStream4dvATI (GLenum stream, const GLdouble *coords); +GLAPI void APIENTRY glNormalStream3bATI (GLenum stream, GLbyte nx, GLbyte ny, GLbyte nz); +GLAPI void APIENTRY glNormalStream3bvATI (GLenum stream, const GLbyte *coords); +GLAPI void APIENTRY glNormalStream3sATI (GLenum stream, GLshort nx, GLshort ny, GLshort nz); +GLAPI void APIENTRY glNormalStream3svATI (GLenum stream, const GLshort *coords); +GLAPI void APIENTRY glNormalStream3iATI (GLenum stream, GLint nx, GLint ny, GLint nz); +GLAPI void APIENTRY glNormalStream3ivATI (GLenum stream, const GLint *coords); +GLAPI void APIENTRY glNormalStream3fATI (GLenum stream, GLfloat nx, GLfloat ny, GLfloat nz); +GLAPI void APIENTRY glNormalStream3fvATI (GLenum stream, const GLfloat *coords); +GLAPI void APIENTRY glNormalStream3dATI (GLenum stream, GLdouble nx, GLdouble ny, GLdouble nz); +GLAPI void APIENTRY glNormalStream3dvATI (GLenum stream, const GLdouble *coords); +GLAPI void APIENTRY glClientActiveVertexStreamATI (GLenum stream); +GLAPI void APIENTRY glVertexBlendEnviATI (GLenum pname, GLint param); +GLAPI void APIENTRY glVertexBlendEnvfATI (GLenum pname, GLfloat param); +#endif +#endif /* GL_ATI_vertex_streams */ + +#ifndef GL_EXT_422_pixels +#define GL_EXT_422_pixels 1 +#define GL_422_EXT 0x80CC +#define GL_422_REV_EXT 0x80CD +#define GL_422_AVERAGE_EXT 0x80CE +#define GL_422_REV_AVERAGE_EXT 0x80CF +#endif /* GL_EXT_422_pixels */ + +#ifndef GL_EXT_abgr +#define GL_EXT_abgr 1 +#define GL_ABGR_EXT 0x8000 +#endif /* GL_EXT_abgr */ + +#ifndef GL_EXT_bgra +#define GL_EXT_bgra 1 +#define GL_BGR_EXT 0x80E0 +#define GL_BGRA_EXT 0x80E1 +#endif /* GL_EXT_bgra */ + +#ifndef GL_EXT_bindable_uniform +#define GL_EXT_bindable_uniform 1 +#define GL_MAX_VERTEX_BINDABLE_UNIFORMS_EXT 0x8DE2 +#define GL_MAX_FRAGMENT_BINDABLE_UNIFORMS_EXT 0x8DE3 +#define GL_MAX_GEOMETRY_BINDABLE_UNIFORMS_EXT 0x8DE4 +#define GL_MAX_BINDABLE_UNIFORM_SIZE_EXT 0x8DED +#define GL_UNIFORM_BUFFER_EXT 0x8DEE +#define GL_UNIFORM_BUFFER_BINDING_EXT 0x8DEF +typedef void (APIENTRYP PFNGLUNIFORMBUFFEREXTPROC) (GLuint program, GLint location, GLuint buffer); +typedef GLint (APIENTRYP PFNGLGETUNIFORMBUFFERSIZEEXTPROC) (GLuint program, GLint location); +typedef GLintptr (APIENTRYP PFNGLGETUNIFORMOFFSETEXTPROC) (GLuint program, GLint location); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glUniformBufferEXT (GLuint program, GLint location, GLuint buffer); +GLAPI GLint APIENTRY glGetUniformBufferSizeEXT (GLuint program, GLint location); +GLAPI GLintptr APIENTRY glGetUniformOffsetEXT (GLuint program, GLint location); +#endif +#endif /* GL_EXT_bindable_uniform */ + +#ifndef GL_EXT_blend_color +#define GL_EXT_blend_color 1 +#define GL_CONSTANT_COLOR_EXT 0x8001 +#define GL_ONE_MINUS_CONSTANT_COLOR_EXT 0x8002 +#define GL_CONSTANT_ALPHA_EXT 0x8003 +#define GL_ONE_MINUS_CONSTANT_ALPHA_EXT 0x8004 +#define GL_BLEND_COLOR_EXT 0x8005 +typedef void (APIENTRYP PFNGLBLENDCOLOREXTPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendColorEXT (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +#endif +#endif /* GL_EXT_blend_color */ + +#ifndef GL_EXT_blend_equation_separate +#define GL_EXT_blend_equation_separate 1 +#define GL_BLEND_EQUATION_RGB_EXT 0x8009 +#define GL_BLEND_EQUATION_ALPHA_EXT 0x883D +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEEXTPROC) (GLenum modeRGB, GLenum modeAlpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendEquationSeparateEXT (GLenum modeRGB, GLenum modeAlpha); +#endif +#endif /* GL_EXT_blend_equation_separate */ + +#ifndef GL_EXT_blend_func_separate +#define GL_EXT_blend_func_separate 1 +#define GL_BLEND_DST_RGB_EXT 0x80C8 +#define GL_BLEND_SRC_RGB_EXT 0x80C9 +#define GL_BLEND_DST_ALPHA_EXT 0x80CA +#define GL_BLEND_SRC_ALPHA_EXT 0x80CB +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEEXTPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendFuncSeparateEXT (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +#endif +#endif /* GL_EXT_blend_func_separate */ + +#ifndef GL_EXT_blend_logic_op +#define GL_EXT_blend_logic_op 1 +#endif /* GL_EXT_blend_logic_op */ + +#ifndef GL_EXT_blend_minmax +#define GL_EXT_blend_minmax 1 +#define GL_MIN_EXT 0x8007 +#define GL_MAX_EXT 0x8008 +#define GL_FUNC_ADD_EXT 0x8006 +#define GL_BLEND_EQUATION_EXT 0x8009 +typedef void (APIENTRYP PFNGLBLENDEQUATIONEXTPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendEquationEXT (GLenum mode); +#endif +#endif /* GL_EXT_blend_minmax */ + +#ifndef GL_EXT_blend_subtract +#define GL_EXT_blend_subtract 1 +#define GL_FUNC_SUBTRACT_EXT 0x800A +#define GL_FUNC_REVERSE_SUBTRACT_EXT 0x800B +#endif /* GL_EXT_blend_subtract */ + +#ifndef GL_EXT_clip_volume_hint +#define GL_EXT_clip_volume_hint 1 +#define GL_CLIP_VOLUME_CLIPPING_HINT_EXT 0x80F0 +#endif /* GL_EXT_clip_volume_hint */ + +#ifndef GL_EXT_cmyka +#define GL_EXT_cmyka 1 +#define GL_CMYK_EXT 0x800C +#define GL_CMYKA_EXT 0x800D +#define GL_PACK_CMYK_HINT_EXT 0x800E +#define GL_UNPACK_CMYK_HINT_EXT 0x800F +#endif /* GL_EXT_cmyka */ + +#ifndef GL_EXT_color_subtable +#define GL_EXT_color_subtable 1 +typedef void (APIENTRYP PFNGLCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorSubTableEXT (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glCopyColorSubTableEXT (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width); +#endif +#endif /* GL_EXT_color_subtable */ + +#ifndef GL_EXT_compiled_vertex_array +#define GL_EXT_compiled_vertex_array 1 +#define GL_ARRAY_ELEMENT_LOCK_FIRST_EXT 0x81A8 +#define GL_ARRAY_ELEMENT_LOCK_COUNT_EXT 0x81A9 +typedef void (APIENTRYP PFNGLLOCKARRAYSEXTPROC) (GLint first, GLsizei count); +typedef void (APIENTRYP PFNGLUNLOCKARRAYSEXTPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glLockArraysEXT (GLint first, GLsizei count); +GLAPI void APIENTRY glUnlockArraysEXT (void); +#endif +#endif /* GL_EXT_compiled_vertex_array */ + +#ifndef GL_EXT_convolution +#define GL_EXT_convolution 1 +#define GL_CONVOLUTION_1D_EXT 0x8010 +#define GL_CONVOLUTION_2D_EXT 0x8011 +#define GL_SEPARABLE_2D_EXT 0x8012 +#define GL_CONVOLUTION_BORDER_MODE_EXT 0x8013 +#define GL_CONVOLUTION_FILTER_SCALE_EXT 0x8014 +#define GL_CONVOLUTION_FILTER_BIAS_EXT 0x8015 +#define GL_REDUCE_EXT 0x8016 +#define GL_CONVOLUTION_FORMAT_EXT 0x8017 +#define GL_CONVOLUTION_WIDTH_EXT 0x8018 +#define GL_CONVOLUTION_HEIGHT_EXT 0x8019 +#define GL_MAX_CONVOLUTION_WIDTH_EXT 0x801A +#define GL_MAX_CONVOLUTION_HEIGHT_EXT 0x801B +#define GL_POST_CONVOLUTION_RED_SCALE_EXT 0x801C +#define GL_POST_CONVOLUTION_GREEN_SCALE_EXT 0x801D +#define GL_POST_CONVOLUTION_BLUE_SCALE_EXT 0x801E +#define GL_POST_CONVOLUTION_ALPHA_SCALE_EXT 0x801F +#define GL_POST_CONVOLUTION_RED_BIAS_EXT 0x8020 +#define GL_POST_CONVOLUTION_GREEN_BIAS_EXT 0x8021 +#define GL_POST_CONVOLUTION_BLUE_BIAS_EXT 0x8022 +#define GL_POST_CONVOLUTION_ALPHA_BIAS_EXT 0x8023 +typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *image); +typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *image); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, void *image); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSEPARABLEFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, void *row, void *column, void *span); +typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *row, const void *column); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glConvolutionFilter1DEXT (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *image); +GLAPI void APIENTRY glConvolutionFilter2DEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *image); +GLAPI void APIENTRY glConvolutionParameterfEXT (GLenum target, GLenum pname, GLfloat params); +GLAPI void APIENTRY glConvolutionParameterfvEXT (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glConvolutionParameteriEXT (GLenum target, GLenum pname, GLint params); +GLAPI void APIENTRY glConvolutionParameterivEXT (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glCopyConvolutionFilter1DEXT (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glCopyConvolutionFilter2DEXT (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetConvolutionFilterEXT (GLenum target, GLenum format, GLenum type, void *image); +GLAPI void APIENTRY glGetConvolutionParameterfvEXT (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetConvolutionParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetSeparableFilterEXT (GLenum target, GLenum format, GLenum type, void *row, void *column, void *span); +GLAPI void APIENTRY glSeparableFilter2DEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *row, const void *column); +#endif +#endif /* GL_EXT_convolution */ + +#ifndef GL_EXT_coordinate_frame +#define GL_EXT_coordinate_frame 1 +#define GL_TANGENT_ARRAY_EXT 0x8439 +#define GL_BINORMAL_ARRAY_EXT 0x843A +#define GL_CURRENT_TANGENT_EXT 0x843B +#define GL_CURRENT_BINORMAL_EXT 0x843C +#define GL_TANGENT_ARRAY_TYPE_EXT 0x843E +#define GL_TANGENT_ARRAY_STRIDE_EXT 0x843F +#define GL_BINORMAL_ARRAY_TYPE_EXT 0x8440 +#define GL_BINORMAL_ARRAY_STRIDE_EXT 0x8441 +#define GL_TANGENT_ARRAY_POINTER_EXT 0x8442 +#define GL_BINORMAL_ARRAY_POINTER_EXT 0x8443 +#define GL_MAP1_TANGENT_EXT 0x8444 +#define GL_MAP2_TANGENT_EXT 0x8445 +#define GL_MAP1_BINORMAL_EXT 0x8446 +#define GL_MAP2_BINORMAL_EXT 0x8447 +typedef void (APIENTRYP PFNGLTANGENT3BEXTPROC) (GLbyte tx, GLbyte ty, GLbyte tz); +typedef void (APIENTRYP PFNGLTANGENT3BVEXTPROC) (const GLbyte *v); +typedef void (APIENTRYP PFNGLTANGENT3DEXTPROC) (GLdouble tx, GLdouble ty, GLdouble tz); +typedef void (APIENTRYP PFNGLTANGENT3DVEXTPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLTANGENT3FEXTPROC) (GLfloat tx, GLfloat ty, GLfloat tz); +typedef void (APIENTRYP PFNGLTANGENT3FVEXTPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLTANGENT3IEXTPROC) (GLint tx, GLint ty, GLint tz); +typedef void (APIENTRYP PFNGLTANGENT3IVEXTPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLTANGENT3SEXTPROC) (GLshort tx, GLshort ty, GLshort tz); +typedef void (APIENTRYP PFNGLTANGENT3SVEXTPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLBINORMAL3BEXTPROC) (GLbyte bx, GLbyte by, GLbyte bz); +typedef void (APIENTRYP PFNGLBINORMAL3BVEXTPROC) (const GLbyte *v); +typedef void (APIENTRYP PFNGLBINORMAL3DEXTPROC) (GLdouble bx, GLdouble by, GLdouble bz); +typedef void (APIENTRYP PFNGLBINORMAL3DVEXTPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLBINORMAL3FEXTPROC) (GLfloat bx, GLfloat by, GLfloat bz); +typedef void (APIENTRYP PFNGLBINORMAL3FVEXTPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLBINORMAL3IEXTPROC) (GLint bx, GLint by, GLint bz); +typedef void (APIENTRYP PFNGLBINORMAL3IVEXTPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLBINORMAL3SEXTPROC) (GLshort bx, GLshort by, GLshort bz); +typedef void (APIENTRYP PFNGLBINORMAL3SVEXTPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLTANGENTPOINTEREXTPROC) (GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLBINORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTangent3bEXT (GLbyte tx, GLbyte ty, GLbyte tz); +GLAPI void APIENTRY glTangent3bvEXT (const GLbyte *v); +GLAPI void APIENTRY glTangent3dEXT (GLdouble tx, GLdouble ty, GLdouble tz); +GLAPI void APIENTRY glTangent3dvEXT (const GLdouble *v); +GLAPI void APIENTRY glTangent3fEXT (GLfloat tx, GLfloat ty, GLfloat tz); +GLAPI void APIENTRY glTangent3fvEXT (const GLfloat *v); +GLAPI void APIENTRY glTangent3iEXT (GLint tx, GLint ty, GLint tz); +GLAPI void APIENTRY glTangent3ivEXT (const GLint *v); +GLAPI void APIENTRY glTangent3sEXT (GLshort tx, GLshort ty, GLshort tz); +GLAPI void APIENTRY glTangent3svEXT (const GLshort *v); +GLAPI void APIENTRY glBinormal3bEXT (GLbyte bx, GLbyte by, GLbyte bz); +GLAPI void APIENTRY glBinormal3bvEXT (const GLbyte *v); +GLAPI void APIENTRY glBinormal3dEXT (GLdouble bx, GLdouble by, GLdouble bz); +GLAPI void APIENTRY glBinormal3dvEXT (const GLdouble *v); +GLAPI void APIENTRY glBinormal3fEXT (GLfloat bx, GLfloat by, GLfloat bz); +GLAPI void APIENTRY glBinormal3fvEXT (const GLfloat *v); +GLAPI void APIENTRY glBinormal3iEXT (GLint bx, GLint by, GLint bz); +GLAPI void APIENTRY glBinormal3ivEXT (const GLint *v); +GLAPI void APIENTRY glBinormal3sEXT (GLshort bx, GLshort by, GLshort bz); +GLAPI void APIENTRY glBinormal3svEXT (const GLshort *v); +GLAPI void APIENTRY glTangentPointerEXT (GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glBinormalPointerEXT (GLenum type, GLsizei stride, const void *pointer); +#endif +#endif /* GL_EXT_coordinate_frame */ + +#ifndef GL_EXT_copy_texture +#define GL_EXT_copy_texture 1 +typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCopyTexImage1DEXT (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +GLAPI void APIENTRY glCopyTexImage2DEXT (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +GLAPI void APIENTRY glCopyTexSubImage1DEXT (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glCopyTexSubImage2DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glCopyTexSubImage3DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +#endif +#endif /* GL_EXT_copy_texture */ + +#ifndef GL_EXT_cull_vertex +#define GL_EXT_cull_vertex 1 +#define GL_CULL_VERTEX_EXT 0x81AA +#define GL_CULL_VERTEX_EYE_POSITION_EXT 0x81AB +#define GL_CULL_VERTEX_OBJECT_POSITION_EXT 0x81AC +typedef void (APIENTRYP PFNGLCULLPARAMETERDVEXTPROC) (GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLCULLPARAMETERFVEXTPROC) (GLenum pname, GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCullParameterdvEXT (GLenum pname, GLdouble *params); +GLAPI void APIENTRY glCullParameterfvEXT (GLenum pname, GLfloat *params); +#endif +#endif /* GL_EXT_cull_vertex */ + +#ifndef GL_EXT_debug_label +#define GL_EXT_debug_label 1 +#define GL_PROGRAM_PIPELINE_OBJECT_EXT 0x8A4F +#define GL_PROGRAM_OBJECT_EXT 0x8B40 +#define GL_SHADER_OBJECT_EXT 0x8B48 +#define GL_BUFFER_OBJECT_EXT 0x9151 +#define GL_QUERY_OBJECT_EXT 0x9153 +#define GL_VERTEX_ARRAY_OBJECT_EXT 0x9154 +typedef void (APIENTRYP PFNGLLABELOBJECTEXTPROC) (GLenum type, GLuint object, GLsizei length, const GLchar *label); +typedef void (APIENTRYP PFNGLGETOBJECTLABELEXTPROC) (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glLabelObjectEXT (GLenum type, GLuint object, GLsizei length, const GLchar *label); +GLAPI void APIENTRY glGetObjectLabelEXT (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label); +#endif +#endif /* GL_EXT_debug_label */ + +#ifndef GL_EXT_debug_marker +#define GL_EXT_debug_marker 1 +typedef void (APIENTRYP PFNGLINSERTEVENTMARKEREXTPROC) (GLsizei length, const GLchar *marker); +typedef void (APIENTRYP PFNGLPUSHGROUPMARKEREXTPROC) (GLsizei length, const GLchar *marker); +typedef void (APIENTRYP PFNGLPOPGROUPMARKEREXTPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glInsertEventMarkerEXT (GLsizei length, const GLchar *marker); +GLAPI void APIENTRY glPushGroupMarkerEXT (GLsizei length, const GLchar *marker); +GLAPI void APIENTRY glPopGroupMarkerEXT (void); +#endif +#endif /* GL_EXT_debug_marker */ + +#ifndef GL_EXT_depth_bounds_test +#define GL_EXT_depth_bounds_test 1 +#define GL_DEPTH_BOUNDS_TEST_EXT 0x8890 +#define GL_DEPTH_BOUNDS_EXT 0x8891 +typedef void (APIENTRYP PFNGLDEPTHBOUNDSEXTPROC) (GLclampd zmin, GLclampd zmax); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDepthBoundsEXT (GLclampd zmin, GLclampd zmax); +#endif +#endif /* GL_EXT_depth_bounds_test */ + +#ifndef GL_EXT_direct_state_access +#define GL_EXT_direct_state_access 1 +#define GL_PROGRAM_MATRIX_EXT 0x8E2D +#define GL_TRANSPOSE_PROGRAM_MATRIX_EXT 0x8E2E +#define GL_PROGRAM_MATRIX_STACK_DEPTH_EXT 0x8E2F +typedef void (APIENTRYP PFNGLMATRIXLOADFEXTPROC) (GLenum mode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXLOADDEXTPROC) (GLenum mode, const GLdouble *m); +typedef void (APIENTRYP PFNGLMATRIXMULTFEXTPROC) (GLenum mode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXMULTDEXTPROC) (GLenum mode, const GLdouble *m); +typedef void (APIENTRYP PFNGLMATRIXLOADIDENTITYEXTPROC) (GLenum mode); +typedef void (APIENTRYP PFNGLMATRIXROTATEFEXTPROC) (GLenum mode, GLfloat angle, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLMATRIXROTATEDEXTPROC) (GLenum mode, GLdouble angle, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLMATRIXSCALEFEXTPROC) (GLenum mode, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLMATRIXSCALEDEXTPROC) (GLenum mode, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLMATRIXTRANSLATEFEXTPROC) (GLenum mode, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLMATRIXTRANSLATEDEXTPROC) (GLenum mode, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLMATRIXFRUSTUMEXTPROC) (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +typedef void (APIENTRYP PFNGLMATRIXORTHOEXTPROC) (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +typedef void (APIENTRYP PFNGLMATRIXPOPEXTPROC) (GLenum mode); +typedef void (APIENTRYP PFNGLMATRIXPUSHEXTPROC) (GLenum mode); +typedef void (APIENTRYP PFNGLCLIENTATTRIBDEFAULTEXTPROC) (GLbitfield mask); +typedef void (APIENTRYP PFNGLPUSHCLIENTATTRIBDEFAULTEXTPROC) (GLbitfield mask); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCOPYTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +typedef void (APIENTRYP PFNGLCOPYTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETTEXTUREIMAGEEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum format, GLenum type, void *pixels); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLBINDMULTITEXTUREEXTPROC) (GLenum texunit, GLenum target, GLuint texture); +typedef void (APIENTRYP PFNGLMULTITEXCOORDPOINTEREXTPROC) (GLenum texunit, GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLMULTITEXENVFEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLMULTITEXENVFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLMULTITEXENVIEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLMULTITEXENVIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLMULTITEXGENDEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLdouble param); +typedef void (APIENTRYP PFNGLMULTITEXGENDVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, const GLdouble *params); +typedef void (APIENTRYP PFNGLMULTITEXGENFEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLMULTITEXGENFVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLMULTITEXGENIEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLMULTITEXGENIVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLGETMULTITEXENVFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMULTITEXENVIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMULTITEXGENDVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETMULTITEXGENFVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMULTITEXGENIVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLMULTITEXPARAMETERFEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLMULTITEXPARAMETERFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCOPYMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +typedef void (APIENTRYP PFNGLCOPYMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +typedef void (APIENTRYP PFNGLCOPYMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETMULTITEXIMAGEEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum format, GLenum type, void *pixels); +typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMULTITEXLEVELPARAMETERFVEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMULTITEXLEVELPARAMETERIVEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLMULTITEXIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCOPYMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLENABLECLIENTSTATEINDEXEDEXTPROC) (GLenum array, GLuint index); +typedef void (APIENTRYP PFNGLDISABLECLIENTSTATEINDEXEDEXTPROC) (GLenum array, GLuint index); +typedef void (APIENTRYP PFNGLGETFLOATINDEXEDVEXTPROC) (GLenum target, GLuint index, GLfloat *data); +typedef void (APIENTRYP PFNGLGETDOUBLEINDEXEDVEXTPROC) (GLenum target, GLuint index, GLdouble *data); +typedef void (APIENTRYP PFNGLGETPOINTERINDEXEDVEXTPROC) (GLenum target, GLuint index, void **data); +typedef void (APIENTRYP PFNGLENABLEINDEXEDEXTPROC) (GLenum target, GLuint index); +typedef void (APIENTRYP PFNGLDISABLEINDEXEDEXTPROC) (GLenum target, GLuint index); +typedef GLboolean (APIENTRYP PFNGLISENABLEDINDEXEDEXTPROC) (GLenum target, GLuint index); +typedef void (APIENTRYP PFNGLGETINTEGERINDEXEDVEXTPROC) (GLenum target, GLuint index, GLint *data); +typedef void (APIENTRYP PFNGLGETBOOLEANINDEXEDVEXTPROC) (GLenum target, GLuint index, GLboolean *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTUREIMAGEEXTPROC) (GLuint texture, GLenum target, GLint lod, void *img); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDMULTITEXIMAGEEXTPROC) (GLenum texunit, GLenum target, GLint lod, void *img); +typedef void (APIENTRYP PFNGLMATRIXLOADTRANSPOSEFEXTPROC) (GLenum mode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXLOADTRANSPOSEDEXTPROC) (GLenum mode, const GLdouble *m); +typedef void (APIENTRYP PFNGLMATRIXMULTTRANSPOSEFEXTPROC) (GLenum mode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXMULTTRANSPOSEDEXTPROC) (GLenum mode, const GLdouble *m); +typedef void (APIENTRYP PFNGLNAMEDBUFFERDATAEXTPROC) (GLuint buffer, GLsizeiptr size, const void *data, GLenum usage); +typedef void (APIENTRYP PFNGLNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); +typedef void *(APIENTRYP PFNGLMAPNAMEDBUFFEREXTPROC) (GLuint buffer, GLenum access); +typedef GLboolean (APIENTRYP PFNGLUNMAPNAMEDBUFFEREXTPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERIVEXTPROC) (GLuint buffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPOINTERVEXTPROC) (GLuint buffer, GLenum pname, void **params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, void *data); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FEXTPROC) (GLuint program, GLint location, GLfloat v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IEXTPROC) (GLuint program, GLint location, GLint v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLTEXTUREBUFFEREXTPROC) (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer); +typedef void (APIENTRYP PFNGLMULTITEXBUFFEREXTPROC) (GLenum texunit, GLenum target, GLenum internalformat, GLuint buffer); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIUIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLuint *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIUIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIUIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLuint *params); +typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERIIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERIUIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIEXTPROC) (GLuint program, GLint location, GLuint v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERS4FVEXTPROC) (GLuint program, GLenum target, GLuint index, GLsizei count, const GLfloat *params); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4IEXTPROC) (GLuint program, GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4IVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLint *params); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERSI4IVEXTPROC) (GLuint program, GLenum target, GLuint index, GLsizei count, const GLint *params); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4UIEXTPROC) (GLuint program, GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4UIVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLuint *params); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERSI4UIVEXTPROC) (GLuint program, GLenum target, GLuint index, GLsizei count, const GLuint *params); +typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERIIVEXTPROC) (GLuint program, GLenum target, GLuint index, GLint *params); +typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERIUIVEXTPROC) (GLuint program, GLenum target, GLuint index, GLuint *params); +typedef void (APIENTRYP PFNGLENABLECLIENTSTATEIEXTPROC) (GLenum array, GLuint index); +typedef void (APIENTRYP PFNGLDISABLECLIENTSTATEIEXTPROC) (GLenum array, GLuint index); +typedef void (APIENTRYP PFNGLGETFLOATI_VEXTPROC) (GLenum pname, GLuint index, GLfloat *params); +typedef void (APIENTRYP PFNGLGETDOUBLEI_VEXTPROC) (GLenum pname, GLuint index, GLdouble *params); +typedef void (APIENTRYP PFNGLGETPOINTERI_VEXTPROC) (GLenum pname, GLuint index, void **params); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMSTRINGEXTPROC) (GLuint program, GLenum target, GLenum format, GLsizei len, const void *string); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4DEXTPROC) (GLuint program, GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4DVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLdouble *params); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4FEXTPROC) (GLuint program, GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4FVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERDVEXTPROC) (GLuint program, GLenum target, GLuint index, GLdouble *params); +typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERFVEXTPROC) (GLuint program, GLenum target, GLuint index, GLfloat *params); +typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMIVEXTPROC) (GLuint program, GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMSTRINGEXTPROC) (GLuint program, GLenum target, GLenum pname, void *string); +typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEEXTPROC) (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETNAMEDRENDERBUFFERPARAMETERIVEXTPROC) (GLuint renderbuffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLECOVERAGEEXTPROC) (GLuint renderbuffer, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); +typedef GLenum (APIENTRYP PFNGLCHECKNAMEDFRAMEBUFFERSTATUSEXTPROC) (GLuint framebuffer, GLenum target); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURE1DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURE2DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURE3DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERRENDERBUFFEREXTPROC) (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGENERATETEXTUREMIPMAPEXTPROC) (GLuint texture, GLenum target); +typedef void (APIENTRYP PFNGLGENERATEMULTITEXMIPMAPEXTPROC) (GLenum texunit, GLenum target); +typedef void (APIENTRYP PFNGLFRAMEBUFFERDRAWBUFFEREXTPROC) (GLuint framebuffer, GLenum mode); +typedef void (APIENTRYP PFNGLFRAMEBUFFERDRAWBUFFERSEXTPROC) (GLuint framebuffer, GLsizei n, const GLenum *bufs); +typedef void (APIENTRYP PFNGLFRAMEBUFFERREADBUFFEREXTPROC) (GLuint framebuffer, GLenum mode); +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLNAMEDCOPYBUFFERSUBDATAEXTPROC) (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTUREEXTPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURELAYEREXTPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTUREFACEEXTPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLenum face); +typedef void (APIENTRYP PFNGLTEXTURERENDERBUFFEREXTPROC) (GLuint texture, GLenum target, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLMULTITEXRENDERBUFFEREXTPROC) (GLenum texunit, GLenum target, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYCOLOROFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYEDGEFLAGOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYINDEXOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYNORMALOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYTEXCOORDOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYMULTITEXCOORDOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum texunit, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYFOGCOORDOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYSECONDARYCOLOROFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBIOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLENABLEVERTEXARRAYEXTPROC) (GLuint vaobj, GLenum array); +typedef void (APIENTRYP PFNGLDISABLEVERTEXARRAYEXTPROC) (GLuint vaobj, GLenum array); +typedef void (APIENTRYP PFNGLENABLEVERTEXARRAYATTRIBEXTPROC) (GLuint vaobj, GLuint index); +typedef void (APIENTRYP PFNGLDISABLEVERTEXARRAYATTRIBEXTPROC) (GLuint vaobj, GLuint index); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERVEXTPROC) (GLuint vaobj, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERVEXTPROC) (GLuint vaobj, GLenum pname, void **param); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, void **param); +typedef void *(APIENTRYP PFNGLMAPNAMEDBUFFERRANGEEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access); +typedef void (APIENTRYP PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length); +typedef void (APIENTRYP PFNGLNAMEDBUFFERSTORAGEEXTPROC) (GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags); +typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERDATAEXTPROC) (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLenum internalformat, GLsizeiptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERPARAMETERIEXTPROC) (GLuint framebuffer, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DEXTPROC) (GLuint program, GLint location, GLdouble x); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DEXTPROC) (GLuint program, GLint location, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DEXTPROC) (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DEXTPROC) (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLTEXTUREBUFFERRANGEEXTPROC) (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE1DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DMULTISAMPLEEXTPROC) (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DMULTISAMPLEEXTPROC) (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLVERTEXARRAYBINDVERTEXBUFFEREXTPROC) (GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBFORMATEXTPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBIFORMATEXTPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBLFORMATEXTPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBBINDINGEXTPROC) (GLuint vaobj, GLuint attribindex, GLuint bindingindex); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXBINDINGDIVISOREXTPROC) (GLuint vaobj, GLuint bindingindex, GLuint divisor); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBLOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLTEXTUREPAGECOMMITMENTEXTPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBDIVISOREXTPROC) (GLuint vaobj, GLuint index, GLuint divisor); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMatrixLoadfEXT (GLenum mode, const GLfloat *m); +GLAPI void APIENTRY glMatrixLoaddEXT (GLenum mode, const GLdouble *m); +GLAPI void APIENTRY glMatrixMultfEXT (GLenum mode, const GLfloat *m); +GLAPI void APIENTRY glMatrixMultdEXT (GLenum mode, const GLdouble *m); +GLAPI void APIENTRY glMatrixLoadIdentityEXT (GLenum mode); +GLAPI void APIENTRY glMatrixRotatefEXT (GLenum mode, GLfloat angle, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glMatrixRotatedEXT (GLenum mode, GLdouble angle, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glMatrixScalefEXT (GLenum mode, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glMatrixScaledEXT (GLenum mode, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glMatrixTranslatefEXT (GLenum mode, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glMatrixTranslatedEXT (GLenum mode, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glMatrixFrustumEXT (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +GLAPI void APIENTRY glMatrixOrthoEXT (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +GLAPI void APIENTRY glMatrixPopEXT (GLenum mode); +GLAPI void APIENTRY glMatrixPushEXT (GLenum mode); +GLAPI void APIENTRY glClientAttribDefaultEXT (GLbitfield mask); +GLAPI void APIENTRY glPushClientAttribDefaultEXT (GLbitfield mask); +GLAPI void APIENTRY glTextureParameterfEXT (GLuint texture, GLenum target, GLenum pname, GLfloat param); +GLAPI void APIENTRY glTextureParameterfvEXT (GLuint texture, GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glTextureParameteriEXT (GLuint texture, GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glTextureParameterivEXT (GLuint texture, GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glCopyTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +GLAPI void APIENTRY glCopyTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +GLAPI void APIENTRY glCopyTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glCopyTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetTextureImageEXT (GLuint texture, GLenum target, GLint level, GLenum format, GLenum type, void *pixels); +GLAPI void APIENTRY glGetTextureParameterfvEXT (GLuint texture, GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetTextureParameterivEXT (GLuint texture, GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetTextureLevelParameterfvEXT (GLuint texture, GLenum target, GLint level, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetTextureLevelParameterivEXT (GLuint texture, GLenum target, GLint level, GLenum pname, GLint *params); +GLAPI void APIENTRY glTextureImage3DEXT (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTextureSubImage3DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glCopyTextureSubImage3DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glBindMultiTextureEXT (GLenum texunit, GLenum target, GLuint texture); +GLAPI void APIENTRY glMultiTexCoordPointerEXT (GLenum texunit, GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glMultiTexEnvfEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat param); +GLAPI void APIENTRY glMultiTexEnvfvEXT (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glMultiTexEnviEXT (GLenum texunit, GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glMultiTexEnvivEXT (GLenum texunit, GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glMultiTexGendEXT (GLenum texunit, GLenum coord, GLenum pname, GLdouble param); +GLAPI void APIENTRY glMultiTexGendvEXT (GLenum texunit, GLenum coord, GLenum pname, const GLdouble *params); +GLAPI void APIENTRY glMultiTexGenfEXT (GLenum texunit, GLenum coord, GLenum pname, GLfloat param); +GLAPI void APIENTRY glMultiTexGenfvEXT (GLenum texunit, GLenum coord, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glMultiTexGeniEXT (GLenum texunit, GLenum coord, GLenum pname, GLint param); +GLAPI void APIENTRY glMultiTexGenivEXT (GLenum texunit, GLenum coord, GLenum pname, const GLint *params); +GLAPI void APIENTRY glGetMultiTexEnvfvEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMultiTexEnvivEXT (GLenum texunit, GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMultiTexGendvEXT (GLenum texunit, GLenum coord, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glGetMultiTexGenfvEXT (GLenum texunit, GLenum coord, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMultiTexGenivEXT (GLenum texunit, GLenum coord, GLenum pname, GLint *params); +GLAPI void APIENTRY glMultiTexParameteriEXT (GLenum texunit, GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glMultiTexParameterivEXT (GLenum texunit, GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glMultiTexParameterfEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat param); +GLAPI void APIENTRY glMultiTexParameterfvEXT (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glCopyMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +GLAPI void APIENTRY glCopyMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +GLAPI void APIENTRY glCopyMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glCopyMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetMultiTexImageEXT (GLenum texunit, GLenum target, GLint level, GLenum format, GLenum type, void *pixels); +GLAPI void APIENTRY glGetMultiTexParameterfvEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMultiTexParameterivEXT (GLenum texunit, GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMultiTexLevelParameterfvEXT (GLenum texunit, GLenum target, GLint level, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMultiTexLevelParameterivEXT (GLenum texunit, GLenum target, GLint level, GLenum pname, GLint *params); +GLAPI void APIENTRY glMultiTexImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glMultiTexSubImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glCopyMultiTexSubImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glEnableClientStateIndexedEXT (GLenum array, GLuint index); +GLAPI void APIENTRY glDisableClientStateIndexedEXT (GLenum array, GLuint index); +GLAPI void APIENTRY glGetFloatIndexedvEXT (GLenum target, GLuint index, GLfloat *data); +GLAPI void APIENTRY glGetDoubleIndexedvEXT (GLenum target, GLuint index, GLdouble *data); +GLAPI void APIENTRY glGetPointerIndexedvEXT (GLenum target, GLuint index, void **data); +GLAPI void APIENTRY glEnableIndexedEXT (GLenum target, GLuint index); +GLAPI void APIENTRY glDisableIndexedEXT (GLenum target, GLuint index); +GLAPI GLboolean APIENTRY glIsEnabledIndexedEXT (GLenum target, GLuint index); +GLAPI void APIENTRY glGetIntegerIndexedvEXT (GLenum target, GLuint index, GLint *data); +GLAPI void APIENTRY glGetBooleanIndexedvEXT (GLenum target, GLuint index, GLboolean *data); +GLAPI void APIENTRY glCompressedTextureImage3DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedTextureSubImage3DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glGetCompressedTextureImageEXT (GLuint texture, GLenum target, GLint lod, void *img); +GLAPI void APIENTRY glCompressedMultiTexImage3DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedMultiTexSubImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glGetCompressedMultiTexImageEXT (GLenum texunit, GLenum target, GLint lod, void *img); +GLAPI void APIENTRY glMatrixLoadTransposefEXT (GLenum mode, const GLfloat *m); +GLAPI void APIENTRY glMatrixLoadTransposedEXT (GLenum mode, const GLdouble *m); +GLAPI void APIENTRY glMatrixMultTransposefEXT (GLenum mode, const GLfloat *m); +GLAPI void APIENTRY glMatrixMultTransposedEXT (GLenum mode, const GLdouble *m); +GLAPI void APIENTRY glNamedBufferDataEXT (GLuint buffer, GLsizeiptr size, const void *data, GLenum usage); +GLAPI void APIENTRY glNamedBufferSubDataEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); +GLAPI void *APIENTRY glMapNamedBufferEXT (GLuint buffer, GLenum access); +GLAPI GLboolean APIENTRY glUnmapNamedBufferEXT (GLuint buffer); +GLAPI void APIENTRY glGetNamedBufferParameterivEXT (GLuint buffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetNamedBufferPointervEXT (GLuint buffer, GLenum pname, void **params); +GLAPI void APIENTRY glGetNamedBufferSubDataEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, void *data); +GLAPI void APIENTRY glProgramUniform1fEXT (GLuint program, GLint location, GLfloat v0); +GLAPI void APIENTRY glProgramUniform2fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1); +GLAPI void APIENTRY glProgramUniform3fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +GLAPI void APIENTRY glProgramUniform4fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +GLAPI void APIENTRY glProgramUniform1iEXT (GLuint program, GLint location, GLint v0); +GLAPI void APIENTRY glProgramUniform2iEXT (GLuint program, GLint location, GLint v0, GLint v1); +GLAPI void APIENTRY glProgramUniform3iEXT (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); +GLAPI void APIENTRY glProgramUniform4iEXT (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +GLAPI void APIENTRY glProgramUniform1fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform2fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform3fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform4fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform1ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform2ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform3ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform4ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniformMatrix2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix2x3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix3x2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix2x4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix4x2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix3x4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix4x3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glTextureBufferEXT (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer); +GLAPI void APIENTRY glMultiTexBufferEXT (GLenum texunit, GLenum target, GLenum internalformat, GLuint buffer); +GLAPI void APIENTRY glTextureParameterIivEXT (GLuint texture, GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glTextureParameterIuivEXT (GLuint texture, GLenum target, GLenum pname, const GLuint *params); +GLAPI void APIENTRY glGetTextureParameterIivEXT (GLuint texture, GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetTextureParameterIuivEXT (GLuint texture, GLenum target, GLenum pname, GLuint *params); +GLAPI void APIENTRY glMultiTexParameterIivEXT (GLenum texunit, GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glMultiTexParameterIuivEXT (GLenum texunit, GLenum target, GLenum pname, const GLuint *params); +GLAPI void APIENTRY glGetMultiTexParameterIivEXT (GLenum texunit, GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMultiTexParameterIuivEXT (GLenum texunit, GLenum target, GLenum pname, GLuint *params); +GLAPI void APIENTRY glProgramUniform1uiEXT (GLuint program, GLint location, GLuint v0); +GLAPI void APIENTRY glProgramUniform2uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1); +GLAPI void APIENTRY glProgramUniform3uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); +GLAPI void APIENTRY glProgramUniform4uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +GLAPI void APIENTRY glProgramUniform1uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniform2uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniform3uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniform4uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glNamedProgramLocalParameters4fvEXT (GLuint program, GLenum target, GLuint index, GLsizei count, const GLfloat *params); +GLAPI void APIENTRY glNamedProgramLocalParameterI4iEXT (GLuint program, GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glNamedProgramLocalParameterI4ivEXT (GLuint program, GLenum target, GLuint index, const GLint *params); +GLAPI void APIENTRY glNamedProgramLocalParametersI4ivEXT (GLuint program, GLenum target, GLuint index, GLsizei count, const GLint *params); +GLAPI void APIENTRY glNamedProgramLocalParameterI4uiEXT (GLuint program, GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +GLAPI void APIENTRY glNamedProgramLocalParameterI4uivEXT (GLuint program, GLenum target, GLuint index, const GLuint *params); +GLAPI void APIENTRY glNamedProgramLocalParametersI4uivEXT (GLuint program, GLenum target, GLuint index, GLsizei count, const GLuint *params); +GLAPI void APIENTRY glGetNamedProgramLocalParameterIivEXT (GLuint program, GLenum target, GLuint index, GLint *params); +GLAPI void APIENTRY glGetNamedProgramLocalParameterIuivEXT (GLuint program, GLenum target, GLuint index, GLuint *params); +GLAPI void APIENTRY glEnableClientStateiEXT (GLenum array, GLuint index); +GLAPI void APIENTRY glDisableClientStateiEXT (GLenum array, GLuint index); +GLAPI void APIENTRY glGetFloati_vEXT (GLenum pname, GLuint index, GLfloat *params); +GLAPI void APIENTRY glGetDoublei_vEXT (GLenum pname, GLuint index, GLdouble *params); +GLAPI void APIENTRY glGetPointeri_vEXT (GLenum pname, GLuint index, void **params); +GLAPI void APIENTRY glNamedProgramStringEXT (GLuint program, GLenum target, GLenum format, GLsizei len, const void *string); +GLAPI void APIENTRY glNamedProgramLocalParameter4dEXT (GLuint program, GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glNamedProgramLocalParameter4dvEXT (GLuint program, GLenum target, GLuint index, const GLdouble *params); +GLAPI void APIENTRY glNamedProgramLocalParameter4fEXT (GLuint program, GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glNamedProgramLocalParameter4fvEXT (GLuint program, GLenum target, GLuint index, const GLfloat *params); +GLAPI void APIENTRY glGetNamedProgramLocalParameterdvEXT (GLuint program, GLenum target, GLuint index, GLdouble *params); +GLAPI void APIENTRY glGetNamedProgramLocalParameterfvEXT (GLuint program, GLenum target, GLuint index, GLfloat *params); +GLAPI void APIENTRY glGetNamedProgramivEXT (GLuint program, GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetNamedProgramStringEXT (GLuint program, GLenum target, GLenum pname, void *string); +GLAPI void APIENTRY glNamedRenderbufferStorageEXT (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetNamedRenderbufferParameterivEXT (GLuint renderbuffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glNamedRenderbufferStorageMultisampleEXT (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glNamedRenderbufferStorageMultisampleCoverageEXT (GLuint renderbuffer, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI GLenum APIENTRY glCheckNamedFramebufferStatusEXT (GLuint framebuffer, GLenum target); +GLAPI void APIENTRY glNamedFramebufferTexture1DEXT (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI void APIENTRY glNamedFramebufferTexture2DEXT (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI void APIENTRY glNamedFramebufferTexture3DEXT (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +GLAPI void APIENTRY glNamedFramebufferRenderbufferEXT (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +GLAPI void APIENTRY glGetNamedFramebufferAttachmentParameterivEXT (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params); +GLAPI void APIENTRY glGenerateTextureMipmapEXT (GLuint texture, GLenum target); +GLAPI void APIENTRY glGenerateMultiTexMipmapEXT (GLenum texunit, GLenum target); +GLAPI void APIENTRY glFramebufferDrawBufferEXT (GLuint framebuffer, GLenum mode); +GLAPI void APIENTRY glFramebufferDrawBuffersEXT (GLuint framebuffer, GLsizei n, const GLenum *bufs); +GLAPI void APIENTRY glFramebufferReadBufferEXT (GLuint framebuffer, GLenum mode); +GLAPI void APIENTRY glGetFramebufferParameterivEXT (GLuint framebuffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glNamedCopyBufferSubDataEXT (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +GLAPI void APIENTRY glNamedFramebufferTextureEXT (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); +GLAPI void APIENTRY glNamedFramebufferTextureLayerEXT (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); +GLAPI void APIENTRY glNamedFramebufferTextureFaceEXT (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLenum face); +GLAPI void APIENTRY glTextureRenderbufferEXT (GLuint texture, GLenum target, GLuint renderbuffer); +GLAPI void APIENTRY glMultiTexRenderbufferEXT (GLenum texunit, GLenum target, GLuint renderbuffer); +GLAPI void APIENTRY glVertexArrayVertexOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayColorOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayEdgeFlagOffsetEXT (GLuint vaobj, GLuint buffer, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayIndexOffsetEXT (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayNormalOffsetEXT (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayTexCoordOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayMultiTexCoordOffsetEXT (GLuint vaobj, GLuint buffer, GLenum texunit, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayFogCoordOffsetEXT (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArraySecondaryColorOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayVertexAttribOffsetEXT (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayVertexAttribIOffsetEXT (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glEnableVertexArrayEXT (GLuint vaobj, GLenum array); +GLAPI void APIENTRY glDisableVertexArrayEXT (GLuint vaobj, GLenum array); +GLAPI void APIENTRY glEnableVertexArrayAttribEXT (GLuint vaobj, GLuint index); +GLAPI void APIENTRY glDisableVertexArrayAttribEXT (GLuint vaobj, GLuint index); +GLAPI void APIENTRY glGetVertexArrayIntegervEXT (GLuint vaobj, GLenum pname, GLint *param); +GLAPI void APIENTRY glGetVertexArrayPointervEXT (GLuint vaobj, GLenum pname, void **param); +GLAPI void APIENTRY glGetVertexArrayIntegeri_vEXT (GLuint vaobj, GLuint index, GLenum pname, GLint *param); +GLAPI void APIENTRY glGetVertexArrayPointeri_vEXT (GLuint vaobj, GLuint index, GLenum pname, void **param); +GLAPI void *APIENTRY glMapNamedBufferRangeEXT (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access); +GLAPI void APIENTRY glFlushMappedNamedBufferRangeEXT (GLuint buffer, GLintptr offset, GLsizeiptr length); +GLAPI void APIENTRY glNamedBufferStorageEXT (GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags); +GLAPI void APIENTRY glClearNamedBufferDataEXT (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glClearNamedBufferSubDataEXT (GLuint buffer, GLenum internalformat, GLsizeiptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glNamedFramebufferParameteriEXT (GLuint framebuffer, GLenum pname, GLint param); +GLAPI void APIENTRY glGetNamedFramebufferParameterivEXT (GLuint framebuffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glProgramUniform1dEXT (GLuint program, GLint location, GLdouble x); +GLAPI void APIENTRY glProgramUniform2dEXT (GLuint program, GLint location, GLdouble x, GLdouble y); +GLAPI void APIENTRY glProgramUniform3dEXT (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glProgramUniform4dEXT (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glProgramUniform1dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform2dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform3dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform4dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix2dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix3dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix4dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix2x3dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix2x4dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix3x2dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix3x4dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix4x2dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix4x3dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glTextureBufferRangeEXT (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glTextureStorage1DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +GLAPI void APIENTRY glTextureStorage2DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glTextureStorage3DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +GLAPI void APIENTRY glTextureStorage2DMultisampleEXT (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTextureStorage3DMultisampleEXT (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glVertexArrayBindVertexBufferEXT (GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +GLAPI void APIENTRY glVertexArrayVertexAttribFormatEXT (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +GLAPI void APIENTRY glVertexArrayVertexAttribIFormatEXT (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI void APIENTRY glVertexArrayVertexAttribLFormatEXT (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI void APIENTRY glVertexArrayVertexAttribBindingEXT (GLuint vaobj, GLuint attribindex, GLuint bindingindex); +GLAPI void APIENTRY glVertexArrayVertexBindingDivisorEXT (GLuint vaobj, GLuint bindingindex, GLuint divisor); +GLAPI void APIENTRY glVertexArrayVertexAttribLOffsetEXT (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glTexturePageCommitmentEXT (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit); +GLAPI void APIENTRY glVertexArrayVertexAttribDivisorEXT (GLuint vaobj, GLuint index, GLuint divisor); +#endif +#endif /* GL_EXT_direct_state_access */ + +#ifndef GL_EXT_draw_buffers2 +#define GL_EXT_draw_buffers2 1 +typedef void (APIENTRYP PFNGLCOLORMASKINDEXEDEXTPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorMaskIndexedEXT (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +#endif +#endif /* GL_EXT_draw_buffers2 */ + +#ifndef GL_EXT_draw_instanced +#define GL_EXT_draw_instanced 1 +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDEXTPROC) (GLenum mode, GLint start, GLsizei count, GLsizei primcount); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawArraysInstancedEXT (GLenum mode, GLint start, GLsizei count, GLsizei primcount); +GLAPI void APIENTRY glDrawElementsInstancedEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); +#endif +#endif /* GL_EXT_draw_instanced */ + +#ifndef GL_EXT_draw_range_elements +#define GL_EXT_draw_range_elements 1 +#define GL_MAX_ELEMENTS_VERTICES_EXT 0x80E8 +#define GL_MAX_ELEMENTS_INDICES_EXT 0x80E9 +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSEXTPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawRangeElementsEXT (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); +#endif +#endif /* GL_EXT_draw_range_elements */ + +#ifndef GL_EXT_fog_coord +#define GL_EXT_fog_coord 1 +#define GL_FOG_COORDINATE_SOURCE_EXT 0x8450 +#define GL_FOG_COORDINATE_EXT 0x8451 +#define GL_FRAGMENT_DEPTH_EXT 0x8452 +#define GL_CURRENT_FOG_COORDINATE_EXT 0x8453 +#define GL_FOG_COORDINATE_ARRAY_TYPE_EXT 0x8454 +#define GL_FOG_COORDINATE_ARRAY_STRIDE_EXT 0x8455 +#define GL_FOG_COORDINATE_ARRAY_POINTER_EXT 0x8456 +#define GL_FOG_COORDINATE_ARRAY_EXT 0x8457 +typedef void (APIENTRYP PFNGLFOGCOORDFEXTPROC) (GLfloat coord); +typedef void (APIENTRYP PFNGLFOGCOORDFVEXTPROC) (const GLfloat *coord); +typedef void (APIENTRYP PFNGLFOGCOORDDEXTPROC) (GLdouble coord); +typedef void (APIENTRYP PFNGLFOGCOORDDVEXTPROC) (const GLdouble *coord); +typedef void (APIENTRYP PFNGLFOGCOORDPOINTEREXTPROC) (GLenum type, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFogCoordfEXT (GLfloat coord); +GLAPI void APIENTRY glFogCoordfvEXT (const GLfloat *coord); +GLAPI void APIENTRY glFogCoorddEXT (GLdouble coord); +GLAPI void APIENTRY glFogCoorddvEXT (const GLdouble *coord); +GLAPI void APIENTRY glFogCoordPointerEXT (GLenum type, GLsizei stride, const void *pointer); +#endif +#endif /* GL_EXT_fog_coord */ + +#ifndef GL_EXT_framebuffer_blit +#define GL_EXT_framebuffer_blit 1 +#define GL_READ_FRAMEBUFFER_EXT 0x8CA8 +#define GL_DRAW_FRAMEBUFFER_EXT 0x8CA9 +#define GL_DRAW_FRAMEBUFFER_BINDING_EXT 0x8CA6 +#define GL_READ_FRAMEBUFFER_BINDING_EXT 0x8CAA +typedef void (APIENTRYP PFNGLBLITFRAMEBUFFEREXTPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlitFramebufferEXT (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +#endif +#endif /* GL_EXT_framebuffer_blit */ + +#ifndef GL_EXT_framebuffer_multisample +#define GL_EXT_framebuffer_multisample 1 +#define GL_RENDERBUFFER_SAMPLES_EXT 0x8CAB +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT 0x8D56 +#define GL_MAX_SAMPLES_EXT 0x8D57 +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glRenderbufferStorageMultisampleEXT (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +#endif +#endif /* GL_EXT_framebuffer_multisample */ + +#ifndef GL_EXT_framebuffer_multisample_blit_scaled +#define GL_EXT_framebuffer_multisample_blit_scaled 1 +#define GL_SCALED_RESOLVE_FASTEST_EXT 0x90BA +#define GL_SCALED_RESOLVE_NICEST_EXT 0x90BB +#endif /* GL_EXT_framebuffer_multisample_blit_scaled */ + +#ifndef GL_EXT_framebuffer_object +#define GL_EXT_framebuffer_object 1 +#define GL_INVALID_FRAMEBUFFER_OPERATION_EXT 0x0506 +#define GL_MAX_RENDERBUFFER_SIZE_EXT 0x84E8 +#define GL_FRAMEBUFFER_BINDING_EXT 0x8CA6 +#define GL_RENDERBUFFER_BINDING_EXT 0x8CA7 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT 0x8CD0 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT 0x8CD1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT 0x8CD2 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT 0x8CD3 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT 0x8CD4 +#define GL_FRAMEBUFFER_COMPLETE_EXT 0x8CD5 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT 0x8CD9 +#define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT 0x8CDA +#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT 0x8CDB +#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT 0x8CDC +#define GL_FRAMEBUFFER_UNSUPPORTED_EXT 0x8CDD +#define GL_MAX_COLOR_ATTACHMENTS_EXT 0x8CDF +#define GL_COLOR_ATTACHMENT0_EXT 0x8CE0 +#define GL_COLOR_ATTACHMENT1_EXT 0x8CE1 +#define GL_COLOR_ATTACHMENT2_EXT 0x8CE2 +#define GL_COLOR_ATTACHMENT3_EXT 0x8CE3 +#define GL_COLOR_ATTACHMENT4_EXT 0x8CE4 +#define GL_COLOR_ATTACHMENT5_EXT 0x8CE5 +#define GL_COLOR_ATTACHMENT6_EXT 0x8CE6 +#define GL_COLOR_ATTACHMENT7_EXT 0x8CE7 +#define GL_COLOR_ATTACHMENT8_EXT 0x8CE8 +#define GL_COLOR_ATTACHMENT9_EXT 0x8CE9 +#define GL_COLOR_ATTACHMENT10_EXT 0x8CEA +#define GL_COLOR_ATTACHMENT11_EXT 0x8CEB +#define GL_COLOR_ATTACHMENT12_EXT 0x8CEC +#define GL_COLOR_ATTACHMENT13_EXT 0x8CED +#define GL_COLOR_ATTACHMENT14_EXT 0x8CEE +#define GL_COLOR_ATTACHMENT15_EXT 0x8CEF +#define GL_DEPTH_ATTACHMENT_EXT 0x8D00 +#define GL_STENCIL_ATTACHMENT_EXT 0x8D20 +#define GL_FRAMEBUFFER_EXT 0x8D40 +#define GL_RENDERBUFFER_EXT 0x8D41 +#define GL_RENDERBUFFER_WIDTH_EXT 0x8D42 +#define GL_RENDERBUFFER_HEIGHT_EXT 0x8D43 +#define GL_RENDERBUFFER_INTERNAL_FORMAT_EXT 0x8D44 +#define GL_STENCIL_INDEX1_EXT 0x8D46 +#define GL_STENCIL_INDEX4_EXT 0x8D47 +#define GL_STENCIL_INDEX8_EXT 0x8D48 +#define GL_STENCIL_INDEX16_EXT 0x8D49 +#define GL_RENDERBUFFER_RED_SIZE_EXT 0x8D50 +#define GL_RENDERBUFFER_GREEN_SIZE_EXT 0x8D51 +#define GL_RENDERBUFFER_BLUE_SIZE_EXT 0x8D52 +#define GL_RENDERBUFFER_ALPHA_SIZE_EXT 0x8D53 +#define GL_RENDERBUFFER_DEPTH_SIZE_EXT 0x8D54 +#define GL_RENDERBUFFER_STENCIL_SIZE_EXT 0x8D55 +typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFEREXTPROC) (GLuint renderbuffer); +typedef void (APIENTRYP PFNGLBINDRENDERBUFFEREXTPROC) (GLenum target, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSEXTPROC) (GLsizei n, const GLuint *renderbuffers); +typedef void (APIENTRYP PFNGLGENRENDERBUFFERSEXTPROC) (GLsizei n, GLuint *renderbuffers); +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFEREXTPROC) (GLuint framebuffer); +typedef void (APIENTRYP PFNGLBINDFRAMEBUFFEREXTPROC) (GLenum target, GLuint framebuffer); +typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSEXTPROC) (GLsizei n, const GLuint *framebuffers); +typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC) (GLsizei n, GLuint *framebuffers); +typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) (GLenum target); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGENERATEMIPMAPEXTPROC) (GLenum target); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLboolean APIENTRY glIsRenderbufferEXT (GLuint renderbuffer); +GLAPI void APIENTRY glBindRenderbufferEXT (GLenum target, GLuint renderbuffer); +GLAPI void APIENTRY glDeleteRenderbuffersEXT (GLsizei n, const GLuint *renderbuffers); +GLAPI void APIENTRY glGenRenderbuffersEXT (GLsizei n, GLuint *renderbuffers); +GLAPI void APIENTRY glRenderbufferStorageEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetRenderbufferParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI GLboolean APIENTRY glIsFramebufferEXT (GLuint framebuffer); +GLAPI void APIENTRY glBindFramebufferEXT (GLenum target, GLuint framebuffer); +GLAPI void APIENTRY glDeleteFramebuffersEXT (GLsizei n, const GLuint *framebuffers); +GLAPI void APIENTRY glGenFramebuffersEXT (GLsizei n, GLuint *framebuffers); +GLAPI GLenum APIENTRY glCheckFramebufferStatusEXT (GLenum target); +GLAPI void APIENTRY glFramebufferTexture1DEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI void APIENTRY glFramebufferTexture2DEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI void APIENTRY glFramebufferTexture3DEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +GLAPI void APIENTRY glFramebufferRenderbufferEXT (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +GLAPI void APIENTRY glGetFramebufferAttachmentParameterivEXT (GLenum target, GLenum attachment, GLenum pname, GLint *params); +GLAPI void APIENTRY glGenerateMipmapEXT (GLenum target); +#endif +#endif /* GL_EXT_framebuffer_object */ + +#ifndef GL_EXT_framebuffer_sRGB +#define GL_EXT_framebuffer_sRGB 1 +#define GL_FRAMEBUFFER_SRGB_EXT 0x8DB9 +#define GL_FRAMEBUFFER_SRGB_CAPABLE_EXT 0x8DBA +#endif /* GL_EXT_framebuffer_sRGB */ + +#ifndef GL_EXT_geometry_shader4 +#define GL_EXT_geometry_shader4 1 +#define GL_GEOMETRY_SHADER_EXT 0x8DD9 +#define GL_GEOMETRY_VERTICES_OUT_EXT 0x8DDA +#define GL_GEOMETRY_INPUT_TYPE_EXT 0x8DDB +#define GL_GEOMETRY_OUTPUT_TYPE_EXT 0x8DDC +#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_EXT 0x8C29 +#define GL_MAX_GEOMETRY_VARYING_COMPONENTS_EXT 0x8DDD +#define GL_MAX_VERTEX_VARYING_COMPONENTS_EXT 0x8DDE +#define GL_MAX_VARYING_COMPONENTS_EXT 0x8B4B +#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT 0x8DDF +#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT 0x8DE0 +#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_EXT 0x8DE1 +#define GL_LINES_ADJACENCY_EXT 0x000A +#define GL_LINE_STRIP_ADJACENCY_EXT 0x000B +#define GL_TRIANGLES_ADJACENCY_EXT 0x000C +#define GL_TRIANGLE_STRIP_ADJACENCY_EXT 0x000D +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_EXT 0x8DA8 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_EXT 0x8DA9 +#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_EXT 0x8DA7 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT 0x8CD4 +#define GL_PROGRAM_POINT_SIZE_EXT 0x8642 +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIEXTPROC) (GLuint program, GLenum pname, GLint value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramParameteriEXT (GLuint program, GLenum pname, GLint value); +#endif +#endif /* GL_EXT_geometry_shader4 */ + +#ifndef GL_EXT_gpu_program_parameters +#define GL_EXT_gpu_program_parameters 1 +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERS4FVEXTPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERS4FVEXTPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramEnvParameters4fvEXT (GLenum target, GLuint index, GLsizei count, const GLfloat *params); +GLAPI void APIENTRY glProgramLocalParameters4fvEXT (GLenum target, GLuint index, GLsizei count, const GLfloat *params); +#endif +#endif /* GL_EXT_gpu_program_parameters */ + +#ifndef GL_EXT_gpu_shader4 +#define GL_EXT_gpu_shader4 1 +#define GL_VERTEX_ATTRIB_ARRAY_INTEGER_EXT 0x88FD +#define GL_SAMPLER_1D_ARRAY_EXT 0x8DC0 +#define GL_SAMPLER_2D_ARRAY_EXT 0x8DC1 +#define GL_SAMPLER_BUFFER_EXT 0x8DC2 +#define GL_SAMPLER_1D_ARRAY_SHADOW_EXT 0x8DC3 +#define GL_SAMPLER_2D_ARRAY_SHADOW_EXT 0x8DC4 +#define GL_SAMPLER_CUBE_SHADOW_EXT 0x8DC5 +#define GL_UNSIGNED_INT_VEC2_EXT 0x8DC6 +#define GL_UNSIGNED_INT_VEC3_EXT 0x8DC7 +#define GL_UNSIGNED_INT_VEC4_EXT 0x8DC8 +#define GL_INT_SAMPLER_1D_EXT 0x8DC9 +#define GL_INT_SAMPLER_2D_EXT 0x8DCA +#define GL_INT_SAMPLER_3D_EXT 0x8DCB +#define GL_INT_SAMPLER_CUBE_EXT 0x8DCC +#define GL_INT_SAMPLER_2D_RECT_EXT 0x8DCD +#define GL_INT_SAMPLER_1D_ARRAY_EXT 0x8DCE +#define GL_INT_SAMPLER_2D_ARRAY_EXT 0x8DCF +#define GL_INT_SAMPLER_BUFFER_EXT 0x8DD0 +#define GL_UNSIGNED_INT_SAMPLER_1D_EXT 0x8DD1 +#define GL_UNSIGNED_INT_SAMPLER_2D_EXT 0x8DD2 +#define GL_UNSIGNED_INT_SAMPLER_3D_EXT 0x8DD3 +#define GL_UNSIGNED_INT_SAMPLER_CUBE_EXT 0x8DD4 +#define GL_UNSIGNED_INT_SAMPLER_2D_RECT_EXT 0x8DD5 +#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY_EXT 0x8DD6 +#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY_EXT 0x8DD7 +#define GL_UNSIGNED_INT_SAMPLER_BUFFER_EXT 0x8DD8 +#define GL_MIN_PROGRAM_TEXEL_OFFSET_EXT 0x8904 +#define GL_MAX_PROGRAM_TEXEL_OFFSET_EXT 0x8905 +typedef void (APIENTRYP PFNGLGETUNIFORMUIVEXTPROC) (GLuint program, GLint location, GLuint *params); +typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONEXTPROC) (GLuint program, GLuint color, const GLchar *name); +typedef GLint (APIENTRYP PFNGLGETFRAGDATALOCATIONEXTPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLUNIFORM1UIEXTPROC) (GLint location, GLuint v0); +typedef void (APIENTRYP PFNGLUNIFORM2UIEXTPROC) (GLint location, GLuint v0, GLuint v1); +typedef void (APIENTRYP PFNGLUNIFORM3UIEXTPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2); +typedef void (APIENTRYP PFNGLUNIFORM4UIEXTPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +typedef void (APIENTRYP PFNGLUNIFORM1UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLUNIFORM2UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLUNIFORM3UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLUNIFORM4UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetUniformuivEXT (GLuint program, GLint location, GLuint *params); +GLAPI void APIENTRY glBindFragDataLocationEXT (GLuint program, GLuint color, const GLchar *name); +GLAPI GLint APIENTRY glGetFragDataLocationEXT (GLuint program, const GLchar *name); +GLAPI void APIENTRY glUniform1uiEXT (GLint location, GLuint v0); +GLAPI void APIENTRY glUniform2uiEXT (GLint location, GLuint v0, GLuint v1); +GLAPI void APIENTRY glUniform3uiEXT (GLint location, GLuint v0, GLuint v1, GLuint v2); +GLAPI void APIENTRY glUniform4uiEXT (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +GLAPI void APIENTRY glUniform1uivEXT (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glUniform2uivEXT (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glUniform3uivEXT (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glUniform4uivEXT (GLint location, GLsizei count, const GLuint *value); +#endif +#endif /* GL_EXT_gpu_shader4 */ + +#ifndef GL_EXT_histogram +#define GL_EXT_histogram 1 +#define GL_HISTOGRAM_EXT 0x8024 +#define GL_PROXY_HISTOGRAM_EXT 0x8025 +#define GL_HISTOGRAM_WIDTH_EXT 0x8026 +#define GL_HISTOGRAM_FORMAT_EXT 0x8027 +#define GL_HISTOGRAM_RED_SIZE_EXT 0x8028 +#define GL_HISTOGRAM_GREEN_SIZE_EXT 0x8029 +#define GL_HISTOGRAM_BLUE_SIZE_EXT 0x802A +#define GL_HISTOGRAM_ALPHA_SIZE_EXT 0x802B +#define GL_HISTOGRAM_LUMINANCE_SIZE_EXT 0x802C +#define GL_HISTOGRAM_SINK_EXT 0x802D +#define GL_MINMAX_EXT 0x802E +#define GL_MINMAX_FORMAT_EXT 0x802F +#define GL_MINMAX_SINK_EXT 0x8030 +#define GL_TABLE_TOO_LARGE_EXT 0x8031 +typedef void (APIENTRYP PFNGLGETHISTOGRAMEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMINMAXEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLHISTOGRAMEXTPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink); +typedef void (APIENTRYP PFNGLMINMAXEXTPROC) (GLenum target, GLenum internalformat, GLboolean sink); +typedef void (APIENTRYP PFNGLRESETHISTOGRAMEXTPROC) (GLenum target); +typedef void (APIENTRYP PFNGLRESETMINMAXEXTPROC) (GLenum target); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetHistogramEXT (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +GLAPI void APIENTRY glGetHistogramParameterfvEXT (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetHistogramParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMinmaxEXT (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +GLAPI void APIENTRY glGetMinmaxParameterfvEXT (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMinmaxParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glHistogramEXT (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink); +GLAPI void APIENTRY glMinmaxEXT (GLenum target, GLenum internalformat, GLboolean sink); +GLAPI void APIENTRY glResetHistogramEXT (GLenum target); +GLAPI void APIENTRY glResetMinmaxEXT (GLenum target); +#endif +#endif /* GL_EXT_histogram */ + +#ifndef GL_EXT_index_array_formats +#define GL_EXT_index_array_formats 1 +#define GL_IUI_V2F_EXT 0x81AD +#define GL_IUI_V3F_EXT 0x81AE +#define GL_IUI_N3F_V2F_EXT 0x81AF +#define GL_IUI_N3F_V3F_EXT 0x81B0 +#define GL_T2F_IUI_V2F_EXT 0x81B1 +#define GL_T2F_IUI_V3F_EXT 0x81B2 +#define GL_T2F_IUI_N3F_V2F_EXT 0x81B3 +#define GL_T2F_IUI_N3F_V3F_EXT 0x81B4 +#endif /* GL_EXT_index_array_formats */ + +#ifndef GL_EXT_index_func +#define GL_EXT_index_func 1 +#define GL_INDEX_TEST_EXT 0x81B5 +#define GL_INDEX_TEST_FUNC_EXT 0x81B6 +#define GL_INDEX_TEST_REF_EXT 0x81B7 +typedef void (APIENTRYP PFNGLINDEXFUNCEXTPROC) (GLenum func, GLclampf ref); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glIndexFuncEXT (GLenum func, GLclampf ref); +#endif +#endif /* GL_EXT_index_func */ + +#ifndef GL_EXT_index_material +#define GL_EXT_index_material 1 +#define GL_INDEX_MATERIAL_EXT 0x81B8 +#define GL_INDEX_MATERIAL_PARAMETER_EXT 0x81B9 +#define GL_INDEX_MATERIAL_FACE_EXT 0x81BA +typedef void (APIENTRYP PFNGLINDEXMATERIALEXTPROC) (GLenum face, GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glIndexMaterialEXT (GLenum face, GLenum mode); +#endif +#endif /* GL_EXT_index_material */ + +#ifndef GL_EXT_index_texture +#define GL_EXT_index_texture 1 +#endif /* GL_EXT_index_texture */ + +#ifndef GL_EXT_light_texture +#define GL_EXT_light_texture 1 +#define GL_FRAGMENT_MATERIAL_EXT 0x8349 +#define GL_FRAGMENT_NORMAL_EXT 0x834A +#define GL_FRAGMENT_COLOR_EXT 0x834C +#define GL_ATTENUATION_EXT 0x834D +#define GL_SHADOW_ATTENUATION_EXT 0x834E +#define GL_TEXTURE_APPLICATION_MODE_EXT 0x834F +#define GL_TEXTURE_LIGHT_EXT 0x8350 +#define GL_TEXTURE_MATERIAL_FACE_EXT 0x8351 +#define GL_TEXTURE_MATERIAL_PARAMETER_EXT 0x8352 +typedef void (APIENTRYP PFNGLAPPLYTEXTUREEXTPROC) (GLenum mode); +typedef void (APIENTRYP PFNGLTEXTURELIGHTEXTPROC) (GLenum pname); +typedef void (APIENTRYP PFNGLTEXTUREMATERIALEXTPROC) (GLenum face, GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glApplyTextureEXT (GLenum mode); +GLAPI void APIENTRY glTextureLightEXT (GLenum pname); +GLAPI void APIENTRY glTextureMaterialEXT (GLenum face, GLenum mode); +#endif +#endif /* GL_EXT_light_texture */ + +#ifndef GL_EXT_misc_attribute +#define GL_EXT_misc_attribute 1 +#endif /* GL_EXT_misc_attribute */ + +#ifndef GL_EXT_multi_draw_arrays +#define GL_EXT_multi_draw_arrays 1 +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiDrawArraysEXT (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); +GLAPI void APIENTRY glMultiDrawElementsEXT (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount); +#endif +#endif /* GL_EXT_multi_draw_arrays */ + +#ifndef GL_EXT_multisample +#define GL_EXT_multisample 1 +#define GL_MULTISAMPLE_EXT 0x809D +#define GL_SAMPLE_ALPHA_TO_MASK_EXT 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE_EXT 0x809F +#define GL_SAMPLE_MASK_EXT 0x80A0 +#define GL_1PASS_EXT 0x80A1 +#define GL_2PASS_0_EXT 0x80A2 +#define GL_2PASS_1_EXT 0x80A3 +#define GL_4PASS_0_EXT 0x80A4 +#define GL_4PASS_1_EXT 0x80A5 +#define GL_4PASS_2_EXT 0x80A6 +#define GL_4PASS_3_EXT 0x80A7 +#define GL_SAMPLE_BUFFERS_EXT 0x80A8 +#define GL_SAMPLES_EXT 0x80A9 +#define GL_SAMPLE_MASK_VALUE_EXT 0x80AA +#define GL_SAMPLE_MASK_INVERT_EXT 0x80AB +#define GL_SAMPLE_PATTERN_EXT 0x80AC +#define GL_MULTISAMPLE_BIT_EXT 0x20000000 +typedef void (APIENTRYP PFNGLSAMPLEMASKEXTPROC) (GLclampf value, GLboolean invert); +typedef void (APIENTRYP PFNGLSAMPLEPATTERNEXTPROC) (GLenum pattern); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSampleMaskEXT (GLclampf value, GLboolean invert); +GLAPI void APIENTRY glSamplePatternEXT (GLenum pattern); +#endif +#endif /* GL_EXT_multisample */ + +#ifndef GL_EXT_packed_depth_stencil +#define GL_EXT_packed_depth_stencil 1 +#define GL_DEPTH_STENCIL_EXT 0x84F9 +#define GL_UNSIGNED_INT_24_8_EXT 0x84FA +#define GL_DEPTH24_STENCIL8_EXT 0x88F0 +#define GL_TEXTURE_STENCIL_SIZE_EXT 0x88F1 +#endif /* GL_EXT_packed_depth_stencil */ + +#ifndef GL_EXT_packed_float +#define GL_EXT_packed_float 1 +#define GL_R11F_G11F_B10F_EXT 0x8C3A +#define GL_UNSIGNED_INT_10F_11F_11F_REV_EXT 0x8C3B +#define GL_RGBA_SIGNED_COMPONENTS_EXT 0x8C3C +#endif /* GL_EXT_packed_float */ + +#ifndef GL_EXT_packed_pixels +#define GL_EXT_packed_pixels 1 +#define GL_UNSIGNED_BYTE_3_3_2_EXT 0x8032 +#define GL_UNSIGNED_SHORT_4_4_4_4_EXT 0x8033 +#define GL_UNSIGNED_SHORT_5_5_5_1_EXT 0x8034 +#define GL_UNSIGNED_INT_8_8_8_8_EXT 0x8035 +#define GL_UNSIGNED_INT_10_10_10_2_EXT 0x8036 +#endif /* GL_EXT_packed_pixels */ + +#ifndef GL_EXT_paletted_texture +#define GL_EXT_paletted_texture 1 +#define GL_COLOR_INDEX1_EXT 0x80E2 +#define GL_COLOR_INDEX2_EXT 0x80E3 +#define GL_COLOR_INDEX4_EXT 0x80E4 +#define GL_COLOR_INDEX8_EXT 0x80E5 +#define GL_COLOR_INDEX12_EXT 0x80E6 +#define GL_COLOR_INDEX16_EXT 0x80E7 +#define GL_TEXTURE_INDEX_SIZE_EXT 0x80ED +typedef void (APIENTRYP PFNGLCOLORTABLEEXTPROC) (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const void *table); +typedef void (APIENTRYP PFNGLGETCOLORTABLEEXTPROC) (GLenum target, GLenum format, GLenum type, void *data); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorTableEXT (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const void *table); +GLAPI void APIENTRY glGetColorTableEXT (GLenum target, GLenum format, GLenum type, void *data); +GLAPI void APIENTRY glGetColorTableParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetColorTableParameterfvEXT (GLenum target, GLenum pname, GLfloat *params); +#endif +#endif /* GL_EXT_paletted_texture */ + +#ifndef GL_EXT_pixel_buffer_object +#define GL_EXT_pixel_buffer_object 1 +#define GL_PIXEL_PACK_BUFFER_EXT 0x88EB +#define GL_PIXEL_UNPACK_BUFFER_EXT 0x88EC +#define GL_PIXEL_PACK_BUFFER_BINDING_EXT 0x88ED +#define GL_PIXEL_UNPACK_BUFFER_BINDING_EXT 0x88EF +#endif /* GL_EXT_pixel_buffer_object */ + +#ifndef GL_EXT_pixel_transform +#define GL_EXT_pixel_transform 1 +#define GL_PIXEL_TRANSFORM_2D_EXT 0x8330 +#define GL_PIXEL_MAG_FILTER_EXT 0x8331 +#define GL_PIXEL_MIN_FILTER_EXT 0x8332 +#define GL_PIXEL_CUBIC_WEIGHT_EXT 0x8333 +#define GL_CUBIC_EXT 0x8334 +#define GL_AVERAGE_EXT 0x8335 +#define GL_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8336 +#define GL_MAX_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8337 +#define GL_PIXEL_TRANSFORM_2D_MATRIX_EXT 0x8338 +typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETPIXELTRANSFORMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPIXELTRANSFORMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPixelTransformParameteriEXT (GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glPixelTransformParameterfEXT (GLenum target, GLenum pname, GLfloat param); +GLAPI void APIENTRY glPixelTransformParameterivEXT (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glPixelTransformParameterfvEXT (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glGetPixelTransformParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetPixelTransformParameterfvEXT (GLenum target, GLenum pname, GLfloat *params); +#endif +#endif /* GL_EXT_pixel_transform */ + +#ifndef GL_EXT_pixel_transform_color_table +#define GL_EXT_pixel_transform_color_table 1 +#endif /* GL_EXT_pixel_transform_color_table */ + +#ifndef GL_EXT_point_parameters +#define GL_EXT_point_parameters 1 +#define GL_POINT_SIZE_MIN_EXT 0x8126 +#define GL_POINT_SIZE_MAX_EXT 0x8127 +#define GL_POINT_FADE_THRESHOLD_SIZE_EXT 0x8128 +#define GL_DISTANCE_ATTENUATION_EXT 0x8129 +typedef void (APIENTRYP PFNGLPOINTPARAMETERFEXTPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVEXTPROC) (GLenum pname, const GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPointParameterfEXT (GLenum pname, GLfloat param); +GLAPI void APIENTRY glPointParameterfvEXT (GLenum pname, const GLfloat *params); +#endif +#endif /* GL_EXT_point_parameters */ + +#ifndef GL_EXT_polygon_offset +#define GL_EXT_polygon_offset 1 +#define GL_POLYGON_OFFSET_EXT 0x8037 +#define GL_POLYGON_OFFSET_FACTOR_EXT 0x8038 +#define GL_POLYGON_OFFSET_BIAS_EXT 0x8039 +typedef void (APIENTRYP PFNGLPOLYGONOFFSETEXTPROC) (GLfloat factor, GLfloat bias); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPolygonOffsetEXT (GLfloat factor, GLfloat bias); +#endif +#endif /* GL_EXT_polygon_offset */ + +#ifndef GL_EXT_polygon_offset_clamp +#define GL_EXT_polygon_offset_clamp 1 +#define GL_POLYGON_OFFSET_CLAMP_EXT 0x8E1B +typedef void (APIENTRYP PFNGLPOLYGONOFFSETCLAMPEXTPROC) (GLfloat factor, GLfloat units, GLfloat clamp); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPolygonOffsetClampEXT (GLfloat factor, GLfloat units, GLfloat clamp); +#endif +#endif /* GL_EXT_polygon_offset_clamp */ + +#ifndef GL_EXT_post_depth_coverage +#define GL_EXT_post_depth_coverage 1 +#endif /* GL_EXT_post_depth_coverage */ + +#ifndef GL_EXT_provoking_vertex +#define GL_EXT_provoking_vertex 1 +#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION_EXT 0x8E4C +#define GL_FIRST_VERTEX_CONVENTION_EXT 0x8E4D +#define GL_LAST_VERTEX_CONVENTION_EXT 0x8E4E +#define GL_PROVOKING_VERTEX_EXT 0x8E4F +typedef void (APIENTRYP PFNGLPROVOKINGVERTEXEXTPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProvokingVertexEXT (GLenum mode); +#endif +#endif /* GL_EXT_provoking_vertex */ + +#ifndef GL_EXT_raster_multisample +#define GL_EXT_raster_multisample 1 +#define GL_RASTER_MULTISAMPLE_EXT 0x9327 +#define GL_RASTER_SAMPLES_EXT 0x9328 +#define GL_MAX_RASTER_SAMPLES_EXT 0x9329 +#define GL_RASTER_FIXED_SAMPLE_LOCATIONS_EXT 0x932A +#define GL_MULTISAMPLE_RASTERIZATION_ALLOWED_EXT 0x932B +#define GL_EFFECTIVE_RASTER_SAMPLES_EXT 0x932C +typedef void (APIENTRYP PFNGLRASTERSAMPLESEXTPROC) (GLuint samples, GLboolean fixedsamplelocations); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glRasterSamplesEXT (GLuint samples, GLboolean fixedsamplelocations); +#endif +#endif /* GL_EXT_raster_multisample */ + +#ifndef GL_EXT_rescale_normal +#define GL_EXT_rescale_normal 1 +#define GL_RESCALE_NORMAL_EXT 0x803A +#endif /* GL_EXT_rescale_normal */ + +#ifndef GL_EXT_secondary_color +#define GL_EXT_secondary_color 1 +#define GL_COLOR_SUM_EXT 0x8458 +#define GL_CURRENT_SECONDARY_COLOR_EXT 0x8459 +#define GL_SECONDARY_COLOR_ARRAY_SIZE_EXT 0x845A +#define GL_SECONDARY_COLOR_ARRAY_TYPE_EXT 0x845B +#define GL_SECONDARY_COLOR_ARRAY_STRIDE_EXT 0x845C +#define GL_SECONDARY_COLOR_ARRAY_POINTER_EXT 0x845D +#define GL_SECONDARY_COLOR_ARRAY_EXT 0x845E +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BEXTPROC) (GLbyte red, GLbyte green, GLbyte blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVEXTPROC) (const GLbyte *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DEXTPROC) (GLdouble red, GLdouble green, GLdouble blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVEXTPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FEXTPROC) (GLfloat red, GLfloat green, GLfloat blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVEXTPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IEXTPROC) (GLint red, GLint green, GLint blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVEXTPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SEXTPROC) (GLshort red, GLshort green, GLshort blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVEXTPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBEXTPROC) (GLubyte red, GLubyte green, GLubyte blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVEXTPROC) (const GLubyte *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIEXTPROC) (GLuint red, GLuint green, GLuint blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVEXTPROC) (const GLuint *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USEXTPROC) (GLushort red, GLushort green, GLushort blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVEXTPROC) (const GLushort *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSecondaryColor3bEXT (GLbyte red, GLbyte green, GLbyte blue); +GLAPI void APIENTRY glSecondaryColor3bvEXT (const GLbyte *v); +GLAPI void APIENTRY glSecondaryColor3dEXT (GLdouble red, GLdouble green, GLdouble blue); +GLAPI void APIENTRY glSecondaryColor3dvEXT (const GLdouble *v); +GLAPI void APIENTRY glSecondaryColor3fEXT (GLfloat red, GLfloat green, GLfloat blue); +GLAPI void APIENTRY glSecondaryColor3fvEXT (const GLfloat *v); +GLAPI void APIENTRY glSecondaryColor3iEXT (GLint red, GLint green, GLint blue); +GLAPI void APIENTRY glSecondaryColor3ivEXT (const GLint *v); +GLAPI void APIENTRY glSecondaryColor3sEXT (GLshort red, GLshort green, GLshort blue); +GLAPI void APIENTRY glSecondaryColor3svEXT (const GLshort *v); +GLAPI void APIENTRY glSecondaryColor3ubEXT (GLubyte red, GLubyte green, GLubyte blue); +GLAPI void APIENTRY glSecondaryColor3ubvEXT (const GLubyte *v); +GLAPI void APIENTRY glSecondaryColor3uiEXT (GLuint red, GLuint green, GLuint blue); +GLAPI void APIENTRY glSecondaryColor3uivEXT (const GLuint *v); +GLAPI void APIENTRY glSecondaryColor3usEXT (GLushort red, GLushort green, GLushort blue); +GLAPI void APIENTRY glSecondaryColor3usvEXT (const GLushort *v); +GLAPI void APIENTRY glSecondaryColorPointerEXT (GLint size, GLenum type, GLsizei stride, const void *pointer); +#endif +#endif /* GL_EXT_secondary_color */ + +#ifndef GL_EXT_separate_shader_objects +#define GL_EXT_separate_shader_objects 1 +#define GL_ACTIVE_PROGRAM_EXT 0x8B8D +typedef void (APIENTRYP PFNGLUSESHADERPROGRAMEXTPROC) (GLenum type, GLuint program); +typedef void (APIENTRYP PFNGLACTIVEPROGRAMEXTPROC) (GLuint program); +typedef GLuint (APIENTRYP PFNGLCREATESHADERPROGRAMEXTPROC) (GLenum type, const GLchar *string); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glUseShaderProgramEXT (GLenum type, GLuint program); +GLAPI void APIENTRY glActiveProgramEXT (GLuint program); +GLAPI GLuint APIENTRY glCreateShaderProgramEXT (GLenum type, const GLchar *string); +#endif +#endif /* GL_EXT_separate_shader_objects */ + +#ifndef GL_EXT_separate_specular_color +#define GL_EXT_separate_specular_color 1 +#define GL_LIGHT_MODEL_COLOR_CONTROL_EXT 0x81F8 +#define GL_SINGLE_COLOR_EXT 0x81F9 +#define GL_SEPARATE_SPECULAR_COLOR_EXT 0x81FA +#endif /* GL_EXT_separate_specular_color */ + +#ifndef GL_EXT_shader_image_load_formatted +#define GL_EXT_shader_image_load_formatted 1 +#endif /* GL_EXT_shader_image_load_formatted */ + +#ifndef GL_EXT_shader_image_load_store +#define GL_EXT_shader_image_load_store 1 +#define GL_MAX_IMAGE_UNITS_EXT 0x8F38 +#define GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS_EXT 0x8F39 +#define GL_IMAGE_BINDING_NAME_EXT 0x8F3A +#define GL_IMAGE_BINDING_LEVEL_EXT 0x8F3B +#define GL_IMAGE_BINDING_LAYERED_EXT 0x8F3C +#define GL_IMAGE_BINDING_LAYER_EXT 0x8F3D +#define GL_IMAGE_BINDING_ACCESS_EXT 0x8F3E +#define GL_IMAGE_1D_EXT 0x904C +#define GL_IMAGE_2D_EXT 0x904D +#define GL_IMAGE_3D_EXT 0x904E +#define GL_IMAGE_2D_RECT_EXT 0x904F +#define GL_IMAGE_CUBE_EXT 0x9050 +#define GL_IMAGE_BUFFER_EXT 0x9051 +#define GL_IMAGE_1D_ARRAY_EXT 0x9052 +#define GL_IMAGE_2D_ARRAY_EXT 0x9053 +#define GL_IMAGE_CUBE_MAP_ARRAY_EXT 0x9054 +#define GL_IMAGE_2D_MULTISAMPLE_EXT 0x9055 +#define GL_IMAGE_2D_MULTISAMPLE_ARRAY_EXT 0x9056 +#define GL_INT_IMAGE_1D_EXT 0x9057 +#define GL_INT_IMAGE_2D_EXT 0x9058 +#define GL_INT_IMAGE_3D_EXT 0x9059 +#define GL_INT_IMAGE_2D_RECT_EXT 0x905A +#define GL_INT_IMAGE_CUBE_EXT 0x905B +#define GL_INT_IMAGE_BUFFER_EXT 0x905C +#define GL_INT_IMAGE_1D_ARRAY_EXT 0x905D +#define GL_INT_IMAGE_2D_ARRAY_EXT 0x905E +#define GL_INT_IMAGE_CUBE_MAP_ARRAY_EXT 0x905F +#define GL_INT_IMAGE_2D_MULTISAMPLE_EXT 0x9060 +#define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY_EXT 0x9061 +#define GL_UNSIGNED_INT_IMAGE_1D_EXT 0x9062 +#define GL_UNSIGNED_INT_IMAGE_2D_EXT 0x9063 +#define GL_UNSIGNED_INT_IMAGE_3D_EXT 0x9064 +#define GL_UNSIGNED_INT_IMAGE_2D_RECT_EXT 0x9065 +#define GL_UNSIGNED_INT_IMAGE_CUBE_EXT 0x9066 +#define GL_UNSIGNED_INT_IMAGE_BUFFER_EXT 0x9067 +#define GL_UNSIGNED_INT_IMAGE_1D_ARRAY_EXT 0x9068 +#define GL_UNSIGNED_INT_IMAGE_2D_ARRAY_EXT 0x9069 +#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY_EXT 0x906A +#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_EXT 0x906B +#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY_EXT 0x906C +#define GL_MAX_IMAGE_SAMPLES_EXT 0x906D +#define GL_IMAGE_BINDING_FORMAT_EXT 0x906E +#define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT_EXT 0x00000001 +#define GL_ELEMENT_ARRAY_BARRIER_BIT_EXT 0x00000002 +#define GL_UNIFORM_BARRIER_BIT_EXT 0x00000004 +#define GL_TEXTURE_FETCH_BARRIER_BIT_EXT 0x00000008 +#define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT_EXT 0x00000020 +#define GL_COMMAND_BARRIER_BIT_EXT 0x00000040 +#define GL_PIXEL_BUFFER_BARRIER_BIT_EXT 0x00000080 +#define GL_TEXTURE_UPDATE_BARRIER_BIT_EXT 0x00000100 +#define GL_BUFFER_UPDATE_BARRIER_BIT_EXT 0x00000200 +#define GL_FRAMEBUFFER_BARRIER_BIT_EXT 0x00000400 +#define GL_TRANSFORM_FEEDBACK_BARRIER_BIT_EXT 0x00000800 +#define GL_ATOMIC_COUNTER_BARRIER_BIT_EXT 0x00001000 +#define GL_ALL_BARRIER_BITS_EXT 0xFFFFFFFF +typedef void (APIENTRYP PFNGLBINDIMAGETEXTUREEXTPROC) (GLuint index, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLint format); +typedef void (APIENTRYP PFNGLMEMORYBARRIEREXTPROC) (GLbitfield barriers); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindImageTextureEXT (GLuint index, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLint format); +GLAPI void APIENTRY glMemoryBarrierEXT (GLbitfield barriers); +#endif +#endif /* GL_EXT_shader_image_load_store */ + +#ifndef GL_EXT_shader_integer_mix +#define GL_EXT_shader_integer_mix 1 +#endif /* GL_EXT_shader_integer_mix */ + +#ifndef GL_EXT_shadow_funcs +#define GL_EXT_shadow_funcs 1 +#endif /* GL_EXT_shadow_funcs */ + +#ifndef GL_EXT_shared_texture_palette +#define GL_EXT_shared_texture_palette 1 +#define GL_SHARED_TEXTURE_PALETTE_EXT 0x81FB +#endif /* GL_EXT_shared_texture_palette */ + +#ifndef GL_EXT_sparse_texture2 +#define GL_EXT_sparse_texture2 1 +#endif /* GL_EXT_sparse_texture2 */ + +#ifndef GL_EXT_stencil_clear_tag +#define GL_EXT_stencil_clear_tag 1 +#define GL_STENCIL_TAG_BITS_EXT 0x88F2 +#define GL_STENCIL_CLEAR_TAG_VALUE_EXT 0x88F3 +typedef void (APIENTRYP PFNGLSTENCILCLEARTAGEXTPROC) (GLsizei stencilTagBits, GLuint stencilClearTag); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glStencilClearTagEXT (GLsizei stencilTagBits, GLuint stencilClearTag); +#endif +#endif /* GL_EXT_stencil_clear_tag */ + +#ifndef GL_EXT_stencil_two_side +#define GL_EXT_stencil_two_side 1 +#define GL_STENCIL_TEST_TWO_SIDE_EXT 0x8910 +#define GL_ACTIVE_STENCIL_FACE_EXT 0x8911 +typedef void (APIENTRYP PFNGLACTIVESTENCILFACEEXTPROC) (GLenum face); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glActiveStencilFaceEXT (GLenum face); +#endif +#endif /* GL_EXT_stencil_two_side */ + +#ifndef GL_EXT_stencil_wrap +#define GL_EXT_stencil_wrap 1 +#define GL_INCR_WRAP_EXT 0x8507 +#define GL_DECR_WRAP_EXT 0x8508 +#endif /* GL_EXT_stencil_wrap */ + +#ifndef GL_EXT_subtexture +#define GL_EXT_subtexture 1 +typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexSubImage1DEXT (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTexSubImage2DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +#endif +#endif /* GL_EXT_subtexture */ + +#ifndef GL_EXT_texture +#define GL_EXT_texture 1 +#define GL_ALPHA4_EXT 0x803B +#define GL_ALPHA8_EXT 0x803C +#define GL_ALPHA12_EXT 0x803D +#define GL_ALPHA16_EXT 0x803E +#define GL_LUMINANCE4_EXT 0x803F +#define GL_LUMINANCE8_EXT 0x8040 +#define GL_LUMINANCE12_EXT 0x8041 +#define GL_LUMINANCE16_EXT 0x8042 +#define GL_LUMINANCE4_ALPHA4_EXT 0x8043 +#define GL_LUMINANCE6_ALPHA2_EXT 0x8044 +#define GL_LUMINANCE8_ALPHA8_EXT 0x8045 +#define GL_LUMINANCE12_ALPHA4_EXT 0x8046 +#define GL_LUMINANCE12_ALPHA12_EXT 0x8047 +#define GL_LUMINANCE16_ALPHA16_EXT 0x8048 +#define GL_INTENSITY_EXT 0x8049 +#define GL_INTENSITY4_EXT 0x804A +#define GL_INTENSITY8_EXT 0x804B +#define GL_INTENSITY12_EXT 0x804C +#define GL_INTENSITY16_EXT 0x804D +#define GL_RGB2_EXT 0x804E +#define GL_RGB4_EXT 0x804F +#define GL_RGB5_EXT 0x8050 +#define GL_RGB8_EXT 0x8051 +#define GL_RGB10_EXT 0x8052 +#define GL_RGB12_EXT 0x8053 +#define GL_RGB16_EXT 0x8054 +#define GL_RGBA2_EXT 0x8055 +#define GL_RGBA4_EXT 0x8056 +#define GL_RGB5_A1_EXT 0x8057 +#define GL_RGBA8_EXT 0x8058 +#define GL_RGB10_A2_EXT 0x8059 +#define GL_RGBA12_EXT 0x805A +#define GL_RGBA16_EXT 0x805B +#define GL_TEXTURE_RED_SIZE_EXT 0x805C +#define GL_TEXTURE_GREEN_SIZE_EXT 0x805D +#define GL_TEXTURE_BLUE_SIZE_EXT 0x805E +#define GL_TEXTURE_ALPHA_SIZE_EXT 0x805F +#define GL_TEXTURE_LUMINANCE_SIZE_EXT 0x8060 +#define GL_TEXTURE_INTENSITY_SIZE_EXT 0x8061 +#define GL_REPLACE_EXT 0x8062 +#define GL_PROXY_TEXTURE_1D_EXT 0x8063 +#define GL_PROXY_TEXTURE_2D_EXT 0x8064 +#define GL_TEXTURE_TOO_LARGE_EXT 0x8065 +#endif /* GL_EXT_texture */ + +#ifndef GL_EXT_texture3D +#define GL_EXT_texture3D 1 +#define GL_PACK_SKIP_IMAGES_EXT 0x806B +#define GL_PACK_IMAGE_HEIGHT_EXT 0x806C +#define GL_UNPACK_SKIP_IMAGES_EXT 0x806D +#define GL_UNPACK_IMAGE_HEIGHT_EXT 0x806E +#define GL_TEXTURE_3D_EXT 0x806F +#define GL_PROXY_TEXTURE_3D_EXT 0x8070 +#define GL_TEXTURE_DEPTH_EXT 0x8071 +#define GL_TEXTURE_WRAP_R_EXT 0x8072 +#define GL_MAX_3D_TEXTURE_SIZE_EXT 0x8073 +typedef void (APIENTRYP PFNGLTEXIMAGE3DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexImage3DEXT (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTexSubImage3DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +#endif +#endif /* GL_EXT_texture3D */ + +#ifndef GL_EXT_texture_array +#define GL_EXT_texture_array 1 +#define GL_TEXTURE_1D_ARRAY_EXT 0x8C18 +#define GL_PROXY_TEXTURE_1D_ARRAY_EXT 0x8C19 +#define GL_TEXTURE_2D_ARRAY_EXT 0x8C1A +#define GL_PROXY_TEXTURE_2D_ARRAY_EXT 0x8C1B +#define GL_TEXTURE_BINDING_1D_ARRAY_EXT 0x8C1C +#define GL_TEXTURE_BINDING_2D_ARRAY_EXT 0x8C1D +#define GL_MAX_ARRAY_TEXTURE_LAYERS_EXT 0x88FF +#define GL_COMPARE_REF_DEPTH_TO_TEXTURE_EXT 0x884E +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYEREXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFramebufferTextureLayerEXT (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +#endif +#endif /* GL_EXT_texture_array */ + +#ifndef GL_EXT_texture_buffer_object +#define GL_EXT_texture_buffer_object 1 +#define GL_TEXTURE_BUFFER_EXT 0x8C2A +#define GL_MAX_TEXTURE_BUFFER_SIZE_EXT 0x8C2B +#define GL_TEXTURE_BINDING_BUFFER_EXT 0x8C2C +#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING_EXT 0x8C2D +#define GL_TEXTURE_BUFFER_FORMAT_EXT 0x8C2E +typedef void (APIENTRYP PFNGLTEXBUFFEREXTPROC) (GLenum target, GLenum internalformat, GLuint buffer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexBufferEXT (GLenum target, GLenum internalformat, GLuint buffer); +#endif +#endif /* GL_EXT_texture_buffer_object */ + +#ifndef GL_EXT_texture_compression_latc +#define GL_EXT_texture_compression_latc 1 +#define GL_COMPRESSED_LUMINANCE_LATC1_EXT 0x8C70 +#define GL_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT 0x8C71 +#define GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT 0x8C72 +#define GL_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT 0x8C73 +#endif /* GL_EXT_texture_compression_latc */ + +#ifndef GL_EXT_texture_compression_rgtc +#define GL_EXT_texture_compression_rgtc 1 +#define GL_COMPRESSED_RED_RGTC1_EXT 0x8DBB +#define GL_COMPRESSED_SIGNED_RED_RGTC1_EXT 0x8DBC +#define GL_COMPRESSED_RED_GREEN_RGTC2_EXT 0x8DBD +#define GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT 0x8DBE +#endif /* GL_EXT_texture_compression_rgtc */ + +#ifndef GL_EXT_texture_compression_s3tc +#define GL_EXT_texture_compression_s3tc 1 +#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 +#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 +#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 +#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 +#endif /* GL_EXT_texture_compression_s3tc */ + +#ifndef GL_EXT_texture_cube_map +#define GL_EXT_texture_cube_map 1 +#define GL_NORMAL_MAP_EXT 0x8511 +#define GL_REFLECTION_MAP_EXT 0x8512 +#define GL_TEXTURE_CUBE_MAP_EXT 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP_EXT 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT 0x851A +#define GL_PROXY_TEXTURE_CUBE_MAP_EXT 0x851B +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_EXT 0x851C +#endif /* GL_EXT_texture_cube_map */ + +#ifndef GL_EXT_texture_env_add +#define GL_EXT_texture_env_add 1 +#endif /* GL_EXT_texture_env_add */ + +#ifndef GL_EXT_texture_env_combine +#define GL_EXT_texture_env_combine 1 +#define GL_COMBINE_EXT 0x8570 +#define GL_COMBINE_RGB_EXT 0x8571 +#define GL_COMBINE_ALPHA_EXT 0x8572 +#define GL_RGB_SCALE_EXT 0x8573 +#define GL_ADD_SIGNED_EXT 0x8574 +#define GL_INTERPOLATE_EXT 0x8575 +#define GL_CONSTANT_EXT 0x8576 +#define GL_PRIMARY_COLOR_EXT 0x8577 +#define GL_PREVIOUS_EXT 0x8578 +#define GL_SOURCE0_RGB_EXT 0x8580 +#define GL_SOURCE1_RGB_EXT 0x8581 +#define GL_SOURCE2_RGB_EXT 0x8582 +#define GL_SOURCE0_ALPHA_EXT 0x8588 +#define GL_SOURCE1_ALPHA_EXT 0x8589 +#define GL_SOURCE2_ALPHA_EXT 0x858A +#define GL_OPERAND0_RGB_EXT 0x8590 +#define GL_OPERAND1_RGB_EXT 0x8591 +#define GL_OPERAND2_RGB_EXT 0x8592 +#define GL_OPERAND0_ALPHA_EXT 0x8598 +#define GL_OPERAND1_ALPHA_EXT 0x8599 +#define GL_OPERAND2_ALPHA_EXT 0x859A +#endif /* GL_EXT_texture_env_combine */ + +#ifndef GL_EXT_texture_env_dot3 +#define GL_EXT_texture_env_dot3 1 +#define GL_DOT3_RGB_EXT 0x8740 +#define GL_DOT3_RGBA_EXT 0x8741 +#endif /* GL_EXT_texture_env_dot3 */ + +#ifndef GL_EXT_texture_filter_anisotropic +#define GL_EXT_texture_filter_anisotropic 1 +#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE +#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF +#endif /* GL_EXT_texture_filter_anisotropic */ + +#ifndef GL_EXT_texture_filter_minmax +#define GL_EXT_texture_filter_minmax 1 +#endif /* GL_EXT_texture_filter_minmax */ + +#ifndef GL_EXT_texture_integer +#define GL_EXT_texture_integer 1 +#define GL_RGBA32UI_EXT 0x8D70 +#define GL_RGB32UI_EXT 0x8D71 +#define GL_ALPHA32UI_EXT 0x8D72 +#define GL_INTENSITY32UI_EXT 0x8D73 +#define GL_LUMINANCE32UI_EXT 0x8D74 +#define GL_LUMINANCE_ALPHA32UI_EXT 0x8D75 +#define GL_RGBA16UI_EXT 0x8D76 +#define GL_RGB16UI_EXT 0x8D77 +#define GL_ALPHA16UI_EXT 0x8D78 +#define GL_INTENSITY16UI_EXT 0x8D79 +#define GL_LUMINANCE16UI_EXT 0x8D7A +#define GL_LUMINANCE_ALPHA16UI_EXT 0x8D7B +#define GL_RGBA8UI_EXT 0x8D7C +#define GL_RGB8UI_EXT 0x8D7D +#define GL_ALPHA8UI_EXT 0x8D7E +#define GL_INTENSITY8UI_EXT 0x8D7F +#define GL_LUMINANCE8UI_EXT 0x8D80 +#define GL_LUMINANCE_ALPHA8UI_EXT 0x8D81 +#define GL_RGBA32I_EXT 0x8D82 +#define GL_RGB32I_EXT 0x8D83 +#define GL_ALPHA32I_EXT 0x8D84 +#define GL_INTENSITY32I_EXT 0x8D85 +#define GL_LUMINANCE32I_EXT 0x8D86 +#define GL_LUMINANCE_ALPHA32I_EXT 0x8D87 +#define GL_RGBA16I_EXT 0x8D88 +#define GL_RGB16I_EXT 0x8D89 +#define GL_ALPHA16I_EXT 0x8D8A +#define GL_INTENSITY16I_EXT 0x8D8B +#define GL_LUMINANCE16I_EXT 0x8D8C +#define GL_LUMINANCE_ALPHA16I_EXT 0x8D8D +#define GL_RGBA8I_EXT 0x8D8E +#define GL_RGB8I_EXT 0x8D8F +#define GL_ALPHA8I_EXT 0x8D90 +#define GL_INTENSITY8I_EXT 0x8D91 +#define GL_LUMINANCE8I_EXT 0x8D92 +#define GL_LUMINANCE_ALPHA8I_EXT 0x8D93 +#define GL_RED_INTEGER_EXT 0x8D94 +#define GL_GREEN_INTEGER_EXT 0x8D95 +#define GL_BLUE_INTEGER_EXT 0x8D96 +#define GL_ALPHA_INTEGER_EXT 0x8D97 +#define GL_RGB_INTEGER_EXT 0x8D98 +#define GL_RGBA_INTEGER_EXT 0x8D99 +#define GL_BGR_INTEGER_EXT 0x8D9A +#define GL_BGRA_INTEGER_EXT 0x8D9B +#define GL_LUMINANCE_INTEGER_EXT 0x8D9C +#define GL_LUMINANCE_ALPHA_INTEGER_EXT 0x8D9D +#define GL_RGBA_INTEGER_MODE_EXT 0x8D9E +typedef void (APIENTRYP PFNGLTEXPARAMETERIIVEXTPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLTEXPARAMETERIUIVEXTPROC) (GLenum target, GLenum pname, const GLuint *params); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIUIVEXTPROC) (GLenum target, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLCLEARCOLORIIEXTPROC) (GLint red, GLint green, GLint blue, GLint alpha); +typedef void (APIENTRYP PFNGLCLEARCOLORIUIEXTPROC) (GLuint red, GLuint green, GLuint blue, GLuint alpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexParameterIivEXT (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glTexParameterIuivEXT (GLenum target, GLenum pname, const GLuint *params); +GLAPI void APIENTRY glGetTexParameterIivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetTexParameterIuivEXT (GLenum target, GLenum pname, GLuint *params); +GLAPI void APIENTRY glClearColorIiEXT (GLint red, GLint green, GLint blue, GLint alpha); +GLAPI void APIENTRY glClearColorIuiEXT (GLuint red, GLuint green, GLuint blue, GLuint alpha); +#endif +#endif /* GL_EXT_texture_integer */ + +#ifndef GL_EXT_texture_lod_bias +#define GL_EXT_texture_lod_bias 1 +#define GL_MAX_TEXTURE_LOD_BIAS_EXT 0x84FD +#define GL_TEXTURE_FILTER_CONTROL_EXT 0x8500 +#define GL_TEXTURE_LOD_BIAS_EXT 0x8501 +#endif /* GL_EXT_texture_lod_bias */ + +#ifndef GL_EXT_texture_mirror_clamp +#define GL_EXT_texture_mirror_clamp 1 +#define GL_MIRROR_CLAMP_EXT 0x8742 +#define GL_MIRROR_CLAMP_TO_EDGE_EXT 0x8743 +#define GL_MIRROR_CLAMP_TO_BORDER_EXT 0x8912 +#endif /* GL_EXT_texture_mirror_clamp */ + +#ifndef GL_EXT_texture_object +#define GL_EXT_texture_object 1 +#define GL_TEXTURE_PRIORITY_EXT 0x8066 +#define GL_TEXTURE_RESIDENT_EXT 0x8067 +#define GL_TEXTURE_1D_BINDING_EXT 0x8068 +#define GL_TEXTURE_2D_BINDING_EXT 0x8069 +#define GL_TEXTURE_3D_BINDING_EXT 0x806A +typedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTEXTPROC) (GLsizei n, const GLuint *textures, GLboolean *residences); +typedef void (APIENTRYP PFNGLBINDTEXTUREEXTPROC) (GLenum target, GLuint texture); +typedef void (APIENTRYP PFNGLDELETETEXTURESEXTPROC) (GLsizei n, const GLuint *textures); +typedef void (APIENTRYP PFNGLGENTEXTURESEXTPROC) (GLsizei n, GLuint *textures); +typedef GLboolean (APIENTRYP PFNGLISTEXTUREEXTPROC) (GLuint texture); +typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESEXTPROC) (GLsizei n, const GLuint *textures, const GLclampf *priorities); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLboolean APIENTRY glAreTexturesResidentEXT (GLsizei n, const GLuint *textures, GLboolean *residences); +GLAPI void APIENTRY glBindTextureEXT (GLenum target, GLuint texture); +GLAPI void APIENTRY glDeleteTexturesEXT (GLsizei n, const GLuint *textures); +GLAPI void APIENTRY glGenTexturesEXT (GLsizei n, GLuint *textures); +GLAPI GLboolean APIENTRY glIsTextureEXT (GLuint texture); +GLAPI void APIENTRY glPrioritizeTexturesEXT (GLsizei n, const GLuint *textures, const GLclampf *priorities); +#endif +#endif /* GL_EXT_texture_object */ + +#ifndef GL_EXT_texture_perturb_normal +#define GL_EXT_texture_perturb_normal 1 +#define GL_PERTURB_EXT 0x85AE +#define GL_TEXTURE_NORMAL_EXT 0x85AF +typedef void (APIENTRYP PFNGLTEXTURENORMALEXTPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTextureNormalEXT (GLenum mode); +#endif +#endif /* GL_EXT_texture_perturb_normal */ + +#ifndef GL_EXT_texture_sRGB +#define GL_EXT_texture_sRGB 1 +#define GL_SRGB_EXT 0x8C40 +#define GL_SRGB8_EXT 0x8C41 +#define GL_SRGB_ALPHA_EXT 0x8C42 +#define GL_SRGB8_ALPHA8_EXT 0x8C43 +#define GL_SLUMINANCE_ALPHA_EXT 0x8C44 +#define GL_SLUMINANCE8_ALPHA8_EXT 0x8C45 +#define GL_SLUMINANCE_EXT 0x8C46 +#define GL_SLUMINANCE8_EXT 0x8C47 +#define GL_COMPRESSED_SRGB_EXT 0x8C48 +#define GL_COMPRESSED_SRGB_ALPHA_EXT 0x8C49 +#define GL_COMPRESSED_SLUMINANCE_EXT 0x8C4A +#define GL_COMPRESSED_SLUMINANCE_ALPHA_EXT 0x8C4B +#define GL_COMPRESSED_SRGB_S3TC_DXT1_EXT 0x8C4C +#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT 0x8C4D +#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT 0x8C4E +#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT 0x8C4F +#endif /* GL_EXT_texture_sRGB */ + +#ifndef GL_EXT_texture_sRGB_decode +#define GL_EXT_texture_sRGB_decode 1 +#define GL_TEXTURE_SRGB_DECODE_EXT 0x8A48 +#define GL_DECODE_EXT 0x8A49 +#define GL_SKIP_DECODE_EXT 0x8A4A +#endif /* GL_EXT_texture_sRGB_decode */ + +#ifndef GL_EXT_texture_shared_exponent +#define GL_EXT_texture_shared_exponent 1 +#define GL_RGB9_E5_EXT 0x8C3D +#define GL_UNSIGNED_INT_5_9_9_9_REV_EXT 0x8C3E +#define GL_TEXTURE_SHARED_SIZE_EXT 0x8C3F +#endif /* GL_EXT_texture_shared_exponent */ + +#ifndef GL_EXT_texture_snorm +#define GL_EXT_texture_snorm 1 +#define GL_ALPHA_SNORM 0x9010 +#define GL_LUMINANCE_SNORM 0x9011 +#define GL_LUMINANCE_ALPHA_SNORM 0x9012 +#define GL_INTENSITY_SNORM 0x9013 +#define GL_ALPHA8_SNORM 0x9014 +#define GL_LUMINANCE8_SNORM 0x9015 +#define GL_LUMINANCE8_ALPHA8_SNORM 0x9016 +#define GL_INTENSITY8_SNORM 0x9017 +#define GL_ALPHA16_SNORM 0x9018 +#define GL_LUMINANCE16_SNORM 0x9019 +#define GL_LUMINANCE16_ALPHA16_SNORM 0x901A +#define GL_INTENSITY16_SNORM 0x901B +#define GL_RED_SNORM 0x8F90 +#define GL_RG_SNORM 0x8F91 +#define GL_RGB_SNORM 0x8F92 +#define GL_RGBA_SNORM 0x8F93 +#endif /* GL_EXT_texture_snorm */ + +#ifndef GL_EXT_texture_swizzle +#define GL_EXT_texture_swizzle 1 +#define GL_TEXTURE_SWIZZLE_R_EXT 0x8E42 +#define GL_TEXTURE_SWIZZLE_G_EXT 0x8E43 +#define GL_TEXTURE_SWIZZLE_B_EXT 0x8E44 +#define GL_TEXTURE_SWIZZLE_A_EXT 0x8E45 +#define GL_TEXTURE_SWIZZLE_RGBA_EXT 0x8E46 +#endif /* GL_EXT_texture_swizzle */ + +#ifndef GL_EXT_timer_query +#define GL_EXT_timer_query 1 +#define GL_TIME_ELAPSED_EXT 0x88BF +typedef void (APIENTRYP PFNGLGETQUERYOBJECTI64VEXTPROC) (GLuint id, GLenum pname, GLint64 *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUI64VEXTPROC) (GLuint id, GLenum pname, GLuint64 *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetQueryObjecti64vEXT (GLuint id, GLenum pname, GLint64 *params); +GLAPI void APIENTRY glGetQueryObjectui64vEXT (GLuint id, GLenum pname, GLuint64 *params); +#endif +#endif /* GL_EXT_timer_query */ + +#ifndef GL_EXT_transform_feedback +#define GL_EXT_transform_feedback 1 +#define GL_TRANSFORM_FEEDBACK_BUFFER_EXT 0x8C8E +#define GL_TRANSFORM_FEEDBACK_BUFFER_START_EXT 0x8C84 +#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE_EXT 0x8C85 +#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING_EXT 0x8C8F +#define GL_INTERLEAVED_ATTRIBS_EXT 0x8C8C +#define GL_SEPARATE_ATTRIBS_EXT 0x8C8D +#define GL_PRIMITIVES_GENERATED_EXT 0x8C87 +#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_EXT 0x8C88 +#define GL_RASTERIZER_DISCARD_EXT 0x8C89 +#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT 0x8C8A +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS_EXT 0x8C8B +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT 0x8C80 +#define GL_TRANSFORM_FEEDBACK_VARYINGS_EXT 0x8C83 +#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE_EXT 0x8C7F +#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH_EXT 0x8C76 +typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKEXTPROC) (GLenum primitiveMode); +typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKEXTPROC) (void); +typedef void (APIENTRYP PFNGLBINDBUFFERRANGEEXTPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLBINDBUFFEROFFSETEXTPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset); +typedef void (APIENTRYP PFNGLBINDBUFFERBASEEXTPROC) (GLenum target, GLuint index, GLuint buffer); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSEXTPROC) (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGEXTPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginTransformFeedbackEXT (GLenum primitiveMode); +GLAPI void APIENTRY glEndTransformFeedbackEXT (void); +GLAPI void APIENTRY glBindBufferRangeEXT (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glBindBufferOffsetEXT (GLenum target, GLuint index, GLuint buffer, GLintptr offset); +GLAPI void APIENTRY glBindBufferBaseEXT (GLenum target, GLuint index, GLuint buffer); +GLAPI void APIENTRY glTransformFeedbackVaryingsEXT (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); +GLAPI void APIENTRY glGetTransformFeedbackVaryingEXT (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +#endif +#endif /* GL_EXT_transform_feedback */ + +#ifndef GL_EXT_vertex_array +#define GL_EXT_vertex_array 1 +#define GL_VERTEX_ARRAY_EXT 0x8074 +#define GL_NORMAL_ARRAY_EXT 0x8075 +#define GL_COLOR_ARRAY_EXT 0x8076 +#define GL_INDEX_ARRAY_EXT 0x8077 +#define GL_TEXTURE_COORD_ARRAY_EXT 0x8078 +#define GL_EDGE_FLAG_ARRAY_EXT 0x8079 +#define GL_VERTEX_ARRAY_SIZE_EXT 0x807A +#define GL_VERTEX_ARRAY_TYPE_EXT 0x807B +#define GL_VERTEX_ARRAY_STRIDE_EXT 0x807C +#define GL_VERTEX_ARRAY_COUNT_EXT 0x807D +#define GL_NORMAL_ARRAY_TYPE_EXT 0x807E +#define GL_NORMAL_ARRAY_STRIDE_EXT 0x807F +#define GL_NORMAL_ARRAY_COUNT_EXT 0x8080 +#define GL_COLOR_ARRAY_SIZE_EXT 0x8081 +#define GL_COLOR_ARRAY_TYPE_EXT 0x8082 +#define GL_COLOR_ARRAY_STRIDE_EXT 0x8083 +#define GL_COLOR_ARRAY_COUNT_EXT 0x8084 +#define GL_INDEX_ARRAY_TYPE_EXT 0x8085 +#define GL_INDEX_ARRAY_STRIDE_EXT 0x8086 +#define GL_INDEX_ARRAY_COUNT_EXT 0x8087 +#define GL_TEXTURE_COORD_ARRAY_SIZE_EXT 0x8088 +#define GL_TEXTURE_COORD_ARRAY_TYPE_EXT 0x8089 +#define GL_TEXTURE_COORD_ARRAY_STRIDE_EXT 0x808A +#define GL_TEXTURE_COORD_ARRAY_COUNT_EXT 0x808B +#define GL_EDGE_FLAG_ARRAY_STRIDE_EXT 0x808C +#define GL_EDGE_FLAG_ARRAY_COUNT_EXT 0x808D +#define GL_VERTEX_ARRAY_POINTER_EXT 0x808E +#define GL_NORMAL_ARRAY_POINTER_EXT 0x808F +#define GL_COLOR_ARRAY_POINTER_EXT 0x8090 +#define GL_INDEX_ARRAY_POINTER_EXT 0x8091 +#define GL_TEXTURE_COORD_ARRAY_POINTER_EXT 0x8092 +#define GL_EDGE_FLAG_ARRAY_POINTER_EXT 0x8093 +typedef void (APIENTRYP PFNGLARRAYELEMENTEXTPROC) (GLint i); +typedef void (APIENTRYP PFNGLCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer); +typedef void (APIENTRYP PFNGLDRAWARRAYSEXTPROC) (GLenum mode, GLint first, GLsizei count); +typedef void (APIENTRYP PFNGLEDGEFLAGPOINTEREXTPROC) (GLsizei stride, GLsizei count, const GLboolean *pointer); +typedef void (APIENTRYP PFNGLGETPOINTERVEXTPROC) (GLenum pname, void **params); +typedef void (APIENTRYP PFNGLINDEXPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const void *pointer); +typedef void (APIENTRYP PFNGLNORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const void *pointer); +typedef void (APIENTRYP PFNGLTEXCOORDPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer); +typedef void (APIENTRYP PFNGLVERTEXPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glArrayElementEXT (GLint i); +GLAPI void APIENTRY glColorPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer); +GLAPI void APIENTRY glDrawArraysEXT (GLenum mode, GLint first, GLsizei count); +GLAPI void APIENTRY glEdgeFlagPointerEXT (GLsizei stride, GLsizei count, const GLboolean *pointer); +GLAPI void APIENTRY glGetPointervEXT (GLenum pname, void **params); +GLAPI void APIENTRY glIndexPointerEXT (GLenum type, GLsizei stride, GLsizei count, const void *pointer); +GLAPI void APIENTRY glNormalPointerEXT (GLenum type, GLsizei stride, GLsizei count, const void *pointer); +GLAPI void APIENTRY glTexCoordPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer); +GLAPI void APIENTRY glVertexPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer); +#endif +#endif /* GL_EXT_vertex_array */ + +#ifndef GL_EXT_vertex_array_bgra +#define GL_EXT_vertex_array_bgra 1 +#endif /* GL_EXT_vertex_array_bgra */ + +#ifndef GL_EXT_vertex_attrib_64bit +#define GL_EXT_vertex_attrib_64bit 1 +#define GL_DOUBLE_VEC2_EXT 0x8FFC +#define GL_DOUBLE_VEC3_EXT 0x8FFD +#define GL_DOUBLE_VEC4_EXT 0x8FFE +#define GL_DOUBLE_MAT2_EXT 0x8F46 +#define GL_DOUBLE_MAT3_EXT 0x8F47 +#define GL_DOUBLE_MAT4_EXT 0x8F48 +#define GL_DOUBLE_MAT2x3_EXT 0x8F49 +#define GL_DOUBLE_MAT2x4_EXT 0x8F4A +#define GL_DOUBLE_MAT3x2_EXT 0x8F4B +#define GL_DOUBLE_MAT3x4_EXT 0x8F4C +#define GL_DOUBLE_MAT4x2_EXT 0x8F4D +#define GL_DOUBLE_MAT4x3_EXT 0x8F4E +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DEXTPROC) (GLuint index, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DEXTPROC) (GLuint index, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DEXTPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DEXTPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DVEXTPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DVEXTPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DVEXTPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DVEXTPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBLPOINTEREXTPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLDVEXTPROC) (GLuint index, GLenum pname, GLdouble *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribL1dEXT (GLuint index, GLdouble x); +GLAPI void APIENTRY glVertexAttribL2dEXT (GLuint index, GLdouble x, GLdouble y); +GLAPI void APIENTRY glVertexAttribL3dEXT (GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glVertexAttribL4dEXT (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glVertexAttribL1dvEXT (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribL2dvEXT (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribL3dvEXT (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribL4dvEXT (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribLPointerEXT (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glGetVertexAttribLdvEXT (GLuint index, GLenum pname, GLdouble *params); +#endif +#endif /* GL_EXT_vertex_attrib_64bit */ + +#ifndef GL_EXT_vertex_shader +#define GL_EXT_vertex_shader 1 +#define GL_VERTEX_SHADER_EXT 0x8780 +#define GL_VERTEX_SHADER_BINDING_EXT 0x8781 +#define GL_OP_INDEX_EXT 0x8782 +#define GL_OP_NEGATE_EXT 0x8783 +#define GL_OP_DOT3_EXT 0x8784 +#define GL_OP_DOT4_EXT 0x8785 +#define GL_OP_MUL_EXT 0x8786 +#define GL_OP_ADD_EXT 0x8787 +#define GL_OP_MADD_EXT 0x8788 +#define GL_OP_FRAC_EXT 0x8789 +#define GL_OP_MAX_EXT 0x878A +#define GL_OP_MIN_EXT 0x878B +#define GL_OP_SET_GE_EXT 0x878C +#define GL_OP_SET_LT_EXT 0x878D +#define GL_OP_CLAMP_EXT 0x878E +#define GL_OP_FLOOR_EXT 0x878F +#define GL_OP_ROUND_EXT 0x8790 +#define GL_OP_EXP_BASE_2_EXT 0x8791 +#define GL_OP_LOG_BASE_2_EXT 0x8792 +#define GL_OP_POWER_EXT 0x8793 +#define GL_OP_RECIP_EXT 0x8794 +#define GL_OP_RECIP_SQRT_EXT 0x8795 +#define GL_OP_SUB_EXT 0x8796 +#define GL_OP_CROSS_PRODUCT_EXT 0x8797 +#define GL_OP_MULTIPLY_MATRIX_EXT 0x8798 +#define GL_OP_MOV_EXT 0x8799 +#define GL_OUTPUT_VERTEX_EXT 0x879A +#define GL_OUTPUT_COLOR0_EXT 0x879B +#define GL_OUTPUT_COLOR1_EXT 0x879C +#define GL_OUTPUT_TEXTURE_COORD0_EXT 0x879D +#define GL_OUTPUT_TEXTURE_COORD1_EXT 0x879E +#define GL_OUTPUT_TEXTURE_COORD2_EXT 0x879F +#define GL_OUTPUT_TEXTURE_COORD3_EXT 0x87A0 +#define GL_OUTPUT_TEXTURE_COORD4_EXT 0x87A1 +#define GL_OUTPUT_TEXTURE_COORD5_EXT 0x87A2 +#define GL_OUTPUT_TEXTURE_COORD6_EXT 0x87A3 +#define GL_OUTPUT_TEXTURE_COORD7_EXT 0x87A4 +#define GL_OUTPUT_TEXTURE_COORD8_EXT 0x87A5 +#define GL_OUTPUT_TEXTURE_COORD9_EXT 0x87A6 +#define GL_OUTPUT_TEXTURE_COORD10_EXT 0x87A7 +#define GL_OUTPUT_TEXTURE_COORD11_EXT 0x87A8 +#define GL_OUTPUT_TEXTURE_COORD12_EXT 0x87A9 +#define GL_OUTPUT_TEXTURE_COORD13_EXT 0x87AA +#define GL_OUTPUT_TEXTURE_COORD14_EXT 0x87AB +#define GL_OUTPUT_TEXTURE_COORD15_EXT 0x87AC +#define GL_OUTPUT_TEXTURE_COORD16_EXT 0x87AD +#define GL_OUTPUT_TEXTURE_COORD17_EXT 0x87AE +#define GL_OUTPUT_TEXTURE_COORD18_EXT 0x87AF +#define GL_OUTPUT_TEXTURE_COORD19_EXT 0x87B0 +#define GL_OUTPUT_TEXTURE_COORD20_EXT 0x87B1 +#define GL_OUTPUT_TEXTURE_COORD21_EXT 0x87B2 +#define GL_OUTPUT_TEXTURE_COORD22_EXT 0x87B3 +#define GL_OUTPUT_TEXTURE_COORD23_EXT 0x87B4 +#define GL_OUTPUT_TEXTURE_COORD24_EXT 0x87B5 +#define GL_OUTPUT_TEXTURE_COORD25_EXT 0x87B6 +#define GL_OUTPUT_TEXTURE_COORD26_EXT 0x87B7 +#define GL_OUTPUT_TEXTURE_COORD27_EXT 0x87B8 +#define GL_OUTPUT_TEXTURE_COORD28_EXT 0x87B9 +#define GL_OUTPUT_TEXTURE_COORD29_EXT 0x87BA +#define GL_OUTPUT_TEXTURE_COORD30_EXT 0x87BB +#define GL_OUTPUT_TEXTURE_COORD31_EXT 0x87BC +#define GL_OUTPUT_FOG_EXT 0x87BD +#define GL_SCALAR_EXT 0x87BE +#define GL_VECTOR_EXT 0x87BF +#define GL_MATRIX_EXT 0x87C0 +#define GL_VARIANT_EXT 0x87C1 +#define GL_INVARIANT_EXT 0x87C2 +#define GL_LOCAL_CONSTANT_EXT 0x87C3 +#define GL_LOCAL_EXT 0x87C4 +#define GL_MAX_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87C5 +#define GL_MAX_VERTEX_SHADER_VARIANTS_EXT 0x87C6 +#define GL_MAX_VERTEX_SHADER_INVARIANTS_EXT 0x87C7 +#define GL_MAX_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87C8 +#define GL_MAX_VERTEX_SHADER_LOCALS_EXT 0x87C9 +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CA +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_VARIANTS_EXT 0x87CB +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87CC +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INVARIANTS_EXT 0x87CD +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCALS_EXT 0x87CE +#define GL_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CF +#define GL_VERTEX_SHADER_VARIANTS_EXT 0x87D0 +#define GL_VERTEX_SHADER_INVARIANTS_EXT 0x87D1 +#define GL_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87D2 +#define GL_VERTEX_SHADER_LOCALS_EXT 0x87D3 +#define GL_VERTEX_SHADER_OPTIMIZED_EXT 0x87D4 +#define GL_X_EXT 0x87D5 +#define GL_Y_EXT 0x87D6 +#define GL_Z_EXT 0x87D7 +#define GL_W_EXT 0x87D8 +#define GL_NEGATIVE_X_EXT 0x87D9 +#define GL_NEGATIVE_Y_EXT 0x87DA +#define GL_NEGATIVE_Z_EXT 0x87DB +#define GL_NEGATIVE_W_EXT 0x87DC +#define GL_ZERO_EXT 0x87DD +#define GL_ONE_EXT 0x87DE +#define GL_NEGATIVE_ONE_EXT 0x87DF +#define GL_NORMALIZED_RANGE_EXT 0x87E0 +#define GL_FULL_RANGE_EXT 0x87E1 +#define GL_CURRENT_VERTEX_EXT 0x87E2 +#define GL_MVP_MATRIX_EXT 0x87E3 +#define GL_VARIANT_VALUE_EXT 0x87E4 +#define GL_VARIANT_DATATYPE_EXT 0x87E5 +#define GL_VARIANT_ARRAY_STRIDE_EXT 0x87E6 +#define GL_VARIANT_ARRAY_TYPE_EXT 0x87E7 +#define GL_VARIANT_ARRAY_EXT 0x87E8 +#define GL_VARIANT_ARRAY_POINTER_EXT 0x87E9 +#define GL_INVARIANT_VALUE_EXT 0x87EA +#define GL_INVARIANT_DATATYPE_EXT 0x87EB +#define GL_LOCAL_CONSTANT_VALUE_EXT 0x87EC +#define GL_LOCAL_CONSTANT_DATATYPE_EXT 0x87ED +typedef void (APIENTRYP PFNGLBEGINVERTEXSHADEREXTPROC) (void); +typedef void (APIENTRYP PFNGLENDVERTEXSHADEREXTPROC) (void); +typedef void (APIENTRYP PFNGLBINDVERTEXSHADEREXTPROC) (GLuint id); +typedef GLuint (APIENTRYP PFNGLGENVERTEXSHADERSEXTPROC) (GLuint range); +typedef void (APIENTRYP PFNGLDELETEVERTEXSHADEREXTPROC) (GLuint id); +typedef void (APIENTRYP PFNGLSHADEROP1EXTPROC) (GLenum op, GLuint res, GLuint arg1); +typedef void (APIENTRYP PFNGLSHADEROP2EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2); +typedef void (APIENTRYP PFNGLSHADEROP3EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2, GLuint arg3); +typedef void (APIENTRYP PFNGLSWIZZLEEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW); +typedef void (APIENTRYP PFNGLWRITEMASKEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW); +typedef void (APIENTRYP PFNGLINSERTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num); +typedef void (APIENTRYP PFNGLEXTRACTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num); +typedef GLuint (APIENTRYP PFNGLGENSYMBOLSEXTPROC) (GLenum datatype, GLenum storagetype, GLenum range, GLuint components); +typedef void (APIENTRYP PFNGLSETINVARIANTEXTPROC) (GLuint id, GLenum type, const void *addr); +typedef void (APIENTRYP PFNGLSETLOCALCONSTANTEXTPROC) (GLuint id, GLenum type, const void *addr); +typedef void (APIENTRYP PFNGLVARIANTBVEXTPROC) (GLuint id, const GLbyte *addr); +typedef void (APIENTRYP PFNGLVARIANTSVEXTPROC) (GLuint id, const GLshort *addr); +typedef void (APIENTRYP PFNGLVARIANTIVEXTPROC) (GLuint id, const GLint *addr); +typedef void (APIENTRYP PFNGLVARIANTFVEXTPROC) (GLuint id, const GLfloat *addr); +typedef void (APIENTRYP PFNGLVARIANTDVEXTPROC) (GLuint id, const GLdouble *addr); +typedef void (APIENTRYP PFNGLVARIANTUBVEXTPROC) (GLuint id, const GLubyte *addr); +typedef void (APIENTRYP PFNGLVARIANTUSVEXTPROC) (GLuint id, const GLushort *addr); +typedef void (APIENTRYP PFNGLVARIANTUIVEXTPROC) (GLuint id, const GLuint *addr); +typedef void (APIENTRYP PFNGLVARIANTPOINTEREXTPROC) (GLuint id, GLenum type, GLuint stride, const void *addr); +typedef void (APIENTRYP PFNGLENABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id); +typedef void (APIENTRYP PFNGLDISABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id); +typedef GLuint (APIENTRYP PFNGLBINDLIGHTPARAMETEREXTPROC) (GLenum light, GLenum value); +typedef GLuint (APIENTRYP PFNGLBINDMATERIALPARAMETEREXTPROC) (GLenum face, GLenum value); +typedef GLuint (APIENTRYP PFNGLBINDTEXGENPARAMETEREXTPROC) (GLenum unit, GLenum coord, GLenum value); +typedef GLuint (APIENTRYP PFNGLBINDTEXTUREUNITPARAMETEREXTPROC) (GLenum unit, GLenum value); +typedef GLuint (APIENTRYP PFNGLBINDPARAMETEREXTPROC) (GLenum value); +typedef GLboolean (APIENTRYP PFNGLISVARIANTENABLEDEXTPROC) (GLuint id, GLenum cap); +typedef void (APIENTRYP PFNGLGETVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data); +typedef void (APIENTRYP PFNGLGETVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data); +typedef void (APIENTRYP PFNGLGETVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data); +typedef void (APIENTRYP PFNGLGETVARIANTPOINTERVEXTPROC) (GLuint id, GLenum value, void **data); +typedef void (APIENTRYP PFNGLGETINVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data); +typedef void (APIENTRYP PFNGLGETINVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data); +typedef void (APIENTRYP PFNGLGETINVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data); +typedef void (APIENTRYP PFNGLGETLOCALCONSTANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data); +typedef void (APIENTRYP PFNGLGETLOCALCONSTANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data); +typedef void (APIENTRYP PFNGLGETLOCALCONSTANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginVertexShaderEXT (void); +GLAPI void APIENTRY glEndVertexShaderEXT (void); +GLAPI void APIENTRY glBindVertexShaderEXT (GLuint id); +GLAPI GLuint APIENTRY glGenVertexShadersEXT (GLuint range); +GLAPI void APIENTRY glDeleteVertexShaderEXT (GLuint id); +GLAPI void APIENTRY glShaderOp1EXT (GLenum op, GLuint res, GLuint arg1); +GLAPI void APIENTRY glShaderOp2EXT (GLenum op, GLuint res, GLuint arg1, GLuint arg2); +GLAPI void APIENTRY glShaderOp3EXT (GLenum op, GLuint res, GLuint arg1, GLuint arg2, GLuint arg3); +GLAPI void APIENTRY glSwizzleEXT (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW); +GLAPI void APIENTRY glWriteMaskEXT (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW); +GLAPI void APIENTRY glInsertComponentEXT (GLuint res, GLuint src, GLuint num); +GLAPI void APIENTRY glExtractComponentEXT (GLuint res, GLuint src, GLuint num); +GLAPI GLuint APIENTRY glGenSymbolsEXT (GLenum datatype, GLenum storagetype, GLenum range, GLuint components); +GLAPI void APIENTRY glSetInvariantEXT (GLuint id, GLenum type, const void *addr); +GLAPI void APIENTRY glSetLocalConstantEXT (GLuint id, GLenum type, const void *addr); +GLAPI void APIENTRY glVariantbvEXT (GLuint id, const GLbyte *addr); +GLAPI void APIENTRY glVariantsvEXT (GLuint id, const GLshort *addr); +GLAPI void APIENTRY glVariantivEXT (GLuint id, const GLint *addr); +GLAPI void APIENTRY glVariantfvEXT (GLuint id, const GLfloat *addr); +GLAPI void APIENTRY glVariantdvEXT (GLuint id, const GLdouble *addr); +GLAPI void APIENTRY glVariantubvEXT (GLuint id, const GLubyte *addr); +GLAPI void APIENTRY glVariantusvEXT (GLuint id, const GLushort *addr); +GLAPI void APIENTRY glVariantuivEXT (GLuint id, const GLuint *addr); +GLAPI void APIENTRY glVariantPointerEXT (GLuint id, GLenum type, GLuint stride, const void *addr); +GLAPI void APIENTRY glEnableVariantClientStateEXT (GLuint id); +GLAPI void APIENTRY glDisableVariantClientStateEXT (GLuint id); +GLAPI GLuint APIENTRY glBindLightParameterEXT (GLenum light, GLenum value); +GLAPI GLuint APIENTRY glBindMaterialParameterEXT (GLenum face, GLenum value); +GLAPI GLuint APIENTRY glBindTexGenParameterEXT (GLenum unit, GLenum coord, GLenum value); +GLAPI GLuint APIENTRY glBindTextureUnitParameterEXT (GLenum unit, GLenum value); +GLAPI GLuint APIENTRY glBindParameterEXT (GLenum value); +GLAPI GLboolean APIENTRY glIsVariantEnabledEXT (GLuint id, GLenum cap); +GLAPI void APIENTRY glGetVariantBooleanvEXT (GLuint id, GLenum value, GLboolean *data); +GLAPI void APIENTRY glGetVariantIntegervEXT (GLuint id, GLenum value, GLint *data); +GLAPI void APIENTRY glGetVariantFloatvEXT (GLuint id, GLenum value, GLfloat *data); +GLAPI void APIENTRY glGetVariantPointervEXT (GLuint id, GLenum value, void **data); +GLAPI void APIENTRY glGetInvariantBooleanvEXT (GLuint id, GLenum value, GLboolean *data); +GLAPI void APIENTRY glGetInvariantIntegervEXT (GLuint id, GLenum value, GLint *data); +GLAPI void APIENTRY glGetInvariantFloatvEXT (GLuint id, GLenum value, GLfloat *data); +GLAPI void APIENTRY glGetLocalConstantBooleanvEXT (GLuint id, GLenum value, GLboolean *data); +GLAPI void APIENTRY glGetLocalConstantIntegervEXT (GLuint id, GLenum value, GLint *data); +GLAPI void APIENTRY glGetLocalConstantFloatvEXT (GLuint id, GLenum value, GLfloat *data); +#endif +#endif /* GL_EXT_vertex_shader */ + +#ifndef GL_EXT_vertex_weighting +#define GL_EXT_vertex_weighting 1 +#define GL_MODELVIEW0_STACK_DEPTH_EXT 0x0BA3 +#define GL_MODELVIEW1_STACK_DEPTH_EXT 0x8502 +#define GL_MODELVIEW0_MATRIX_EXT 0x0BA6 +#define GL_MODELVIEW1_MATRIX_EXT 0x8506 +#define GL_VERTEX_WEIGHTING_EXT 0x8509 +#define GL_MODELVIEW0_EXT 0x1700 +#define GL_MODELVIEW1_EXT 0x850A +#define GL_CURRENT_VERTEX_WEIGHT_EXT 0x850B +#define GL_VERTEX_WEIGHT_ARRAY_EXT 0x850C +#define GL_VERTEX_WEIGHT_ARRAY_SIZE_EXT 0x850D +#define GL_VERTEX_WEIGHT_ARRAY_TYPE_EXT 0x850E +#define GL_VERTEX_WEIGHT_ARRAY_STRIDE_EXT 0x850F +#define GL_VERTEX_WEIGHT_ARRAY_POINTER_EXT 0x8510 +typedef void (APIENTRYP PFNGLVERTEXWEIGHTFEXTPROC) (GLfloat weight); +typedef void (APIENTRYP PFNGLVERTEXWEIGHTFVEXTPROC) (const GLfloat *weight); +typedef void (APIENTRYP PFNGLVERTEXWEIGHTPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexWeightfEXT (GLfloat weight); +GLAPI void APIENTRY glVertexWeightfvEXT (const GLfloat *weight); +GLAPI void APIENTRY glVertexWeightPointerEXT (GLint size, GLenum type, GLsizei stride, const void *pointer); +#endif +#endif /* GL_EXT_vertex_weighting */ + +#ifndef GL_EXT_window_rectangles +#define GL_EXT_window_rectangles 1 +#define GL_INCLUSIVE_EXT 0x8F10 +#define GL_EXCLUSIVE_EXT 0x8F11 +#define GL_WINDOW_RECTANGLE_EXT 0x8F12 +#define GL_WINDOW_RECTANGLE_MODE_EXT 0x8F13 +#define GL_MAX_WINDOW_RECTANGLES_EXT 0x8F14 +#define GL_NUM_WINDOW_RECTANGLES_EXT 0x8F15 +typedef void (APIENTRYP PFNGLWINDOWRECTANGLESEXTPROC) (GLenum mode, GLsizei count, const GLint *box); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glWindowRectanglesEXT (GLenum mode, GLsizei count, const GLint *box); +#endif +#endif /* GL_EXT_window_rectangles */ + +#ifndef GL_EXT_x11_sync_object +#define GL_EXT_x11_sync_object 1 +#define GL_SYNC_X11_FENCE_EXT 0x90E1 +typedef GLsync (APIENTRYP PFNGLIMPORTSYNCEXTPROC) (GLenum external_sync_type, GLintptr external_sync, GLbitfield flags); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLsync APIENTRY glImportSyncEXT (GLenum external_sync_type, GLintptr external_sync, GLbitfield flags); +#endif +#endif /* GL_EXT_x11_sync_object */ + +#ifndef GL_GREMEDY_frame_terminator +#define GL_GREMEDY_frame_terminator 1 +typedef void (APIENTRYP PFNGLFRAMETERMINATORGREMEDYPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFrameTerminatorGREMEDY (void); +#endif +#endif /* GL_GREMEDY_frame_terminator */ + +#ifndef GL_GREMEDY_string_marker +#define GL_GREMEDY_string_marker 1 +typedef void (APIENTRYP PFNGLSTRINGMARKERGREMEDYPROC) (GLsizei len, const void *string); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glStringMarkerGREMEDY (GLsizei len, const void *string); +#endif +#endif /* GL_GREMEDY_string_marker */ + +#ifndef GL_HP_convolution_border_modes +#define GL_HP_convolution_border_modes 1 +#define GL_IGNORE_BORDER_HP 0x8150 +#define GL_CONSTANT_BORDER_HP 0x8151 +#define GL_REPLICATE_BORDER_HP 0x8153 +#define GL_CONVOLUTION_BORDER_COLOR_HP 0x8154 +#endif /* GL_HP_convolution_border_modes */ + +#ifndef GL_HP_image_transform +#define GL_HP_image_transform 1 +#define GL_IMAGE_SCALE_X_HP 0x8155 +#define GL_IMAGE_SCALE_Y_HP 0x8156 +#define GL_IMAGE_TRANSLATE_X_HP 0x8157 +#define GL_IMAGE_TRANSLATE_Y_HP 0x8158 +#define GL_IMAGE_ROTATE_ANGLE_HP 0x8159 +#define GL_IMAGE_ROTATE_ORIGIN_X_HP 0x815A +#define GL_IMAGE_ROTATE_ORIGIN_Y_HP 0x815B +#define GL_IMAGE_MAG_FILTER_HP 0x815C +#define GL_IMAGE_MIN_FILTER_HP 0x815D +#define GL_IMAGE_CUBIC_WEIGHT_HP 0x815E +#define GL_CUBIC_HP 0x815F +#define GL_AVERAGE_HP 0x8160 +#define GL_IMAGE_TRANSFORM_2D_HP 0x8161 +#define GL_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8162 +#define GL_PROXY_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8163 +typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIHPPROC) (GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFHPPROC) (GLenum target, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glImageTransformParameteriHP (GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glImageTransformParameterfHP (GLenum target, GLenum pname, GLfloat param); +GLAPI void APIENTRY glImageTransformParameterivHP (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glImageTransformParameterfvHP (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glGetImageTransformParameterivHP (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetImageTransformParameterfvHP (GLenum target, GLenum pname, GLfloat *params); +#endif +#endif /* GL_HP_image_transform */ + +#ifndef GL_HP_occlusion_test +#define GL_HP_occlusion_test 1 +#define GL_OCCLUSION_TEST_HP 0x8165 +#define GL_OCCLUSION_TEST_RESULT_HP 0x8166 +#endif /* GL_HP_occlusion_test */ + +#ifndef GL_HP_texture_lighting +#define GL_HP_texture_lighting 1 +#define GL_TEXTURE_LIGHTING_MODE_HP 0x8167 +#define GL_TEXTURE_POST_SPECULAR_HP 0x8168 +#define GL_TEXTURE_PRE_SPECULAR_HP 0x8169 +#endif /* GL_HP_texture_lighting */ + +#ifndef GL_IBM_cull_vertex +#define GL_IBM_cull_vertex 1 +#define GL_CULL_VERTEX_IBM 103050 +#endif /* GL_IBM_cull_vertex */ + +#ifndef GL_IBM_multimode_draw_arrays +#define GL_IBM_multimode_draw_arrays 1 +typedef void (APIENTRYP PFNGLMULTIMODEDRAWARRAYSIBMPROC) (const GLenum *mode, const GLint *first, const GLsizei *count, GLsizei primcount, GLint modestride); +typedef void (APIENTRYP PFNGLMULTIMODEDRAWELEMENTSIBMPROC) (const GLenum *mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount, GLint modestride); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiModeDrawArraysIBM (const GLenum *mode, const GLint *first, const GLsizei *count, GLsizei primcount, GLint modestride); +GLAPI void APIENTRY glMultiModeDrawElementsIBM (const GLenum *mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount, GLint modestride); +#endif +#endif /* GL_IBM_multimode_draw_arrays */ + +#ifndef GL_IBM_rasterpos_clip +#define GL_IBM_rasterpos_clip 1 +#define GL_RASTER_POSITION_UNCLIPPED_IBM 0x19262 +#endif /* GL_IBM_rasterpos_clip */ + +#ifndef GL_IBM_static_data +#define GL_IBM_static_data 1 +#define GL_ALL_STATIC_DATA_IBM 103060 +#define GL_STATIC_VERTEX_ARRAY_IBM 103061 +typedef void (APIENTRYP PFNGLFLUSHSTATICDATAIBMPROC) (GLenum target); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFlushStaticDataIBM (GLenum target); +#endif +#endif /* GL_IBM_static_data */ + +#ifndef GL_IBM_texture_mirrored_repeat +#define GL_IBM_texture_mirrored_repeat 1 +#define GL_MIRRORED_REPEAT_IBM 0x8370 +#endif /* GL_IBM_texture_mirrored_repeat */ + +#ifndef GL_IBM_vertex_array_lists +#define GL_IBM_vertex_array_lists 1 +#define GL_VERTEX_ARRAY_LIST_IBM 103070 +#define GL_NORMAL_ARRAY_LIST_IBM 103071 +#define GL_COLOR_ARRAY_LIST_IBM 103072 +#define GL_INDEX_ARRAY_LIST_IBM 103073 +#define GL_TEXTURE_COORD_ARRAY_LIST_IBM 103074 +#define GL_EDGE_FLAG_ARRAY_LIST_IBM 103075 +#define GL_FOG_COORDINATE_ARRAY_LIST_IBM 103076 +#define GL_SECONDARY_COLOR_ARRAY_LIST_IBM 103077 +#define GL_VERTEX_ARRAY_LIST_STRIDE_IBM 103080 +#define GL_NORMAL_ARRAY_LIST_STRIDE_IBM 103081 +#define GL_COLOR_ARRAY_LIST_STRIDE_IBM 103082 +#define GL_INDEX_ARRAY_LIST_STRIDE_IBM 103083 +#define GL_TEXTURE_COORD_ARRAY_LIST_STRIDE_IBM 103084 +#define GL_EDGE_FLAG_ARRAY_LIST_STRIDE_IBM 103085 +#define GL_FOG_COORDINATE_ARRAY_LIST_STRIDE_IBM 103086 +#define GL_SECONDARY_COLOR_ARRAY_LIST_STRIDE_IBM 103087 +typedef void (APIENTRYP PFNGLCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLEDGEFLAGPOINTERLISTIBMPROC) (GLint stride, const GLboolean **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLFOGCOORDPOINTERLISTIBMPROC) (GLenum type, GLint stride, const void **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLINDEXPOINTERLISTIBMPROC) (GLenum type, GLint stride, const void **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLNORMALPOINTERLISTIBMPROC) (GLenum type, GLint stride, const void **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLTEXCOORDPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLVERTEXPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorPointerListIBM (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +GLAPI void APIENTRY glSecondaryColorPointerListIBM (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +GLAPI void APIENTRY glEdgeFlagPointerListIBM (GLint stride, const GLboolean **pointer, GLint ptrstride); +GLAPI void APIENTRY glFogCoordPointerListIBM (GLenum type, GLint stride, const void **pointer, GLint ptrstride); +GLAPI void APIENTRY glIndexPointerListIBM (GLenum type, GLint stride, const void **pointer, GLint ptrstride); +GLAPI void APIENTRY glNormalPointerListIBM (GLenum type, GLint stride, const void **pointer, GLint ptrstride); +GLAPI void APIENTRY glTexCoordPointerListIBM (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +GLAPI void APIENTRY glVertexPointerListIBM (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +#endif +#endif /* GL_IBM_vertex_array_lists */ + +#ifndef GL_INGR_blend_func_separate +#define GL_INGR_blend_func_separate 1 +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINGRPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendFuncSeparateINGR (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +#endif +#endif /* GL_INGR_blend_func_separate */ + +#ifndef GL_INGR_color_clamp +#define GL_INGR_color_clamp 1 +#define GL_RED_MIN_CLAMP_INGR 0x8560 +#define GL_GREEN_MIN_CLAMP_INGR 0x8561 +#define GL_BLUE_MIN_CLAMP_INGR 0x8562 +#define GL_ALPHA_MIN_CLAMP_INGR 0x8563 +#define GL_RED_MAX_CLAMP_INGR 0x8564 +#define GL_GREEN_MAX_CLAMP_INGR 0x8565 +#define GL_BLUE_MAX_CLAMP_INGR 0x8566 +#define GL_ALPHA_MAX_CLAMP_INGR 0x8567 +#endif /* GL_INGR_color_clamp */ + +#ifndef GL_INGR_interlace_read +#define GL_INGR_interlace_read 1 +#define GL_INTERLACE_READ_INGR 0x8568 +#endif /* GL_INGR_interlace_read */ + +#ifndef GL_INTEL_conservative_rasterization +#define GL_INTEL_conservative_rasterization 1 +#define GL_CONSERVATIVE_RASTERIZATION_INTEL 0x83FE +#endif /* GL_INTEL_conservative_rasterization */ + +#ifndef GL_INTEL_fragment_shader_ordering +#define GL_INTEL_fragment_shader_ordering 1 +#endif /* GL_INTEL_fragment_shader_ordering */ + +#ifndef GL_INTEL_framebuffer_CMAA +#define GL_INTEL_framebuffer_CMAA 1 +typedef void (APIENTRYP PFNGLAPPLYFRAMEBUFFERATTACHMENTCMAAINTELPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glApplyFramebufferAttachmentCMAAINTEL (void); +#endif +#endif /* GL_INTEL_framebuffer_CMAA */ + +#ifndef GL_INTEL_map_texture +#define GL_INTEL_map_texture 1 +#define GL_TEXTURE_MEMORY_LAYOUT_INTEL 0x83FF +#define GL_LAYOUT_DEFAULT_INTEL 0 +#define GL_LAYOUT_LINEAR_INTEL 1 +#define GL_LAYOUT_LINEAR_CPU_CACHED_INTEL 2 +typedef void (APIENTRYP PFNGLSYNCTEXTUREINTELPROC) (GLuint texture); +typedef void (APIENTRYP PFNGLUNMAPTEXTURE2DINTELPROC) (GLuint texture, GLint level); +typedef void *(APIENTRYP PFNGLMAPTEXTURE2DINTELPROC) (GLuint texture, GLint level, GLbitfield access, GLint *stride, GLenum *layout); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSyncTextureINTEL (GLuint texture); +GLAPI void APIENTRY glUnmapTexture2DINTEL (GLuint texture, GLint level); +GLAPI void *APIENTRY glMapTexture2DINTEL (GLuint texture, GLint level, GLbitfield access, GLint *stride, GLenum *layout); +#endif +#endif /* GL_INTEL_map_texture */ + +#ifndef GL_INTEL_parallel_arrays +#define GL_INTEL_parallel_arrays 1 +#define GL_PARALLEL_ARRAYS_INTEL 0x83F4 +#define GL_VERTEX_ARRAY_PARALLEL_POINTERS_INTEL 0x83F5 +#define GL_NORMAL_ARRAY_PARALLEL_POINTERS_INTEL 0x83F6 +#define GL_COLOR_ARRAY_PARALLEL_POINTERS_INTEL 0x83F7 +#define GL_TEXTURE_COORD_ARRAY_PARALLEL_POINTERS_INTEL 0x83F8 +typedef void (APIENTRYP PFNGLVERTEXPOINTERVINTELPROC) (GLint size, GLenum type, const void **pointer); +typedef void (APIENTRYP PFNGLNORMALPOINTERVINTELPROC) (GLenum type, const void **pointer); +typedef void (APIENTRYP PFNGLCOLORPOINTERVINTELPROC) (GLint size, GLenum type, const void **pointer); +typedef void (APIENTRYP PFNGLTEXCOORDPOINTERVINTELPROC) (GLint size, GLenum type, const void **pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexPointervINTEL (GLint size, GLenum type, const void **pointer); +GLAPI void APIENTRY glNormalPointervINTEL (GLenum type, const void **pointer); +GLAPI void APIENTRY glColorPointervINTEL (GLint size, GLenum type, const void **pointer); +GLAPI void APIENTRY glTexCoordPointervINTEL (GLint size, GLenum type, const void **pointer); +#endif +#endif /* GL_INTEL_parallel_arrays */ + +#ifndef GL_INTEL_performance_query +#define GL_INTEL_performance_query 1 +#define GL_PERFQUERY_SINGLE_CONTEXT_INTEL 0x00000000 +#define GL_PERFQUERY_GLOBAL_CONTEXT_INTEL 0x00000001 +#define GL_PERFQUERY_WAIT_INTEL 0x83FB +#define GL_PERFQUERY_FLUSH_INTEL 0x83FA +#define GL_PERFQUERY_DONOT_FLUSH_INTEL 0x83F9 +#define GL_PERFQUERY_COUNTER_EVENT_INTEL 0x94F0 +#define GL_PERFQUERY_COUNTER_DURATION_NORM_INTEL 0x94F1 +#define GL_PERFQUERY_COUNTER_DURATION_RAW_INTEL 0x94F2 +#define GL_PERFQUERY_COUNTER_THROUGHPUT_INTEL 0x94F3 +#define GL_PERFQUERY_COUNTER_RAW_INTEL 0x94F4 +#define GL_PERFQUERY_COUNTER_TIMESTAMP_INTEL 0x94F5 +#define GL_PERFQUERY_COUNTER_DATA_UINT32_INTEL 0x94F8 +#define GL_PERFQUERY_COUNTER_DATA_UINT64_INTEL 0x94F9 +#define GL_PERFQUERY_COUNTER_DATA_FLOAT_INTEL 0x94FA +#define GL_PERFQUERY_COUNTER_DATA_DOUBLE_INTEL 0x94FB +#define GL_PERFQUERY_COUNTER_DATA_BOOL32_INTEL 0x94FC +#define GL_PERFQUERY_QUERY_NAME_LENGTH_MAX_INTEL 0x94FD +#define GL_PERFQUERY_COUNTER_NAME_LENGTH_MAX_INTEL 0x94FE +#define GL_PERFQUERY_COUNTER_DESC_LENGTH_MAX_INTEL 0x94FF +#define GL_PERFQUERY_GPA_EXTENDED_COUNTERS_INTEL 0x9500 +typedef void (APIENTRYP PFNGLBEGINPERFQUERYINTELPROC) (GLuint queryHandle); +typedef void (APIENTRYP PFNGLCREATEPERFQUERYINTELPROC) (GLuint queryId, GLuint *queryHandle); +typedef void (APIENTRYP PFNGLDELETEPERFQUERYINTELPROC) (GLuint queryHandle); +typedef void (APIENTRYP PFNGLENDPERFQUERYINTELPROC) (GLuint queryHandle); +typedef void (APIENTRYP PFNGLGETFIRSTPERFQUERYIDINTELPROC) (GLuint *queryId); +typedef void (APIENTRYP PFNGLGETNEXTPERFQUERYIDINTELPROC) (GLuint queryId, GLuint *nextQueryId); +typedef void (APIENTRYP PFNGLGETPERFCOUNTERINFOINTELPROC) (GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue); +typedef void (APIENTRYP PFNGLGETPERFQUERYDATAINTELPROC) (GLuint queryHandle, GLuint flags, GLsizei dataSize, GLvoid *data, GLuint *bytesWritten); +typedef void (APIENTRYP PFNGLGETPERFQUERYIDBYNAMEINTELPROC) (GLchar *queryName, GLuint *queryId); +typedef void (APIENTRYP PFNGLGETPERFQUERYINFOINTELPROC) (GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *noInstances, GLuint *capsMask); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginPerfQueryINTEL (GLuint queryHandle); +GLAPI void APIENTRY glCreatePerfQueryINTEL (GLuint queryId, GLuint *queryHandle); +GLAPI void APIENTRY glDeletePerfQueryINTEL (GLuint queryHandle); +GLAPI void APIENTRY glEndPerfQueryINTEL (GLuint queryHandle); +GLAPI void APIENTRY glGetFirstPerfQueryIdINTEL (GLuint *queryId); +GLAPI void APIENTRY glGetNextPerfQueryIdINTEL (GLuint queryId, GLuint *nextQueryId); +GLAPI void APIENTRY glGetPerfCounterInfoINTEL (GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue); +GLAPI void APIENTRY glGetPerfQueryDataINTEL (GLuint queryHandle, GLuint flags, GLsizei dataSize, GLvoid *data, GLuint *bytesWritten); +GLAPI void APIENTRY glGetPerfQueryIdByNameINTEL (GLchar *queryName, GLuint *queryId); +GLAPI void APIENTRY glGetPerfQueryInfoINTEL (GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *noInstances, GLuint *capsMask); +#endif +#endif /* GL_INTEL_performance_query */ + +#ifndef GL_MESAX_texture_stack +#define GL_MESAX_texture_stack 1 +#define GL_TEXTURE_1D_STACK_MESAX 0x8759 +#define GL_TEXTURE_2D_STACK_MESAX 0x875A +#define GL_PROXY_TEXTURE_1D_STACK_MESAX 0x875B +#define GL_PROXY_TEXTURE_2D_STACK_MESAX 0x875C +#define GL_TEXTURE_1D_STACK_BINDING_MESAX 0x875D +#define GL_TEXTURE_2D_STACK_BINDING_MESAX 0x875E +#endif /* GL_MESAX_texture_stack */ + +#ifndef GL_MESA_pack_invert +#define GL_MESA_pack_invert 1 +#define GL_PACK_INVERT_MESA 0x8758 +#endif /* GL_MESA_pack_invert */ + +#ifndef GL_MESA_resize_buffers +#define GL_MESA_resize_buffers 1 +typedef void (APIENTRYP PFNGLRESIZEBUFFERSMESAPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glResizeBuffersMESA (void); +#endif +#endif /* GL_MESA_resize_buffers */ + +#ifndef GL_MESA_shader_integer_functions +#define GL_MESA_shader_integer_functions 1 +#endif /* GL_MESA_shader_integer_functions */ + +#ifndef GL_MESA_window_pos +#define GL_MESA_window_pos 1 +typedef void (APIENTRYP PFNGLWINDOWPOS2DMESAPROC) (GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLWINDOWPOS2DVMESAPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2FMESAPROC) (GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLWINDOWPOS2FVMESAPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2IMESAPROC) (GLint x, GLint y); +typedef void (APIENTRYP PFNGLWINDOWPOS2IVMESAPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2SMESAPROC) (GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLWINDOWPOS2SVMESAPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3DMESAPROC) (GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLWINDOWPOS3DVMESAPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3FMESAPROC) (GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLWINDOWPOS3FVMESAPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3IMESAPROC) (GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLWINDOWPOS3IVMESAPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3SMESAPROC) (GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLWINDOWPOS3SVMESAPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLWINDOWPOS4DMESAPROC) (GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLWINDOWPOS4DVMESAPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS4FMESAPROC) (GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLWINDOWPOS4FVMESAPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS4IMESAPROC) (GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLWINDOWPOS4IVMESAPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS4SMESAPROC) (GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLWINDOWPOS4SVMESAPROC) (const GLshort *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glWindowPos2dMESA (GLdouble x, GLdouble y); +GLAPI void APIENTRY glWindowPos2dvMESA (const GLdouble *v); +GLAPI void APIENTRY glWindowPos2fMESA (GLfloat x, GLfloat y); +GLAPI void APIENTRY glWindowPos2fvMESA (const GLfloat *v); +GLAPI void APIENTRY glWindowPos2iMESA (GLint x, GLint y); +GLAPI void APIENTRY glWindowPos2ivMESA (const GLint *v); +GLAPI void APIENTRY glWindowPos2sMESA (GLshort x, GLshort y); +GLAPI void APIENTRY glWindowPos2svMESA (const GLshort *v); +GLAPI void APIENTRY glWindowPos3dMESA (GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glWindowPos3dvMESA (const GLdouble *v); +GLAPI void APIENTRY glWindowPos3fMESA (GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glWindowPos3fvMESA (const GLfloat *v); +GLAPI void APIENTRY glWindowPos3iMESA (GLint x, GLint y, GLint z); +GLAPI void APIENTRY glWindowPos3ivMESA (const GLint *v); +GLAPI void APIENTRY glWindowPos3sMESA (GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glWindowPos3svMESA (const GLshort *v); +GLAPI void APIENTRY glWindowPos4dMESA (GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glWindowPos4dvMESA (const GLdouble *v); +GLAPI void APIENTRY glWindowPos4fMESA (GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glWindowPos4fvMESA (const GLfloat *v); +GLAPI void APIENTRY glWindowPos4iMESA (GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glWindowPos4ivMESA (const GLint *v); +GLAPI void APIENTRY glWindowPos4sMESA (GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI void APIENTRY glWindowPos4svMESA (const GLshort *v); +#endif +#endif /* GL_MESA_window_pos */ + +#ifndef GL_MESA_ycbcr_texture +#define GL_MESA_ycbcr_texture 1 +#define GL_UNSIGNED_SHORT_8_8_MESA 0x85BA +#define GL_UNSIGNED_SHORT_8_8_REV_MESA 0x85BB +#define GL_YCBCR_MESA 0x8757 +#endif /* GL_MESA_ycbcr_texture */ + +#ifndef GL_NVX_blend_equation_advanced_multi_draw_buffers +#define GL_NVX_blend_equation_advanced_multi_draw_buffers 1 +#endif /* GL_NVX_blend_equation_advanced_multi_draw_buffers */ + +#ifndef GL_NVX_conditional_render +#define GL_NVX_conditional_render 1 +typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERNVXPROC) (GLuint id); +typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERNVXPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginConditionalRenderNVX (GLuint id); +GLAPI void APIENTRY glEndConditionalRenderNVX (void); +#endif +#endif /* GL_NVX_conditional_render */ + +#ifndef GL_NVX_gpu_memory_info +#define GL_NVX_gpu_memory_info 1 +#define GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX 0x9047 +#define GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX 0x9048 +#define GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX 0x9049 +#define GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX 0x904A +#define GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX 0x904B +#endif /* GL_NVX_gpu_memory_info */ + +#ifndef GL_NVX_linked_gpu_multicast +#define GL_NVX_linked_gpu_multicast 1 +#define GL_LGPU_SEPARATE_STORAGE_BIT_NVX 0x0800 +#define GL_MAX_LGPU_GPUS_NVX 0x92BA +typedef void (APIENTRYP PFNGLLGPUNAMEDBUFFERSUBDATANVXPROC) (GLbitfield gpuMask, GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); +typedef void (APIENTRYP PFNGLLGPUCOPYIMAGESUBDATANVXPROC) (GLuint sourceGpu, GLbitfield destinationGpuMask, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srxY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth); +typedef void (APIENTRYP PFNGLLGPUINTERLOCKNVXPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glLGPUNamedBufferSubDataNVX (GLbitfield gpuMask, GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); +GLAPI void APIENTRY glLGPUCopyImageSubDataNVX (GLuint sourceGpu, GLbitfield destinationGpuMask, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srxY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth); +GLAPI void APIENTRY glLGPUInterlockNVX (void); +#endif +#endif /* GL_NVX_linked_gpu_multicast */ + +#ifndef GL_NV_alpha_to_coverage_dither_control +#define GL_NV_alpha_to_coverage_dither_control 1 +#define GL_ALPHA_TO_COVERAGE_DITHER_DEFAULT_NV 0x934D +#define GL_ALPHA_TO_COVERAGE_DITHER_ENABLE_NV 0x934E +#define GL_ALPHA_TO_COVERAGE_DITHER_DISABLE_NV 0x934F +#define GL_ALPHA_TO_COVERAGE_DITHER_MODE_NV 0x92BF +typedef void (APIENTRYP PFNGLALPHATOCOVERAGEDITHERCONTROLNVPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glAlphaToCoverageDitherControlNV (GLenum mode); +#endif +#endif /* GL_NV_alpha_to_coverage_dither_control */ + +#ifndef GL_NV_bindless_multi_draw_indirect +#define GL_NV_bindless_multi_draw_indirect 1 +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTBINDLESSNVPROC) (GLenum mode, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTBINDLESSNVPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiDrawArraysIndirectBindlessNV (GLenum mode, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount); +GLAPI void APIENTRY glMultiDrawElementsIndirectBindlessNV (GLenum mode, GLenum type, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount); +#endif +#endif /* GL_NV_bindless_multi_draw_indirect */ + +#ifndef GL_NV_bindless_multi_draw_indirect_count +#define GL_NV_bindless_multi_draw_indirect_count 1 +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTBINDLESSCOUNTNVPROC) (GLenum mode, const void *indirect, GLsizei drawCount, GLsizei maxDrawCount, GLsizei stride, GLint vertexBufferCount); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTBINDLESSCOUNTNVPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei drawCount, GLsizei maxDrawCount, GLsizei stride, GLint vertexBufferCount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiDrawArraysIndirectBindlessCountNV (GLenum mode, const void *indirect, GLsizei drawCount, GLsizei maxDrawCount, GLsizei stride, GLint vertexBufferCount); +GLAPI void APIENTRY glMultiDrawElementsIndirectBindlessCountNV (GLenum mode, GLenum type, const void *indirect, GLsizei drawCount, GLsizei maxDrawCount, GLsizei stride, GLint vertexBufferCount); +#endif +#endif /* GL_NV_bindless_multi_draw_indirect_count */ + +#ifndef GL_NV_bindless_texture +#define GL_NV_bindless_texture 1 +typedef GLuint64 (APIENTRYP PFNGLGETTEXTUREHANDLENVPROC) (GLuint texture); +typedef GLuint64 (APIENTRYP PFNGLGETTEXTURESAMPLERHANDLENVPROC) (GLuint texture, GLuint sampler); +typedef void (APIENTRYP PFNGLMAKETEXTUREHANDLERESIDENTNVPROC) (GLuint64 handle); +typedef void (APIENTRYP PFNGLMAKETEXTUREHANDLENONRESIDENTNVPROC) (GLuint64 handle); +typedef GLuint64 (APIENTRYP PFNGLGETIMAGEHANDLENVPROC) (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); +typedef void (APIENTRYP PFNGLMAKEIMAGEHANDLERESIDENTNVPROC) (GLuint64 handle, GLenum access); +typedef void (APIENTRYP PFNGLMAKEIMAGEHANDLENONRESIDENTNVPROC) (GLuint64 handle); +typedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64NVPROC) (GLint location, GLuint64 value); +typedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64VNVPROC) (GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64NVPROC) (GLuint program, GLint location, GLuint64 value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *values); +typedef GLboolean (APIENTRYP PFNGLISTEXTUREHANDLERESIDENTNVPROC) (GLuint64 handle); +typedef GLboolean (APIENTRYP PFNGLISIMAGEHANDLERESIDENTNVPROC) (GLuint64 handle); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLuint64 APIENTRY glGetTextureHandleNV (GLuint texture); +GLAPI GLuint64 APIENTRY glGetTextureSamplerHandleNV (GLuint texture, GLuint sampler); +GLAPI void APIENTRY glMakeTextureHandleResidentNV (GLuint64 handle); +GLAPI void APIENTRY glMakeTextureHandleNonResidentNV (GLuint64 handle); +GLAPI GLuint64 APIENTRY glGetImageHandleNV (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); +GLAPI void APIENTRY glMakeImageHandleResidentNV (GLuint64 handle, GLenum access); +GLAPI void APIENTRY glMakeImageHandleNonResidentNV (GLuint64 handle); +GLAPI void APIENTRY glUniformHandleui64NV (GLint location, GLuint64 value); +GLAPI void APIENTRY glUniformHandleui64vNV (GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glProgramUniformHandleui64NV (GLuint program, GLint location, GLuint64 value); +GLAPI void APIENTRY glProgramUniformHandleui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64 *values); +GLAPI GLboolean APIENTRY glIsTextureHandleResidentNV (GLuint64 handle); +GLAPI GLboolean APIENTRY glIsImageHandleResidentNV (GLuint64 handle); +#endif +#endif /* GL_NV_bindless_texture */ + +#ifndef GL_NV_blend_equation_advanced +#define GL_NV_blend_equation_advanced 1 +#define GL_BLEND_OVERLAP_NV 0x9281 +#define GL_BLEND_PREMULTIPLIED_SRC_NV 0x9280 +#define GL_BLUE_NV 0x1905 +#define GL_COLORBURN_NV 0x929A +#define GL_COLORDODGE_NV 0x9299 +#define GL_CONJOINT_NV 0x9284 +#define GL_CONTRAST_NV 0x92A1 +#define GL_DARKEN_NV 0x9297 +#define GL_DIFFERENCE_NV 0x929E +#define GL_DISJOINT_NV 0x9283 +#define GL_DST_ATOP_NV 0x928F +#define GL_DST_IN_NV 0x928B +#define GL_DST_NV 0x9287 +#define GL_DST_OUT_NV 0x928D +#define GL_DST_OVER_NV 0x9289 +#define GL_EXCLUSION_NV 0x92A0 +#define GL_GREEN_NV 0x1904 +#define GL_HARDLIGHT_NV 0x929B +#define GL_HARDMIX_NV 0x92A9 +#define GL_HSL_COLOR_NV 0x92AF +#define GL_HSL_HUE_NV 0x92AD +#define GL_HSL_LUMINOSITY_NV 0x92B0 +#define GL_HSL_SATURATION_NV 0x92AE +#define GL_INVERT_OVG_NV 0x92B4 +#define GL_INVERT_RGB_NV 0x92A3 +#define GL_LIGHTEN_NV 0x9298 +#define GL_LINEARBURN_NV 0x92A5 +#define GL_LINEARDODGE_NV 0x92A4 +#define GL_LINEARLIGHT_NV 0x92A7 +#define GL_MINUS_CLAMPED_NV 0x92B3 +#define GL_MINUS_NV 0x929F +#define GL_MULTIPLY_NV 0x9294 +#define GL_OVERLAY_NV 0x9296 +#define GL_PINLIGHT_NV 0x92A8 +#define GL_PLUS_CLAMPED_ALPHA_NV 0x92B2 +#define GL_PLUS_CLAMPED_NV 0x92B1 +#define GL_PLUS_DARKER_NV 0x9292 +#define GL_PLUS_NV 0x9291 +#define GL_RED_NV 0x1903 +#define GL_SCREEN_NV 0x9295 +#define GL_SOFTLIGHT_NV 0x929C +#define GL_SRC_ATOP_NV 0x928E +#define GL_SRC_IN_NV 0x928A +#define GL_SRC_NV 0x9286 +#define GL_SRC_OUT_NV 0x928C +#define GL_SRC_OVER_NV 0x9288 +#define GL_UNCORRELATED_NV 0x9282 +#define GL_VIVIDLIGHT_NV 0x92A6 +#define GL_XOR_NV 0x1506 +typedef void (APIENTRYP PFNGLBLENDPARAMETERINVPROC) (GLenum pname, GLint value); +typedef void (APIENTRYP PFNGLBLENDBARRIERNVPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendParameteriNV (GLenum pname, GLint value); +GLAPI void APIENTRY glBlendBarrierNV (void); +#endif +#endif /* GL_NV_blend_equation_advanced */ + +#ifndef GL_NV_blend_equation_advanced_coherent +#define GL_NV_blend_equation_advanced_coherent 1 +#define GL_BLEND_ADVANCED_COHERENT_NV 0x9285 +#endif /* GL_NV_blend_equation_advanced_coherent */ + +#ifndef GL_NV_blend_square +#define GL_NV_blend_square 1 +#endif /* GL_NV_blend_square */ + +#ifndef GL_NV_clip_space_w_scaling +#define GL_NV_clip_space_w_scaling 1 +#define GL_VIEWPORT_POSITION_W_SCALE_NV 0x937C +#define GL_VIEWPORT_POSITION_W_SCALE_X_COEFF_NV 0x937D +#define GL_VIEWPORT_POSITION_W_SCALE_Y_COEFF_NV 0x937E +typedef void (APIENTRYP PFNGLVIEWPORTPOSITIONWSCALENVPROC) (GLuint index, GLfloat xcoeff, GLfloat ycoeff); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glViewportPositionWScaleNV (GLuint index, GLfloat xcoeff, GLfloat ycoeff); +#endif +#endif /* GL_NV_clip_space_w_scaling */ + +#ifndef GL_NV_command_list +#define GL_NV_command_list 1 +#define GL_TERMINATE_SEQUENCE_COMMAND_NV 0x0000 +#define GL_NOP_COMMAND_NV 0x0001 +#define GL_DRAW_ELEMENTS_COMMAND_NV 0x0002 +#define GL_DRAW_ARRAYS_COMMAND_NV 0x0003 +#define GL_DRAW_ELEMENTS_STRIP_COMMAND_NV 0x0004 +#define GL_DRAW_ARRAYS_STRIP_COMMAND_NV 0x0005 +#define GL_DRAW_ELEMENTS_INSTANCED_COMMAND_NV 0x0006 +#define GL_DRAW_ARRAYS_INSTANCED_COMMAND_NV 0x0007 +#define GL_ELEMENT_ADDRESS_COMMAND_NV 0x0008 +#define GL_ATTRIBUTE_ADDRESS_COMMAND_NV 0x0009 +#define GL_UNIFORM_ADDRESS_COMMAND_NV 0x000A +#define GL_BLEND_COLOR_COMMAND_NV 0x000B +#define GL_STENCIL_REF_COMMAND_NV 0x000C +#define GL_LINE_WIDTH_COMMAND_NV 0x000D +#define GL_POLYGON_OFFSET_COMMAND_NV 0x000E +#define GL_ALPHA_REF_COMMAND_NV 0x000F +#define GL_VIEWPORT_COMMAND_NV 0x0010 +#define GL_SCISSOR_COMMAND_NV 0x0011 +#define GL_FRONT_FACE_COMMAND_NV 0x0012 +typedef void (APIENTRYP PFNGLCREATESTATESNVPROC) (GLsizei n, GLuint *states); +typedef void (APIENTRYP PFNGLDELETESTATESNVPROC) (GLsizei n, const GLuint *states); +typedef GLboolean (APIENTRYP PFNGLISSTATENVPROC) (GLuint state); +typedef void (APIENTRYP PFNGLSTATECAPTURENVPROC) (GLuint state, GLenum mode); +typedef GLuint (APIENTRYP PFNGLGETCOMMANDHEADERNVPROC) (GLenum tokenID, GLuint size); +typedef GLushort (APIENTRYP PFNGLGETSTAGEINDEXNVPROC) (GLenum shadertype); +typedef void (APIENTRYP PFNGLDRAWCOMMANDSNVPROC) (GLenum primitiveMode, GLuint buffer, const GLintptr *indirects, const GLsizei *sizes, GLuint count); +typedef void (APIENTRYP PFNGLDRAWCOMMANDSADDRESSNVPROC) (GLenum primitiveMode, const GLuint64 *indirects, const GLsizei *sizes, GLuint count); +typedef void (APIENTRYP PFNGLDRAWCOMMANDSSTATESNVPROC) (GLuint buffer, const GLintptr *indirects, const GLsizei *sizes, const GLuint *states, const GLuint *fbos, GLuint count); +typedef void (APIENTRYP PFNGLDRAWCOMMANDSSTATESADDRESSNVPROC) (const GLuint64 *indirects, const GLsizei *sizes, const GLuint *states, const GLuint *fbos, GLuint count); +typedef void (APIENTRYP PFNGLCREATECOMMANDLISTSNVPROC) (GLsizei n, GLuint *lists); +typedef void (APIENTRYP PFNGLDELETECOMMANDLISTSNVPROC) (GLsizei n, const GLuint *lists); +typedef GLboolean (APIENTRYP PFNGLISCOMMANDLISTNVPROC) (GLuint list); +typedef void (APIENTRYP PFNGLLISTDRAWCOMMANDSSTATESCLIENTNVPROC) (GLuint list, GLuint segment, const void **indirects, const GLsizei *sizes, const GLuint *states, const GLuint *fbos, GLuint count); +typedef void (APIENTRYP PFNGLCOMMANDLISTSEGMENTSNVPROC) (GLuint list, GLuint segments); +typedef void (APIENTRYP PFNGLCOMPILECOMMANDLISTNVPROC) (GLuint list); +typedef void (APIENTRYP PFNGLCALLCOMMANDLISTNVPROC) (GLuint list); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCreateStatesNV (GLsizei n, GLuint *states); +GLAPI void APIENTRY glDeleteStatesNV (GLsizei n, const GLuint *states); +GLAPI GLboolean APIENTRY glIsStateNV (GLuint state); +GLAPI void APIENTRY glStateCaptureNV (GLuint state, GLenum mode); +GLAPI GLuint APIENTRY glGetCommandHeaderNV (GLenum tokenID, GLuint size); +GLAPI GLushort APIENTRY glGetStageIndexNV (GLenum shadertype); +GLAPI void APIENTRY glDrawCommandsNV (GLenum primitiveMode, GLuint buffer, const GLintptr *indirects, const GLsizei *sizes, GLuint count); +GLAPI void APIENTRY glDrawCommandsAddressNV (GLenum primitiveMode, const GLuint64 *indirects, const GLsizei *sizes, GLuint count); +GLAPI void APIENTRY glDrawCommandsStatesNV (GLuint buffer, const GLintptr *indirects, const GLsizei *sizes, const GLuint *states, const GLuint *fbos, GLuint count); +GLAPI void APIENTRY glDrawCommandsStatesAddressNV (const GLuint64 *indirects, const GLsizei *sizes, const GLuint *states, const GLuint *fbos, GLuint count); +GLAPI void APIENTRY glCreateCommandListsNV (GLsizei n, GLuint *lists); +GLAPI void APIENTRY glDeleteCommandListsNV (GLsizei n, const GLuint *lists); +GLAPI GLboolean APIENTRY glIsCommandListNV (GLuint list); +GLAPI void APIENTRY glListDrawCommandsStatesClientNV (GLuint list, GLuint segment, const void **indirects, const GLsizei *sizes, const GLuint *states, const GLuint *fbos, GLuint count); +GLAPI void APIENTRY glCommandListSegmentsNV (GLuint list, GLuint segments); +GLAPI void APIENTRY glCompileCommandListNV (GLuint list); +GLAPI void APIENTRY glCallCommandListNV (GLuint list); +#endif +#endif /* GL_NV_command_list */ + +#ifndef GL_NV_compute_program5 +#define GL_NV_compute_program5 1 +#define GL_COMPUTE_PROGRAM_NV 0x90FB +#define GL_COMPUTE_PROGRAM_PARAMETER_BUFFER_NV 0x90FC +#endif /* GL_NV_compute_program5 */ + +#ifndef GL_NV_conditional_render +#define GL_NV_conditional_render 1 +#define GL_QUERY_WAIT_NV 0x8E13 +#define GL_QUERY_NO_WAIT_NV 0x8E14 +#define GL_QUERY_BY_REGION_WAIT_NV 0x8E15 +#define GL_QUERY_BY_REGION_NO_WAIT_NV 0x8E16 +typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERNVPROC) (GLuint id, GLenum mode); +typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERNVPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginConditionalRenderNV (GLuint id, GLenum mode); +GLAPI void APIENTRY glEndConditionalRenderNV (void); +#endif +#endif /* GL_NV_conditional_render */ + +#ifndef GL_NV_conservative_raster +#define GL_NV_conservative_raster 1 +#define GL_CONSERVATIVE_RASTERIZATION_NV 0x9346 +#define GL_SUBPIXEL_PRECISION_BIAS_X_BITS_NV 0x9347 +#define GL_SUBPIXEL_PRECISION_BIAS_Y_BITS_NV 0x9348 +#define GL_MAX_SUBPIXEL_PRECISION_BIAS_BITS_NV 0x9349 +typedef void (APIENTRYP PFNGLSUBPIXELPRECISIONBIASNVPROC) (GLuint xbits, GLuint ybits); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSubpixelPrecisionBiasNV (GLuint xbits, GLuint ybits); +#endif +#endif /* GL_NV_conservative_raster */ + +#ifndef GL_NV_conservative_raster_dilate +#define GL_NV_conservative_raster_dilate 1 +#define GL_CONSERVATIVE_RASTER_DILATE_NV 0x9379 +#define GL_CONSERVATIVE_RASTER_DILATE_RANGE_NV 0x937A +#define GL_CONSERVATIVE_RASTER_DILATE_GRANULARITY_NV 0x937B +typedef void (APIENTRYP PFNGLCONSERVATIVERASTERPARAMETERFNVPROC) (GLenum pname, GLfloat value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glConservativeRasterParameterfNV (GLenum pname, GLfloat value); +#endif +#endif /* GL_NV_conservative_raster_dilate */ + +#ifndef GL_NV_conservative_raster_pre_snap_triangles +#define GL_NV_conservative_raster_pre_snap_triangles 1 +#define GL_CONSERVATIVE_RASTER_MODE_NV 0x954D +#define GL_CONSERVATIVE_RASTER_MODE_POST_SNAP_NV 0x954E +#define GL_CONSERVATIVE_RASTER_MODE_PRE_SNAP_TRIANGLES_NV 0x954F +typedef void (APIENTRYP PFNGLCONSERVATIVERASTERPARAMETERINVPROC) (GLenum pname, GLint param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glConservativeRasterParameteriNV (GLenum pname, GLint param); +#endif +#endif /* GL_NV_conservative_raster_pre_snap_triangles */ + +#ifndef GL_NV_copy_depth_to_color +#define GL_NV_copy_depth_to_color 1 +#define GL_DEPTH_STENCIL_TO_RGBA_NV 0x886E +#define GL_DEPTH_STENCIL_TO_BGRA_NV 0x886F +#endif /* GL_NV_copy_depth_to_color */ + +#ifndef GL_NV_copy_image +#define GL_NV_copy_image 1 +typedef void (APIENTRYP PFNGLCOPYIMAGESUBDATANVPROC) (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCopyImageSubDataNV (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth); +#endif +#endif /* GL_NV_copy_image */ + +#ifndef GL_NV_deep_texture3D +#define GL_NV_deep_texture3D 1 +#define GL_MAX_DEEP_3D_TEXTURE_WIDTH_HEIGHT_NV 0x90D0 +#define GL_MAX_DEEP_3D_TEXTURE_DEPTH_NV 0x90D1 +#endif /* GL_NV_deep_texture3D */ + +#ifndef GL_NV_depth_buffer_float +#define GL_NV_depth_buffer_float 1 +#define GL_DEPTH_COMPONENT32F_NV 0x8DAB +#define GL_DEPTH32F_STENCIL8_NV 0x8DAC +#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV_NV 0x8DAD +#define GL_DEPTH_BUFFER_FLOAT_MODE_NV 0x8DAF +typedef void (APIENTRYP PFNGLDEPTHRANGEDNVPROC) (GLdouble zNear, GLdouble zFar); +typedef void (APIENTRYP PFNGLCLEARDEPTHDNVPROC) (GLdouble depth); +typedef void (APIENTRYP PFNGLDEPTHBOUNDSDNVPROC) (GLdouble zmin, GLdouble zmax); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDepthRangedNV (GLdouble zNear, GLdouble zFar); +GLAPI void APIENTRY glClearDepthdNV (GLdouble depth); +GLAPI void APIENTRY glDepthBoundsdNV (GLdouble zmin, GLdouble zmax); +#endif +#endif /* GL_NV_depth_buffer_float */ + +#ifndef GL_NV_depth_clamp +#define GL_NV_depth_clamp 1 +#define GL_DEPTH_CLAMP_NV 0x864F +#endif /* GL_NV_depth_clamp */ + +#ifndef GL_NV_draw_texture +#define GL_NV_draw_texture 1 +typedef void (APIENTRYP PFNGLDRAWTEXTURENVPROC) (GLuint texture, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawTextureNV (GLuint texture, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1); +#endif +#endif /* GL_NV_draw_texture */ + +#ifndef GL_NV_draw_vulkan_image +#define GL_NV_draw_vulkan_image 1 +typedef void (APIENTRY *GLVULKANPROCNV)(void); +typedef void (APIENTRYP PFNGLDRAWVKIMAGENVPROC) (GLuint64 vkImage, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1); +typedef GLVULKANPROCNV (APIENTRYP PFNGLGETVKPROCADDRNVPROC) (const GLchar *name); +typedef void (APIENTRYP PFNGLWAITVKSEMAPHORENVPROC) (GLuint64 vkSemaphore); +typedef void (APIENTRYP PFNGLSIGNALVKSEMAPHORENVPROC) (GLuint64 vkSemaphore); +typedef void (APIENTRYP PFNGLSIGNALVKFENCENVPROC) (GLuint64 vkFence); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawVkImageNV (GLuint64 vkImage, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1); +GLAPI GLVULKANPROCNV APIENTRY glGetVkProcAddrNV (const GLchar *name); +GLAPI void APIENTRY glWaitVkSemaphoreNV (GLuint64 vkSemaphore); +GLAPI void APIENTRY glSignalVkSemaphoreNV (GLuint64 vkSemaphore); +GLAPI void APIENTRY glSignalVkFenceNV (GLuint64 vkFence); +#endif +#endif /* GL_NV_draw_vulkan_image */ + +#ifndef GL_NV_evaluators +#define GL_NV_evaluators 1 +#define GL_EVAL_2D_NV 0x86C0 +#define GL_EVAL_TRIANGULAR_2D_NV 0x86C1 +#define GL_MAP_TESSELLATION_NV 0x86C2 +#define GL_MAP_ATTRIB_U_ORDER_NV 0x86C3 +#define GL_MAP_ATTRIB_V_ORDER_NV 0x86C4 +#define GL_EVAL_FRACTIONAL_TESSELLATION_NV 0x86C5 +#define GL_EVAL_VERTEX_ATTRIB0_NV 0x86C6 +#define GL_EVAL_VERTEX_ATTRIB1_NV 0x86C7 +#define GL_EVAL_VERTEX_ATTRIB2_NV 0x86C8 +#define GL_EVAL_VERTEX_ATTRIB3_NV 0x86C9 +#define GL_EVAL_VERTEX_ATTRIB4_NV 0x86CA +#define GL_EVAL_VERTEX_ATTRIB5_NV 0x86CB +#define GL_EVAL_VERTEX_ATTRIB6_NV 0x86CC +#define GL_EVAL_VERTEX_ATTRIB7_NV 0x86CD +#define GL_EVAL_VERTEX_ATTRIB8_NV 0x86CE +#define GL_EVAL_VERTEX_ATTRIB9_NV 0x86CF +#define GL_EVAL_VERTEX_ATTRIB10_NV 0x86D0 +#define GL_EVAL_VERTEX_ATTRIB11_NV 0x86D1 +#define GL_EVAL_VERTEX_ATTRIB12_NV 0x86D2 +#define GL_EVAL_VERTEX_ATTRIB13_NV 0x86D3 +#define GL_EVAL_VERTEX_ATTRIB14_NV 0x86D4 +#define GL_EVAL_VERTEX_ATTRIB15_NV 0x86D5 +#define GL_MAX_MAP_TESSELLATION_NV 0x86D6 +#define GL_MAX_RATIONAL_EVAL_ORDER_NV 0x86D7 +typedef void (APIENTRYP PFNGLMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const void *points); +typedef void (APIENTRYP PFNGLMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLboolean packed, void *points); +typedef void (APIENTRYP PFNGLGETMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERIVNVPROC) (GLenum target, GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLEVALMAPSNVPROC) (GLenum target, GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMapControlPointsNV (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const void *points); +GLAPI void APIENTRY glMapParameterivNV (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glMapParameterfvNV (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glGetMapControlPointsNV (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLboolean packed, void *points); +GLAPI void APIENTRY glGetMapParameterivNV (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMapParameterfvNV (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMapAttribParameterivNV (GLenum target, GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMapAttribParameterfvNV (GLenum target, GLuint index, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glEvalMapsNV (GLenum target, GLenum mode); +#endif +#endif /* GL_NV_evaluators */ + +#ifndef GL_NV_explicit_multisample +#define GL_NV_explicit_multisample 1 +#define GL_SAMPLE_POSITION_NV 0x8E50 +#define GL_SAMPLE_MASK_NV 0x8E51 +#define GL_SAMPLE_MASK_VALUE_NV 0x8E52 +#define GL_TEXTURE_BINDING_RENDERBUFFER_NV 0x8E53 +#define GL_TEXTURE_RENDERBUFFER_DATA_STORE_BINDING_NV 0x8E54 +#define GL_TEXTURE_RENDERBUFFER_NV 0x8E55 +#define GL_SAMPLER_RENDERBUFFER_NV 0x8E56 +#define GL_INT_SAMPLER_RENDERBUFFER_NV 0x8E57 +#define GL_UNSIGNED_INT_SAMPLER_RENDERBUFFER_NV 0x8E58 +#define GL_MAX_SAMPLE_MASK_WORDS_NV 0x8E59 +typedef void (APIENTRYP PFNGLGETMULTISAMPLEFVNVPROC) (GLenum pname, GLuint index, GLfloat *val); +typedef void (APIENTRYP PFNGLSAMPLEMASKINDEXEDNVPROC) (GLuint index, GLbitfield mask); +typedef void (APIENTRYP PFNGLTEXRENDERBUFFERNVPROC) (GLenum target, GLuint renderbuffer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetMultisamplefvNV (GLenum pname, GLuint index, GLfloat *val); +GLAPI void APIENTRY glSampleMaskIndexedNV (GLuint index, GLbitfield mask); +GLAPI void APIENTRY glTexRenderbufferNV (GLenum target, GLuint renderbuffer); +#endif +#endif /* GL_NV_explicit_multisample */ + +#ifndef GL_NV_fence +#define GL_NV_fence 1 +#define GL_ALL_COMPLETED_NV 0x84F2 +#define GL_FENCE_STATUS_NV 0x84F3 +#define GL_FENCE_CONDITION_NV 0x84F4 +typedef void (APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences); +typedef void (APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences); +typedef GLboolean (APIENTRYP PFNGLISFENCENVPROC) (GLuint fence); +typedef GLboolean (APIENTRYP PFNGLTESTFENCENVPROC) (GLuint fence); +typedef void (APIENTRYP PFNGLGETFENCEIVNVPROC) (GLuint fence, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence); +typedef void (APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDeleteFencesNV (GLsizei n, const GLuint *fences); +GLAPI void APIENTRY glGenFencesNV (GLsizei n, GLuint *fences); +GLAPI GLboolean APIENTRY glIsFenceNV (GLuint fence); +GLAPI GLboolean APIENTRY glTestFenceNV (GLuint fence); +GLAPI void APIENTRY glGetFenceivNV (GLuint fence, GLenum pname, GLint *params); +GLAPI void APIENTRY glFinishFenceNV (GLuint fence); +GLAPI void APIENTRY glSetFenceNV (GLuint fence, GLenum condition); +#endif +#endif /* GL_NV_fence */ + +#ifndef GL_NV_fill_rectangle +#define GL_NV_fill_rectangle 1 +#define GL_FILL_RECTANGLE_NV 0x933C +#endif /* GL_NV_fill_rectangle */ + +#ifndef GL_NV_float_buffer +#define GL_NV_float_buffer 1 +#define GL_FLOAT_R_NV 0x8880 +#define GL_FLOAT_RG_NV 0x8881 +#define GL_FLOAT_RGB_NV 0x8882 +#define GL_FLOAT_RGBA_NV 0x8883 +#define GL_FLOAT_R16_NV 0x8884 +#define GL_FLOAT_R32_NV 0x8885 +#define GL_FLOAT_RG16_NV 0x8886 +#define GL_FLOAT_RG32_NV 0x8887 +#define GL_FLOAT_RGB16_NV 0x8888 +#define GL_FLOAT_RGB32_NV 0x8889 +#define GL_FLOAT_RGBA16_NV 0x888A +#define GL_FLOAT_RGBA32_NV 0x888B +#define GL_TEXTURE_FLOAT_COMPONENTS_NV 0x888C +#define GL_FLOAT_CLEAR_COLOR_VALUE_NV 0x888D +#define GL_FLOAT_RGBA_MODE_NV 0x888E +#endif /* GL_NV_float_buffer */ + +#ifndef GL_NV_fog_distance +#define GL_NV_fog_distance 1 +#define GL_FOG_DISTANCE_MODE_NV 0x855A +#define GL_EYE_RADIAL_NV 0x855B +#define GL_EYE_PLANE_ABSOLUTE_NV 0x855C +#endif /* GL_NV_fog_distance */ + +#ifndef GL_NV_fragment_coverage_to_color +#define GL_NV_fragment_coverage_to_color 1 +#define GL_FRAGMENT_COVERAGE_TO_COLOR_NV 0x92DD +#define GL_FRAGMENT_COVERAGE_COLOR_NV 0x92DE +typedef void (APIENTRYP PFNGLFRAGMENTCOVERAGECOLORNVPROC) (GLuint color); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFragmentCoverageColorNV (GLuint color); +#endif +#endif /* GL_NV_fragment_coverage_to_color */ + +#ifndef GL_NV_fragment_program +#define GL_NV_fragment_program 1 +#define GL_MAX_FRAGMENT_PROGRAM_LOCAL_PARAMETERS_NV 0x8868 +#define GL_FRAGMENT_PROGRAM_NV 0x8870 +#define GL_MAX_TEXTURE_COORDS_NV 0x8871 +#define GL_MAX_TEXTURE_IMAGE_UNITS_NV 0x8872 +#define GL_FRAGMENT_PROGRAM_BINDING_NV 0x8873 +#define GL_PROGRAM_ERROR_STRING_NV 0x8874 +typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v); +typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLdouble *v); +typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERFVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERDVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramNamedParameter4fNV (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glProgramNamedParameter4fvNV (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v); +GLAPI void APIENTRY glProgramNamedParameter4dNV (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glProgramNamedParameter4dvNV (GLuint id, GLsizei len, const GLubyte *name, const GLdouble *v); +GLAPI void APIENTRY glGetProgramNamedParameterfvNV (GLuint id, GLsizei len, const GLubyte *name, GLfloat *params); +GLAPI void APIENTRY glGetProgramNamedParameterdvNV (GLuint id, GLsizei len, const GLubyte *name, GLdouble *params); +#endif +#endif /* GL_NV_fragment_program */ + +#ifndef GL_NV_fragment_program2 +#define GL_NV_fragment_program2 1 +#define GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV 0x88F4 +#define GL_MAX_PROGRAM_CALL_DEPTH_NV 0x88F5 +#define GL_MAX_PROGRAM_IF_DEPTH_NV 0x88F6 +#define GL_MAX_PROGRAM_LOOP_DEPTH_NV 0x88F7 +#define GL_MAX_PROGRAM_LOOP_COUNT_NV 0x88F8 +#endif /* GL_NV_fragment_program2 */ + +#ifndef GL_NV_fragment_program4 +#define GL_NV_fragment_program4 1 +#endif /* GL_NV_fragment_program4 */ + +#ifndef GL_NV_fragment_program_option +#define GL_NV_fragment_program_option 1 +#endif /* GL_NV_fragment_program_option */ + +#ifndef GL_NV_fragment_shader_interlock +#define GL_NV_fragment_shader_interlock 1 +#endif /* GL_NV_fragment_shader_interlock */ + +#ifndef GL_NV_framebuffer_mixed_samples +#define GL_NV_framebuffer_mixed_samples 1 +#define GL_COVERAGE_MODULATION_TABLE_NV 0x9331 +#define GL_COLOR_SAMPLES_NV 0x8E20 +#define GL_DEPTH_SAMPLES_NV 0x932D +#define GL_STENCIL_SAMPLES_NV 0x932E +#define GL_MIXED_DEPTH_SAMPLES_SUPPORTED_NV 0x932F +#define GL_MIXED_STENCIL_SAMPLES_SUPPORTED_NV 0x9330 +#define GL_COVERAGE_MODULATION_NV 0x9332 +#define GL_COVERAGE_MODULATION_TABLE_SIZE_NV 0x9333 +typedef void (APIENTRYP PFNGLCOVERAGEMODULATIONTABLENVPROC) (GLsizei n, const GLfloat *v); +typedef void (APIENTRYP PFNGLGETCOVERAGEMODULATIONTABLENVPROC) (GLsizei bufsize, GLfloat *v); +typedef void (APIENTRYP PFNGLCOVERAGEMODULATIONNVPROC) (GLenum components); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCoverageModulationTableNV (GLsizei n, const GLfloat *v); +GLAPI void APIENTRY glGetCoverageModulationTableNV (GLsizei bufsize, GLfloat *v); +GLAPI void APIENTRY glCoverageModulationNV (GLenum components); +#endif +#endif /* GL_NV_framebuffer_mixed_samples */ + +#ifndef GL_NV_framebuffer_multisample_coverage +#define GL_NV_framebuffer_multisample_coverage 1 +#define GL_RENDERBUFFER_COVERAGE_SAMPLES_NV 0x8CAB +#define GL_RENDERBUFFER_COLOR_SAMPLES_NV 0x8E10 +#define GL_MAX_MULTISAMPLE_COVERAGE_MODES_NV 0x8E11 +#define GL_MULTISAMPLE_COVERAGE_MODES_NV 0x8E12 +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLECOVERAGENVPROC) (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glRenderbufferStorageMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); +#endif +#endif /* GL_NV_framebuffer_multisample_coverage */ + +#ifndef GL_NV_geometry_program4 +#define GL_NV_geometry_program4 1 +#define GL_GEOMETRY_PROGRAM_NV 0x8C26 +#define GL_MAX_PROGRAM_OUTPUT_VERTICES_NV 0x8C27 +#define GL_MAX_PROGRAM_TOTAL_OUTPUT_COMPONENTS_NV 0x8C28 +typedef void (APIENTRYP PFNGLPROGRAMVERTEXLIMITNVPROC) (GLenum target, GLint limit); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREEXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREFACEEXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramVertexLimitNV (GLenum target, GLint limit); +GLAPI void APIENTRY glFramebufferTextureEXT (GLenum target, GLenum attachment, GLuint texture, GLint level); +GLAPI void APIENTRY glFramebufferTextureFaceEXT (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); +#endif +#endif /* GL_NV_geometry_program4 */ + +#ifndef GL_NV_geometry_shader4 +#define GL_NV_geometry_shader4 1 +#endif /* GL_NV_geometry_shader4 */ + +#ifndef GL_NV_geometry_shader_passthrough +#define GL_NV_geometry_shader_passthrough 1 +#endif /* GL_NV_geometry_shader_passthrough */ + +#ifndef GL_NV_gpu_multicast +#define GL_NV_gpu_multicast 1 +#define GL_PER_GPU_STORAGE_BIT_NV 0x0800 +#define GL_MULTICAST_GPUS_NV 0x92BA +#define GL_RENDER_GPU_MASK_NV 0x9558 +#define GL_PER_GPU_STORAGE_NV 0x9548 +#define GL_MULTICAST_PROGRAMMABLE_SAMPLE_LOCATION_NV 0x9549 +typedef void (APIENTRYP PFNGLRENDERGPUMASKNVPROC) (GLbitfield mask); +typedef void (APIENTRYP PFNGLMULTICASTBUFFERSUBDATANVPROC) (GLbitfield gpuMask, GLuint buffer, GLintptr offset, GLsizeiptr size, const GLvoid *data); +typedef void (APIENTRYP PFNGLMULTICASTCOPYBUFFERSUBDATANVPROC) (GLuint readGpu, GLbitfield writeGpuMask, GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLMULTICASTCOPYIMAGESUBDATANVPROC) (GLuint srcGpu, GLbitfield dstGpuMask, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); +typedef void (APIENTRYP PFNGLMULTICASTBLITFRAMEBUFFERNVPROC) (GLuint srcGpu, GLuint dstGpu, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +typedef void (APIENTRYP PFNGLMULTICASTFRAMEBUFFERSAMPLELOCATIONSFVNVPROC) (GLuint gpu, GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTICASTBARRIERNVPROC) (void); +typedef void (APIENTRYP PFNGLMULTICASTWAITSYNCNVPROC) (GLuint signalGpu, GLbitfield waitGpuMask); +typedef void (APIENTRYP PFNGLMULTICASTGETQUERYOBJECTIVNVPROC) (GLuint gpu, GLuint id, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLMULTICASTGETQUERYOBJECTUIVNVPROC) (GLuint gpu, GLuint id, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLMULTICASTGETQUERYOBJECTI64VNVPROC) (GLuint gpu, GLuint id, GLenum pname, GLint64 *params); +typedef void (APIENTRYP PFNGLMULTICASTGETQUERYOBJECTUI64VNVPROC) (GLuint gpu, GLuint id, GLenum pname, GLuint64 *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glRenderGpuMaskNV (GLbitfield mask); +GLAPI void APIENTRY glMulticastBufferSubDataNV (GLbitfield gpuMask, GLuint buffer, GLintptr offset, GLsizeiptr size, const GLvoid *data); +GLAPI void APIENTRY glMulticastCopyBufferSubDataNV (GLuint readGpu, GLbitfield writeGpuMask, GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +GLAPI void APIENTRY glMulticastCopyImageSubDataNV (GLuint srcGpu, GLbitfield dstGpuMask, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); +GLAPI void APIENTRY glMulticastBlitFramebufferNV (GLuint srcGpu, GLuint dstGpu, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +GLAPI void APIENTRY glMulticastFramebufferSampleLocationsfvNV (GLuint gpu, GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glMulticastBarrierNV (void); +GLAPI void APIENTRY glMulticastWaitSyncNV (GLuint signalGpu, GLbitfield waitGpuMask); +GLAPI void APIENTRY glMulticastGetQueryObjectivNV (GLuint gpu, GLuint id, GLenum pname, GLint *params); +GLAPI void APIENTRY glMulticastGetQueryObjectuivNV (GLuint gpu, GLuint id, GLenum pname, GLuint *params); +GLAPI void APIENTRY glMulticastGetQueryObjecti64vNV (GLuint gpu, GLuint id, GLenum pname, GLint64 *params); +GLAPI void APIENTRY glMulticastGetQueryObjectui64vNV (GLuint gpu, GLuint id, GLenum pname, GLuint64 *params); +#endif +#endif /* GL_NV_gpu_multicast */ + +#ifndef GL_NV_gpu_program4 +#define GL_NV_gpu_program4 1 +#define GL_MIN_PROGRAM_TEXEL_OFFSET_NV 0x8904 +#define GL_MAX_PROGRAM_TEXEL_OFFSET_NV 0x8905 +#define GL_PROGRAM_ATTRIB_COMPONENTS_NV 0x8906 +#define GL_PROGRAM_RESULT_COMPONENTS_NV 0x8907 +#define GL_MAX_PROGRAM_ATTRIB_COMPONENTS_NV 0x8908 +#define GL_MAX_PROGRAM_RESULT_COMPONENTS_NV 0x8909 +#define GL_MAX_PROGRAM_GENERIC_ATTRIBS_NV 0x8DA5 +#define GL_MAX_PROGRAM_GENERIC_RESULTS_NV 0x8DA6 +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4INVPROC) (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4IVNVPROC) (GLenum target, GLuint index, const GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERSI4IVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4UINVPROC) (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4UIVNVPROC) (GLenum target, GLuint index, const GLuint *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERSI4UIVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLuint *params); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4INVPROC) (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4IVNVPROC) (GLenum target, GLuint index, const GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERSI4IVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4UINVPROC) (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4UIVNVPROC) (GLenum target, GLuint index, const GLuint *params); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERSI4UIVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLuint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERIIVNVPROC) (GLenum target, GLuint index, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERIUIVNVPROC) (GLenum target, GLuint index, GLuint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERIIVNVPROC) (GLenum target, GLuint index, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERIUIVNVPROC) (GLenum target, GLuint index, GLuint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramLocalParameterI4iNV (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glProgramLocalParameterI4ivNV (GLenum target, GLuint index, const GLint *params); +GLAPI void APIENTRY glProgramLocalParametersI4ivNV (GLenum target, GLuint index, GLsizei count, const GLint *params); +GLAPI void APIENTRY glProgramLocalParameterI4uiNV (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +GLAPI void APIENTRY glProgramLocalParameterI4uivNV (GLenum target, GLuint index, const GLuint *params); +GLAPI void APIENTRY glProgramLocalParametersI4uivNV (GLenum target, GLuint index, GLsizei count, const GLuint *params); +GLAPI void APIENTRY glProgramEnvParameterI4iNV (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glProgramEnvParameterI4ivNV (GLenum target, GLuint index, const GLint *params); +GLAPI void APIENTRY glProgramEnvParametersI4ivNV (GLenum target, GLuint index, GLsizei count, const GLint *params); +GLAPI void APIENTRY glProgramEnvParameterI4uiNV (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +GLAPI void APIENTRY glProgramEnvParameterI4uivNV (GLenum target, GLuint index, const GLuint *params); +GLAPI void APIENTRY glProgramEnvParametersI4uivNV (GLenum target, GLuint index, GLsizei count, const GLuint *params); +GLAPI void APIENTRY glGetProgramLocalParameterIivNV (GLenum target, GLuint index, GLint *params); +GLAPI void APIENTRY glGetProgramLocalParameterIuivNV (GLenum target, GLuint index, GLuint *params); +GLAPI void APIENTRY glGetProgramEnvParameterIivNV (GLenum target, GLuint index, GLint *params); +GLAPI void APIENTRY glGetProgramEnvParameterIuivNV (GLenum target, GLuint index, GLuint *params); +#endif +#endif /* GL_NV_gpu_program4 */ + +#ifndef GL_NV_gpu_program5 +#define GL_NV_gpu_program5 1 +#define GL_MAX_GEOMETRY_PROGRAM_INVOCATIONS_NV 0x8E5A +#define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET_NV 0x8E5B +#define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET_NV 0x8E5C +#define GL_FRAGMENT_PROGRAM_INTERPOLATION_OFFSET_BITS_NV 0x8E5D +#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_NV 0x8E5E +#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_NV 0x8E5F +#define GL_MAX_PROGRAM_SUBROUTINE_PARAMETERS_NV 0x8F44 +#define GL_MAX_PROGRAM_SUBROUTINE_NUM_NV 0x8F45 +typedef void (APIENTRYP PFNGLPROGRAMSUBROUTINEPARAMETERSUIVNVPROC) (GLenum target, GLsizei count, const GLuint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMSUBROUTINEPARAMETERUIVNVPROC) (GLenum target, GLuint index, GLuint *param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramSubroutineParametersuivNV (GLenum target, GLsizei count, const GLuint *params); +GLAPI void APIENTRY glGetProgramSubroutineParameteruivNV (GLenum target, GLuint index, GLuint *param); +#endif +#endif /* GL_NV_gpu_program5 */ + +#ifndef GL_NV_gpu_program5_mem_extended +#define GL_NV_gpu_program5_mem_extended 1 +#endif /* GL_NV_gpu_program5_mem_extended */ + +#ifndef GL_NV_gpu_shader5 +#define GL_NV_gpu_shader5 1 +#endif /* GL_NV_gpu_shader5 */ + +#ifndef GL_NV_half_float +#define GL_NV_half_float 1 +typedef unsigned short GLhalfNV; +#define GL_HALF_FLOAT_NV 0x140B +typedef void (APIENTRYP PFNGLVERTEX2HNVPROC) (GLhalfNV x, GLhalfNV y); +typedef void (APIENTRYP PFNGLVERTEX2HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEX3HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z); +typedef void (APIENTRYP PFNGLVERTEX3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEX4HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w); +typedef void (APIENTRYP PFNGLVERTEX4HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLNORMAL3HNVPROC) (GLhalfNV nx, GLhalfNV ny, GLhalfNV nz); +typedef void (APIENTRYP PFNGLNORMAL3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue); +typedef void (APIENTRYP PFNGLCOLOR3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLCOLOR4HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue, GLhalfNV alpha); +typedef void (APIENTRYP PFNGLCOLOR4HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLTEXCOORD1HNVPROC) (GLhalfNV s); +typedef void (APIENTRYP PFNGLTEXCOORD1HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLTEXCOORD2HNVPROC) (GLhalfNV s, GLhalfNV t); +typedef void (APIENTRYP PFNGLTEXCOORD2HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLTEXCOORD3HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r); +typedef void (APIENTRYP PFNGLTEXCOORD3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLTEXCOORD4HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q); +typedef void (APIENTRYP PFNGLTEXCOORD4HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1HNVPROC) (GLenum target, GLhalfNV s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1HVNVPROC) (GLenum target, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2HVNVPROC) (GLenum target, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3HVNVPROC) (GLenum target, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4HVNVPROC) (GLenum target, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLFOGCOORDHNVPROC) (GLhalfNV fog); +typedef void (APIENTRYP PFNGLFOGCOORDHVNVPROC) (const GLhalfNV *fog); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXWEIGHTHNVPROC) (GLhalfNV weight); +typedef void (APIENTRYP PFNGLVERTEXWEIGHTHVNVPROC) (const GLhalfNV *weight); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1HNVPROC) (GLuint index, GLhalfNV x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1HVNVPROC) (GLuint index, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2HVNVPROC) (GLuint index, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3HVNVPROC) (GLuint index, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4HVNVPROC) (GLuint index, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS1HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS2HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS3HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertex2hNV (GLhalfNV x, GLhalfNV y); +GLAPI void APIENTRY glVertex2hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glVertex3hNV (GLhalfNV x, GLhalfNV y, GLhalfNV z); +GLAPI void APIENTRY glVertex3hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glVertex4hNV (GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w); +GLAPI void APIENTRY glVertex4hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glNormal3hNV (GLhalfNV nx, GLhalfNV ny, GLhalfNV nz); +GLAPI void APIENTRY glNormal3hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glColor3hNV (GLhalfNV red, GLhalfNV green, GLhalfNV blue); +GLAPI void APIENTRY glColor3hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glColor4hNV (GLhalfNV red, GLhalfNV green, GLhalfNV blue, GLhalfNV alpha); +GLAPI void APIENTRY glColor4hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glTexCoord1hNV (GLhalfNV s); +GLAPI void APIENTRY glTexCoord1hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glTexCoord2hNV (GLhalfNV s, GLhalfNV t); +GLAPI void APIENTRY glTexCoord2hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glTexCoord3hNV (GLhalfNV s, GLhalfNV t, GLhalfNV r); +GLAPI void APIENTRY glTexCoord3hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glTexCoord4hNV (GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q); +GLAPI void APIENTRY glTexCoord4hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glMultiTexCoord1hNV (GLenum target, GLhalfNV s); +GLAPI void APIENTRY glMultiTexCoord1hvNV (GLenum target, const GLhalfNV *v); +GLAPI void APIENTRY glMultiTexCoord2hNV (GLenum target, GLhalfNV s, GLhalfNV t); +GLAPI void APIENTRY glMultiTexCoord2hvNV (GLenum target, const GLhalfNV *v); +GLAPI void APIENTRY glMultiTexCoord3hNV (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r); +GLAPI void APIENTRY glMultiTexCoord3hvNV (GLenum target, const GLhalfNV *v); +GLAPI void APIENTRY glMultiTexCoord4hNV (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q); +GLAPI void APIENTRY glMultiTexCoord4hvNV (GLenum target, const GLhalfNV *v); +GLAPI void APIENTRY glFogCoordhNV (GLhalfNV fog); +GLAPI void APIENTRY glFogCoordhvNV (const GLhalfNV *fog); +GLAPI void APIENTRY glSecondaryColor3hNV (GLhalfNV red, GLhalfNV green, GLhalfNV blue); +GLAPI void APIENTRY glSecondaryColor3hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glVertexWeighthNV (GLhalfNV weight); +GLAPI void APIENTRY glVertexWeighthvNV (const GLhalfNV *weight); +GLAPI void APIENTRY glVertexAttrib1hNV (GLuint index, GLhalfNV x); +GLAPI void APIENTRY glVertexAttrib1hvNV (GLuint index, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttrib2hNV (GLuint index, GLhalfNV x, GLhalfNV y); +GLAPI void APIENTRY glVertexAttrib2hvNV (GLuint index, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttrib3hNV (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z); +GLAPI void APIENTRY glVertexAttrib3hvNV (GLuint index, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttrib4hNV (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w); +GLAPI void APIENTRY glVertexAttrib4hvNV (GLuint index, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttribs1hvNV (GLuint index, GLsizei n, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttribs2hvNV (GLuint index, GLsizei n, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttribs3hvNV (GLuint index, GLsizei n, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttribs4hvNV (GLuint index, GLsizei n, const GLhalfNV *v); +#endif +#endif /* GL_NV_half_float */ + +#ifndef GL_NV_internalformat_sample_query +#define GL_NV_internalformat_sample_query 1 +#define GL_MULTISAMPLES_NV 0x9371 +#define GL_SUPERSAMPLE_SCALE_X_NV 0x9372 +#define GL_SUPERSAMPLE_SCALE_Y_NV 0x9373 +#define GL_CONFORMANT_NV 0x9374 +typedef void (APIENTRYP PFNGLGETINTERNALFORMATSAMPLEIVNVPROC) (GLenum target, GLenum internalformat, GLsizei samples, GLenum pname, GLsizei bufSize, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetInternalformatSampleivNV (GLenum target, GLenum internalformat, GLsizei samples, GLenum pname, GLsizei bufSize, GLint *params); +#endif +#endif /* GL_NV_internalformat_sample_query */ + +#ifndef GL_NV_light_max_exponent +#define GL_NV_light_max_exponent 1 +#define GL_MAX_SHININESS_NV 0x8504 +#define GL_MAX_SPOT_EXPONENT_NV 0x8505 +#endif /* GL_NV_light_max_exponent */ + +#ifndef GL_NV_multisample_coverage +#define GL_NV_multisample_coverage 1 +#endif /* GL_NV_multisample_coverage */ + +#ifndef GL_NV_multisample_filter_hint +#define GL_NV_multisample_filter_hint 1 +#define GL_MULTISAMPLE_FILTER_HINT_NV 0x8534 +#endif /* GL_NV_multisample_filter_hint */ + +#ifndef GL_NV_occlusion_query +#define GL_NV_occlusion_query 1 +#define GL_PIXEL_COUNTER_BITS_NV 0x8864 +#define GL_CURRENT_OCCLUSION_QUERY_ID_NV 0x8865 +#define GL_PIXEL_COUNT_NV 0x8866 +#define GL_PIXEL_COUNT_AVAILABLE_NV 0x8867 +typedef void (APIENTRYP PFNGLGENOCCLUSIONQUERIESNVPROC) (GLsizei n, GLuint *ids); +typedef void (APIENTRYP PFNGLDELETEOCCLUSIONQUERIESNVPROC) (GLsizei n, const GLuint *ids); +typedef GLboolean (APIENTRYP PFNGLISOCCLUSIONQUERYNVPROC) (GLuint id); +typedef void (APIENTRYP PFNGLBEGINOCCLUSIONQUERYNVPROC) (GLuint id); +typedef void (APIENTRYP PFNGLENDOCCLUSIONQUERYNVPROC) (void); +typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYIVNVPROC) (GLuint id, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYUIVNVPROC) (GLuint id, GLenum pname, GLuint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenOcclusionQueriesNV (GLsizei n, GLuint *ids); +GLAPI void APIENTRY glDeleteOcclusionQueriesNV (GLsizei n, const GLuint *ids); +GLAPI GLboolean APIENTRY glIsOcclusionQueryNV (GLuint id); +GLAPI void APIENTRY glBeginOcclusionQueryNV (GLuint id); +GLAPI void APIENTRY glEndOcclusionQueryNV (void); +GLAPI void APIENTRY glGetOcclusionQueryivNV (GLuint id, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetOcclusionQueryuivNV (GLuint id, GLenum pname, GLuint *params); +#endif +#endif /* GL_NV_occlusion_query */ + +#ifndef GL_NV_packed_depth_stencil +#define GL_NV_packed_depth_stencil 1 +#define GL_DEPTH_STENCIL_NV 0x84F9 +#define GL_UNSIGNED_INT_24_8_NV 0x84FA +#endif /* GL_NV_packed_depth_stencil */ + +#ifndef GL_NV_parameter_buffer_object +#define GL_NV_parameter_buffer_object 1 +#define GL_MAX_PROGRAM_PARAMETER_BUFFER_BINDINGS_NV 0x8DA0 +#define GL_MAX_PROGRAM_PARAMETER_BUFFER_SIZE_NV 0x8DA1 +#define GL_VERTEX_PROGRAM_PARAMETER_BUFFER_NV 0x8DA2 +#define GL_GEOMETRY_PROGRAM_PARAMETER_BUFFER_NV 0x8DA3 +#define GL_FRAGMENT_PROGRAM_PARAMETER_BUFFER_NV 0x8DA4 +typedef void (APIENTRYP PFNGLPROGRAMBUFFERPARAMETERSFVNVPROC) (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLfloat *params); +typedef void (APIENTRYP PFNGLPROGRAMBUFFERPARAMETERSIIVNVPROC) (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMBUFFERPARAMETERSIUIVNVPROC) (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLuint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramBufferParametersfvNV (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLfloat *params); +GLAPI void APIENTRY glProgramBufferParametersIivNV (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLint *params); +GLAPI void APIENTRY glProgramBufferParametersIuivNV (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLuint *params); +#endif +#endif /* GL_NV_parameter_buffer_object */ + +#ifndef GL_NV_parameter_buffer_object2 +#define GL_NV_parameter_buffer_object2 1 +#endif /* GL_NV_parameter_buffer_object2 */ + +#ifndef GL_NV_path_rendering +#define GL_NV_path_rendering 1 +#define GL_PATH_FORMAT_SVG_NV 0x9070 +#define GL_PATH_FORMAT_PS_NV 0x9071 +#define GL_STANDARD_FONT_NAME_NV 0x9072 +#define GL_SYSTEM_FONT_NAME_NV 0x9073 +#define GL_FILE_NAME_NV 0x9074 +#define GL_PATH_STROKE_WIDTH_NV 0x9075 +#define GL_PATH_END_CAPS_NV 0x9076 +#define GL_PATH_INITIAL_END_CAP_NV 0x9077 +#define GL_PATH_TERMINAL_END_CAP_NV 0x9078 +#define GL_PATH_JOIN_STYLE_NV 0x9079 +#define GL_PATH_MITER_LIMIT_NV 0x907A +#define GL_PATH_DASH_CAPS_NV 0x907B +#define GL_PATH_INITIAL_DASH_CAP_NV 0x907C +#define GL_PATH_TERMINAL_DASH_CAP_NV 0x907D +#define GL_PATH_DASH_OFFSET_NV 0x907E +#define GL_PATH_CLIENT_LENGTH_NV 0x907F +#define GL_PATH_FILL_MODE_NV 0x9080 +#define GL_PATH_FILL_MASK_NV 0x9081 +#define GL_PATH_FILL_COVER_MODE_NV 0x9082 +#define GL_PATH_STROKE_COVER_MODE_NV 0x9083 +#define GL_PATH_STROKE_MASK_NV 0x9084 +#define GL_COUNT_UP_NV 0x9088 +#define GL_COUNT_DOWN_NV 0x9089 +#define GL_PATH_OBJECT_BOUNDING_BOX_NV 0x908A +#define GL_CONVEX_HULL_NV 0x908B +#define GL_BOUNDING_BOX_NV 0x908D +#define GL_TRANSLATE_X_NV 0x908E +#define GL_TRANSLATE_Y_NV 0x908F +#define GL_TRANSLATE_2D_NV 0x9090 +#define GL_TRANSLATE_3D_NV 0x9091 +#define GL_AFFINE_2D_NV 0x9092 +#define GL_AFFINE_3D_NV 0x9094 +#define GL_TRANSPOSE_AFFINE_2D_NV 0x9096 +#define GL_TRANSPOSE_AFFINE_3D_NV 0x9098 +#define GL_UTF8_NV 0x909A +#define GL_UTF16_NV 0x909B +#define GL_BOUNDING_BOX_OF_BOUNDING_BOXES_NV 0x909C +#define GL_PATH_COMMAND_COUNT_NV 0x909D +#define GL_PATH_COORD_COUNT_NV 0x909E +#define GL_PATH_DASH_ARRAY_COUNT_NV 0x909F +#define GL_PATH_COMPUTED_LENGTH_NV 0x90A0 +#define GL_PATH_FILL_BOUNDING_BOX_NV 0x90A1 +#define GL_PATH_STROKE_BOUNDING_BOX_NV 0x90A2 +#define GL_SQUARE_NV 0x90A3 +#define GL_ROUND_NV 0x90A4 +#define GL_TRIANGULAR_NV 0x90A5 +#define GL_BEVEL_NV 0x90A6 +#define GL_MITER_REVERT_NV 0x90A7 +#define GL_MITER_TRUNCATE_NV 0x90A8 +#define GL_SKIP_MISSING_GLYPH_NV 0x90A9 +#define GL_USE_MISSING_GLYPH_NV 0x90AA +#define GL_PATH_ERROR_POSITION_NV 0x90AB +#define GL_ACCUM_ADJACENT_PAIRS_NV 0x90AD +#define GL_ADJACENT_PAIRS_NV 0x90AE +#define GL_FIRST_TO_REST_NV 0x90AF +#define GL_PATH_GEN_MODE_NV 0x90B0 +#define GL_PATH_GEN_COEFF_NV 0x90B1 +#define GL_PATH_GEN_COMPONENTS_NV 0x90B3 +#define GL_PATH_STENCIL_FUNC_NV 0x90B7 +#define GL_PATH_STENCIL_REF_NV 0x90B8 +#define GL_PATH_STENCIL_VALUE_MASK_NV 0x90B9 +#define GL_PATH_STENCIL_DEPTH_OFFSET_FACTOR_NV 0x90BD +#define GL_PATH_STENCIL_DEPTH_OFFSET_UNITS_NV 0x90BE +#define GL_PATH_COVER_DEPTH_FUNC_NV 0x90BF +#define GL_PATH_DASH_OFFSET_RESET_NV 0x90B4 +#define GL_MOVE_TO_RESETS_NV 0x90B5 +#define GL_MOVE_TO_CONTINUES_NV 0x90B6 +#define GL_CLOSE_PATH_NV 0x00 +#define GL_MOVE_TO_NV 0x02 +#define GL_RELATIVE_MOVE_TO_NV 0x03 +#define GL_LINE_TO_NV 0x04 +#define GL_RELATIVE_LINE_TO_NV 0x05 +#define GL_HORIZONTAL_LINE_TO_NV 0x06 +#define GL_RELATIVE_HORIZONTAL_LINE_TO_NV 0x07 +#define GL_VERTICAL_LINE_TO_NV 0x08 +#define GL_RELATIVE_VERTICAL_LINE_TO_NV 0x09 +#define GL_QUADRATIC_CURVE_TO_NV 0x0A +#define GL_RELATIVE_QUADRATIC_CURVE_TO_NV 0x0B +#define GL_CUBIC_CURVE_TO_NV 0x0C +#define GL_RELATIVE_CUBIC_CURVE_TO_NV 0x0D +#define GL_SMOOTH_QUADRATIC_CURVE_TO_NV 0x0E +#define GL_RELATIVE_SMOOTH_QUADRATIC_CURVE_TO_NV 0x0F +#define GL_SMOOTH_CUBIC_CURVE_TO_NV 0x10 +#define GL_RELATIVE_SMOOTH_CUBIC_CURVE_TO_NV 0x11 +#define GL_SMALL_CCW_ARC_TO_NV 0x12 +#define GL_RELATIVE_SMALL_CCW_ARC_TO_NV 0x13 +#define GL_SMALL_CW_ARC_TO_NV 0x14 +#define GL_RELATIVE_SMALL_CW_ARC_TO_NV 0x15 +#define GL_LARGE_CCW_ARC_TO_NV 0x16 +#define GL_RELATIVE_LARGE_CCW_ARC_TO_NV 0x17 +#define GL_LARGE_CW_ARC_TO_NV 0x18 +#define GL_RELATIVE_LARGE_CW_ARC_TO_NV 0x19 +#define GL_RESTART_PATH_NV 0xF0 +#define GL_DUP_FIRST_CUBIC_CURVE_TO_NV 0xF2 +#define GL_DUP_LAST_CUBIC_CURVE_TO_NV 0xF4 +#define GL_RECT_NV 0xF6 +#define GL_CIRCULAR_CCW_ARC_TO_NV 0xF8 +#define GL_CIRCULAR_CW_ARC_TO_NV 0xFA +#define GL_CIRCULAR_TANGENT_ARC_TO_NV 0xFC +#define GL_ARC_TO_NV 0xFE +#define GL_RELATIVE_ARC_TO_NV 0xFF +#define GL_BOLD_BIT_NV 0x01 +#define GL_ITALIC_BIT_NV 0x02 +#define GL_GLYPH_WIDTH_BIT_NV 0x01 +#define GL_GLYPH_HEIGHT_BIT_NV 0x02 +#define GL_GLYPH_HORIZONTAL_BEARING_X_BIT_NV 0x04 +#define GL_GLYPH_HORIZONTAL_BEARING_Y_BIT_NV 0x08 +#define GL_GLYPH_HORIZONTAL_BEARING_ADVANCE_BIT_NV 0x10 +#define GL_GLYPH_VERTICAL_BEARING_X_BIT_NV 0x20 +#define GL_GLYPH_VERTICAL_BEARING_Y_BIT_NV 0x40 +#define GL_GLYPH_VERTICAL_BEARING_ADVANCE_BIT_NV 0x80 +#define GL_GLYPH_HAS_KERNING_BIT_NV 0x100 +#define GL_FONT_X_MIN_BOUNDS_BIT_NV 0x00010000 +#define GL_FONT_Y_MIN_BOUNDS_BIT_NV 0x00020000 +#define GL_FONT_X_MAX_BOUNDS_BIT_NV 0x00040000 +#define GL_FONT_Y_MAX_BOUNDS_BIT_NV 0x00080000 +#define GL_FONT_UNITS_PER_EM_BIT_NV 0x00100000 +#define GL_FONT_ASCENDER_BIT_NV 0x00200000 +#define GL_FONT_DESCENDER_BIT_NV 0x00400000 +#define GL_FONT_HEIGHT_BIT_NV 0x00800000 +#define GL_FONT_MAX_ADVANCE_WIDTH_BIT_NV 0x01000000 +#define GL_FONT_MAX_ADVANCE_HEIGHT_BIT_NV 0x02000000 +#define GL_FONT_UNDERLINE_POSITION_BIT_NV 0x04000000 +#define GL_FONT_UNDERLINE_THICKNESS_BIT_NV 0x08000000 +#define GL_FONT_HAS_KERNING_BIT_NV 0x10000000 +#define GL_ROUNDED_RECT_NV 0xE8 +#define GL_RELATIVE_ROUNDED_RECT_NV 0xE9 +#define GL_ROUNDED_RECT2_NV 0xEA +#define GL_RELATIVE_ROUNDED_RECT2_NV 0xEB +#define GL_ROUNDED_RECT4_NV 0xEC +#define GL_RELATIVE_ROUNDED_RECT4_NV 0xED +#define GL_ROUNDED_RECT8_NV 0xEE +#define GL_RELATIVE_ROUNDED_RECT8_NV 0xEF +#define GL_RELATIVE_RECT_NV 0xF7 +#define GL_FONT_GLYPHS_AVAILABLE_NV 0x9368 +#define GL_FONT_TARGET_UNAVAILABLE_NV 0x9369 +#define GL_FONT_UNAVAILABLE_NV 0x936A +#define GL_FONT_UNINTELLIGIBLE_NV 0x936B +#define GL_CONIC_CURVE_TO_NV 0x1A +#define GL_RELATIVE_CONIC_CURVE_TO_NV 0x1B +#define GL_FONT_NUM_GLYPH_INDICES_BIT_NV 0x20000000 +#define GL_STANDARD_FONT_FORMAT_NV 0x936C +#define GL_2_BYTES_NV 0x1407 +#define GL_3_BYTES_NV 0x1408 +#define GL_4_BYTES_NV 0x1409 +#define GL_EYE_LINEAR_NV 0x2400 +#define GL_OBJECT_LINEAR_NV 0x2401 +#define GL_CONSTANT_NV 0x8576 +#define GL_PATH_FOG_GEN_MODE_NV 0x90AC +#define GL_PRIMARY_COLOR_NV 0x852C +#define GL_SECONDARY_COLOR_NV 0x852D +#define GL_PATH_GEN_COLOR_FORMAT_NV 0x90B2 +#define GL_PATH_PROJECTION_NV 0x1701 +#define GL_PATH_MODELVIEW_NV 0x1700 +#define GL_PATH_MODELVIEW_STACK_DEPTH_NV 0x0BA3 +#define GL_PATH_MODELVIEW_MATRIX_NV 0x0BA6 +#define GL_PATH_MAX_MODELVIEW_STACK_DEPTH_NV 0x0D36 +#define GL_PATH_TRANSPOSE_MODELVIEW_MATRIX_NV 0x84E3 +#define GL_PATH_PROJECTION_STACK_DEPTH_NV 0x0BA4 +#define GL_PATH_PROJECTION_MATRIX_NV 0x0BA7 +#define GL_PATH_MAX_PROJECTION_STACK_DEPTH_NV 0x0D38 +#define GL_PATH_TRANSPOSE_PROJECTION_MATRIX_NV 0x84E4 +#define GL_FRAGMENT_INPUT_NV 0x936D +typedef GLuint (APIENTRYP PFNGLGENPATHSNVPROC) (GLsizei range); +typedef void (APIENTRYP PFNGLDELETEPATHSNVPROC) (GLuint path, GLsizei range); +typedef GLboolean (APIENTRYP PFNGLISPATHNVPROC) (GLuint path); +typedef void (APIENTRYP PFNGLPATHCOMMANDSNVPROC) (GLuint path, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); +typedef void (APIENTRYP PFNGLPATHCOORDSNVPROC) (GLuint path, GLsizei numCoords, GLenum coordType, const void *coords); +typedef void (APIENTRYP PFNGLPATHSUBCOMMANDSNVPROC) (GLuint path, GLsizei commandStart, GLsizei commandsToDelete, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); +typedef void (APIENTRYP PFNGLPATHSUBCOORDSNVPROC) (GLuint path, GLsizei coordStart, GLsizei numCoords, GLenum coordType, const void *coords); +typedef void (APIENTRYP PFNGLPATHSTRINGNVPROC) (GLuint path, GLenum format, GLsizei length, const void *pathString); +typedef void (APIENTRYP PFNGLPATHGLYPHSNVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLsizei numGlyphs, GLenum type, const void *charcodes, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +typedef void (APIENTRYP PFNGLPATHGLYPHRANGENVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyph, GLsizei numGlyphs, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +typedef void (APIENTRYP PFNGLWEIGHTPATHSNVPROC) (GLuint resultPath, GLsizei numPaths, const GLuint *paths, const GLfloat *weights); +typedef void (APIENTRYP PFNGLCOPYPATHNVPROC) (GLuint resultPath, GLuint srcPath); +typedef void (APIENTRYP PFNGLINTERPOLATEPATHSNVPROC) (GLuint resultPath, GLuint pathA, GLuint pathB, GLfloat weight); +typedef void (APIENTRYP PFNGLTRANSFORMPATHNVPROC) (GLuint resultPath, GLuint srcPath, GLenum transformType, const GLfloat *transformValues); +typedef void (APIENTRYP PFNGLPATHPARAMETERIVNVPROC) (GLuint path, GLenum pname, const GLint *value); +typedef void (APIENTRYP PFNGLPATHPARAMETERINVPROC) (GLuint path, GLenum pname, GLint value); +typedef void (APIENTRYP PFNGLPATHPARAMETERFVNVPROC) (GLuint path, GLenum pname, const GLfloat *value); +typedef void (APIENTRYP PFNGLPATHPARAMETERFNVPROC) (GLuint path, GLenum pname, GLfloat value); +typedef void (APIENTRYP PFNGLPATHDASHARRAYNVPROC) (GLuint path, GLsizei dashCount, const GLfloat *dashArray); +typedef void (APIENTRYP PFNGLPATHSTENCILFUNCNVPROC) (GLenum func, GLint ref, GLuint mask); +typedef void (APIENTRYP PFNGLPATHSTENCILDEPTHOFFSETNVPROC) (GLfloat factor, GLfloat units); +typedef void (APIENTRYP PFNGLSTENCILFILLPATHNVPROC) (GLuint path, GLenum fillMode, GLuint mask); +typedef void (APIENTRYP PFNGLSTENCILSTROKEPATHNVPROC) (GLuint path, GLint reference, GLuint mask); +typedef void (APIENTRYP PFNGLSTENCILFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum transformType, const GLfloat *transformValues); +typedef void (APIENTRYP PFNGLSTENCILSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum transformType, const GLfloat *transformValues); +typedef void (APIENTRYP PFNGLPATHCOVERDEPTHFUNCNVPROC) (GLenum func); +typedef void (APIENTRYP PFNGLCOVERFILLPATHNVPROC) (GLuint path, GLenum coverMode); +typedef void (APIENTRYP PFNGLCOVERSTROKEPATHNVPROC) (GLuint path, GLenum coverMode); +typedef void (APIENTRYP PFNGLCOVERFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +typedef void (APIENTRYP PFNGLCOVERSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +typedef void (APIENTRYP PFNGLGETPATHPARAMETERIVNVPROC) (GLuint path, GLenum pname, GLint *value); +typedef void (APIENTRYP PFNGLGETPATHPARAMETERFVNVPROC) (GLuint path, GLenum pname, GLfloat *value); +typedef void (APIENTRYP PFNGLGETPATHCOMMANDSNVPROC) (GLuint path, GLubyte *commands); +typedef void (APIENTRYP PFNGLGETPATHCOORDSNVPROC) (GLuint path, GLfloat *coords); +typedef void (APIENTRYP PFNGLGETPATHDASHARRAYNVPROC) (GLuint path, GLfloat *dashArray); +typedef void (APIENTRYP PFNGLGETPATHMETRICSNVPROC) (GLbitfield metricQueryMask, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLsizei stride, GLfloat *metrics); +typedef void (APIENTRYP PFNGLGETPATHMETRICRANGENVPROC) (GLbitfield metricQueryMask, GLuint firstPathName, GLsizei numPaths, GLsizei stride, GLfloat *metrics); +typedef void (APIENTRYP PFNGLGETPATHSPACINGNVPROC) (GLenum pathListMode, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLfloat advanceScale, GLfloat kerningScale, GLenum transformType, GLfloat *returnedSpacing); +typedef GLboolean (APIENTRYP PFNGLISPOINTINFILLPATHNVPROC) (GLuint path, GLuint mask, GLfloat x, GLfloat y); +typedef GLboolean (APIENTRYP PFNGLISPOINTINSTROKEPATHNVPROC) (GLuint path, GLfloat x, GLfloat y); +typedef GLfloat (APIENTRYP PFNGLGETPATHLENGTHNVPROC) (GLuint path, GLsizei startSegment, GLsizei numSegments); +typedef GLboolean (APIENTRYP PFNGLPOINTALONGPATHNVPROC) (GLuint path, GLsizei startSegment, GLsizei numSegments, GLfloat distance, GLfloat *x, GLfloat *y, GLfloat *tangentX, GLfloat *tangentY); +typedef void (APIENTRYP PFNGLMATRIXLOAD3X2FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXLOAD3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXLOADTRANSPOSE3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXMULT3X2FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXMULT3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXMULTTRANSPOSE3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (APIENTRYP PFNGLSTENCILTHENCOVERFILLPATHNVPROC) (GLuint path, GLenum fillMode, GLuint mask, GLenum coverMode); +typedef void (APIENTRYP PFNGLSTENCILTHENCOVERSTROKEPATHNVPROC) (GLuint path, GLint reference, GLuint mask, GLenum coverMode); +typedef void (APIENTRYP PFNGLSTENCILTHENCOVERFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +typedef void (APIENTRYP PFNGLSTENCILTHENCOVERSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +typedef GLenum (APIENTRYP PFNGLPATHGLYPHINDEXRANGENVPROC) (GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint pathParameterTemplate, GLfloat emScale, GLuint baseAndCount[2]); +typedef GLenum (APIENTRYP PFNGLPATHGLYPHINDEXARRAYNVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +typedef GLenum (APIENTRYP PFNGLPATHMEMORYGLYPHINDEXARRAYNVPROC) (GLuint firstPathName, GLenum fontTarget, GLsizeiptr fontSize, const void *fontData, GLsizei faceIndex, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +typedef void (APIENTRYP PFNGLPROGRAMPATHFRAGMENTINPUTGENNVPROC) (GLuint program, GLint location, GLenum genMode, GLint components, const GLfloat *coeffs); +typedef void (APIENTRYP PFNGLGETPROGRAMRESOURCEFVNVPROC) (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLfloat *params); +typedef void (APIENTRYP PFNGLPATHCOLORGENNVPROC) (GLenum color, GLenum genMode, GLenum colorFormat, const GLfloat *coeffs); +typedef void (APIENTRYP PFNGLPATHTEXGENNVPROC) (GLenum texCoordSet, GLenum genMode, GLint components, const GLfloat *coeffs); +typedef void (APIENTRYP PFNGLPATHFOGGENNVPROC) (GLenum genMode); +typedef void (APIENTRYP PFNGLGETPATHCOLORGENIVNVPROC) (GLenum color, GLenum pname, GLint *value); +typedef void (APIENTRYP PFNGLGETPATHCOLORGENFVNVPROC) (GLenum color, GLenum pname, GLfloat *value); +typedef void (APIENTRYP PFNGLGETPATHTEXGENIVNVPROC) (GLenum texCoordSet, GLenum pname, GLint *value); +typedef void (APIENTRYP PFNGLGETPATHTEXGENFVNVPROC) (GLenum texCoordSet, GLenum pname, GLfloat *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLuint APIENTRY glGenPathsNV (GLsizei range); +GLAPI void APIENTRY glDeletePathsNV (GLuint path, GLsizei range); +GLAPI GLboolean APIENTRY glIsPathNV (GLuint path); +GLAPI void APIENTRY glPathCommandsNV (GLuint path, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); +GLAPI void APIENTRY glPathCoordsNV (GLuint path, GLsizei numCoords, GLenum coordType, const void *coords); +GLAPI void APIENTRY glPathSubCommandsNV (GLuint path, GLsizei commandStart, GLsizei commandsToDelete, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); +GLAPI void APIENTRY glPathSubCoordsNV (GLuint path, GLsizei coordStart, GLsizei numCoords, GLenum coordType, const void *coords); +GLAPI void APIENTRY glPathStringNV (GLuint path, GLenum format, GLsizei length, const void *pathString); +GLAPI void APIENTRY glPathGlyphsNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLsizei numGlyphs, GLenum type, const void *charcodes, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +GLAPI void APIENTRY glPathGlyphRangeNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyph, GLsizei numGlyphs, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +GLAPI void APIENTRY glWeightPathsNV (GLuint resultPath, GLsizei numPaths, const GLuint *paths, const GLfloat *weights); +GLAPI void APIENTRY glCopyPathNV (GLuint resultPath, GLuint srcPath); +GLAPI void APIENTRY glInterpolatePathsNV (GLuint resultPath, GLuint pathA, GLuint pathB, GLfloat weight); +GLAPI void APIENTRY glTransformPathNV (GLuint resultPath, GLuint srcPath, GLenum transformType, const GLfloat *transformValues); +GLAPI void APIENTRY glPathParameterivNV (GLuint path, GLenum pname, const GLint *value); +GLAPI void APIENTRY glPathParameteriNV (GLuint path, GLenum pname, GLint value); +GLAPI void APIENTRY glPathParameterfvNV (GLuint path, GLenum pname, const GLfloat *value); +GLAPI void APIENTRY glPathParameterfNV (GLuint path, GLenum pname, GLfloat value); +GLAPI void APIENTRY glPathDashArrayNV (GLuint path, GLsizei dashCount, const GLfloat *dashArray); +GLAPI void APIENTRY glPathStencilFuncNV (GLenum func, GLint ref, GLuint mask); +GLAPI void APIENTRY glPathStencilDepthOffsetNV (GLfloat factor, GLfloat units); +GLAPI void APIENTRY glStencilFillPathNV (GLuint path, GLenum fillMode, GLuint mask); +GLAPI void APIENTRY glStencilStrokePathNV (GLuint path, GLint reference, GLuint mask); +GLAPI void APIENTRY glStencilFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum transformType, const GLfloat *transformValues); +GLAPI void APIENTRY glStencilStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum transformType, const GLfloat *transformValues); +GLAPI void APIENTRY glPathCoverDepthFuncNV (GLenum func); +GLAPI void APIENTRY glCoverFillPathNV (GLuint path, GLenum coverMode); +GLAPI void APIENTRY glCoverStrokePathNV (GLuint path, GLenum coverMode); +GLAPI void APIENTRY glCoverFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +GLAPI void APIENTRY glCoverStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +GLAPI void APIENTRY glGetPathParameterivNV (GLuint path, GLenum pname, GLint *value); +GLAPI void APIENTRY glGetPathParameterfvNV (GLuint path, GLenum pname, GLfloat *value); +GLAPI void APIENTRY glGetPathCommandsNV (GLuint path, GLubyte *commands); +GLAPI void APIENTRY glGetPathCoordsNV (GLuint path, GLfloat *coords); +GLAPI void APIENTRY glGetPathDashArrayNV (GLuint path, GLfloat *dashArray); +GLAPI void APIENTRY glGetPathMetricsNV (GLbitfield metricQueryMask, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLsizei stride, GLfloat *metrics); +GLAPI void APIENTRY glGetPathMetricRangeNV (GLbitfield metricQueryMask, GLuint firstPathName, GLsizei numPaths, GLsizei stride, GLfloat *metrics); +GLAPI void APIENTRY glGetPathSpacingNV (GLenum pathListMode, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLfloat advanceScale, GLfloat kerningScale, GLenum transformType, GLfloat *returnedSpacing); +GLAPI GLboolean APIENTRY glIsPointInFillPathNV (GLuint path, GLuint mask, GLfloat x, GLfloat y); +GLAPI GLboolean APIENTRY glIsPointInStrokePathNV (GLuint path, GLfloat x, GLfloat y); +GLAPI GLfloat APIENTRY glGetPathLengthNV (GLuint path, GLsizei startSegment, GLsizei numSegments); +GLAPI GLboolean APIENTRY glPointAlongPathNV (GLuint path, GLsizei startSegment, GLsizei numSegments, GLfloat distance, GLfloat *x, GLfloat *y, GLfloat *tangentX, GLfloat *tangentY); +GLAPI void APIENTRY glMatrixLoad3x2fNV (GLenum matrixMode, const GLfloat *m); +GLAPI void APIENTRY glMatrixLoad3x3fNV (GLenum matrixMode, const GLfloat *m); +GLAPI void APIENTRY glMatrixLoadTranspose3x3fNV (GLenum matrixMode, const GLfloat *m); +GLAPI void APIENTRY glMatrixMult3x2fNV (GLenum matrixMode, const GLfloat *m); +GLAPI void APIENTRY glMatrixMult3x3fNV (GLenum matrixMode, const GLfloat *m); +GLAPI void APIENTRY glMatrixMultTranspose3x3fNV (GLenum matrixMode, const GLfloat *m); +GLAPI void APIENTRY glStencilThenCoverFillPathNV (GLuint path, GLenum fillMode, GLuint mask, GLenum coverMode); +GLAPI void APIENTRY glStencilThenCoverStrokePathNV (GLuint path, GLint reference, GLuint mask, GLenum coverMode); +GLAPI void APIENTRY glStencilThenCoverFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +GLAPI void APIENTRY glStencilThenCoverStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +GLAPI GLenum APIENTRY glPathGlyphIndexRangeNV (GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint pathParameterTemplate, GLfloat emScale, GLuint baseAndCount[2]); +GLAPI GLenum APIENTRY glPathGlyphIndexArrayNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +GLAPI GLenum APIENTRY glPathMemoryGlyphIndexArrayNV (GLuint firstPathName, GLenum fontTarget, GLsizeiptr fontSize, const void *fontData, GLsizei faceIndex, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +GLAPI void APIENTRY glProgramPathFragmentInputGenNV (GLuint program, GLint location, GLenum genMode, GLint components, const GLfloat *coeffs); +GLAPI void APIENTRY glGetProgramResourcefvNV (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLfloat *params); +GLAPI void APIENTRY glPathColorGenNV (GLenum color, GLenum genMode, GLenum colorFormat, const GLfloat *coeffs); +GLAPI void APIENTRY glPathTexGenNV (GLenum texCoordSet, GLenum genMode, GLint components, const GLfloat *coeffs); +GLAPI void APIENTRY glPathFogGenNV (GLenum genMode); +GLAPI void APIENTRY glGetPathColorGenivNV (GLenum color, GLenum pname, GLint *value); +GLAPI void APIENTRY glGetPathColorGenfvNV (GLenum color, GLenum pname, GLfloat *value); +GLAPI void APIENTRY glGetPathTexGenivNV (GLenum texCoordSet, GLenum pname, GLint *value); +GLAPI void APIENTRY glGetPathTexGenfvNV (GLenum texCoordSet, GLenum pname, GLfloat *value); +#endif +#endif /* GL_NV_path_rendering */ + +#ifndef GL_NV_path_rendering_shared_edge +#define GL_NV_path_rendering_shared_edge 1 +#define GL_SHARED_EDGE_NV 0xC0 +#endif /* GL_NV_path_rendering_shared_edge */ + +#ifndef GL_NV_pixel_data_range +#define GL_NV_pixel_data_range 1 +#define GL_WRITE_PIXEL_DATA_RANGE_NV 0x8878 +#define GL_READ_PIXEL_DATA_RANGE_NV 0x8879 +#define GL_WRITE_PIXEL_DATA_RANGE_LENGTH_NV 0x887A +#define GL_READ_PIXEL_DATA_RANGE_LENGTH_NV 0x887B +#define GL_WRITE_PIXEL_DATA_RANGE_POINTER_NV 0x887C +#define GL_READ_PIXEL_DATA_RANGE_POINTER_NV 0x887D +typedef void (APIENTRYP PFNGLPIXELDATARANGENVPROC) (GLenum target, GLsizei length, const void *pointer); +typedef void (APIENTRYP PFNGLFLUSHPIXELDATARANGENVPROC) (GLenum target); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPixelDataRangeNV (GLenum target, GLsizei length, const void *pointer); +GLAPI void APIENTRY glFlushPixelDataRangeNV (GLenum target); +#endif +#endif /* GL_NV_pixel_data_range */ + +#ifndef GL_NV_point_sprite +#define GL_NV_point_sprite 1 +#define GL_POINT_SPRITE_NV 0x8861 +#define GL_COORD_REPLACE_NV 0x8862 +#define GL_POINT_SPRITE_R_MODE_NV 0x8863 +typedef void (APIENTRYP PFNGLPOINTPARAMETERINVPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERIVNVPROC) (GLenum pname, const GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPointParameteriNV (GLenum pname, GLint param); +GLAPI void APIENTRY glPointParameterivNV (GLenum pname, const GLint *params); +#endif +#endif /* GL_NV_point_sprite */ + +#ifndef GL_NV_present_video +#define GL_NV_present_video 1 +#define GL_FRAME_NV 0x8E26 +#define GL_FIELDS_NV 0x8E27 +#define GL_CURRENT_TIME_NV 0x8E28 +#define GL_NUM_FILL_STREAMS_NV 0x8E29 +#define GL_PRESENT_TIME_NV 0x8E2A +#define GL_PRESENT_DURATION_NV 0x8E2B +typedef void (APIENTRYP PFNGLPRESENTFRAMEKEYEDNVPROC) (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLuint key0, GLenum target1, GLuint fill1, GLuint key1); +typedef void (APIENTRYP PFNGLPRESENTFRAMEDUALFILLNVPROC) (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLenum target1, GLuint fill1, GLenum target2, GLuint fill2, GLenum target3, GLuint fill3); +typedef void (APIENTRYP PFNGLGETVIDEOIVNVPROC) (GLuint video_slot, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVIDEOUIVNVPROC) (GLuint video_slot, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLGETVIDEOI64VNVPROC) (GLuint video_slot, GLenum pname, GLint64EXT *params); +typedef void (APIENTRYP PFNGLGETVIDEOUI64VNVPROC) (GLuint video_slot, GLenum pname, GLuint64EXT *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPresentFrameKeyedNV (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLuint key0, GLenum target1, GLuint fill1, GLuint key1); +GLAPI void APIENTRY glPresentFrameDualFillNV (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLenum target1, GLuint fill1, GLenum target2, GLuint fill2, GLenum target3, GLuint fill3); +GLAPI void APIENTRY glGetVideoivNV (GLuint video_slot, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVideouivNV (GLuint video_slot, GLenum pname, GLuint *params); +GLAPI void APIENTRY glGetVideoi64vNV (GLuint video_slot, GLenum pname, GLint64EXT *params); +GLAPI void APIENTRY glGetVideoui64vNV (GLuint video_slot, GLenum pname, GLuint64EXT *params); +#endif +#endif /* GL_NV_present_video */ + +#ifndef GL_NV_primitive_restart +#define GL_NV_primitive_restart 1 +#define GL_PRIMITIVE_RESTART_NV 0x8558 +#define GL_PRIMITIVE_RESTART_INDEX_NV 0x8559 +typedef void (APIENTRYP PFNGLPRIMITIVERESTARTNVPROC) (void); +typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXNVPROC) (GLuint index); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPrimitiveRestartNV (void); +GLAPI void APIENTRY glPrimitiveRestartIndexNV (GLuint index); +#endif +#endif /* GL_NV_primitive_restart */ + +#ifndef GL_NV_register_combiners +#define GL_NV_register_combiners 1 +#define GL_REGISTER_COMBINERS_NV 0x8522 +#define GL_VARIABLE_A_NV 0x8523 +#define GL_VARIABLE_B_NV 0x8524 +#define GL_VARIABLE_C_NV 0x8525 +#define GL_VARIABLE_D_NV 0x8526 +#define GL_VARIABLE_E_NV 0x8527 +#define GL_VARIABLE_F_NV 0x8528 +#define GL_VARIABLE_G_NV 0x8529 +#define GL_CONSTANT_COLOR0_NV 0x852A +#define GL_CONSTANT_COLOR1_NV 0x852B +#define GL_SPARE0_NV 0x852E +#define GL_SPARE1_NV 0x852F +#define GL_DISCARD_NV 0x8530 +#define GL_E_TIMES_F_NV 0x8531 +#define GL_SPARE0_PLUS_SECONDARY_COLOR_NV 0x8532 +#define GL_UNSIGNED_IDENTITY_NV 0x8536 +#define GL_UNSIGNED_INVERT_NV 0x8537 +#define GL_EXPAND_NORMAL_NV 0x8538 +#define GL_EXPAND_NEGATE_NV 0x8539 +#define GL_HALF_BIAS_NORMAL_NV 0x853A +#define GL_HALF_BIAS_NEGATE_NV 0x853B +#define GL_SIGNED_IDENTITY_NV 0x853C +#define GL_SIGNED_NEGATE_NV 0x853D +#define GL_SCALE_BY_TWO_NV 0x853E +#define GL_SCALE_BY_FOUR_NV 0x853F +#define GL_SCALE_BY_ONE_HALF_NV 0x8540 +#define GL_BIAS_BY_NEGATIVE_ONE_HALF_NV 0x8541 +#define GL_COMBINER_INPUT_NV 0x8542 +#define GL_COMBINER_MAPPING_NV 0x8543 +#define GL_COMBINER_COMPONENT_USAGE_NV 0x8544 +#define GL_COMBINER_AB_DOT_PRODUCT_NV 0x8545 +#define GL_COMBINER_CD_DOT_PRODUCT_NV 0x8546 +#define GL_COMBINER_MUX_SUM_NV 0x8547 +#define GL_COMBINER_SCALE_NV 0x8548 +#define GL_COMBINER_BIAS_NV 0x8549 +#define GL_COMBINER_AB_OUTPUT_NV 0x854A +#define GL_COMBINER_CD_OUTPUT_NV 0x854B +#define GL_COMBINER_SUM_OUTPUT_NV 0x854C +#define GL_MAX_GENERAL_COMBINERS_NV 0x854D +#define GL_NUM_GENERAL_COMBINERS_NV 0x854E +#define GL_COLOR_SUM_CLAMP_NV 0x854F +#define GL_COMBINER0_NV 0x8550 +#define GL_COMBINER1_NV 0x8551 +#define GL_COMBINER2_NV 0x8552 +#define GL_COMBINER3_NV 0x8553 +#define GL_COMBINER4_NV 0x8554 +#define GL_COMBINER5_NV 0x8555 +#define GL_COMBINER6_NV 0x8556 +#define GL_COMBINER7_NV 0x8557 +typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFVNVPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFNVPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLCOMBINERPARAMETERIVNVPROC) (GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOMBINERPARAMETERINVPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLCOMBINERINPUTNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage); +typedef void (APIENTRYP PFNGLCOMBINEROUTPUTNVPROC) (GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum); +typedef void (APIENTRYP PFNGLFINALCOMBINERINPUTNVPROC) (GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage); +typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC) (GLenum variable, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC) (GLenum variable, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCombinerParameterfvNV (GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glCombinerParameterfNV (GLenum pname, GLfloat param); +GLAPI void APIENTRY glCombinerParameterivNV (GLenum pname, const GLint *params); +GLAPI void APIENTRY glCombinerParameteriNV (GLenum pname, GLint param); +GLAPI void APIENTRY glCombinerInputNV (GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage); +GLAPI void APIENTRY glCombinerOutputNV (GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum); +GLAPI void APIENTRY glFinalCombinerInputNV (GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage); +GLAPI void APIENTRY glGetCombinerInputParameterfvNV (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetCombinerInputParameterivNV (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetCombinerOutputParameterfvNV (GLenum stage, GLenum portion, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetCombinerOutputParameterivNV (GLenum stage, GLenum portion, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetFinalCombinerInputParameterfvNV (GLenum variable, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetFinalCombinerInputParameterivNV (GLenum variable, GLenum pname, GLint *params); +#endif +#endif /* GL_NV_register_combiners */ + +#ifndef GL_NV_register_combiners2 +#define GL_NV_register_combiners2 1 +#define GL_PER_STAGE_CONSTANTS_NV 0x8535 +typedef void (APIENTRYP PFNGLCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCombinerStageParameterfvNV (GLenum stage, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glGetCombinerStageParameterfvNV (GLenum stage, GLenum pname, GLfloat *params); +#endif +#endif /* GL_NV_register_combiners2 */ + +#ifndef GL_NV_robustness_video_memory_purge +#define GL_NV_robustness_video_memory_purge 1 +#define GL_PURGED_CONTEXT_RESET_NV 0x92BB +#endif /* GL_NV_robustness_video_memory_purge */ + +#ifndef GL_NV_sample_locations +#define GL_NV_sample_locations 1 +#define GL_SAMPLE_LOCATION_SUBPIXEL_BITS_NV 0x933D +#define GL_SAMPLE_LOCATION_PIXEL_GRID_WIDTH_NV 0x933E +#define GL_SAMPLE_LOCATION_PIXEL_GRID_HEIGHT_NV 0x933F +#define GL_PROGRAMMABLE_SAMPLE_LOCATION_TABLE_SIZE_NV 0x9340 +#define GL_SAMPLE_LOCATION_NV 0x8E50 +#define GL_PROGRAMMABLE_SAMPLE_LOCATION_NV 0x9341 +#define GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_NV 0x9342 +#define GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_NV 0x9343 +typedef void (APIENTRYP PFNGLFRAMEBUFFERSAMPLELOCATIONSFVNVPROC) (GLenum target, GLuint start, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVNVPROC) (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLRESOLVEDEPTHVALUESNVPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFramebufferSampleLocationsfvNV (GLenum target, GLuint start, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glNamedFramebufferSampleLocationsfvNV (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glResolveDepthValuesNV (void); +#endif +#endif /* GL_NV_sample_locations */ + +#ifndef GL_NV_sample_mask_override_coverage +#define GL_NV_sample_mask_override_coverage 1 +#endif /* GL_NV_sample_mask_override_coverage */ + +#ifndef GL_NV_shader_atomic_counters +#define GL_NV_shader_atomic_counters 1 +#endif /* GL_NV_shader_atomic_counters */ + +#ifndef GL_NV_shader_atomic_float +#define GL_NV_shader_atomic_float 1 +#endif /* GL_NV_shader_atomic_float */ + +#ifndef GL_NV_shader_atomic_float64 +#define GL_NV_shader_atomic_float64 1 +#endif /* GL_NV_shader_atomic_float64 */ + +#ifndef GL_NV_shader_atomic_fp16_vector +#define GL_NV_shader_atomic_fp16_vector 1 +#endif /* GL_NV_shader_atomic_fp16_vector */ + +#ifndef GL_NV_shader_atomic_int64 +#define GL_NV_shader_atomic_int64 1 +#endif /* GL_NV_shader_atomic_int64 */ + +#ifndef GL_NV_shader_buffer_load +#define GL_NV_shader_buffer_load 1 +#define GL_BUFFER_GPU_ADDRESS_NV 0x8F1D +#define GL_GPU_ADDRESS_NV 0x8F34 +#define GL_MAX_SHADER_BUFFER_ADDRESS_NV 0x8F35 +typedef void (APIENTRYP PFNGLMAKEBUFFERRESIDENTNVPROC) (GLenum target, GLenum access); +typedef void (APIENTRYP PFNGLMAKEBUFFERNONRESIDENTNVPROC) (GLenum target); +typedef GLboolean (APIENTRYP PFNGLISBUFFERRESIDENTNVPROC) (GLenum target); +typedef void (APIENTRYP PFNGLMAKENAMEDBUFFERRESIDENTNVPROC) (GLuint buffer, GLenum access); +typedef void (APIENTRYP PFNGLMAKENAMEDBUFFERNONRESIDENTNVPROC) (GLuint buffer); +typedef GLboolean (APIENTRYP PFNGLISNAMEDBUFFERRESIDENTNVPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERUI64VNVPROC) (GLenum target, GLenum pname, GLuint64EXT *params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERUI64VNVPROC) (GLuint buffer, GLenum pname, GLuint64EXT *params); +typedef void (APIENTRYP PFNGLGETINTEGERUI64VNVPROC) (GLenum value, GLuint64EXT *result); +typedef void (APIENTRYP PFNGLUNIFORMUI64NVPROC) (GLint location, GLuint64EXT value); +typedef void (APIENTRYP PFNGLUNIFORMUI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMUI64NVPROC) (GLuint program, GLint location, GLuint64EXT value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMUI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMakeBufferResidentNV (GLenum target, GLenum access); +GLAPI void APIENTRY glMakeBufferNonResidentNV (GLenum target); +GLAPI GLboolean APIENTRY glIsBufferResidentNV (GLenum target); +GLAPI void APIENTRY glMakeNamedBufferResidentNV (GLuint buffer, GLenum access); +GLAPI void APIENTRY glMakeNamedBufferNonResidentNV (GLuint buffer); +GLAPI GLboolean APIENTRY glIsNamedBufferResidentNV (GLuint buffer); +GLAPI void APIENTRY glGetBufferParameterui64vNV (GLenum target, GLenum pname, GLuint64EXT *params); +GLAPI void APIENTRY glGetNamedBufferParameterui64vNV (GLuint buffer, GLenum pname, GLuint64EXT *params); +GLAPI void APIENTRY glGetIntegerui64vNV (GLenum value, GLuint64EXT *result); +GLAPI void APIENTRY glUniformui64NV (GLint location, GLuint64EXT value); +GLAPI void APIENTRY glUniformui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glProgramUniformui64NV (GLuint program, GLint location, GLuint64EXT value); +GLAPI void APIENTRY glProgramUniformui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +#endif +#endif /* GL_NV_shader_buffer_load */ + +#ifndef GL_NV_shader_buffer_store +#define GL_NV_shader_buffer_store 1 +#define GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV 0x00000010 +#endif /* GL_NV_shader_buffer_store */ + +#ifndef GL_NV_shader_storage_buffer_object +#define GL_NV_shader_storage_buffer_object 1 +#endif /* GL_NV_shader_storage_buffer_object */ + +#ifndef GL_NV_shader_thread_group +#define GL_NV_shader_thread_group 1 +#define GL_WARP_SIZE_NV 0x9339 +#define GL_WARPS_PER_SM_NV 0x933A +#define GL_SM_COUNT_NV 0x933B +#endif /* GL_NV_shader_thread_group */ + +#ifndef GL_NV_shader_thread_shuffle +#define GL_NV_shader_thread_shuffle 1 +#endif /* GL_NV_shader_thread_shuffle */ + +#ifndef GL_NV_stereo_view_rendering +#define GL_NV_stereo_view_rendering 1 +#endif /* GL_NV_stereo_view_rendering */ + +#ifndef GL_NV_tessellation_program5 +#define GL_NV_tessellation_program5 1 +#define GL_MAX_PROGRAM_PATCH_ATTRIBS_NV 0x86D8 +#define GL_TESS_CONTROL_PROGRAM_NV 0x891E +#define GL_TESS_EVALUATION_PROGRAM_NV 0x891F +#define GL_TESS_CONTROL_PROGRAM_PARAMETER_BUFFER_NV 0x8C74 +#define GL_TESS_EVALUATION_PROGRAM_PARAMETER_BUFFER_NV 0x8C75 +#endif /* GL_NV_tessellation_program5 */ + +#ifndef GL_NV_texgen_emboss +#define GL_NV_texgen_emboss 1 +#define GL_EMBOSS_LIGHT_NV 0x855D +#define GL_EMBOSS_CONSTANT_NV 0x855E +#define GL_EMBOSS_MAP_NV 0x855F +#endif /* GL_NV_texgen_emboss */ + +#ifndef GL_NV_texgen_reflection +#define GL_NV_texgen_reflection 1 +#define GL_NORMAL_MAP_NV 0x8511 +#define GL_REFLECTION_MAP_NV 0x8512 +#endif /* GL_NV_texgen_reflection */ + +#ifndef GL_NV_texture_barrier +#define GL_NV_texture_barrier 1 +typedef void (APIENTRYP PFNGLTEXTUREBARRIERNVPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTextureBarrierNV (void); +#endif +#endif /* GL_NV_texture_barrier */ + +#ifndef GL_NV_texture_compression_vtc +#define GL_NV_texture_compression_vtc 1 +#endif /* GL_NV_texture_compression_vtc */ + +#ifndef GL_NV_texture_env_combine4 +#define GL_NV_texture_env_combine4 1 +#define GL_COMBINE4_NV 0x8503 +#define GL_SOURCE3_RGB_NV 0x8583 +#define GL_SOURCE3_ALPHA_NV 0x858B +#define GL_OPERAND3_RGB_NV 0x8593 +#define GL_OPERAND3_ALPHA_NV 0x859B +#endif /* GL_NV_texture_env_combine4 */ + +#ifndef GL_NV_texture_expand_normal +#define GL_NV_texture_expand_normal 1 +#define GL_TEXTURE_UNSIGNED_REMAP_MODE_NV 0x888F +#endif /* GL_NV_texture_expand_normal */ + +#ifndef GL_NV_texture_multisample +#define GL_NV_texture_multisample 1 +#define GL_TEXTURE_COVERAGE_SAMPLES_NV 0x9045 +#define GL_TEXTURE_COLOR_SAMPLES_NV 0x9046 +typedef void (APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLECOVERAGENVPROC) (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations); +typedef void (APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLECOVERAGENVPROC) (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE2DMULTISAMPLENVPROC) (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE3DMULTISAMPLENVPROC) (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE2DMULTISAMPLECOVERAGENVPROC) (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE3DMULTISAMPLECOVERAGENVPROC) (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexImage2DMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations); +GLAPI void APIENTRY glTexImage3DMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations); +GLAPI void APIENTRY glTextureImage2DMultisampleNV (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations); +GLAPI void APIENTRY glTextureImage3DMultisampleNV (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations); +GLAPI void APIENTRY glTextureImage2DMultisampleCoverageNV (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations); +GLAPI void APIENTRY glTextureImage3DMultisampleCoverageNV (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations); +#endif +#endif /* GL_NV_texture_multisample */ + +#ifndef GL_NV_texture_rectangle +#define GL_NV_texture_rectangle 1 +#define GL_TEXTURE_RECTANGLE_NV 0x84F5 +#define GL_TEXTURE_BINDING_RECTANGLE_NV 0x84F6 +#define GL_PROXY_TEXTURE_RECTANGLE_NV 0x84F7 +#define GL_MAX_RECTANGLE_TEXTURE_SIZE_NV 0x84F8 +#endif /* GL_NV_texture_rectangle */ + +#ifndef GL_NV_texture_shader +#define GL_NV_texture_shader 1 +#define GL_OFFSET_TEXTURE_RECTANGLE_NV 0x864C +#define GL_OFFSET_TEXTURE_RECTANGLE_SCALE_NV 0x864D +#define GL_DOT_PRODUCT_TEXTURE_RECTANGLE_NV 0x864E +#define GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV 0x86D9 +#define GL_UNSIGNED_INT_S8_S8_8_8_NV 0x86DA +#define GL_UNSIGNED_INT_8_8_S8_S8_REV_NV 0x86DB +#define GL_DSDT_MAG_INTENSITY_NV 0x86DC +#define GL_SHADER_CONSISTENT_NV 0x86DD +#define GL_TEXTURE_SHADER_NV 0x86DE +#define GL_SHADER_OPERATION_NV 0x86DF +#define GL_CULL_MODES_NV 0x86E0 +#define GL_OFFSET_TEXTURE_MATRIX_NV 0x86E1 +#define GL_OFFSET_TEXTURE_SCALE_NV 0x86E2 +#define GL_OFFSET_TEXTURE_BIAS_NV 0x86E3 +#define GL_OFFSET_TEXTURE_2D_MATRIX_NV 0x86E1 +#define GL_OFFSET_TEXTURE_2D_SCALE_NV 0x86E2 +#define GL_OFFSET_TEXTURE_2D_BIAS_NV 0x86E3 +#define GL_PREVIOUS_TEXTURE_INPUT_NV 0x86E4 +#define GL_CONST_EYE_NV 0x86E5 +#define GL_PASS_THROUGH_NV 0x86E6 +#define GL_CULL_FRAGMENT_NV 0x86E7 +#define GL_OFFSET_TEXTURE_2D_NV 0x86E8 +#define GL_DEPENDENT_AR_TEXTURE_2D_NV 0x86E9 +#define GL_DEPENDENT_GB_TEXTURE_2D_NV 0x86EA +#define GL_DOT_PRODUCT_NV 0x86EC +#define GL_DOT_PRODUCT_DEPTH_REPLACE_NV 0x86ED +#define GL_DOT_PRODUCT_TEXTURE_2D_NV 0x86EE +#define GL_DOT_PRODUCT_TEXTURE_CUBE_MAP_NV 0x86F0 +#define GL_DOT_PRODUCT_DIFFUSE_CUBE_MAP_NV 0x86F1 +#define GL_DOT_PRODUCT_REFLECT_CUBE_MAP_NV 0x86F2 +#define GL_DOT_PRODUCT_CONST_EYE_REFLECT_CUBE_MAP_NV 0x86F3 +#define GL_HILO_NV 0x86F4 +#define GL_DSDT_NV 0x86F5 +#define GL_DSDT_MAG_NV 0x86F6 +#define GL_DSDT_MAG_VIB_NV 0x86F7 +#define GL_HILO16_NV 0x86F8 +#define GL_SIGNED_HILO_NV 0x86F9 +#define GL_SIGNED_HILO16_NV 0x86FA +#define GL_SIGNED_RGBA_NV 0x86FB +#define GL_SIGNED_RGBA8_NV 0x86FC +#define GL_SIGNED_RGB_NV 0x86FE +#define GL_SIGNED_RGB8_NV 0x86FF +#define GL_SIGNED_LUMINANCE_NV 0x8701 +#define GL_SIGNED_LUMINANCE8_NV 0x8702 +#define GL_SIGNED_LUMINANCE_ALPHA_NV 0x8703 +#define GL_SIGNED_LUMINANCE8_ALPHA8_NV 0x8704 +#define GL_SIGNED_ALPHA_NV 0x8705 +#define GL_SIGNED_ALPHA8_NV 0x8706 +#define GL_SIGNED_INTENSITY_NV 0x8707 +#define GL_SIGNED_INTENSITY8_NV 0x8708 +#define GL_DSDT8_NV 0x8709 +#define GL_DSDT8_MAG8_NV 0x870A +#define GL_DSDT8_MAG8_INTENSITY8_NV 0x870B +#define GL_SIGNED_RGB_UNSIGNED_ALPHA_NV 0x870C +#define GL_SIGNED_RGB8_UNSIGNED_ALPHA8_NV 0x870D +#define GL_HI_SCALE_NV 0x870E +#define GL_LO_SCALE_NV 0x870F +#define GL_DS_SCALE_NV 0x8710 +#define GL_DT_SCALE_NV 0x8711 +#define GL_MAGNITUDE_SCALE_NV 0x8712 +#define GL_VIBRANCE_SCALE_NV 0x8713 +#define GL_HI_BIAS_NV 0x8714 +#define GL_LO_BIAS_NV 0x8715 +#define GL_DS_BIAS_NV 0x8716 +#define GL_DT_BIAS_NV 0x8717 +#define GL_MAGNITUDE_BIAS_NV 0x8718 +#define GL_VIBRANCE_BIAS_NV 0x8719 +#define GL_TEXTURE_BORDER_VALUES_NV 0x871A +#define GL_TEXTURE_HI_SIZE_NV 0x871B +#define GL_TEXTURE_LO_SIZE_NV 0x871C +#define GL_TEXTURE_DS_SIZE_NV 0x871D +#define GL_TEXTURE_DT_SIZE_NV 0x871E +#define GL_TEXTURE_MAG_SIZE_NV 0x871F +#endif /* GL_NV_texture_shader */ + +#ifndef GL_NV_texture_shader2 +#define GL_NV_texture_shader2 1 +#define GL_DOT_PRODUCT_TEXTURE_3D_NV 0x86EF +#endif /* GL_NV_texture_shader2 */ + +#ifndef GL_NV_texture_shader3 +#define GL_NV_texture_shader3 1 +#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_NV 0x8850 +#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_SCALE_NV 0x8851 +#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8852 +#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_SCALE_NV 0x8853 +#define GL_OFFSET_HILO_TEXTURE_2D_NV 0x8854 +#define GL_OFFSET_HILO_TEXTURE_RECTANGLE_NV 0x8855 +#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_2D_NV 0x8856 +#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8857 +#define GL_DEPENDENT_HILO_TEXTURE_2D_NV 0x8858 +#define GL_DEPENDENT_RGB_TEXTURE_3D_NV 0x8859 +#define GL_DEPENDENT_RGB_TEXTURE_CUBE_MAP_NV 0x885A +#define GL_DOT_PRODUCT_PASS_THROUGH_NV 0x885B +#define GL_DOT_PRODUCT_TEXTURE_1D_NV 0x885C +#define GL_DOT_PRODUCT_AFFINE_DEPTH_REPLACE_NV 0x885D +#define GL_HILO8_NV 0x885E +#define GL_SIGNED_HILO8_NV 0x885F +#define GL_FORCE_BLUE_TO_ONE_NV 0x8860 +#endif /* GL_NV_texture_shader3 */ + +#ifndef GL_NV_transform_feedback +#define GL_NV_transform_feedback 1 +#define GL_BACK_PRIMARY_COLOR_NV 0x8C77 +#define GL_BACK_SECONDARY_COLOR_NV 0x8C78 +#define GL_TEXTURE_COORD_NV 0x8C79 +#define GL_CLIP_DISTANCE_NV 0x8C7A +#define GL_VERTEX_ID_NV 0x8C7B +#define GL_PRIMITIVE_ID_NV 0x8C7C +#define GL_GENERIC_ATTRIB_NV 0x8C7D +#define GL_TRANSFORM_FEEDBACK_ATTRIBS_NV 0x8C7E +#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE_NV 0x8C7F +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_NV 0x8C80 +#define GL_ACTIVE_VARYINGS_NV 0x8C81 +#define GL_ACTIVE_VARYING_MAX_LENGTH_NV 0x8C82 +#define GL_TRANSFORM_FEEDBACK_VARYINGS_NV 0x8C83 +#define GL_TRANSFORM_FEEDBACK_BUFFER_START_NV 0x8C84 +#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE_NV 0x8C85 +#define GL_TRANSFORM_FEEDBACK_RECORD_NV 0x8C86 +#define GL_PRIMITIVES_GENERATED_NV 0x8C87 +#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_NV 0x8C88 +#define GL_RASTERIZER_DISCARD_NV 0x8C89 +#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_NV 0x8C8A +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS_NV 0x8C8B +#define GL_INTERLEAVED_ATTRIBS_NV 0x8C8C +#define GL_SEPARATE_ATTRIBS_NV 0x8C8D +#define GL_TRANSFORM_FEEDBACK_BUFFER_NV 0x8C8E +#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING_NV 0x8C8F +#define GL_LAYER_NV 0x8DAA +#define GL_NEXT_BUFFER_NV -2 +#define GL_SKIP_COMPONENTS4_NV -3 +#define GL_SKIP_COMPONENTS3_NV -4 +#define GL_SKIP_COMPONENTS2_NV -5 +#define GL_SKIP_COMPONENTS1_NV -6 +typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKNVPROC) (GLenum primitiveMode); +typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKNVPROC) (void); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKATTRIBSNVPROC) (GLsizei count, const GLint *attribs, GLenum bufferMode); +typedef void (APIENTRYP PFNGLBINDBUFFERRANGENVPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLBINDBUFFEROFFSETNVPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset); +typedef void (APIENTRYP PFNGLBINDBUFFERBASENVPROC) (GLenum target, GLuint index, GLuint buffer); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSNVPROC) (GLuint program, GLsizei count, const GLint *locations, GLenum bufferMode); +typedef void (APIENTRYP PFNGLACTIVEVARYINGNVPROC) (GLuint program, const GLchar *name); +typedef GLint (APIENTRYP PFNGLGETVARYINGLOCATIONNVPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLGETACTIVEVARYINGNVPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGNVPROC) (GLuint program, GLuint index, GLint *location); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKSTREAMATTRIBSNVPROC) (GLsizei count, const GLint *attribs, GLsizei nbuffers, const GLint *bufstreams, GLenum bufferMode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginTransformFeedbackNV (GLenum primitiveMode); +GLAPI void APIENTRY glEndTransformFeedbackNV (void); +GLAPI void APIENTRY glTransformFeedbackAttribsNV (GLsizei count, const GLint *attribs, GLenum bufferMode); +GLAPI void APIENTRY glBindBufferRangeNV (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glBindBufferOffsetNV (GLenum target, GLuint index, GLuint buffer, GLintptr offset); +GLAPI void APIENTRY glBindBufferBaseNV (GLenum target, GLuint index, GLuint buffer); +GLAPI void APIENTRY glTransformFeedbackVaryingsNV (GLuint program, GLsizei count, const GLint *locations, GLenum bufferMode); +GLAPI void APIENTRY glActiveVaryingNV (GLuint program, const GLchar *name); +GLAPI GLint APIENTRY glGetVaryingLocationNV (GLuint program, const GLchar *name); +GLAPI void APIENTRY glGetActiveVaryingNV (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +GLAPI void APIENTRY glGetTransformFeedbackVaryingNV (GLuint program, GLuint index, GLint *location); +GLAPI void APIENTRY glTransformFeedbackStreamAttribsNV (GLsizei count, const GLint *attribs, GLsizei nbuffers, const GLint *bufstreams, GLenum bufferMode); +#endif +#endif /* GL_NV_transform_feedback */ + +#ifndef GL_NV_transform_feedback2 +#define GL_NV_transform_feedback2 1 +#define GL_TRANSFORM_FEEDBACK_NV 0x8E22 +#define GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED_NV 0x8E23 +#define GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE_NV 0x8E24 +#define GL_TRANSFORM_FEEDBACK_BINDING_NV 0x8E25 +typedef void (APIENTRYP PFNGLBINDTRANSFORMFEEDBACKNVPROC) (GLenum target, GLuint id); +typedef void (APIENTRYP PFNGLDELETETRANSFORMFEEDBACKSNVPROC) (GLsizei n, const GLuint *ids); +typedef void (APIENTRYP PFNGLGENTRANSFORMFEEDBACKSNVPROC) (GLsizei n, GLuint *ids); +typedef GLboolean (APIENTRYP PFNGLISTRANSFORMFEEDBACKNVPROC) (GLuint id); +typedef void (APIENTRYP PFNGLPAUSETRANSFORMFEEDBACKNVPROC) (void); +typedef void (APIENTRYP PFNGLRESUMETRANSFORMFEEDBACKNVPROC) (void); +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKNVPROC) (GLenum mode, GLuint id); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindTransformFeedbackNV (GLenum target, GLuint id); +GLAPI void APIENTRY glDeleteTransformFeedbacksNV (GLsizei n, const GLuint *ids); +GLAPI void APIENTRY glGenTransformFeedbacksNV (GLsizei n, GLuint *ids); +GLAPI GLboolean APIENTRY glIsTransformFeedbackNV (GLuint id); +GLAPI void APIENTRY glPauseTransformFeedbackNV (void); +GLAPI void APIENTRY glResumeTransformFeedbackNV (void); +GLAPI void APIENTRY glDrawTransformFeedbackNV (GLenum mode, GLuint id); +#endif +#endif /* GL_NV_transform_feedback2 */ + +#ifndef GL_NV_uniform_buffer_unified_memory +#define GL_NV_uniform_buffer_unified_memory 1 +#define GL_UNIFORM_BUFFER_UNIFIED_NV 0x936E +#define GL_UNIFORM_BUFFER_ADDRESS_NV 0x936F +#define GL_UNIFORM_BUFFER_LENGTH_NV 0x9370 +#endif /* GL_NV_uniform_buffer_unified_memory */ + +#ifndef GL_NV_vdpau_interop +#define GL_NV_vdpau_interop 1 +typedef GLintptr GLvdpauSurfaceNV; +#define GL_SURFACE_STATE_NV 0x86EB +#define GL_SURFACE_REGISTERED_NV 0x86FD +#define GL_SURFACE_MAPPED_NV 0x8700 +#define GL_WRITE_DISCARD_NV 0x88BE +typedef void (APIENTRYP PFNGLVDPAUINITNVPROC) (const void *vdpDevice, const void *getProcAddress); +typedef void (APIENTRYP PFNGLVDPAUFININVPROC) (void); +typedef GLvdpauSurfaceNV (APIENTRYP PFNGLVDPAUREGISTERVIDEOSURFACENVPROC) (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames); +typedef GLvdpauSurfaceNV (APIENTRYP PFNGLVDPAUREGISTEROUTPUTSURFACENVPROC) (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames); +typedef GLboolean (APIENTRYP PFNGLVDPAUISSURFACENVPROC) (GLvdpauSurfaceNV surface); +typedef void (APIENTRYP PFNGLVDPAUUNREGISTERSURFACENVPROC) (GLvdpauSurfaceNV surface); +typedef void (APIENTRYP PFNGLVDPAUGETSURFACEIVNVPROC) (GLvdpauSurfaceNV surface, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); +typedef void (APIENTRYP PFNGLVDPAUSURFACEACCESSNVPROC) (GLvdpauSurfaceNV surface, GLenum access); +typedef void (APIENTRYP PFNGLVDPAUMAPSURFACESNVPROC) (GLsizei numSurfaces, const GLvdpauSurfaceNV *surfaces); +typedef void (APIENTRYP PFNGLVDPAUUNMAPSURFACESNVPROC) (GLsizei numSurface, const GLvdpauSurfaceNV *surfaces); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVDPAUInitNV (const void *vdpDevice, const void *getProcAddress); +GLAPI void APIENTRY glVDPAUFiniNV (void); +GLAPI GLvdpauSurfaceNV APIENTRY glVDPAURegisterVideoSurfaceNV (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames); +GLAPI GLvdpauSurfaceNV APIENTRY glVDPAURegisterOutputSurfaceNV (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames); +GLAPI GLboolean APIENTRY glVDPAUIsSurfaceNV (GLvdpauSurfaceNV surface); +GLAPI void APIENTRY glVDPAUUnregisterSurfaceNV (GLvdpauSurfaceNV surface); +GLAPI void APIENTRY glVDPAUGetSurfaceivNV (GLvdpauSurfaceNV surface, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); +GLAPI void APIENTRY glVDPAUSurfaceAccessNV (GLvdpauSurfaceNV surface, GLenum access); +GLAPI void APIENTRY glVDPAUMapSurfacesNV (GLsizei numSurfaces, const GLvdpauSurfaceNV *surfaces); +GLAPI void APIENTRY glVDPAUUnmapSurfacesNV (GLsizei numSurface, const GLvdpauSurfaceNV *surfaces); +#endif +#endif /* GL_NV_vdpau_interop */ + +#ifndef GL_NV_vertex_array_range +#define GL_NV_vertex_array_range 1 +#define GL_VERTEX_ARRAY_RANGE_NV 0x851D +#define GL_VERTEX_ARRAY_RANGE_LENGTH_NV 0x851E +#define GL_VERTEX_ARRAY_RANGE_VALID_NV 0x851F +#define GL_MAX_VERTEX_ARRAY_RANGE_ELEMENT_NV 0x8520 +#define GL_VERTEX_ARRAY_RANGE_POINTER_NV 0x8521 +typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGENVPROC) (void); +typedef void (APIENTRYP PFNGLVERTEXARRAYRANGENVPROC) (GLsizei length, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFlushVertexArrayRangeNV (void); +GLAPI void APIENTRY glVertexArrayRangeNV (GLsizei length, const void *pointer); +#endif +#endif /* GL_NV_vertex_array_range */ + +#ifndef GL_NV_vertex_array_range2 +#define GL_NV_vertex_array_range2 1 +#define GL_VERTEX_ARRAY_RANGE_WITHOUT_FLUSH_NV 0x8533 +#endif /* GL_NV_vertex_array_range2 */ + +#ifndef GL_NV_vertex_attrib_integer_64bit +#define GL_NV_vertex_attrib_integer_64bit 1 +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1I64NVPROC) (GLuint index, GLint64EXT x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1I64VNVPROC) (GLuint index, const GLint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2I64VNVPROC) (GLuint index, const GLint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3I64VNVPROC) (GLuint index, const GLint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4I64VNVPROC) (GLuint index, const GLint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64NVPROC) (GLuint index, GLuint64EXT x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64VNVPROC) (GLuint index, const GLuint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2UI64VNVPROC) (GLuint index, const GLuint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3UI64VNVPROC) (GLuint index, const GLuint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4UI64VNVPROC) (GLuint index, const GLuint64EXT *v); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLI64VNVPROC) (GLuint index, GLenum pname, GLint64EXT *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLUI64VNVPROC) (GLuint index, GLenum pname, GLuint64EXT *params); +typedef void (APIENTRYP PFNGLVERTEXATTRIBLFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLsizei stride); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribL1i64NV (GLuint index, GLint64EXT x); +GLAPI void APIENTRY glVertexAttribL2i64NV (GLuint index, GLint64EXT x, GLint64EXT y); +GLAPI void APIENTRY glVertexAttribL3i64NV (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z); +GLAPI void APIENTRY glVertexAttribL4i64NV (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +GLAPI void APIENTRY glVertexAttribL1i64vNV (GLuint index, const GLint64EXT *v); +GLAPI void APIENTRY glVertexAttribL2i64vNV (GLuint index, const GLint64EXT *v); +GLAPI void APIENTRY glVertexAttribL3i64vNV (GLuint index, const GLint64EXT *v); +GLAPI void APIENTRY glVertexAttribL4i64vNV (GLuint index, const GLint64EXT *v); +GLAPI void APIENTRY glVertexAttribL1ui64NV (GLuint index, GLuint64EXT x); +GLAPI void APIENTRY glVertexAttribL2ui64NV (GLuint index, GLuint64EXT x, GLuint64EXT y); +GLAPI void APIENTRY glVertexAttribL3ui64NV (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +GLAPI void APIENTRY glVertexAttribL4ui64NV (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +GLAPI void APIENTRY glVertexAttribL1ui64vNV (GLuint index, const GLuint64EXT *v); +GLAPI void APIENTRY glVertexAttribL2ui64vNV (GLuint index, const GLuint64EXT *v); +GLAPI void APIENTRY glVertexAttribL3ui64vNV (GLuint index, const GLuint64EXT *v); +GLAPI void APIENTRY glVertexAttribL4ui64vNV (GLuint index, const GLuint64EXT *v); +GLAPI void APIENTRY glGetVertexAttribLi64vNV (GLuint index, GLenum pname, GLint64EXT *params); +GLAPI void APIENTRY glGetVertexAttribLui64vNV (GLuint index, GLenum pname, GLuint64EXT *params); +GLAPI void APIENTRY glVertexAttribLFormatNV (GLuint index, GLint size, GLenum type, GLsizei stride); +#endif +#endif /* GL_NV_vertex_attrib_integer_64bit */ + +#ifndef GL_NV_vertex_buffer_unified_memory +#define GL_NV_vertex_buffer_unified_memory 1 +#define GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV 0x8F1E +#define GL_ELEMENT_ARRAY_UNIFIED_NV 0x8F1F +#define GL_VERTEX_ATTRIB_ARRAY_ADDRESS_NV 0x8F20 +#define GL_VERTEX_ARRAY_ADDRESS_NV 0x8F21 +#define GL_NORMAL_ARRAY_ADDRESS_NV 0x8F22 +#define GL_COLOR_ARRAY_ADDRESS_NV 0x8F23 +#define GL_INDEX_ARRAY_ADDRESS_NV 0x8F24 +#define GL_TEXTURE_COORD_ARRAY_ADDRESS_NV 0x8F25 +#define GL_EDGE_FLAG_ARRAY_ADDRESS_NV 0x8F26 +#define GL_SECONDARY_COLOR_ARRAY_ADDRESS_NV 0x8F27 +#define GL_FOG_COORD_ARRAY_ADDRESS_NV 0x8F28 +#define GL_ELEMENT_ARRAY_ADDRESS_NV 0x8F29 +#define GL_VERTEX_ATTRIB_ARRAY_LENGTH_NV 0x8F2A +#define GL_VERTEX_ARRAY_LENGTH_NV 0x8F2B +#define GL_NORMAL_ARRAY_LENGTH_NV 0x8F2C +#define GL_COLOR_ARRAY_LENGTH_NV 0x8F2D +#define GL_INDEX_ARRAY_LENGTH_NV 0x8F2E +#define GL_TEXTURE_COORD_ARRAY_LENGTH_NV 0x8F2F +#define GL_EDGE_FLAG_ARRAY_LENGTH_NV 0x8F30 +#define GL_SECONDARY_COLOR_ARRAY_LENGTH_NV 0x8F31 +#define GL_FOG_COORD_ARRAY_LENGTH_NV 0x8F32 +#define GL_ELEMENT_ARRAY_LENGTH_NV 0x8F33 +#define GL_DRAW_INDIRECT_UNIFIED_NV 0x8F40 +#define GL_DRAW_INDIRECT_ADDRESS_NV 0x8F41 +#define GL_DRAW_INDIRECT_LENGTH_NV 0x8F42 +typedef void (APIENTRYP PFNGLBUFFERADDRESSRANGENVPROC) (GLenum pname, GLuint index, GLuint64EXT address, GLsizeiptr length); +typedef void (APIENTRYP PFNGLVERTEXFORMATNVPROC) (GLint size, GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLNORMALFORMATNVPROC) (GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLCOLORFORMATNVPROC) (GLint size, GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLINDEXFORMATNVPROC) (GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLTEXCOORDFORMATNVPROC) (GLint size, GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLEDGEFLAGFORMATNVPROC) (GLsizei stride); +typedef void (APIENTRYP PFNGLSECONDARYCOLORFORMATNVPROC) (GLint size, GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLFOGCOORDFORMATNVPROC) (GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLVERTEXATTRIBFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride); +typedef void (APIENTRYP PFNGLVERTEXATTRIBIFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLGETINTEGERUI64I_VNVPROC) (GLenum value, GLuint index, GLuint64EXT *result); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBufferAddressRangeNV (GLenum pname, GLuint index, GLuint64EXT address, GLsizeiptr length); +GLAPI void APIENTRY glVertexFormatNV (GLint size, GLenum type, GLsizei stride); +GLAPI void APIENTRY glNormalFormatNV (GLenum type, GLsizei stride); +GLAPI void APIENTRY glColorFormatNV (GLint size, GLenum type, GLsizei stride); +GLAPI void APIENTRY glIndexFormatNV (GLenum type, GLsizei stride); +GLAPI void APIENTRY glTexCoordFormatNV (GLint size, GLenum type, GLsizei stride); +GLAPI void APIENTRY glEdgeFlagFormatNV (GLsizei stride); +GLAPI void APIENTRY glSecondaryColorFormatNV (GLint size, GLenum type, GLsizei stride); +GLAPI void APIENTRY glFogCoordFormatNV (GLenum type, GLsizei stride); +GLAPI void APIENTRY glVertexAttribFormatNV (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride); +GLAPI void APIENTRY glVertexAttribIFormatNV (GLuint index, GLint size, GLenum type, GLsizei stride); +GLAPI void APIENTRY glGetIntegerui64i_vNV (GLenum value, GLuint index, GLuint64EXT *result); +#endif +#endif /* GL_NV_vertex_buffer_unified_memory */ + +#ifndef GL_NV_vertex_program +#define GL_NV_vertex_program 1 +#define GL_VERTEX_PROGRAM_NV 0x8620 +#define GL_VERTEX_STATE_PROGRAM_NV 0x8621 +#define GL_ATTRIB_ARRAY_SIZE_NV 0x8623 +#define GL_ATTRIB_ARRAY_STRIDE_NV 0x8624 +#define GL_ATTRIB_ARRAY_TYPE_NV 0x8625 +#define GL_CURRENT_ATTRIB_NV 0x8626 +#define GL_PROGRAM_LENGTH_NV 0x8627 +#define GL_PROGRAM_STRING_NV 0x8628 +#define GL_MODELVIEW_PROJECTION_NV 0x8629 +#define GL_IDENTITY_NV 0x862A +#define GL_INVERSE_NV 0x862B +#define GL_TRANSPOSE_NV 0x862C +#define GL_INVERSE_TRANSPOSE_NV 0x862D +#define GL_MAX_TRACK_MATRIX_STACK_DEPTH_NV 0x862E +#define GL_MAX_TRACK_MATRICES_NV 0x862F +#define GL_MATRIX0_NV 0x8630 +#define GL_MATRIX1_NV 0x8631 +#define GL_MATRIX2_NV 0x8632 +#define GL_MATRIX3_NV 0x8633 +#define GL_MATRIX4_NV 0x8634 +#define GL_MATRIX5_NV 0x8635 +#define GL_MATRIX6_NV 0x8636 +#define GL_MATRIX7_NV 0x8637 +#define GL_CURRENT_MATRIX_STACK_DEPTH_NV 0x8640 +#define GL_CURRENT_MATRIX_NV 0x8641 +#define GL_VERTEX_PROGRAM_POINT_SIZE_NV 0x8642 +#define GL_VERTEX_PROGRAM_TWO_SIDE_NV 0x8643 +#define GL_PROGRAM_PARAMETER_NV 0x8644 +#define GL_ATTRIB_ARRAY_POINTER_NV 0x8645 +#define GL_PROGRAM_TARGET_NV 0x8646 +#define GL_PROGRAM_RESIDENT_NV 0x8647 +#define GL_TRACK_MATRIX_NV 0x8648 +#define GL_TRACK_MATRIX_TRANSFORM_NV 0x8649 +#define GL_VERTEX_PROGRAM_BINDING_NV 0x864A +#define GL_PROGRAM_ERROR_POSITION_NV 0x864B +#define GL_VERTEX_ATTRIB_ARRAY0_NV 0x8650 +#define GL_VERTEX_ATTRIB_ARRAY1_NV 0x8651 +#define GL_VERTEX_ATTRIB_ARRAY2_NV 0x8652 +#define GL_VERTEX_ATTRIB_ARRAY3_NV 0x8653 +#define GL_VERTEX_ATTRIB_ARRAY4_NV 0x8654 +#define GL_VERTEX_ATTRIB_ARRAY5_NV 0x8655 +#define GL_VERTEX_ATTRIB_ARRAY6_NV 0x8656 +#define GL_VERTEX_ATTRIB_ARRAY7_NV 0x8657 +#define GL_VERTEX_ATTRIB_ARRAY8_NV 0x8658 +#define GL_VERTEX_ATTRIB_ARRAY9_NV 0x8659 +#define GL_VERTEX_ATTRIB_ARRAY10_NV 0x865A +#define GL_VERTEX_ATTRIB_ARRAY11_NV 0x865B +#define GL_VERTEX_ATTRIB_ARRAY12_NV 0x865C +#define GL_VERTEX_ATTRIB_ARRAY13_NV 0x865D +#define GL_VERTEX_ATTRIB_ARRAY14_NV 0x865E +#define GL_VERTEX_ATTRIB_ARRAY15_NV 0x865F +#define GL_MAP1_VERTEX_ATTRIB0_4_NV 0x8660 +#define GL_MAP1_VERTEX_ATTRIB1_4_NV 0x8661 +#define GL_MAP1_VERTEX_ATTRIB2_4_NV 0x8662 +#define GL_MAP1_VERTEX_ATTRIB3_4_NV 0x8663 +#define GL_MAP1_VERTEX_ATTRIB4_4_NV 0x8664 +#define GL_MAP1_VERTEX_ATTRIB5_4_NV 0x8665 +#define GL_MAP1_VERTEX_ATTRIB6_4_NV 0x8666 +#define GL_MAP1_VERTEX_ATTRIB7_4_NV 0x8667 +#define GL_MAP1_VERTEX_ATTRIB8_4_NV 0x8668 +#define GL_MAP1_VERTEX_ATTRIB9_4_NV 0x8669 +#define GL_MAP1_VERTEX_ATTRIB10_4_NV 0x866A +#define GL_MAP1_VERTEX_ATTRIB11_4_NV 0x866B +#define GL_MAP1_VERTEX_ATTRIB12_4_NV 0x866C +#define GL_MAP1_VERTEX_ATTRIB13_4_NV 0x866D +#define GL_MAP1_VERTEX_ATTRIB14_4_NV 0x866E +#define GL_MAP1_VERTEX_ATTRIB15_4_NV 0x866F +#define GL_MAP2_VERTEX_ATTRIB0_4_NV 0x8670 +#define GL_MAP2_VERTEX_ATTRIB1_4_NV 0x8671 +#define GL_MAP2_VERTEX_ATTRIB2_4_NV 0x8672 +#define GL_MAP2_VERTEX_ATTRIB3_4_NV 0x8673 +#define GL_MAP2_VERTEX_ATTRIB4_4_NV 0x8674 +#define GL_MAP2_VERTEX_ATTRIB5_4_NV 0x8675 +#define GL_MAP2_VERTEX_ATTRIB6_4_NV 0x8676 +#define GL_MAP2_VERTEX_ATTRIB7_4_NV 0x8677 +#define GL_MAP2_VERTEX_ATTRIB8_4_NV 0x8678 +#define GL_MAP2_VERTEX_ATTRIB9_4_NV 0x8679 +#define GL_MAP2_VERTEX_ATTRIB10_4_NV 0x867A +#define GL_MAP2_VERTEX_ATTRIB11_4_NV 0x867B +#define GL_MAP2_VERTEX_ATTRIB12_4_NV 0x867C +#define GL_MAP2_VERTEX_ATTRIB13_4_NV 0x867D +#define GL_MAP2_VERTEX_ATTRIB14_4_NV 0x867E +#define GL_MAP2_VERTEX_ATTRIB15_4_NV 0x867F +typedef GLboolean (APIENTRYP PFNGLAREPROGRAMSRESIDENTNVPROC) (GLsizei n, const GLuint *programs, GLboolean *residences); +typedef void (APIENTRYP PFNGLBINDPROGRAMNVPROC) (GLenum target, GLuint id); +typedef void (APIENTRYP PFNGLDELETEPROGRAMSNVPROC) (GLsizei n, const GLuint *programs); +typedef void (APIENTRYP PFNGLEXECUTEPROGRAMNVPROC) (GLenum target, GLuint id, const GLfloat *params); +typedef void (APIENTRYP PFNGLGENPROGRAMSNVPROC) (GLsizei n, GLuint *programs); +typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERDVNVPROC) (GLenum target, GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMIVNVPROC) (GLuint id, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGNVPROC) (GLuint id, GLenum pname, GLubyte *program); +typedef void (APIENTRYP PFNGLGETTRACKMATRIXIVNVPROC) (GLenum target, GLuint address, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVNVPROC) (GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVNVPROC) (GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVNVPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVNVPROC) (GLuint index, GLenum pname, void **pointer); +typedef GLboolean (APIENTRYP PFNGLISPROGRAMNVPROC) (GLuint id); +typedef void (APIENTRYP PFNGLLOADPROGRAMNVPROC) (GLenum target, GLuint id, GLsizei len, const GLubyte *program); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DNVPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DVNVPROC) (GLenum target, GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FNVPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FVNVPROC) (GLenum target, GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4DVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4FVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLREQUESTRESIDENTPROGRAMSNVPROC) (GLsizei n, const GLuint *programs); +typedef void (APIENTRYP PFNGLTRACKMATRIXNVPROC) (GLenum target, GLuint address, GLenum matrix, GLenum transform); +typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERNVPROC) (GLuint index, GLint fsize, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DNVPROC) (GLuint index, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVNVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FNVPROC) (GLuint index, GLfloat x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVNVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SNVPROC) (GLuint index, GLshort x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVNVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DNVPROC) (GLuint index, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVNVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FNVPROC) (GLuint index, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVNVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SNVPROC) (GLuint index, GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVNVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVNVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVNVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVNVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVNVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVNVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVNVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBNVPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVNVPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS1DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS1FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS1SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS2DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS2FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS2SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS3DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS3FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS3SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4UBVNVPROC) (GLuint index, GLsizei count, const GLubyte *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLboolean APIENTRY glAreProgramsResidentNV (GLsizei n, const GLuint *programs, GLboolean *residences); +GLAPI void APIENTRY glBindProgramNV (GLenum target, GLuint id); +GLAPI void APIENTRY glDeleteProgramsNV (GLsizei n, const GLuint *programs); +GLAPI void APIENTRY glExecuteProgramNV (GLenum target, GLuint id, const GLfloat *params); +GLAPI void APIENTRY glGenProgramsNV (GLsizei n, GLuint *programs); +GLAPI void APIENTRY glGetProgramParameterdvNV (GLenum target, GLuint index, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glGetProgramParameterfvNV (GLenum target, GLuint index, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetProgramivNV (GLuint id, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetProgramStringNV (GLuint id, GLenum pname, GLubyte *program); +GLAPI void APIENTRY glGetTrackMatrixivNV (GLenum target, GLuint address, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribdvNV (GLuint index, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glGetVertexAttribfvNV (GLuint index, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetVertexAttribivNV (GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribPointervNV (GLuint index, GLenum pname, void **pointer); +GLAPI GLboolean APIENTRY glIsProgramNV (GLuint id); +GLAPI void APIENTRY glLoadProgramNV (GLenum target, GLuint id, GLsizei len, const GLubyte *program); +GLAPI void APIENTRY glProgramParameter4dNV (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glProgramParameter4dvNV (GLenum target, GLuint index, const GLdouble *v); +GLAPI void APIENTRY glProgramParameter4fNV (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glProgramParameter4fvNV (GLenum target, GLuint index, const GLfloat *v); +GLAPI void APIENTRY glProgramParameters4dvNV (GLenum target, GLuint index, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glProgramParameters4fvNV (GLenum target, GLuint index, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glRequestResidentProgramsNV (GLsizei n, const GLuint *programs); +GLAPI void APIENTRY glTrackMatrixNV (GLenum target, GLuint address, GLenum matrix, GLenum transform); +GLAPI void APIENTRY glVertexAttribPointerNV (GLuint index, GLint fsize, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glVertexAttrib1dNV (GLuint index, GLdouble x); +GLAPI void APIENTRY glVertexAttrib1dvNV (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib1fNV (GLuint index, GLfloat x); +GLAPI void APIENTRY glVertexAttrib1fvNV (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib1sNV (GLuint index, GLshort x); +GLAPI void APIENTRY glVertexAttrib1svNV (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib2dNV (GLuint index, GLdouble x, GLdouble y); +GLAPI void APIENTRY glVertexAttrib2dvNV (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib2fNV (GLuint index, GLfloat x, GLfloat y); +GLAPI void APIENTRY glVertexAttrib2fvNV (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib2sNV (GLuint index, GLshort x, GLshort y); +GLAPI void APIENTRY glVertexAttrib2svNV (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib3dNV (GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glVertexAttrib3dvNV (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib3fNV (GLuint index, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glVertexAttrib3fvNV (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib3sNV (GLuint index, GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glVertexAttrib3svNV (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4dNV (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glVertexAttrib4dvNV (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib4fNV (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glVertexAttrib4fvNV (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib4sNV (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI void APIENTRY glVertexAttrib4svNV (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4ubNV (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +GLAPI void APIENTRY glVertexAttrib4ubvNV (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttribs1dvNV (GLuint index, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribs1fvNV (GLuint index, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glVertexAttribs1svNV (GLuint index, GLsizei count, const GLshort *v); +GLAPI void APIENTRY glVertexAttribs2dvNV (GLuint index, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribs2fvNV (GLuint index, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glVertexAttribs2svNV (GLuint index, GLsizei count, const GLshort *v); +GLAPI void APIENTRY glVertexAttribs3dvNV (GLuint index, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribs3fvNV (GLuint index, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glVertexAttribs3svNV (GLuint index, GLsizei count, const GLshort *v); +GLAPI void APIENTRY glVertexAttribs4dvNV (GLuint index, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribs4fvNV (GLuint index, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glVertexAttribs4svNV (GLuint index, GLsizei count, const GLshort *v); +GLAPI void APIENTRY glVertexAttribs4ubvNV (GLuint index, GLsizei count, const GLubyte *v); +#endif +#endif /* GL_NV_vertex_program */ + +#ifndef GL_NV_vertex_program1_1 +#define GL_NV_vertex_program1_1 1 +#endif /* GL_NV_vertex_program1_1 */ + +#ifndef GL_NV_vertex_program2 +#define GL_NV_vertex_program2 1 +#endif /* GL_NV_vertex_program2 */ + +#ifndef GL_NV_vertex_program2_option +#define GL_NV_vertex_program2_option 1 +#endif /* GL_NV_vertex_program2_option */ + +#ifndef GL_NV_vertex_program3 +#define GL_NV_vertex_program3 1 +#endif /* GL_NV_vertex_program3 */ + +#ifndef GL_NV_vertex_program4 +#define GL_NV_vertex_program4 1 +#define GL_VERTEX_ATTRIB_ARRAY_INTEGER_NV 0x88FD +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IEXTPROC) (GLuint index, GLint x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IEXTPROC) (GLuint index, GLint x, GLint y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IEXTPROC) (GLuint index, GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IEXTPROC) (GLuint index, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIEXTPROC) (GLuint index, GLuint x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIEXTPROC) (GLuint index, GLuint x, GLuint y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIEXTPROC) (GLuint index, GLuint x, GLuint y, GLuint z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIEXTPROC) (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IVEXTPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IVEXTPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IVEXTPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IVEXTPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIVEXTPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIVEXTPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIVEXTPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIVEXTPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4BVEXTPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4SVEXTPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UBVEXTPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4USVEXTPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBIPOINTEREXTPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIIVEXTPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIUIVEXTPROC) (GLuint index, GLenum pname, GLuint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribI1iEXT (GLuint index, GLint x); +GLAPI void APIENTRY glVertexAttribI2iEXT (GLuint index, GLint x, GLint y); +GLAPI void APIENTRY glVertexAttribI3iEXT (GLuint index, GLint x, GLint y, GLint z); +GLAPI void APIENTRY glVertexAttribI4iEXT (GLuint index, GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glVertexAttribI1uiEXT (GLuint index, GLuint x); +GLAPI void APIENTRY glVertexAttribI2uiEXT (GLuint index, GLuint x, GLuint y); +GLAPI void APIENTRY glVertexAttribI3uiEXT (GLuint index, GLuint x, GLuint y, GLuint z); +GLAPI void APIENTRY glVertexAttribI4uiEXT (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +GLAPI void APIENTRY glVertexAttribI1ivEXT (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI2ivEXT (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI3ivEXT (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI4ivEXT (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI1uivEXT (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI2uivEXT (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI3uivEXT (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI4uivEXT (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI4bvEXT (GLuint index, const GLbyte *v); +GLAPI void APIENTRY glVertexAttribI4svEXT (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttribI4ubvEXT (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttribI4usvEXT (GLuint index, const GLushort *v); +GLAPI void APIENTRY glVertexAttribIPointerEXT (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glGetVertexAttribIivEXT (GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribIuivEXT (GLuint index, GLenum pname, GLuint *params); +#endif +#endif /* GL_NV_vertex_program4 */ + +#ifndef GL_NV_video_capture +#define GL_NV_video_capture 1 +#define GL_VIDEO_BUFFER_NV 0x9020 +#define GL_VIDEO_BUFFER_BINDING_NV 0x9021 +#define GL_FIELD_UPPER_NV 0x9022 +#define GL_FIELD_LOWER_NV 0x9023 +#define GL_NUM_VIDEO_CAPTURE_STREAMS_NV 0x9024 +#define GL_NEXT_VIDEO_CAPTURE_BUFFER_STATUS_NV 0x9025 +#define GL_VIDEO_CAPTURE_TO_422_SUPPORTED_NV 0x9026 +#define GL_LAST_VIDEO_CAPTURE_STATUS_NV 0x9027 +#define GL_VIDEO_BUFFER_PITCH_NV 0x9028 +#define GL_VIDEO_COLOR_CONVERSION_MATRIX_NV 0x9029 +#define GL_VIDEO_COLOR_CONVERSION_MAX_NV 0x902A +#define GL_VIDEO_COLOR_CONVERSION_MIN_NV 0x902B +#define GL_VIDEO_COLOR_CONVERSION_OFFSET_NV 0x902C +#define GL_VIDEO_BUFFER_INTERNAL_FORMAT_NV 0x902D +#define GL_PARTIAL_SUCCESS_NV 0x902E +#define GL_SUCCESS_NV 0x902F +#define GL_FAILURE_NV 0x9030 +#define GL_YCBYCR8_422_NV 0x9031 +#define GL_YCBAYCR8A_4224_NV 0x9032 +#define GL_Z6Y10Z6CB10Z6Y10Z6CR10_422_NV 0x9033 +#define GL_Z6Y10Z6CB10Z6A10Z6Y10Z6CR10Z6A10_4224_NV 0x9034 +#define GL_Z4Y12Z4CB12Z4Y12Z4CR12_422_NV 0x9035 +#define GL_Z4Y12Z4CB12Z4A12Z4Y12Z4CR12Z4A12_4224_NV 0x9036 +#define GL_Z4Y12Z4CB12Z4CR12_444_NV 0x9037 +#define GL_VIDEO_CAPTURE_FRAME_WIDTH_NV 0x9038 +#define GL_VIDEO_CAPTURE_FRAME_HEIGHT_NV 0x9039 +#define GL_VIDEO_CAPTURE_FIELD_UPPER_HEIGHT_NV 0x903A +#define GL_VIDEO_CAPTURE_FIELD_LOWER_HEIGHT_NV 0x903B +#define GL_VIDEO_CAPTURE_SURFACE_ORIGIN_NV 0x903C +typedef void (APIENTRYP PFNGLBEGINVIDEOCAPTURENVPROC) (GLuint video_capture_slot); +typedef void (APIENTRYP PFNGLBINDVIDEOCAPTURESTREAMBUFFERNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLintptrARB offset); +typedef void (APIENTRYP PFNGLBINDVIDEOCAPTURESTREAMTEXTURENVPROC) (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLenum target, GLuint texture); +typedef void (APIENTRYP PFNGLENDVIDEOCAPTURENVPROC) (GLuint video_capture_slot); +typedef void (APIENTRYP PFNGLGETVIDEOCAPTUREIVNVPROC) (GLuint video_capture_slot, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVIDEOCAPTURESTREAMIVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVIDEOCAPTURESTREAMFVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVIDEOCAPTURESTREAMDVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, GLdouble *params); +typedef GLenum (APIENTRYP PFNGLVIDEOCAPTURENVPROC) (GLuint video_capture_slot, GLuint *sequence_num, GLuint64EXT *capture_time); +typedef void (APIENTRYP PFNGLVIDEOCAPTURESTREAMPARAMETERIVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLVIDEOCAPTURESTREAMPARAMETERFVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLVIDEOCAPTURESTREAMPARAMETERDVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLdouble *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginVideoCaptureNV (GLuint video_capture_slot); +GLAPI void APIENTRY glBindVideoCaptureStreamBufferNV (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLintptrARB offset); +GLAPI void APIENTRY glBindVideoCaptureStreamTextureNV (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLenum target, GLuint texture); +GLAPI void APIENTRY glEndVideoCaptureNV (GLuint video_capture_slot); +GLAPI void APIENTRY glGetVideoCaptureivNV (GLuint video_capture_slot, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVideoCaptureStreamivNV (GLuint video_capture_slot, GLuint stream, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVideoCaptureStreamfvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetVideoCaptureStreamdvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, GLdouble *params); +GLAPI GLenum APIENTRY glVideoCaptureNV (GLuint video_capture_slot, GLuint *sequence_num, GLuint64EXT *capture_time); +GLAPI void APIENTRY glVideoCaptureStreamParameterivNV (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLint *params); +GLAPI void APIENTRY glVideoCaptureStreamParameterfvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glVideoCaptureStreamParameterdvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLdouble *params); +#endif +#endif /* GL_NV_video_capture */ + +#ifndef GL_NV_viewport_array2 +#define GL_NV_viewport_array2 1 +#endif /* GL_NV_viewport_array2 */ + +#ifndef GL_NV_viewport_swizzle +#define GL_NV_viewport_swizzle 1 +#define GL_VIEWPORT_SWIZZLE_POSITIVE_X_NV 0x9350 +#define GL_VIEWPORT_SWIZZLE_NEGATIVE_X_NV 0x9351 +#define GL_VIEWPORT_SWIZZLE_POSITIVE_Y_NV 0x9352 +#define GL_VIEWPORT_SWIZZLE_NEGATIVE_Y_NV 0x9353 +#define GL_VIEWPORT_SWIZZLE_POSITIVE_Z_NV 0x9354 +#define GL_VIEWPORT_SWIZZLE_NEGATIVE_Z_NV 0x9355 +#define GL_VIEWPORT_SWIZZLE_POSITIVE_W_NV 0x9356 +#define GL_VIEWPORT_SWIZZLE_NEGATIVE_W_NV 0x9357 +#define GL_VIEWPORT_SWIZZLE_X_NV 0x9358 +#define GL_VIEWPORT_SWIZZLE_Y_NV 0x9359 +#define GL_VIEWPORT_SWIZZLE_Z_NV 0x935A +#define GL_VIEWPORT_SWIZZLE_W_NV 0x935B +typedef void (APIENTRYP PFNGLVIEWPORTSWIZZLENVPROC) (GLuint index, GLenum swizzlex, GLenum swizzley, GLenum swizzlez, GLenum swizzlew); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glViewportSwizzleNV (GLuint index, GLenum swizzlex, GLenum swizzley, GLenum swizzlez, GLenum swizzlew); +#endif +#endif /* GL_NV_viewport_swizzle */ + +#ifndef GL_OML_interlace +#define GL_OML_interlace 1 +#define GL_INTERLACE_OML 0x8980 +#define GL_INTERLACE_READ_OML 0x8981 +#endif /* GL_OML_interlace */ + +#ifndef GL_OML_resample +#define GL_OML_resample 1 +#define GL_PACK_RESAMPLE_OML 0x8984 +#define GL_UNPACK_RESAMPLE_OML 0x8985 +#define GL_RESAMPLE_REPLICATE_OML 0x8986 +#define GL_RESAMPLE_ZERO_FILL_OML 0x8987 +#define GL_RESAMPLE_AVERAGE_OML 0x8988 +#define GL_RESAMPLE_DECIMATE_OML 0x8989 +#endif /* GL_OML_resample */ + +#ifndef GL_OML_subsample +#define GL_OML_subsample 1 +#define GL_FORMAT_SUBSAMPLE_24_24_OML 0x8982 +#define GL_FORMAT_SUBSAMPLE_244_244_OML 0x8983 +#endif /* GL_OML_subsample */ + +#ifndef GL_OVR_multiview +#define GL_OVR_multiview 1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR 0x9630 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR 0x9632 +#define GL_MAX_VIEWS_OVR 0x9631 +#define GL_FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR 0x9633 +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFramebufferTextureMultiviewOVR (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews); +#endif +#endif /* GL_OVR_multiview */ + +#ifndef GL_OVR_multiview2 +#define GL_OVR_multiview2 1 +#endif /* GL_OVR_multiview2 */ + +#ifndef GL_PGI_misc_hints +#define GL_PGI_misc_hints 1 +#define GL_PREFER_DOUBLEBUFFER_HINT_PGI 0x1A1F8 +#define GL_CONSERVE_MEMORY_HINT_PGI 0x1A1FD +#define GL_RECLAIM_MEMORY_HINT_PGI 0x1A1FE +#define GL_NATIVE_GRAPHICS_HANDLE_PGI 0x1A202 +#define GL_NATIVE_GRAPHICS_BEGIN_HINT_PGI 0x1A203 +#define GL_NATIVE_GRAPHICS_END_HINT_PGI 0x1A204 +#define GL_ALWAYS_FAST_HINT_PGI 0x1A20C +#define GL_ALWAYS_SOFT_HINT_PGI 0x1A20D +#define GL_ALLOW_DRAW_OBJ_HINT_PGI 0x1A20E +#define GL_ALLOW_DRAW_WIN_HINT_PGI 0x1A20F +#define GL_ALLOW_DRAW_FRG_HINT_PGI 0x1A210 +#define GL_ALLOW_DRAW_MEM_HINT_PGI 0x1A211 +#define GL_STRICT_DEPTHFUNC_HINT_PGI 0x1A216 +#define GL_STRICT_LIGHTING_HINT_PGI 0x1A217 +#define GL_STRICT_SCISSOR_HINT_PGI 0x1A218 +#define GL_FULL_STIPPLE_HINT_PGI 0x1A219 +#define GL_CLIP_NEAR_HINT_PGI 0x1A220 +#define GL_CLIP_FAR_HINT_PGI 0x1A221 +#define GL_WIDE_LINE_HINT_PGI 0x1A222 +#define GL_BACK_NORMALS_HINT_PGI 0x1A223 +typedef void (APIENTRYP PFNGLHINTPGIPROC) (GLenum target, GLint mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glHintPGI (GLenum target, GLint mode); +#endif +#endif /* GL_PGI_misc_hints */ + +#ifndef GL_PGI_vertex_hints +#define GL_PGI_vertex_hints 1 +#define GL_VERTEX_DATA_HINT_PGI 0x1A22A +#define GL_VERTEX_CONSISTENT_HINT_PGI 0x1A22B +#define GL_MATERIAL_SIDE_HINT_PGI 0x1A22C +#define GL_MAX_VERTEX_HINT_PGI 0x1A22D +#define GL_COLOR3_BIT_PGI 0x00010000 +#define GL_COLOR4_BIT_PGI 0x00020000 +#define GL_EDGEFLAG_BIT_PGI 0x00040000 +#define GL_INDEX_BIT_PGI 0x00080000 +#define GL_MAT_AMBIENT_BIT_PGI 0x00100000 +#define GL_MAT_AMBIENT_AND_DIFFUSE_BIT_PGI 0x00200000 +#define GL_MAT_DIFFUSE_BIT_PGI 0x00400000 +#define GL_MAT_EMISSION_BIT_PGI 0x00800000 +#define GL_MAT_COLOR_INDEXES_BIT_PGI 0x01000000 +#define GL_MAT_SHININESS_BIT_PGI 0x02000000 +#define GL_MAT_SPECULAR_BIT_PGI 0x04000000 +#define GL_NORMAL_BIT_PGI 0x08000000 +#define GL_TEXCOORD1_BIT_PGI 0x10000000 +#define GL_TEXCOORD2_BIT_PGI 0x20000000 +#define GL_TEXCOORD3_BIT_PGI 0x40000000 +#define GL_TEXCOORD4_BIT_PGI 0x80000000 +#define GL_VERTEX23_BIT_PGI 0x00000004 +#define GL_VERTEX4_BIT_PGI 0x00000008 +#endif /* GL_PGI_vertex_hints */ + +#ifndef GL_REND_screen_coordinates +#define GL_REND_screen_coordinates 1 +#define GL_SCREEN_COORDINATES_REND 0x8490 +#define GL_INVERTED_SCREEN_W_REND 0x8491 +#endif /* GL_REND_screen_coordinates */ + +#ifndef GL_S3_s3tc +#define GL_S3_s3tc 1 +#define GL_RGB_S3TC 0x83A0 +#define GL_RGB4_S3TC 0x83A1 +#define GL_RGBA_S3TC 0x83A2 +#define GL_RGBA4_S3TC 0x83A3 +#define GL_RGBA_DXT5_S3TC 0x83A4 +#define GL_RGBA4_DXT5_S3TC 0x83A5 +#endif /* GL_S3_s3tc */ + +#ifndef GL_SGIS_detail_texture +#define GL_SGIS_detail_texture 1 +#define GL_DETAIL_TEXTURE_2D_SGIS 0x8095 +#define GL_DETAIL_TEXTURE_2D_BINDING_SGIS 0x8096 +#define GL_LINEAR_DETAIL_SGIS 0x8097 +#define GL_LINEAR_DETAIL_ALPHA_SGIS 0x8098 +#define GL_LINEAR_DETAIL_COLOR_SGIS 0x8099 +#define GL_DETAIL_TEXTURE_LEVEL_SGIS 0x809A +#define GL_DETAIL_TEXTURE_MODE_SGIS 0x809B +#define GL_DETAIL_TEXTURE_FUNC_POINTS_SGIS 0x809C +typedef void (APIENTRYP PFNGLDETAILTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points); +typedef void (APIENTRYP PFNGLGETDETAILTEXFUNCSGISPROC) (GLenum target, GLfloat *points); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDetailTexFuncSGIS (GLenum target, GLsizei n, const GLfloat *points); +GLAPI void APIENTRY glGetDetailTexFuncSGIS (GLenum target, GLfloat *points); +#endif +#endif /* GL_SGIS_detail_texture */ + +#ifndef GL_SGIS_fog_function +#define GL_SGIS_fog_function 1 +#define GL_FOG_FUNC_SGIS 0x812A +#define GL_FOG_FUNC_POINTS_SGIS 0x812B +#define GL_MAX_FOG_FUNC_POINTS_SGIS 0x812C +typedef void (APIENTRYP PFNGLFOGFUNCSGISPROC) (GLsizei n, const GLfloat *points); +typedef void (APIENTRYP PFNGLGETFOGFUNCSGISPROC) (GLfloat *points); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFogFuncSGIS (GLsizei n, const GLfloat *points); +GLAPI void APIENTRY glGetFogFuncSGIS (GLfloat *points); +#endif +#endif /* GL_SGIS_fog_function */ + +#ifndef GL_SGIS_generate_mipmap +#define GL_SGIS_generate_mipmap 1 +#define GL_GENERATE_MIPMAP_SGIS 0x8191 +#define GL_GENERATE_MIPMAP_HINT_SGIS 0x8192 +#endif /* GL_SGIS_generate_mipmap */ + +#ifndef GL_SGIS_multisample +#define GL_SGIS_multisample 1 +#define GL_MULTISAMPLE_SGIS 0x809D +#define GL_SAMPLE_ALPHA_TO_MASK_SGIS 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE_SGIS 0x809F +#define GL_SAMPLE_MASK_SGIS 0x80A0 +#define GL_1PASS_SGIS 0x80A1 +#define GL_2PASS_0_SGIS 0x80A2 +#define GL_2PASS_1_SGIS 0x80A3 +#define GL_4PASS_0_SGIS 0x80A4 +#define GL_4PASS_1_SGIS 0x80A5 +#define GL_4PASS_2_SGIS 0x80A6 +#define GL_4PASS_3_SGIS 0x80A7 +#define GL_SAMPLE_BUFFERS_SGIS 0x80A8 +#define GL_SAMPLES_SGIS 0x80A9 +#define GL_SAMPLE_MASK_VALUE_SGIS 0x80AA +#define GL_SAMPLE_MASK_INVERT_SGIS 0x80AB +#define GL_SAMPLE_PATTERN_SGIS 0x80AC +typedef void (APIENTRYP PFNGLSAMPLEMASKSGISPROC) (GLclampf value, GLboolean invert); +typedef void (APIENTRYP PFNGLSAMPLEPATTERNSGISPROC) (GLenum pattern); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSampleMaskSGIS (GLclampf value, GLboolean invert); +GLAPI void APIENTRY glSamplePatternSGIS (GLenum pattern); +#endif +#endif /* GL_SGIS_multisample */ + +#ifndef GL_SGIS_pixel_texture +#define GL_SGIS_pixel_texture 1 +#define GL_PIXEL_TEXTURE_SGIS 0x8353 +#define GL_PIXEL_FRAGMENT_RGB_SOURCE_SGIS 0x8354 +#define GL_PIXEL_FRAGMENT_ALPHA_SOURCE_SGIS 0x8355 +#define GL_PIXEL_GROUP_COLOR_SGIS 0x8356 +typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERISGISPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFSGISPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPixelTexGenParameteriSGIS (GLenum pname, GLint param); +GLAPI void APIENTRY glPixelTexGenParameterivSGIS (GLenum pname, const GLint *params); +GLAPI void APIENTRY glPixelTexGenParameterfSGIS (GLenum pname, GLfloat param); +GLAPI void APIENTRY glPixelTexGenParameterfvSGIS (GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glGetPixelTexGenParameterivSGIS (GLenum pname, GLint *params); +GLAPI void APIENTRY glGetPixelTexGenParameterfvSGIS (GLenum pname, GLfloat *params); +#endif +#endif /* GL_SGIS_pixel_texture */ + +#ifndef GL_SGIS_point_line_texgen +#define GL_SGIS_point_line_texgen 1 +#define GL_EYE_DISTANCE_TO_POINT_SGIS 0x81F0 +#define GL_OBJECT_DISTANCE_TO_POINT_SGIS 0x81F1 +#define GL_EYE_DISTANCE_TO_LINE_SGIS 0x81F2 +#define GL_OBJECT_DISTANCE_TO_LINE_SGIS 0x81F3 +#define GL_EYE_POINT_SGIS 0x81F4 +#define GL_OBJECT_POINT_SGIS 0x81F5 +#define GL_EYE_LINE_SGIS 0x81F6 +#define GL_OBJECT_LINE_SGIS 0x81F7 +#endif /* GL_SGIS_point_line_texgen */ + +#ifndef GL_SGIS_point_parameters +#define GL_SGIS_point_parameters 1 +#define GL_POINT_SIZE_MIN_SGIS 0x8126 +#define GL_POINT_SIZE_MAX_SGIS 0x8127 +#define GL_POINT_FADE_THRESHOLD_SIZE_SGIS 0x8128 +#define GL_DISTANCE_ATTENUATION_SGIS 0x8129 +typedef void (APIENTRYP PFNGLPOINTPARAMETERFSGISPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPointParameterfSGIS (GLenum pname, GLfloat param); +GLAPI void APIENTRY glPointParameterfvSGIS (GLenum pname, const GLfloat *params); +#endif +#endif /* GL_SGIS_point_parameters */ + +#ifndef GL_SGIS_sharpen_texture +#define GL_SGIS_sharpen_texture 1 +#define GL_LINEAR_SHARPEN_SGIS 0x80AD +#define GL_LINEAR_SHARPEN_ALPHA_SGIS 0x80AE +#define GL_LINEAR_SHARPEN_COLOR_SGIS 0x80AF +#define GL_SHARPEN_TEXTURE_FUNC_POINTS_SGIS 0x80B0 +typedef void (APIENTRYP PFNGLSHARPENTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points); +typedef void (APIENTRYP PFNGLGETSHARPENTEXFUNCSGISPROC) (GLenum target, GLfloat *points); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSharpenTexFuncSGIS (GLenum target, GLsizei n, const GLfloat *points); +GLAPI void APIENTRY glGetSharpenTexFuncSGIS (GLenum target, GLfloat *points); +#endif +#endif /* GL_SGIS_sharpen_texture */ + +#ifndef GL_SGIS_texture4D +#define GL_SGIS_texture4D 1 +#define GL_PACK_SKIP_VOLUMES_SGIS 0x8130 +#define GL_PACK_IMAGE_DEPTH_SGIS 0x8131 +#define GL_UNPACK_SKIP_VOLUMES_SGIS 0x8132 +#define GL_UNPACK_IMAGE_DEPTH_SGIS 0x8133 +#define GL_TEXTURE_4D_SGIS 0x8134 +#define GL_PROXY_TEXTURE_4D_SGIS 0x8135 +#define GL_TEXTURE_4DSIZE_SGIS 0x8136 +#define GL_TEXTURE_WRAP_Q_SGIS 0x8137 +#define GL_MAX_4D_TEXTURE_SIZE_SGIS 0x8138 +#define GL_TEXTURE_4D_BINDING_SGIS 0x814F +typedef void (APIENTRYP PFNGLTEXIMAGE4DSGISPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE4DSGISPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint woffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLenum format, GLenum type, const void *pixels); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexImage4DSGIS (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTexSubImage4DSGIS (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint woffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLenum format, GLenum type, const void *pixels); +#endif +#endif /* GL_SGIS_texture4D */ + +#ifndef GL_SGIS_texture_border_clamp +#define GL_SGIS_texture_border_clamp 1 +#define GL_CLAMP_TO_BORDER_SGIS 0x812D +#endif /* GL_SGIS_texture_border_clamp */ + +#ifndef GL_SGIS_texture_color_mask +#define GL_SGIS_texture_color_mask 1 +#define GL_TEXTURE_COLOR_WRITEMASK_SGIS 0x81EF +typedef void (APIENTRYP PFNGLTEXTURECOLORMASKSGISPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTextureColorMaskSGIS (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); +#endif +#endif /* GL_SGIS_texture_color_mask */ + +#ifndef GL_SGIS_texture_edge_clamp +#define GL_SGIS_texture_edge_clamp 1 +#define GL_CLAMP_TO_EDGE_SGIS 0x812F +#endif /* GL_SGIS_texture_edge_clamp */ + +#ifndef GL_SGIS_texture_filter4 +#define GL_SGIS_texture_filter4 1 +#define GL_FILTER4_SGIS 0x8146 +#define GL_TEXTURE_FILTER4_SIZE_SGIS 0x8147 +typedef void (APIENTRYP PFNGLGETTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLfloat *weights); +typedef void (APIENTRYP PFNGLTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetTexFilterFuncSGIS (GLenum target, GLenum filter, GLfloat *weights); +GLAPI void APIENTRY glTexFilterFuncSGIS (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights); +#endif +#endif /* GL_SGIS_texture_filter4 */ + +#ifndef GL_SGIS_texture_lod +#define GL_SGIS_texture_lod 1 +#define GL_TEXTURE_MIN_LOD_SGIS 0x813A +#define GL_TEXTURE_MAX_LOD_SGIS 0x813B +#define GL_TEXTURE_BASE_LEVEL_SGIS 0x813C +#define GL_TEXTURE_MAX_LEVEL_SGIS 0x813D +#endif /* GL_SGIS_texture_lod */ + +#ifndef GL_SGIS_texture_select +#define GL_SGIS_texture_select 1 +#define GL_DUAL_ALPHA4_SGIS 0x8110 +#define GL_DUAL_ALPHA8_SGIS 0x8111 +#define GL_DUAL_ALPHA12_SGIS 0x8112 +#define GL_DUAL_ALPHA16_SGIS 0x8113 +#define GL_DUAL_LUMINANCE4_SGIS 0x8114 +#define GL_DUAL_LUMINANCE8_SGIS 0x8115 +#define GL_DUAL_LUMINANCE12_SGIS 0x8116 +#define GL_DUAL_LUMINANCE16_SGIS 0x8117 +#define GL_DUAL_INTENSITY4_SGIS 0x8118 +#define GL_DUAL_INTENSITY8_SGIS 0x8119 +#define GL_DUAL_INTENSITY12_SGIS 0x811A +#define GL_DUAL_INTENSITY16_SGIS 0x811B +#define GL_DUAL_LUMINANCE_ALPHA4_SGIS 0x811C +#define GL_DUAL_LUMINANCE_ALPHA8_SGIS 0x811D +#define GL_QUAD_ALPHA4_SGIS 0x811E +#define GL_QUAD_ALPHA8_SGIS 0x811F +#define GL_QUAD_LUMINANCE4_SGIS 0x8120 +#define GL_QUAD_LUMINANCE8_SGIS 0x8121 +#define GL_QUAD_INTENSITY4_SGIS 0x8122 +#define GL_QUAD_INTENSITY8_SGIS 0x8123 +#define GL_DUAL_TEXTURE_SELECT_SGIS 0x8124 +#define GL_QUAD_TEXTURE_SELECT_SGIS 0x8125 +#endif /* GL_SGIS_texture_select */ + +#ifndef GL_SGIX_async +#define GL_SGIX_async 1 +#define GL_ASYNC_MARKER_SGIX 0x8329 +typedef void (APIENTRYP PFNGLASYNCMARKERSGIXPROC) (GLuint marker); +typedef GLint (APIENTRYP PFNGLFINISHASYNCSGIXPROC) (GLuint *markerp); +typedef GLint (APIENTRYP PFNGLPOLLASYNCSGIXPROC) (GLuint *markerp); +typedef GLuint (APIENTRYP PFNGLGENASYNCMARKERSSGIXPROC) (GLsizei range); +typedef void (APIENTRYP PFNGLDELETEASYNCMARKERSSGIXPROC) (GLuint marker, GLsizei range); +typedef GLboolean (APIENTRYP PFNGLISASYNCMARKERSGIXPROC) (GLuint marker); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glAsyncMarkerSGIX (GLuint marker); +GLAPI GLint APIENTRY glFinishAsyncSGIX (GLuint *markerp); +GLAPI GLint APIENTRY glPollAsyncSGIX (GLuint *markerp); +GLAPI GLuint APIENTRY glGenAsyncMarkersSGIX (GLsizei range); +GLAPI void APIENTRY glDeleteAsyncMarkersSGIX (GLuint marker, GLsizei range); +GLAPI GLboolean APIENTRY glIsAsyncMarkerSGIX (GLuint marker); +#endif +#endif /* GL_SGIX_async */ + +#ifndef GL_SGIX_async_histogram +#define GL_SGIX_async_histogram 1 +#define GL_ASYNC_HISTOGRAM_SGIX 0x832C +#define GL_MAX_ASYNC_HISTOGRAM_SGIX 0x832D +#endif /* GL_SGIX_async_histogram */ + +#ifndef GL_SGIX_async_pixel +#define GL_SGIX_async_pixel 1 +#define GL_ASYNC_TEX_IMAGE_SGIX 0x835C +#define GL_ASYNC_DRAW_PIXELS_SGIX 0x835D +#define GL_ASYNC_READ_PIXELS_SGIX 0x835E +#define GL_MAX_ASYNC_TEX_IMAGE_SGIX 0x835F +#define GL_MAX_ASYNC_DRAW_PIXELS_SGIX 0x8360 +#define GL_MAX_ASYNC_READ_PIXELS_SGIX 0x8361 +#endif /* GL_SGIX_async_pixel */ + +#ifndef GL_SGIX_blend_alpha_minmax +#define GL_SGIX_blend_alpha_minmax 1 +#define GL_ALPHA_MIN_SGIX 0x8320 +#define GL_ALPHA_MAX_SGIX 0x8321 +#endif /* GL_SGIX_blend_alpha_minmax */ + +#ifndef GL_SGIX_calligraphic_fragment +#define GL_SGIX_calligraphic_fragment 1 +#define GL_CALLIGRAPHIC_FRAGMENT_SGIX 0x8183 +#endif /* GL_SGIX_calligraphic_fragment */ + +#ifndef GL_SGIX_clipmap +#define GL_SGIX_clipmap 1 +#define GL_LINEAR_CLIPMAP_LINEAR_SGIX 0x8170 +#define GL_TEXTURE_CLIPMAP_CENTER_SGIX 0x8171 +#define GL_TEXTURE_CLIPMAP_FRAME_SGIX 0x8172 +#define GL_TEXTURE_CLIPMAP_OFFSET_SGIX 0x8173 +#define GL_TEXTURE_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8174 +#define GL_TEXTURE_CLIPMAP_LOD_OFFSET_SGIX 0x8175 +#define GL_TEXTURE_CLIPMAP_DEPTH_SGIX 0x8176 +#define GL_MAX_CLIPMAP_DEPTH_SGIX 0x8177 +#define GL_MAX_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8178 +#define GL_NEAREST_CLIPMAP_NEAREST_SGIX 0x844D +#define GL_NEAREST_CLIPMAP_LINEAR_SGIX 0x844E +#define GL_LINEAR_CLIPMAP_NEAREST_SGIX 0x844F +#endif /* GL_SGIX_clipmap */ + +#ifndef GL_SGIX_convolution_accuracy +#define GL_SGIX_convolution_accuracy 1 +#define GL_CONVOLUTION_HINT_SGIX 0x8316 +#endif /* GL_SGIX_convolution_accuracy */ + +#ifndef GL_SGIX_depth_pass_instrument +#define GL_SGIX_depth_pass_instrument 1 +#endif /* GL_SGIX_depth_pass_instrument */ + +#ifndef GL_SGIX_depth_texture +#define GL_SGIX_depth_texture 1 +#define GL_DEPTH_COMPONENT16_SGIX 0x81A5 +#define GL_DEPTH_COMPONENT24_SGIX 0x81A6 +#define GL_DEPTH_COMPONENT32_SGIX 0x81A7 +#endif /* GL_SGIX_depth_texture */ + +#ifndef GL_SGIX_flush_raster +#define GL_SGIX_flush_raster 1 +typedef void (APIENTRYP PFNGLFLUSHRASTERSGIXPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFlushRasterSGIX (void); +#endif +#endif /* GL_SGIX_flush_raster */ + +#ifndef GL_SGIX_fog_offset +#define GL_SGIX_fog_offset 1 +#define GL_FOG_OFFSET_SGIX 0x8198 +#define GL_FOG_OFFSET_VALUE_SGIX 0x8199 +#endif /* GL_SGIX_fog_offset */ + +#ifndef GL_SGIX_fragment_lighting +#define GL_SGIX_fragment_lighting 1 +#define GL_FRAGMENT_LIGHTING_SGIX 0x8400 +#define GL_FRAGMENT_COLOR_MATERIAL_SGIX 0x8401 +#define GL_FRAGMENT_COLOR_MATERIAL_FACE_SGIX 0x8402 +#define GL_FRAGMENT_COLOR_MATERIAL_PARAMETER_SGIX 0x8403 +#define GL_MAX_FRAGMENT_LIGHTS_SGIX 0x8404 +#define GL_MAX_ACTIVE_LIGHTS_SGIX 0x8405 +#define GL_CURRENT_RASTER_NORMAL_SGIX 0x8406 +#define GL_LIGHT_ENV_MODE_SGIX 0x8407 +#define GL_FRAGMENT_LIGHT_MODEL_LOCAL_VIEWER_SGIX 0x8408 +#define GL_FRAGMENT_LIGHT_MODEL_TWO_SIDE_SGIX 0x8409 +#define GL_FRAGMENT_LIGHT_MODEL_AMBIENT_SGIX 0x840A +#define GL_FRAGMENT_LIGHT_MODEL_NORMAL_INTERPOLATION_SGIX 0x840B +#define GL_FRAGMENT_LIGHT0_SGIX 0x840C +#define GL_FRAGMENT_LIGHT1_SGIX 0x840D +#define GL_FRAGMENT_LIGHT2_SGIX 0x840E +#define GL_FRAGMENT_LIGHT3_SGIX 0x840F +#define GL_FRAGMENT_LIGHT4_SGIX 0x8410 +#define GL_FRAGMENT_LIGHT5_SGIX 0x8411 +#define GL_FRAGMENT_LIGHT6_SGIX 0x8412 +#define GL_FRAGMENT_LIGHT7_SGIX 0x8413 +typedef void (APIENTRYP PFNGLFRAGMENTCOLORMATERIALSGIXPROC) (GLenum face, GLenum mode); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFSGIXPROC) (GLenum light, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTISGIXPROC) (GLenum light, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFSGIXPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFVSGIXPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELISGIXPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELIVSGIXPROC) (GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFSGIXPROC) (GLenum face, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLFRAGMENTMATERIALISGIXPROC) (GLenum face, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLLIGHTENVISGIXPROC) (GLenum pname, GLint param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFragmentColorMaterialSGIX (GLenum face, GLenum mode); +GLAPI void APIENTRY glFragmentLightfSGIX (GLenum light, GLenum pname, GLfloat param); +GLAPI void APIENTRY glFragmentLightfvSGIX (GLenum light, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glFragmentLightiSGIX (GLenum light, GLenum pname, GLint param); +GLAPI void APIENTRY glFragmentLightivSGIX (GLenum light, GLenum pname, const GLint *params); +GLAPI void APIENTRY glFragmentLightModelfSGIX (GLenum pname, GLfloat param); +GLAPI void APIENTRY glFragmentLightModelfvSGIX (GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glFragmentLightModeliSGIX (GLenum pname, GLint param); +GLAPI void APIENTRY glFragmentLightModelivSGIX (GLenum pname, const GLint *params); +GLAPI void APIENTRY glFragmentMaterialfSGIX (GLenum face, GLenum pname, GLfloat param); +GLAPI void APIENTRY glFragmentMaterialfvSGIX (GLenum face, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glFragmentMaterialiSGIX (GLenum face, GLenum pname, GLint param); +GLAPI void APIENTRY glFragmentMaterialivSGIX (GLenum face, GLenum pname, const GLint *params); +GLAPI void APIENTRY glGetFragmentLightfvSGIX (GLenum light, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetFragmentLightivSGIX (GLenum light, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetFragmentMaterialfvSGIX (GLenum face, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetFragmentMaterialivSGIX (GLenum face, GLenum pname, GLint *params); +GLAPI void APIENTRY glLightEnviSGIX (GLenum pname, GLint param); +#endif +#endif /* GL_SGIX_fragment_lighting */ + +#ifndef GL_SGIX_framezoom +#define GL_SGIX_framezoom 1 +#define GL_FRAMEZOOM_SGIX 0x818B +#define GL_FRAMEZOOM_FACTOR_SGIX 0x818C +#define GL_MAX_FRAMEZOOM_FACTOR_SGIX 0x818D +typedef void (APIENTRYP PFNGLFRAMEZOOMSGIXPROC) (GLint factor); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFrameZoomSGIX (GLint factor); +#endif +#endif /* GL_SGIX_framezoom */ + +#ifndef GL_SGIX_igloo_interface +#define GL_SGIX_igloo_interface 1 +typedef void (APIENTRYP PFNGLIGLOOINTERFACESGIXPROC) (GLenum pname, const void *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glIglooInterfaceSGIX (GLenum pname, const void *params); +#endif +#endif /* GL_SGIX_igloo_interface */ + +#ifndef GL_SGIX_instruments +#define GL_SGIX_instruments 1 +#define GL_INSTRUMENT_BUFFER_POINTER_SGIX 0x8180 +#define GL_INSTRUMENT_MEASUREMENTS_SGIX 0x8181 +typedef GLint (APIENTRYP PFNGLGETINSTRUMENTSSGIXPROC) (void); +typedef void (APIENTRYP PFNGLINSTRUMENTSBUFFERSGIXPROC) (GLsizei size, GLint *buffer); +typedef GLint (APIENTRYP PFNGLPOLLINSTRUMENTSSGIXPROC) (GLint *marker_p); +typedef void (APIENTRYP PFNGLREADINSTRUMENTSSGIXPROC) (GLint marker); +typedef void (APIENTRYP PFNGLSTARTINSTRUMENTSSGIXPROC) (void); +typedef void (APIENTRYP PFNGLSTOPINSTRUMENTSSGIXPROC) (GLint marker); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLint APIENTRY glGetInstrumentsSGIX (void); +GLAPI void APIENTRY glInstrumentsBufferSGIX (GLsizei size, GLint *buffer); +GLAPI GLint APIENTRY glPollInstrumentsSGIX (GLint *marker_p); +GLAPI void APIENTRY glReadInstrumentsSGIX (GLint marker); +GLAPI void APIENTRY glStartInstrumentsSGIX (void); +GLAPI void APIENTRY glStopInstrumentsSGIX (GLint marker); +#endif +#endif /* GL_SGIX_instruments */ + +#ifndef GL_SGIX_interlace +#define GL_SGIX_interlace 1 +#define GL_INTERLACE_SGIX 0x8094 +#endif /* GL_SGIX_interlace */ + +#ifndef GL_SGIX_ir_instrument1 +#define GL_SGIX_ir_instrument1 1 +#define GL_IR_INSTRUMENT1_SGIX 0x817F +#endif /* GL_SGIX_ir_instrument1 */ + +#ifndef GL_SGIX_list_priority +#define GL_SGIX_list_priority 1 +#define GL_LIST_PRIORITY_SGIX 0x8182 +typedef void (APIENTRYP PFNGLGETLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLLISTPARAMETERFSGIXPROC) (GLuint list, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLLISTPARAMETERISGIXPROC) (GLuint list, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, const GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetListParameterfvSGIX (GLuint list, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetListParameterivSGIX (GLuint list, GLenum pname, GLint *params); +GLAPI void APIENTRY glListParameterfSGIX (GLuint list, GLenum pname, GLfloat param); +GLAPI void APIENTRY glListParameterfvSGIX (GLuint list, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glListParameteriSGIX (GLuint list, GLenum pname, GLint param); +GLAPI void APIENTRY glListParameterivSGIX (GLuint list, GLenum pname, const GLint *params); +#endif +#endif /* GL_SGIX_list_priority */ + +#ifndef GL_SGIX_pixel_texture +#define GL_SGIX_pixel_texture 1 +#define GL_PIXEL_TEX_GEN_SGIX 0x8139 +#define GL_PIXEL_TEX_GEN_MODE_SGIX 0x832B +typedef void (APIENTRYP PFNGLPIXELTEXGENSGIXPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPixelTexGenSGIX (GLenum mode); +#endif +#endif /* GL_SGIX_pixel_texture */ + +#ifndef GL_SGIX_pixel_tiles +#define GL_SGIX_pixel_tiles 1 +#define GL_PIXEL_TILE_BEST_ALIGNMENT_SGIX 0x813E +#define GL_PIXEL_TILE_CACHE_INCREMENT_SGIX 0x813F +#define GL_PIXEL_TILE_WIDTH_SGIX 0x8140 +#define GL_PIXEL_TILE_HEIGHT_SGIX 0x8141 +#define GL_PIXEL_TILE_GRID_WIDTH_SGIX 0x8142 +#define GL_PIXEL_TILE_GRID_HEIGHT_SGIX 0x8143 +#define GL_PIXEL_TILE_GRID_DEPTH_SGIX 0x8144 +#define GL_PIXEL_TILE_CACHE_SIZE_SGIX 0x8145 +#endif /* GL_SGIX_pixel_tiles */ + +#ifndef GL_SGIX_polynomial_ffd +#define GL_SGIX_polynomial_ffd 1 +#define GL_TEXTURE_DEFORMATION_BIT_SGIX 0x00000001 +#define GL_GEOMETRY_DEFORMATION_BIT_SGIX 0x00000002 +#define GL_GEOMETRY_DEFORMATION_SGIX 0x8194 +#define GL_TEXTURE_DEFORMATION_SGIX 0x8195 +#define GL_DEFORMATIONS_MASK_SGIX 0x8196 +#define GL_MAX_DEFORMATION_ORDER_SGIX 0x8197 +typedef void (APIENTRYP PFNGLDEFORMATIONMAP3DSGIXPROC) (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble *points); +typedef void (APIENTRYP PFNGLDEFORMATIONMAP3FSGIXPROC) (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat *points); +typedef void (APIENTRYP PFNGLDEFORMSGIXPROC) (GLbitfield mask); +typedef void (APIENTRYP PFNGLLOADIDENTITYDEFORMATIONMAPSGIXPROC) (GLbitfield mask); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDeformationMap3dSGIX (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble *points); +GLAPI void APIENTRY glDeformationMap3fSGIX (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat *points); +GLAPI void APIENTRY glDeformSGIX (GLbitfield mask); +GLAPI void APIENTRY glLoadIdentityDeformationMapSGIX (GLbitfield mask); +#endif +#endif /* GL_SGIX_polynomial_ffd */ + +#ifndef GL_SGIX_reference_plane +#define GL_SGIX_reference_plane 1 +#define GL_REFERENCE_PLANE_SGIX 0x817D +#define GL_REFERENCE_PLANE_EQUATION_SGIX 0x817E +typedef void (APIENTRYP PFNGLREFERENCEPLANESGIXPROC) (const GLdouble *equation); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glReferencePlaneSGIX (const GLdouble *equation); +#endif +#endif /* GL_SGIX_reference_plane */ + +#ifndef GL_SGIX_resample +#define GL_SGIX_resample 1 +#define GL_PACK_RESAMPLE_SGIX 0x842E +#define GL_UNPACK_RESAMPLE_SGIX 0x842F +#define GL_RESAMPLE_REPLICATE_SGIX 0x8433 +#define GL_RESAMPLE_ZERO_FILL_SGIX 0x8434 +#define GL_RESAMPLE_DECIMATE_SGIX 0x8430 +#endif /* GL_SGIX_resample */ + +#ifndef GL_SGIX_scalebias_hint +#define GL_SGIX_scalebias_hint 1 +#define GL_SCALEBIAS_HINT_SGIX 0x8322 +#endif /* GL_SGIX_scalebias_hint */ + +#ifndef GL_SGIX_shadow +#define GL_SGIX_shadow 1 +#define GL_TEXTURE_COMPARE_SGIX 0x819A +#define GL_TEXTURE_COMPARE_OPERATOR_SGIX 0x819B +#define GL_TEXTURE_LEQUAL_R_SGIX 0x819C +#define GL_TEXTURE_GEQUAL_R_SGIX 0x819D +#endif /* GL_SGIX_shadow */ + +#ifndef GL_SGIX_shadow_ambient +#define GL_SGIX_shadow_ambient 1 +#define GL_SHADOW_AMBIENT_SGIX 0x80BF +#endif /* GL_SGIX_shadow_ambient */ + +#ifndef GL_SGIX_sprite +#define GL_SGIX_sprite 1 +#define GL_SPRITE_SGIX 0x8148 +#define GL_SPRITE_MODE_SGIX 0x8149 +#define GL_SPRITE_AXIS_SGIX 0x814A +#define GL_SPRITE_TRANSLATION_SGIX 0x814B +#define GL_SPRITE_AXIAL_SGIX 0x814C +#define GL_SPRITE_OBJECT_ALIGNED_SGIX 0x814D +#define GL_SPRITE_EYE_ALIGNED_SGIX 0x814E +typedef void (APIENTRYP PFNGLSPRITEPARAMETERFSGIXPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLSPRITEPARAMETERFVSGIXPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLSPRITEPARAMETERISGIXPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLSPRITEPARAMETERIVSGIXPROC) (GLenum pname, const GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSpriteParameterfSGIX (GLenum pname, GLfloat param); +GLAPI void APIENTRY glSpriteParameterfvSGIX (GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glSpriteParameteriSGIX (GLenum pname, GLint param); +GLAPI void APIENTRY glSpriteParameterivSGIX (GLenum pname, const GLint *params); +#endif +#endif /* GL_SGIX_sprite */ + +#ifndef GL_SGIX_subsample +#define GL_SGIX_subsample 1 +#define GL_PACK_SUBSAMPLE_RATE_SGIX 0x85A0 +#define GL_UNPACK_SUBSAMPLE_RATE_SGIX 0x85A1 +#define GL_PIXEL_SUBSAMPLE_4444_SGIX 0x85A2 +#define GL_PIXEL_SUBSAMPLE_2424_SGIX 0x85A3 +#define GL_PIXEL_SUBSAMPLE_4242_SGIX 0x85A4 +#endif /* GL_SGIX_subsample */ + +#ifndef GL_SGIX_tag_sample_buffer +#define GL_SGIX_tag_sample_buffer 1 +typedef void (APIENTRYP PFNGLTAGSAMPLEBUFFERSGIXPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTagSampleBufferSGIX (void); +#endif +#endif /* GL_SGIX_tag_sample_buffer */ + +#ifndef GL_SGIX_texture_add_env +#define GL_SGIX_texture_add_env 1 +#define GL_TEXTURE_ENV_BIAS_SGIX 0x80BE +#endif /* GL_SGIX_texture_add_env */ + +#ifndef GL_SGIX_texture_coordinate_clamp +#define GL_SGIX_texture_coordinate_clamp 1 +#define GL_TEXTURE_MAX_CLAMP_S_SGIX 0x8369 +#define GL_TEXTURE_MAX_CLAMP_T_SGIX 0x836A +#define GL_TEXTURE_MAX_CLAMP_R_SGIX 0x836B +#endif /* GL_SGIX_texture_coordinate_clamp */ + +#ifndef GL_SGIX_texture_lod_bias +#define GL_SGIX_texture_lod_bias 1 +#define GL_TEXTURE_LOD_BIAS_S_SGIX 0x818E +#define GL_TEXTURE_LOD_BIAS_T_SGIX 0x818F +#define GL_TEXTURE_LOD_BIAS_R_SGIX 0x8190 +#endif /* GL_SGIX_texture_lod_bias */ + +#ifndef GL_SGIX_texture_multi_buffer +#define GL_SGIX_texture_multi_buffer 1 +#define GL_TEXTURE_MULTI_BUFFER_HINT_SGIX 0x812E +#endif /* GL_SGIX_texture_multi_buffer */ + +#ifndef GL_SGIX_texture_scale_bias +#define GL_SGIX_texture_scale_bias 1 +#define GL_POST_TEXTURE_FILTER_BIAS_SGIX 0x8179 +#define GL_POST_TEXTURE_FILTER_SCALE_SGIX 0x817A +#define GL_POST_TEXTURE_FILTER_BIAS_RANGE_SGIX 0x817B +#define GL_POST_TEXTURE_FILTER_SCALE_RANGE_SGIX 0x817C +#endif /* GL_SGIX_texture_scale_bias */ + +#ifndef GL_SGIX_vertex_preclip +#define GL_SGIX_vertex_preclip 1 +#define GL_VERTEX_PRECLIP_SGIX 0x83EE +#define GL_VERTEX_PRECLIP_HINT_SGIX 0x83EF +#endif /* GL_SGIX_vertex_preclip */ + +#ifndef GL_SGIX_ycrcb +#define GL_SGIX_ycrcb 1 +#define GL_YCRCB_422_SGIX 0x81BB +#define GL_YCRCB_444_SGIX 0x81BC +#endif /* GL_SGIX_ycrcb */ + +#ifndef GL_SGIX_ycrcb_subsample +#define GL_SGIX_ycrcb_subsample 1 +#endif /* GL_SGIX_ycrcb_subsample */ + +#ifndef GL_SGIX_ycrcba +#define GL_SGIX_ycrcba 1 +#define GL_YCRCB_SGIX 0x8318 +#define GL_YCRCBA_SGIX 0x8319 +#endif /* GL_SGIX_ycrcba */ + +#ifndef GL_SGI_color_matrix +#define GL_SGI_color_matrix 1 +#define GL_COLOR_MATRIX_SGI 0x80B1 +#define GL_COLOR_MATRIX_STACK_DEPTH_SGI 0x80B2 +#define GL_MAX_COLOR_MATRIX_STACK_DEPTH_SGI 0x80B3 +#define GL_POST_COLOR_MATRIX_RED_SCALE_SGI 0x80B4 +#define GL_POST_COLOR_MATRIX_GREEN_SCALE_SGI 0x80B5 +#define GL_POST_COLOR_MATRIX_BLUE_SCALE_SGI 0x80B6 +#define GL_POST_COLOR_MATRIX_ALPHA_SCALE_SGI 0x80B7 +#define GL_POST_COLOR_MATRIX_RED_BIAS_SGI 0x80B8 +#define GL_POST_COLOR_MATRIX_GREEN_BIAS_SGI 0x80B9 +#define GL_POST_COLOR_MATRIX_BLUE_BIAS_SGI 0x80BA +#define GL_POST_COLOR_MATRIX_ALPHA_BIAS_SGI 0x80BB +#endif /* GL_SGI_color_matrix */ + +#ifndef GL_SGI_color_table +#define GL_SGI_color_table 1 +#define GL_COLOR_TABLE_SGI 0x80D0 +#define GL_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D1 +#define GL_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D2 +#define GL_PROXY_COLOR_TABLE_SGI 0x80D3 +#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D4 +#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D5 +#define GL_COLOR_TABLE_SCALE_SGI 0x80D6 +#define GL_COLOR_TABLE_BIAS_SGI 0x80D7 +#define GL_COLOR_TABLE_FORMAT_SGI 0x80D8 +#define GL_COLOR_TABLE_WIDTH_SGI 0x80D9 +#define GL_COLOR_TABLE_RED_SIZE_SGI 0x80DA +#define GL_COLOR_TABLE_GREEN_SIZE_SGI 0x80DB +#define GL_COLOR_TABLE_BLUE_SIZE_SGI 0x80DC +#define GL_COLOR_TABLE_ALPHA_SIZE_SGI 0x80DD +#define GL_COLOR_TABLE_LUMINANCE_SIZE_SGI 0x80DE +#define GL_COLOR_TABLE_INTENSITY_SIZE_SGI 0x80DF +typedef void (APIENTRYP PFNGLCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *table); +typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOPYCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLGETCOLORTABLESGIPROC) (GLenum target, GLenum format, GLenum type, void *table); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorTableSGI (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *table); +GLAPI void APIENTRY glColorTableParameterfvSGI (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glColorTableParameterivSGI (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glCopyColorTableSGI (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glGetColorTableSGI (GLenum target, GLenum format, GLenum type, void *table); +GLAPI void APIENTRY glGetColorTableParameterfvSGI (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetColorTableParameterivSGI (GLenum target, GLenum pname, GLint *params); +#endif +#endif /* GL_SGI_color_table */ + +#ifndef GL_SGI_texture_color_table +#define GL_SGI_texture_color_table 1 +#define GL_TEXTURE_COLOR_TABLE_SGI 0x80BC +#define GL_PROXY_TEXTURE_COLOR_TABLE_SGI 0x80BD +#endif /* GL_SGI_texture_color_table */ + +#ifndef GL_SUNX_constant_data +#define GL_SUNX_constant_data 1 +#define GL_UNPACK_CONSTANT_DATA_SUNX 0x81D5 +#define GL_TEXTURE_CONSTANT_DATA_SUNX 0x81D6 +typedef void (APIENTRYP PFNGLFINISHTEXTURESUNXPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFinishTextureSUNX (void); +#endif +#endif /* GL_SUNX_constant_data */ + +#ifndef GL_SUN_convolution_border_modes +#define GL_SUN_convolution_border_modes 1 +#define GL_WRAP_BORDER_SUN 0x81D4 +#endif /* GL_SUN_convolution_border_modes */ + +#ifndef GL_SUN_global_alpha +#define GL_SUN_global_alpha 1 +#define GL_GLOBAL_ALPHA_SUN 0x81D9 +#define GL_GLOBAL_ALPHA_FACTOR_SUN 0x81DA +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORBSUNPROC) (GLbyte factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORSSUNPROC) (GLshort factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORISUNPROC) (GLint factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORFSUNPROC) (GLfloat factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORDSUNPROC) (GLdouble factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUBSUNPROC) (GLubyte factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUSSUNPROC) (GLushort factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUISUNPROC) (GLuint factor); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGlobalAlphaFactorbSUN (GLbyte factor); +GLAPI void APIENTRY glGlobalAlphaFactorsSUN (GLshort factor); +GLAPI void APIENTRY glGlobalAlphaFactoriSUN (GLint factor); +GLAPI void APIENTRY glGlobalAlphaFactorfSUN (GLfloat factor); +GLAPI void APIENTRY glGlobalAlphaFactordSUN (GLdouble factor); +GLAPI void APIENTRY glGlobalAlphaFactorubSUN (GLubyte factor); +GLAPI void APIENTRY glGlobalAlphaFactorusSUN (GLushort factor); +GLAPI void APIENTRY glGlobalAlphaFactoruiSUN (GLuint factor); +#endif +#endif /* GL_SUN_global_alpha */ + +#ifndef GL_SUN_mesh_array +#define GL_SUN_mesh_array 1 +#define GL_QUAD_MESH_SUN 0x8614 +#define GL_TRIANGLE_MESH_SUN 0x8615 +typedef void (APIENTRYP PFNGLDRAWMESHARRAYSSUNPROC) (GLenum mode, GLint first, GLsizei count, GLsizei width); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawMeshArraysSUN (GLenum mode, GLint first, GLsizei count, GLsizei width); +#endif +#endif /* GL_SUN_mesh_array */ + +#ifndef GL_SUN_slice_accum +#define GL_SUN_slice_accum 1 +#define GL_SLICE_ACCUM_SUN 0x85CC +#endif /* GL_SUN_slice_accum */ + +#ifndef GL_SUN_triangle_list +#define GL_SUN_triangle_list 1 +#define GL_RESTART_SUN 0x0001 +#define GL_REPLACE_MIDDLE_SUN 0x0002 +#define GL_REPLACE_OLDEST_SUN 0x0003 +#define GL_TRIANGLE_LIST_SUN 0x81D7 +#define GL_REPLACEMENT_CODE_SUN 0x81D8 +#define GL_REPLACEMENT_CODE_ARRAY_SUN 0x85C0 +#define GL_REPLACEMENT_CODE_ARRAY_TYPE_SUN 0x85C1 +#define GL_REPLACEMENT_CODE_ARRAY_STRIDE_SUN 0x85C2 +#define GL_REPLACEMENT_CODE_ARRAY_POINTER_SUN 0x85C3 +#define GL_R1UI_V3F_SUN 0x85C4 +#define GL_R1UI_C4UB_V3F_SUN 0x85C5 +#define GL_R1UI_C3F_V3F_SUN 0x85C6 +#define GL_R1UI_N3F_V3F_SUN 0x85C7 +#define GL_R1UI_C4F_N3F_V3F_SUN 0x85C8 +#define GL_R1UI_T2F_V3F_SUN 0x85C9 +#define GL_R1UI_T2F_N3F_V3F_SUN 0x85CA +#define GL_R1UI_T2F_C4F_N3F_V3F_SUN 0x85CB +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUISUNPROC) (GLuint code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSSUNPROC) (GLushort code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBSUNPROC) (GLubyte code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVSUNPROC) (const GLuint *code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSVSUNPROC) (const GLushort *code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBVSUNPROC) (const GLubyte *code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEPOINTERSUNPROC) (GLenum type, GLsizei stride, const void **pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glReplacementCodeuiSUN (GLuint code); +GLAPI void APIENTRY glReplacementCodeusSUN (GLushort code); +GLAPI void APIENTRY glReplacementCodeubSUN (GLubyte code); +GLAPI void APIENTRY glReplacementCodeuivSUN (const GLuint *code); +GLAPI void APIENTRY glReplacementCodeusvSUN (const GLushort *code); +GLAPI void APIENTRY glReplacementCodeubvSUN (const GLubyte *code); +GLAPI void APIENTRY glReplacementCodePointerSUN (GLenum type, GLsizei stride, const void **pointer); +#endif +#endif /* GL_SUN_triangle_list */ + +#ifndef GL_SUN_vertex +#define GL_SUN_vertex 1 +typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FVSUNPROC) (const GLubyte *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FVSUNPROC) (const GLubyte *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FSUNPROC) (GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FVSUNPROC) (const GLfloat *tc, const GLubyte *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FSUNPROC) (GLuint rc, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FSUNPROC) (GLuint rc, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FVSUNPROC) (const GLuint *rc, const GLubyte *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColor4ubVertex2fSUN (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y); +GLAPI void APIENTRY glColor4ubVertex2fvSUN (const GLubyte *c, const GLfloat *v); +GLAPI void APIENTRY glColor4ubVertex3fSUN (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glColor4ubVertex3fvSUN (const GLubyte *c, const GLfloat *v); +GLAPI void APIENTRY glColor3fVertex3fSUN (GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glColor3fVertex3fvSUN (const GLfloat *c, const GLfloat *v); +GLAPI void APIENTRY glNormal3fVertex3fSUN (GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glNormal3fVertex3fvSUN (const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glColor4fNormal3fVertex3fSUN (GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glColor4fNormal3fVertex3fvSUN (const GLfloat *c, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glTexCoord2fVertex3fSUN (GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glTexCoord2fVertex3fvSUN (const GLfloat *tc, const GLfloat *v); +GLAPI void APIENTRY glTexCoord4fVertex4fSUN (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glTexCoord4fVertex4fvSUN (const GLfloat *tc, const GLfloat *v); +GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fSUN (GLfloat s, GLfloat t, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fvSUN (const GLfloat *tc, const GLubyte *c, const GLfloat *v); +GLAPI void APIENTRY glTexCoord2fColor3fVertex3fSUN (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glTexCoord2fColor3fVertex3fvSUN (const GLfloat *tc, const GLfloat *c, const GLfloat *v); +GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fSUN (GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fvSUN (const GLfloat *tc, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fSUN (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fvSUN (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fSUN (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fvSUN (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiVertex3fSUN (GLuint rc, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiVertex3fvSUN (const GLuint *rc, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fSUN (GLuint rc, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fvSUN (const GLuint *rc, const GLubyte *c, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fSUN (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fvSUN (const GLuint *rc, const GLfloat *c, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fSUN (GLuint rc, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fSUN (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fSUN (GLuint rc, GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fvSUN (const GLuint *rc, const GLfloat *tc, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN (GLuint rc, GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *tc, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN (GLuint rc, GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +#endif +#endif /* GL_SUN_vertex */ + +#ifndef GL_WIN_phong_shading +#define GL_WIN_phong_shading 1 +#define GL_PHONG_WIN 0x80EA +#define GL_PHONG_HINT_WIN 0x80EB +#endif /* GL_WIN_phong_shading */ + +#ifndef GL_WIN_specular_fog +#define GL_WIN_specular_fog 1 +#define GL_FOG_SPECULAR_TEXTURE_WIN 0x80EC +#endif /* GL_WIN_specular_fog */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/external/stb/stb_image.h b/external/stb/stb_image.h new file mode 100644 index 000000000..ae2ada6a6 --- /dev/null +++ b/external/stb/stb_image.h @@ -0,0 +1,7177 @@ +/* stb_image - v2.15 - public domain image loader - http://nothings.org/stb_image.h + 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.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 + 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA + 2.07 (2015-09-13) partial animated GIF support + limited 16-bit PSD support + minor bugs, code cleanup, and compiler warnings + + 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) + Daniel Gibson (16-bit TGA) + socks-the-fox (16-bit PNG) + Jeremy Sawicki (handle all ImageNet JPGs) + Optimizations & bugfixes + Fabian "ryg" Giesen + Arseny Kapoulkine + + Bug & warning fixes + Marc LeBlanc David Woo Guillaume George Martins Mozeiko + Christpher Lloyd Jerry Jansson Joseph Thomson 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 Baldur Karlsson + Janez Zemva John Bartholomew Michal Cichon github:rlyeh + Jonathan Blow Ken Hamada Tero Hanninen github:romigrou + Laurent Gomila Cort Stratton Sergio Gonzalez github:svdijk + Aruelien Pocheville Thibault Reuille Cass Everitt github:snagar + Ryamond Barbiero Paul Du Bois Engin Manap github:Zelex + Michaelangel007@github Philipp Wiesemann Dale Weiler github:grim210 + Oriol Ferrer Mesia Josh Tobin Matthew Gregan github:sammyhw + Blazej Dariusz Roszkowski Gregory Mullen github:phprus + +*/ + +#ifndef STBI_INCLUDE_STB_IMAGE_H +#define STBI_INCLUDE_STB_IMAGE_H + +// DOCUMENTATION +// +// Limitations: +// - no 16-bit-per-channel PNG +// - no 12-bit-per-channel JPEG +// - no JPEGs with arithmetic coding +// - no 1-bit BMP +// - 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 'req_comp' if req_comp is non-zero, or *comp otherwise. +// If req_comp is non-zero, *comp has the number of components that _would_ +// have been output otherwise. E.g. if you set req_comp to 4, you will always +// get RGBA output, but you can check *comp 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, *comp 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. +// +// =========================================================================== +// +// 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 +// make 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 now supports loading HDR images in general, and currently +// the Radiance .HDR file format, although the support is provided +// generically. 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 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 +// + + +#ifndef STBI_NO_STDIO +#include +#endif // STBI_NO_STDIO + +#define STBI_VERSION 1 + +enum +{ + STBI_default = 0, // only used for req_comp + + STBI_grey = 1, + STBI_grey_alpha = 2, + STBI_rgb = 3, + STBI_rgb_alpha = 4 +}; + +typedef unsigned char stbi_uc; +typedef unsigned short stbi_us; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef STB_IMAGE_STATIC +#define STBIDEF static +#else +#define STBIDEF extern +#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 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +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_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 + +//////////////////////////////////// +// +// 16-bits-per-channel interface +// + +STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +#ifndef STBI_NO_STDIO +STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +#endif +// @TODO the other variants + +//////////////////////////////////// +// +// float-per-channel interface +// +#ifndef STBI_NO_LINEAR + STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); + 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_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 +// NOT 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); + +#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); + +#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); + +// 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 +#endif + +#ifndef STBI_NO_STDIO +#include +#endif + +#ifndef STBI_ASSERT +#include +#define STBI_ASSERT(x) assert(x) +#endif + + +#ifndef _MSC_VER + #ifdef __cplusplus + #define stbi_inline inline + #else + #define stbi_inline + #endif +#else + #define stbi_inline __forceinline +#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) 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 + +static int stbi__sse2_available() +{ + int info3 = stbi__cpuid3(); + return ((info3 >> 26) & 1) != 0; +} +#else // assume GCC-style if not VC++ +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) + +static int stbi__sse2_available() +{ + // 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 + +// 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 + +/////////////////////////////////////////////// +// +// 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]; + + 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->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->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) +{ + fseek((FILE*) user, n, SEEK_CUR); +} + +static int stbi__stdio_eof(void *user) +{ + return feof((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); +#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); +#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 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 + +// this is not threadsafe +static const char *stbi__g_failure_reason; + +STBIDEF const char *stbi_failure_reason(void) +{ + return stbi__g_failure_reason; +} + +static int stbi__err(const char *str) +{ + stbi__g_failure_reason = str; + return 0; +} + +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; +} + +// 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); +} + +// 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 +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); +} + +// 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); +} + +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); +} + +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); +} + +// 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 = 0; + +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load = flag_true_if_should_flip; +} + +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); + #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 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; + + if (ri.bits_per_channel != 8) { + STBI_ASSERT(ri.bits_per_channel == 16); + 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 w = *x, h = *y; + int channels = req_comp ? req_comp : *comp; + int row,col,z; + stbi_uc *image = (stbi_uc *) result; + + // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once + for (row = 0; row < (h>>1); row++) { + for (col = 0; col < w; col++) { + for (z = 0; z < channels; z++) { + stbi_uc temp = image[(row * w + col) * channels + z]; + image[(row * w + col) * channels + z] = image[((h - row - 1) * w + col) * channels + z]; + image[((h - row - 1) * w + col) * channels + z] = temp; + } + } + } + } + + 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; + + if (ri.bits_per_channel != 16) { + STBI_ASSERT(ri.bits_per_channel == 8); + 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 w = *x, h = *y; + int channels = req_comp ? req_comp : *comp; + int row,col,z; + stbi__uint16 *image = (stbi__uint16 *) result; + + // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once + for (row = 0; row < (h>>1); row++) { + for (col = 0; col < w; col++) { + for (z = 0; z < channels; z++) { + stbi__uint16 temp = image[(row * w + col) * channels + z]; + image[(row * w + col) * channels + z] = image[((h - row - 1) * w + col) * channels + z]; + image[((h - row - 1) * w + col) * channels + z] = temp; + } + } + } + } + + return (stbi__uint16 *) result; +} + +#ifndef STBI_NO_HDR +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 w = *x, h = *y; + int depth = req_comp ? req_comp : *comp; + int row,col,z; + float temp; + + // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once + for (row = 0; row < (h>>1); row++) { + for (col = 0; col < w; col++) { + for (z = 0; z < depth; z++) { + temp = result[(row * w + col) * depth + z]; + result[(row * w + col) * depth + z] = result[((h - row - 1) * w + col) * depth + z]; + result[((h - row - 1) * w + col) * depth + z] = temp; + } + } + } + } +} +#endif + +#ifndef STBI_NO_STDIO + +static FILE *stbi__fopen(char const *filename, char const *mode) +{ + FILE *f; +#if 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_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_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 + stbi__context s; + stbi__start_file(&s,f); + return stbi__hdr_test(&s); + #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); + 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; +} + +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; +} + +static void stbi__skip(stbi__context *s, int n) +{ + 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; +} + +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; +} + +static int stbi__get16be(stbi__context *s) +{ + int z = stbi__get8(s); + return (z << 8) + stbi__get8(s); +} + +static stbi__uint32 stbi__get32be(stbi__context *s) +{ + stbi__uint32 z = stbi__get16be(s); + return (z << 16) + stbi__get16be(s); +} + +#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 + + +////////////////////////////////////////////////////////////////////////////// +// +// 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); +} + +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); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} + +static stbi__uint16 stbi__compute_y_16(int r, int g, int b) +{ + return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8); +} + +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); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} + +#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 (k < comp) output[i*comp + k] = data[i*comp+k]/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,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 >= (1 << 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 << 8) + (run << 4) + (len + magbits)); + } + } + } +} + +static void stbi__grow_buffer_unsafe(stbi__jpeg *j) +{ + do { + 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 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); + STBI_ASSERT(n >= 0 && n < (int) (sizeof(stbi__bmask)/sizeof(*stbi__bmask))); + 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 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); + 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) << 12) + +// 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] << 2; + 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]] = 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 + 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 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) stbi__err("bad DNL len", "Corrupt JPEG"); + if (NL != j->s->img_y) 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]; + + 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 k = coutput[3][i]; + out[0] = stbi__blinn_8x8(coutput[0][i], k); + out[1] = stbi__blinn_8x8(coutput[1][i], k); + out[2] = stbi__blinn_8x8(coutput[2][i], k); + 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 k = coutput[3][i]; + out[0] = stbi__blinn_8x8(255 - out[0], k); + out[1] = stbi__blinn_8x8(255 - out[1], k); + out[2] = stbi__blinn_8x8(255 - out[2], k); + 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 k = coutput[3][i]; + stbi_uc r = stbi__blinn_8x8(coutput[0][i], k); + stbi_uc g = stbi__blinn_8x8(coutput[1][i], k); + stbi_uc b = stbi__blinn_8x8(coutput[2][i], k); + 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 stbi_uc stbi__zget8(stbi__zbuf *z) +{ + if (z->zbuffer >= z->zbuffer_end) return 0; + return *z->zbuffer++; +} + +static void stbi__fill_bits(stbi__zbuf *z) +{ + do { + STBI_ASSERT(z->code_buffer < (1U << z->num_bits)); + 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]; + STBI_ASSERT(z->size[b] == s); + 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) 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; + int cur, limit, old_limit; + z->zout = zout; + if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); + cur = (int) (z->zout - z->zout_start); + limit = old_limit = (int) (z->zout_end - z->zout_start); + while (cur + n > limit) + 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 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 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 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 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 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 { + STBI_ASSERT(c == 18); + c = stbi__zreceive(a,7)+11; + } + 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; + } + STBI_ASSERT(a->num_bits == 0); + // 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 ((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 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 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"); + + img_width_bytes = (((img_n * x * depth) + 7) >> 3); + img_len = (img_width_bytes + 1) * y; + if (s->img_x == x && s->img_y == y) { + if (raw_len != img_len) return stbi__err("not enough pixels","Corrupt PNG"); + } else { // interlaced: + 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) { + STBI_ASSERT(img_width_bytes <= x); + 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) { + p[0] = p[2] * 255 / a; + p[1] = p[1] * 255 / a; + p[2] = t * 255 / 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) (((a) << 24) + ((b) << 16) + ((c) << 8) + (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]; + 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); if (s->img_x > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)"); + s->img_y = stbi__get32be(s); if (s->img_y > (1 << 24)) 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; + } + STBI_FREE(z->expanded); z->expanded = NULL; + 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 + ri->bits_per_channel = p->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); +} +#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, z >>= 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; +} + +static int stbi__shiftsigned(int v, int shift, int bits) +{ + int result; + int z=0; + + if (shift < 0) v <<= -shift; + else v >>= shift; + result = v; + + z = bits; + while (z < 8) { + result += v >> z; + z += bits; + } + return result; +} + +typedef struct +{ + int bpp, offset, hsz; + unsigned int mr,mg,mb,ma, all_a; +} 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; + + 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 (info->bpp == 1) return stbi__errpuc("monochrome", "BMP type not supported: 1-bit"); + 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); + // 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); + + 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 - 14 - 24) / 3; + } else { + if (info.bpp < 16) + psize = (info.offset - 14 - info.hsz) >> 2; + } + + 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 - 14 - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); + 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; + 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 - 14 - 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); + } + 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)); + 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; + // else: fall-through + case 15: if(is_rgb16) *is_rgb16 = 1; + return STBI_rgb; + case 24: // fall-through + 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); + + // 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) + { + // 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; + // 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); + + // 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 preceeded 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 (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, *old_out; // output buffer (always 4 components) + int flags, bgindex, ratio, transparent, eflags, delay; + stbi_uc pal[256][4]; + stbi_uc lpal[256][4]; + stbi__gif_lzw codes[4096]; + 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; +} 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 (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; + + // 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; + + p = &g->out[g->cur_x + g->cur_y]; + c = &g->color_table[g->codes[code].suffix * 4]; + + if (c[3] >= 128) { + 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 > 4096) 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"); + } + } + } +} + +static void stbi__fill_gif_background(stbi__gif *g, int x0, int y0, int x1, int y1) +{ + int x, y; + stbi_uc *c = g->pal[g->bgindex]; + for (y = y0; y < y1; y += 4 * g->w) { + for (x = x0; x < x1; x += 4) { + stbi_uc *p = &g->out[y + x]; + p[0] = c[2]; + p[1] = c[1]; + p[2] = c[0]; + p[3] = 0; + } + } +} + +// this function is designed to support animated gifs, although stb_image doesn't support it +static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp) +{ + int i; + stbi_uc *prev_out = 0; + + if (g->out == 0 && !stbi__gif_header(s, g, comp,0)) + return 0; // stbi__g_failure_reason set by stbi__gif_header + + if (!stbi__mad3sizes_valid(g->w, g->h, 4, 0)) + return stbi__errpuc("too large", "GIF too large"); + + prev_out = g->out; + g->out = (stbi_uc *) stbi__malloc_mad3(4, g->w, g->h, 0); + if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory"); + + switch ((g->eflags & 0x1C) >> 2) { + case 0: // unspecified (also always used on 1st frame) + stbi__fill_gif_background(g, 0, 0, 4 * g->w, 4 * g->w * g->h); + break; + case 1: // do not dispose + if (prev_out) memcpy(g->out, prev_out, 4 * g->w * g->h); + g->old_out = prev_out; + break; + case 2: // dispose to background + if (prev_out) memcpy(g->out, prev_out, 4 * g->w * g->h); + stbi__fill_gif_background(g, g->start_x, g->start_y, g->max_x, g->max_y); + break; + case 3: // dispose to previous + if (g->old_out) { + for (i = g->start_y; i < g->max_y; i += 4 * g->w) + memcpy(&g->out[i + g->start_x], &g->old_out[i + g->start_x], g->max_x - g->start_x); + } + break; + } + + for (;;) { + switch (stbi__get8(s)) { + case 0x2C: /* Image Descriptor */ + { + int prev_trans = -1; + 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; + + 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) { + if (g->transparent >= 0 && (g->eflags & 0x01)) { + prev_trans = g->pal[g->transparent][3]; + g->pal[g->transparent][3] = 0; + } + 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 == NULL) return NULL; + + if (prev_trans != -1) + g->pal[g->transparent][3] = (stbi_uc) prev_trans; + + return o; + } + + case 0x21: // Comment Extension. + { + int len; + if (stbi__get8(s) == 0xF9) { // Graphic Control Extension. + len = stbi__get8(s); + if (len == 4) { + g->eflags = stbi__get8(s); + g->delay = stbi__get16le(s); + g->transparent = stbi__get8(s); + } 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"); + } + } + + STBI_NOTUSED(req_comp); +} + +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 = (stbi__gif*) stbi__malloc(sizeof(stbi__gif)); + memset(g, 0, sizeof(*g)); + STBI_NOTUSED(ri); + + u = stbi__gif_load_next(s, g, comp, req_comp); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + if (u) { + *x = g->w; + *y = g->h; + if (req_comp && req_comp != 4) + u = stbi__convert_format(u, 4, req_comp, g->w, g->h); + } + else if (g->out) + STBI_FREE(g->out); + STBI_FREE(g); + 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); + + *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) *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; + 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); + if (stbi__get16be(s) != 8) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 3) { + stbi__rewind( s ); + return 0; + } + *comp = 4; + 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; + + *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"); +} + +#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; +} +#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); +} + +#endif // STB_IMAGE_IMPLEMENTATION + +/* + revision history: + 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/external/stb/stb_image_write.h b/external/stb/stb_image_write.h new file mode 100644 index 000000000..df623393d --- /dev/null +++ b/external/stb/stb_image_write.h @@ -0,0 +1,1092 @@ +/* stb_image_write - v1.05 - public domain - http://nothings.org/stb/stb_image_write.h + writes out PNG/BMP/TGA images to C stdio - Sean Barrett 2010-2015 + no warranty implied; use at your own risk + + Before #including, + + #define STB_IMAGE_WRITE_IMPLEMENTATION + + in the file that you want to have the implementation. + + Will probably not work correctly with strict-aliasing optimizations. + +ABOUT: + + This header file is a library for writing images to C stdio. It could be + adapted to write to memory or a general streaming interface; let me know. + + The PNG output is not optimal; it is 20-50% larger than the file + written by a decent optimizing implementation. This library is designed + for source code compactness and simplicity, not optimal image file size + or run-time performance. + +BUILDING: + + You can #define STBIW_ASSERT(x) before the #include to avoid using assert.h. + You can #define STBIW_MALLOC(), STBIW_REALLOC(), and STBIW_FREE() to replace + malloc,realloc,free. + You can define STBIW_MEMMOVE() to replace memmove() + +USAGE: + + There are four functions, one for each image file format: + + int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); + int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); + int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); + int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); + + There are also four equivalent functions that use an arbitrary write function. You are + expected to open/close your file-equivalent before and after calling these: + + int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); + int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); + int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); + int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); + + where the callback is: + void stbi_write_func(void *context, void *data, int size); + + You can define STBI_WRITE_NO_STDIO to disable the file variant of these + functions, so the library will not use stdio.h at all. However, this will + also disable HDR writing, because it requires stdio for formatted output. + + Each function returns 0 on failure and non-0 on success. + + The functions create an image file defined by the parameters. The image + is a rectangle of pixels stored from left-to-right, top-to-bottom. + Each pixel contains 'comp' channels of data stored interleaved with 8-bits + per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is + monochrome color.) The rectangle is 'w' pixels wide and 'h' pixels tall. + The *data pointer points to the first byte of the top-left-most pixel. + For PNG, "stride_in_bytes" is the distance in bytes from the first byte of + a row of pixels to the first byte of the next row of pixels. + + PNG creates output files with the same number of components as the input. + The BMP format expands Y to RGB in the file format and does not + output alpha. + + PNG supports writing rectangles of data even when the bytes storing rows of + data are not consecutive in memory (e.g. sub-rectangles of a larger image), + by supplying the stride between the beginning of adjacent rows. The other + formats do not. (Thus you cannot write a native-format BMP through the BMP + writer, both because it is in BGR order and because it may have padding + at the end of the line.) + + HDR expects linear float data. Since the format is always 32-bit rgb(e) + data, alpha (if provided) is discarded, and for monochrome data it is + replicated across all three channels. + + TGA supports RLE or non-RLE compressed data. To use non-RLE-compressed + data, set the global variable 'stbi_write_tga_with_rle' to 0. + +CREDITS: + + PNG/BMP/TGA + Sean Barrett + HDR + Baldur Karlsson + TGA monochrome: + Jean-Sebastien Guay + misc enhancements: + Tim Kelsey + TGA RLE + Alan Hickman + initial file IO callback implementation + Emmanuel Julien + bugfixes: + github:Chribba + Guillaume Chereau + github:jry2 + github:romigrou + Sergio Gonzalez + Jonas Karlsson + Filip Wasil + Thatcher Ulrich + github:poppolopoppo + Patrick Boettcher + +LICENSE + + See end of file for license information. + +*/ + +#ifndef INCLUDE_STB_IMAGE_WRITE_H +#define INCLUDE_STB_IMAGE_WRITE_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef STB_IMAGE_WRITE_STATIC +#define STBIWDEF static +#else +#define STBIWDEF extern +extern int stbi_write_tga_with_rle; +#endif + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); +STBIWDEF int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); +#endif + +typedef void stbi_write_func(void *context, void *data, int size); + +STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); +STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); + +#ifdef __cplusplus +} +#endif + +#endif//INCLUDE_STB_IMAGE_WRITE_H + +#ifdef STB_IMAGE_WRITE_IMPLEMENTATION + +#ifdef _WIN32 + #ifndef _CRT_SECURE_NO_WARNINGS + #define _CRT_SECURE_NO_WARNINGS + #endif + #ifndef _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_NONSTDC_NO_DEPRECATE + #endif +#endif + +#ifndef STBI_WRITE_NO_STDIO +#include +#endif // STBI_WRITE_NO_STDIO + +#include +#include +#include +#include + +#if defined(STBIW_MALLOC) && defined(STBIW_FREE) && (defined(STBIW_REALLOC) || defined(STBIW_REALLOC_SIZED)) +// ok +#elif !defined(STBIW_MALLOC) && !defined(STBIW_FREE) && !defined(STBIW_REALLOC) && !defined(STBIW_REALLOC_SIZED) +// ok +#else +#error "Must define all or none of STBIW_MALLOC, STBIW_FREE, and STBIW_REALLOC (or STBIW_REALLOC_SIZED)." +#endif + +#ifndef STBIW_MALLOC +#define STBIW_MALLOC(sz) malloc(sz) +#define STBIW_REALLOC(p,newsz) realloc(p,newsz) +#define STBIW_FREE(p) free(p) +#endif + +#ifndef STBIW_REALLOC_SIZED +#define STBIW_REALLOC_SIZED(p,oldsz,newsz) STBIW_REALLOC(p,newsz) +#endif + + +#ifndef STBIW_MEMMOVE +#define STBIW_MEMMOVE(a,b,sz) memmove(a,b,sz) +#endif + + +#ifndef STBIW_ASSERT +#include +#define STBIW_ASSERT(x) assert(x) +#endif + +#define STBIW_UCHAR(x) (unsigned char) ((x) & 0xff) + +typedef struct +{ + stbi_write_func *func; + void *context; +} stbi__write_context; + +// initialize a callback-based context +static void stbi__start_write_callbacks(stbi__write_context *s, stbi_write_func *c, void *context) +{ + s->func = c; + s->context = context; +} + +#ifndef STBI_WRITE_NO_STDIO + +static void stbi__stdio_write(void *context, void *data, int size) +{ + fwrite(data,1,size,(FILE*) context); +} + +static int stbi__start_write_file(stbi__write_context *s, const char *filename) +{ + FILE *f = fopen(filename, "wb"); + stbi__start_write_callbacks(s, stbi__stdio_write, (void *) f); + return f != NULL; +} + +static void stbi__end_write_file(stbi__write_context *s) +{ + fclose((FILE *)s->context); +} + +#endif // !STBI_WRITE_NO_STDIO + +typedef unsigned int stbiw_uint32; +typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1]; + +#ifdef STB_IMAGE_WRITE_STATIC +static int stbi_write_tga_with_rle = 1; +#else +int stbi_write_tga_with_rle = 1; +#endif + +static void stbiw__writefv(stbi__write_context *s, const char *fmt, va_list v) +{ + while (*fmt) { + switch (*fmt++) { + case ' ': break; + case '1': { unsigned char x = STBIW_UCHAR(va_arg(v, int)); + s->func(s->context,&x,1); + break; } + case '2': { int x = va_arg(v,int); + unsigned char b[2]; + b[0] = STBIW_UCHAR(x); + b[1] = STBIW_UCHAR(x>>8); + s->func(s->context,b,2); + break; } + case '4': { stbiw_uint32 x = va_arg(v,int); + unsigned char b[4]; + b[0]=STBIW_UCHAR(x); + b[1]=STBIW_UCHAR(x>>8); + b[2]=STBIW_UCHAR(x>>16); + b[3]=STBIW_UCHAR(x>>24); + s->func(s->context,b,4); + break; } + default: + STBIW_ASSERT(0); + return; + } + } +} + +static void stbiw__writef(stbi__write_context *s, const char *fmt, ...) +{ + va_list v; + va_start(v, fmt); + stbiw__writefv(s, fmt, v); + va_end(v); +} + +static void stbiw__write3(stbi__write_context *s, unsigned char a, unsigned char b, unsigned char c) +{ + unsigned char arr[3]; + arr[0] = a, arr[1] = b, arr[2] = c; + s->func(s->context, arr, 3); +} + +static void stbiw__write_pixel(stbi__write_context *s, int rgb_dir, int comp, int write_alpha, int expand_mono, unsigned char *d) +{ + unsigned char bg[3] = { 255, 0, 255}, px[3]; + int k; + + if (write_alpha < 0) + s->func(s->context, &d[comp - 1], 1); + + switch (comp) { + case 2: // 2 pixels = mono + alpha, alpha is written separately, so same as 1-channel case + case 1: + if (expand_mono) + stbiw__write3(s, d[0], d[0], d[0]); // monochrome bmp + else + s->func(s->context, d, 1); // monochrome TGA + break; + case 4: + if (!write_alpha) { + // composite against pink background + for (k = 0; k < 3; ++k) + px[k] = bg[k] + ((d[k] - bg[k]) * d[3]) / 255; + stbiw__write3(s, px[1 - rgb_dir], px[1], px[1 + rgb_dir]); + break; + } + /* FALLTHROUGH */ + case 3: + stbiw__write3(s, d[1 - rgb_dir], d[1], d[1 + rgb_dir]); + break; + } + if (write_alpha > 0) + s->func(s->context, &d[comp - 1], 1); +} + +static void stbiw__write_pixels(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad, int expand_mono) +{ + stbiw_uint32 zero = 0; + int i,j, j_end; + + if (y <= 0) + return; + + if (vdir < 0) + j_end = -1, j = y-1; + else + j_end = y, j = 0; + + for (; j != j_end; j += vdir) { + for (i=0; i < x; ++i) { + unsigned char *d = (unsigned char *) data + (j*x+i)*comp; + stbiw__write_pixel(s, rgb_dir, comp, write_alpha, expand_mono, d); + } + s->func(s->context, &zero, scanline_pad); + } +} + +static int stbiw__outfile(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, int expand_mono, void *data, int alpha, int pad, const char *fmt, ...) +{ + if (y < 0 || x < 0) { + return 0; + } else { + va_list v; + va_start(v, fmt); + stbiw__writefv(s, fmt, v); + va_end(v); + stbiw__write_pixels(s,rgb_dir,vdir,x,y,comp,data,alpha,pad, expand_mono); + return 1; + } +} + +static int stbi_write_bmp_core(stbi__write_context *s, int x, int y, int comp, const void *data) +{ + int pad = (-x*3) & 3; + return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *) data,0,pad, + "11 4 22 4" "4 44 22 444444", + 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header + 40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header +} + +STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) +{ + stbi__write_context s; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_bmp_core(&s, x, y, comp, data); +} + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data) +{ + stbi__write_context s; + if (stbi__start_write_file(&s,filename)) { + int r = stbi_write_bmp_core(&s, x, y, comp, data); + stbi__end_write_file(&s); + return r; + } else + return 0; +} +#endif //!STBI_WRITE_NO_STDIO + +static int stbi_write_tga_core(stbi__write_context *s, int x, int y, int comp, void *data) +{ + int has_alpha = (comp == 2 || comp == 4); + int colorbytes = has_alpha ? comp-1 : comp; + int format = colorbytes < 2 ? 3 : 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3 + + if (y < 0 || x < 0) + return 0; + + if (!stbi_write_tga_with_rle) { + return stbiw__outfile(s, -1, -1, x, y, comp, 0, (void *) data, has_alpha, 0, + "111 221 2222 11", 0, 0, format, 0, 0, 0, 0, 0, x, y, (colorbytes + has_alpha) * 8, has_alpha * 8); + } else { + int i,j,k; + + stbiw__writef(s, "111 221 2222 11", 0,0,format+8, 0,0,0, 0,0,x,y, (colorbytes + has_alpha) * 8, has_alpha * 8); + + for (j = y - 1; j >= 0; --j) { + unsigned char *row = (unsigned char *) data + j * x * comp; + int len; + + for (i = 0; i < x; i += len) { + unsigned char *begin = row + i * comp; + int diff = 1; + len = 1; + + if (i < x - 1) { + ++len; + diff = memcmp(begin, row + (i + 1) * comp, comp); + if (diff) { + const unsigned char *prev = begin; + for (k = i + 2; k < x && len < 128; ++k) { + if (memcmp(prev, row + k * comp, comp)) { + prev += comp; + ++len; + } else { + --len; + break; + } + } + } else { + for (k = i + 2; k < x && len < 128; ++k) { + if (!memcmp(begin, row + k * comp, comp)) { + ++len; + } else { + break; + } + } + } + } + + if (diff) { + unsigned char header = STBIW_UCHAR(len - 1); + s->func(s->context, &header, 1); + for (k = 0; k < len; ++k) { + stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin + k * comp); + } + } else { + unsigned char header = STBIW_UCHAR(len - 129); + s->func(s->context, &header, 1); + stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin); + } + } + } + } + return 1; +} + +int stbi_write_tga_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) +{ + stbi__write_context s; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_tga_core(&s, x, y, comp, (void *) data); +} + +#ifndef STBI_WRITE_NO_STDIO +int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data) +{ + stbi__write_context s; + if (stbi__start_write_file(&s,filename)) { + int r = stbi_write_tga_core(&s, x, y, comp, (void *) data); + stbi__end_write_file(&s); + return r; + } else + return 0; +} +#endif + +// ************************************************************************************************* +// Radiance RGBE HDR writer +// by Baldur Karlsson + +#define stbiw__max(a, b) ((a) > (b) ? (a) : (b)) + +void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear) +{ + int exponent; + float maxcomp = stbiw__max(linear[0], stbiw__max(linear[1], linear[2])); + + if (maxcomp < 1e-32f) { + rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0; + } else { + float normalize = (float) frexp(maxcomp, &exponent) * 256.0f/maxcomp; + + rgbe[0] = (unsigned char)(linear[0] * normalize); + rgbe[1] = (unsigned char)(linear[1] * normalize); + rgbe[2] = (unsigned char)(linear[2] * normalize); + rgbe[3] = (unsigned char)(exponent + 128); + } +} + +void stbiw__write_run_data(stbi__write_context *s, int length, unsigned char databyte) +{ + unsigned char lengthbyte = STBIW_UCHAR(length+128); + STBIW_ASSERT(length+128 <= 255); + s->func(s->context, &lengthbyte, 1); + s->func(s->context, &databyte, 1); +} + +void stbiw__write_dump_data(stbi__write_context *s, int length, unsigned char *data) +{ + unsigned char lengthbyte = STBIW_UCHAR(length); + STBIW_ASSERT(length <= 128); // inconsistent with spec but consistent with official code + s->func(s->context, &lengthbyte, 1); + s->func(s->context, data, length); +} + +void stbiw__write_hdr_scanline(stbi__write_context *s, int width, int ncomp, unsigned char *scratch, float *scanline) +{ + unsigned char scanlineheader[4] = { 2, 2, 0, 0 }; + unsigned char rgbe[4]; + float linear[3]; + int x; + + scanlineheader[2] = (width&0xff00)>>8; + scanlineheader[3] = (width&0x00ff); + + /* skip RLE for images too small or large */ + if (width < 8 || width >= 32768) { + for (x=0; x < width; x++) { + switch (ncomp) { + case 4: /* fallthrough */ + case 3: linear[2] = scanline[x*ncomp + 2]; + linear[1] = scanline[x*ncomp + 1]; + linear[0] = scanline[x*ncomp + 0]; + break; + default: + linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; + break; + } + stbiw__linear_to_rgbe(rgbe, linear); + s->func(s->context, rgbe, 4); + } + } else { + int c,r; + /* encode into scratch buffer */ + for (x=0; x < width; x++) { + switch(ncomp) { + case 4: /* fallthrough */ + case 3: linear[2] = scanline[x*ncomp + 2]; + linear[1] = scanline[x*ncomp + 1]; + linear[0] = scanline[x*ncomp + 0]; + break; + default: + linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; + break; + } + stbiw__linear_to_rgbe(rgbe, linear); + scratch[x + width*0] = rgbe[0]; + scratch[x + width*1] = rgbe[1]; + scratch[x + width*2] = rgbe[2]; + scratch[x + width*3] = rgbe[3]; + } + + s->func(s->context, scanlineheader, 4); + + /* RLE each component separately */ + for (c=0; c < 4; c++) { + unsigned char *comp = &scratch[width*c]; + + x = 0; + while (x < width) { + // find first run + r = x; + while (r+2 < width) { + if (comp[r] == comp[r+1] && comp[r] == comp[r+2]) + break; + ++r; + } + if (r+2 >= width) + r = width; + // dump up to first run + while (x < r) { + int len = r-x; + if (len > 128) len = 128; + stbiw__write_dump_data(s, len, &comp[x]); + x += len; + } + // if there's a run, output it + if (r+2 < width) { // same test as what we break out of in search loop, so only true if we break'd + // find next byte after run + while (r < width && comp[r] == comp[x]) + ++r; + // output run up to r + while (x < r) { + int len = r-x; + if (len > 127) len = 127; + stbiw__write_run_data(s, len, comp[x]); + x += len; + } + } + } + } + } +} + +static int stbi_write_hdr_core(stbi__write_context *s, int x, int y, int comp, float *data) +{ + if (y <= 0 || x <= 0 || data == NULL) + return 0; + else { + // Each component is stored separately. Allocate scratch space for full output scanline. + unsigned char *scratch = (unsigned char *) STBIW_MALLOC(x*4); + int i, len; + char buffer[128]; + char header[] = "#?RADIANCE\n# Written by stb_image_write.h\nFORMAT=32-bit_rle_rgbe\n"; + s->func(s->context, header, sizeof(header)-1); + + len = sprintf(buffer, "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); + s->func(s->context, buffer, len); + + for(i=0; i < y; i++) + stbiw__write_hdr_scanline(s, x, comp, scratch, data + comp*i*x); + STBIW_FREE(scratch); + return 1; + } +} + +int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const float *data) +{ + stbi__write_context s; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_hdr_core(&s, x, y, comp, (float *) data); +} + +#ifndef STBI_WRITE_NO_STDIO +int stbi_write_hdr(char const *filename, int x, int y, int comp, const float *data) +{ + stbi__write_context s; + if (stbi__start_write_file(&s,filename)) { + int r = stbi_write_hdr_core(&s, x, y, comp, (float *) data); + stbi__end_write_file(&s); + return r; + } else + return 0; +} +#endif // STBI_WRITE_NO_STDIO + + +////////////////////////////////////////////////////////////////////////////// +// +// PNG writer +// + +// stretchy buffer; stbiw__sbpush() == vector<>::push_back() -- stbiw__sbcount() == vector<>::size() +#define stbiw__sbraw(a) ((int *) (a) - 2) +#define stbiw__sbm(a) stbiw__sbraw(a)[0] +#define stbiw__sbn(a) stbiw__sbraw(a)[1] + +#define stbiw__sbneedgrow(a,n) ((a)==0 || stbiw__sbn(a)+n >= stbiw__sbm(a)) +#define stbiw__sbmaybegrow(a,n) (stbiw__sbneedgrow(a,(n)) ? stbiw__sbgrow(a,n) : 0) +#define stbiw__sbgrow(a,n) stbiw__sbgrowf((void **) &(a), (n), sizeof(*(a))) + +#define stbiw__sbpush(a, v) (stbiw__sbmaybegrow(a,1), (a)[stbiw__sbn(a)++] = (v)) +#define stbiw__sbcount(a) ((a) ? stbiw__sbn(a) : 0) +#define stbiw__sbfree(a) ((a) ? STBIW_FREE(stbiw__sbraw(a)),0 : 0) + +static void *stbiw__sbgrowf(void **arr, int increment, int itemsize) +{ + int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1; + void *p = STBIW_REALLOC_SIZED(*arr ? stbiw__sbraw(*arr) : 0, *arr ? (stbiw__sbm(*arr)*itemsize + sizeof(int)*2) : 0, itemsize * m + sizeof(int)*2); + STBIW_ASSERT(p); + if (p) { + if (!*arr) ((int *) p)[1] = 0; + *arr = (void *) ((int *) p + 2); + stbiw__sbm(*arr) = m; + } + return *arr; +} + +static unsigned char *stbiw__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount) +{ + while (*bitcount >= 8) { + stbiw__sbpush(data, STBIW_UCHAR(*bitbuffer)); + *bitbuffer >>= 8; + *bitcount -= 8; + } + return data; +} + +static int stbiw__zlib_bitrev(int code, int codebits) +{ + int res=0; + while (codebits--) { + res = (res << 1) | (code & 1); + code >>= 1; + } + return res; +} + +static unsigned int stbiw__zlib_countm(unsigned char *a, unsigned char *b, int limit) +{ + int i; + for (i=0; i < limit && i < 258; ++i) + if (a[i] != b[i]) break; + return i; +} + +static unsigned int stbiw__zhash(unsigned char *data) +{ + stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16); + hash ^= hash << 3; + hash += hash >> 5; + hash ^= hash << 4; + hash += hash >> 17; + hash ^= hash << 25; + hash += hash >> 6; + return hash; +} + +#define stbiw__zlib_flush() (out = stbiw__zlib_flushf(out, &bitbuf, &bitcount)) +#define stbiw__zlib_add(code,codebits) \ + (bitbuf |= (code) << bitcount, bitcount += (codebits), stbiw__zlib_flush()) +#define stbiw__zlib_huffa(b,c) stbiw__zlib_add(stbiw__zlib_bitrev(b,c),c) +// default huffman tables +#define stbiw__zlib_huff1(n) stbiw__zlib_huffa(0x30 + (n), 8) +#define stbiw__zlib_huff2(n) stbiw__zlib_huffa(0x190 + (n)-144, 9) +#define stbiw__zlib_huff3(n) stbiw__zlib_huffa(0 + (n)-256,7) +#define stbiw__zlib_huff4(n) stbiw__zlib_huffa(0xc0 + (n)-280,8) +#define stbiw__zlib_huff(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : (n) <= 255 ? stbiw__zlib_huff2(n) : (n) <= 279 ? stbiw__zlib_huff3(n) : stbiw__zlib_huff4(n)) +#define stbiw__zlib_huffb(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : stbiw__zlib_huff2(n)) + +#define stbiw__ZHASH 16384 + +unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality) +{ + static unsigned short lengthc[] = { 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, 259 }; + static unsigned char lengtheb[]= { 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 }; + static unsigned short distc[] = { 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, 32768 }; + static unsigned char disteb[] = { 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 }; + unsigned int bitbuf=0; + int i,j, bitcount=0; + unsigned char *out = NULL; + unsigned char ***hash_table = (unsigned char***) STBIW_MALLOC(stbiw__ZHASH * sizeof(char**)); + if (quality < 5) quality = 5; + + stbiw__sbpush(out, 0x78); // DEFLATE 32K window + stbiw__sbpush(out, 0x5e); // FLEVEL = 1 + stbiw__zlib_add(1,1); // BFINAL = 1 + stbiw__zlib_add(1,2); // BTYPE = 1 -- fixed huffman + + for (i=0; i < stbiw__ZHASH; ++i) + hash_table[i] = NULL; + + i=0; + while (i < data_len-3) { + // hash next 3 bytes of data to be compressed + int h = stbiw__zhash(data+i)&(stbiw__ZHASH-1), best=3; + unsigned char *bestloc = 0; + unsigned char **hlist = hash_table[h]; + int n = stbiw__sbcount(hlist); + for (j=0; j < n; ++j) { + if (hlist[j]-data > i-32768) { // if entry lies within window + int d = stbiw__zlib_countm(hlist[j], data+i, data_len-i); + if (d >= best) best=d,bestloc=hlist[j]; + } + } + // when hash table entry is too long, delete half the entries + if (hash_table[h] && stbiw__sbn(hash_table[h]) == 2*quality) { + STBIW_MEMMOVE(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality); + stbiw__sbn(hash_table[h]) = quality; + } + stbiw__sbpush(hash_table[h],data+i); + + if (bestloc) { + // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal + h = stbiw__zhash(data+i+1)&(stbiw__ZHASH-1); + hlist = hash_table[h]; + n = stbiw__sbcount(hlist); + for (j=0; j < n; ++j) { + if (hlist[j]-data > i-32767) { + int e = stbiw__zlib_countm(hlist[j], data+i+1, data_len-i-1); + if (e > best) { // if next match is better, bail on current match + bestloc = NULL; + break; + } + } + } + } + + if (bestloc) { + int d = (int) (data+i - bestloc); // distance back + STBIW_ASSERT(d <= 32767 && best <= 258); + for (j=0; best > lengthc[j+1]-1; ++j); + stbiw__zlib_huff(j+257); + if (lengtheb[j]) stbiw__zlib_add(best - lengthc[j], lengtheb[j]); + for (j=0; d > distc[j+1]-1; ++j); + stbiw__zlib_add(stbiw__zlib_bitrev(j,5),5); + if (disteb[j]) stbiw__zlib_add(d - distc[j], disteb[j]); + i += best; + } else { + stbiw__zlib_huffb(data[i]); + ++i; + } + } + // write out final bytes + for (;i < data_len; ++i) + stbiw__zlib_huffb(data[i]); + stbiw__zlib_huff(256); // end of block + // pad with 0 bits to byte boundary + while (bitcount) + stbiw__zlib_add(0,1); + + for (i=0; i < stbiw__ZHASH; ++i) + (void) stbiw__sbfree(hash_table[i]); + STBIW_FREE(hash_table); + + { + // compute adler32 on input + unsigned int s1=1, s2=0; + int blocklen = (int) (data_len % 5552); + j=0; + while (j < data_len) { + for (i=0; i < blocklen; ++i) s1 += data[j+i], s2 += s1; + s1 %= 65521, s2 %= 65521; + j += blocklen; + blocklen = 5552; + } + stbiw__sbpush(out, STBIW_UCHAR(s2 >> 8)); + stbiw__sbpush(out, STBIW_UCHAR(s2)); + stbiw__sbpush(out, STBIW_UCHAR(s1 >> 8)); + stbiw__sbpush(out, STBIW_UCHAR(s1)); + } + *out_len = stbiw__sbn(out); + // make returned pointer freeable + STBIW_MEMMOVE(stbiw__sbraw(out), out, *out_len); + return (unsigned char *) stbiw__sbraw(out); +} + +static unsigned int stbiw__crc32(unsigned char *buffer, int len) +{ + static unsigned int crc_table[256] = + { + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, + 0x0eDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, + 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, + 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, + 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, + 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, + 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, + 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, + 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, + 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, + 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, + 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, + 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, + 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, + 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, + 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, + 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, + 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, + 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, + 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, + 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, + 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, + 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, + 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, + 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, + 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, + 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, + 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, + 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, + 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, + 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D + }; + + unsigned int crc = ~0u; + int i; + for (i=0; i < len; ++i) + crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)]; + return ~crc; +} + +#define stbiw__wpng4(o,a,b,c,d) ((o)[0]=STBIW_UCHAR(a),(o)[1]=STBIW_UCHAR(b),(o)[2]=STBIW_UCHAR(c),(o)[3]=STBIW_UCHAR(d),(o)+=4) +#define stbiw__wp32(data,v) stbiw__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v)); +#define stbiw__wptag(data,s) stbiw__wpng4(data, s[0],s[1],s[2],s[3]) + +static void stbiw__wpcrc(unsigned char **data, int len) +{ + unsigned int crc = stbiw__crc32(*data - len - 4, len+4); + stbiw__wp32(*data, crc); +} + +static unsigned char stbiw__paeth(int a, int b, int c) +{ + int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c); + if (pa <= pb && pa <= pc) return STBIW_UCHAR(a); + if (pb <= pc) return STBIW_UCHAR(b); + return STBIW_UCHAR(c); +} + +// @OPTIMIZE: provide an option that always forces left-predict or paeth predict +unsigned char *stbi_write_png_to_mem(unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len) +{ + int ctype[5] = { -1, 0, 4, 2, 6 }; + unsigned char sig[8] = { 137,80,78,71,13,10,26,10 }; + unsigned char *out,*o, *filt, *zlib; + signed char *line_buffer; + int i,j,k,p,zlen; + + if (stride_bytes == 0) + stride_bytes = x * n; + + filt = (unsigned char *) STBIW_MALLOC((x*n+1) * y); if (!filt) return 0; + line_buffer = (signed char *) STBIW_MALLOC(x * n); if (!line_buffer) { STBIW_FREE(filt); return 0; } + for (j=0; j < y; ++j) { + static int mapping[] = { 0,1,2,3,4 }; + static int firstmap[] = { 0,1,0,5,6 }; + int *mymap = (j != 0) ? mapping : firstmap; + int best = 0, bestval = 0x7fffffff; + for (p=0; p < 2; ++p) { + for (k= p?best:0; k < 5; ++k) { // @TODO: clarity: rewrite this to go 0..5, and 'continue' the unwanted ones during 2nd pass + int type = mymap[k],est=0; + unsigned char *z = pixels + stride_bytes*j; + for (i=0; i < n; ++i) + switch (type) { + case 0: line_buffer[i] = z[i]; break; + case 1: line_buffer[i] = z[i]; break; + case 2: line_buffer[i] = z[i] - z[i-stride_bytes]; break; + case 3: line_buffer[i] = z[i] - (z[i-stride_bytes]>>1); break; + case 4: line_buffer[i] = (signed char) (z[i] - stbiw__paeth(0,z[i-stride_bytes],0)); break; + case 5: line_buffer[i] = z[i]; break; + case 6: line_buffer[i] = z[i]; break; + } + for (i=n; i < x*n; ++i) { + switch (type) { + case 0: line_buffer[i] = z[i]; break; + case 1: line_buffer[i] = z[i] - z[i-n]; break; + case 2: line_buffer[i] = z[i] - z[i-stride_bytes]; break; + case 3: line_buffer[i] = z[i] - ((z[i-n] + z[i-stride_bytes])>>1); break; + case 4: line_buffer[i] = z[i] - stbiw__paeth(z[i-n], z[i-stride_bytes], z[i-stride_bytes-n]); break; + case 5: line_buffer[i] = z[i] - (z[i-n]>>1); break; + case 6: line_buffer[i] = z[i] - stbiw__paeth(z[i-n], 0,0); break; + } + } + if (p) break; + for (i=0; i < x*n; ++i) + est += abs((signed char) line_buffer[i]); + if (est < bestval) { bestval = est; best = k; } + } + } + // when we get here, best contains the filter type, and line_buffer contains the data + filt[j*(x*n+1)] = (unsigned char) best; + STBIW_MEMMOVE(filt+j*(x*n+1)+1, line_buffer, x*n); + } + STBIW_FREE(line_buffer); + zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, 8); // increase 8 to get smaller but use more memory + STBIW_FREE(filt); + if (!zlib) return 0; + + // each tag requires 12 bytes of overhead + out = (unsigned char *) STBIW_MALLOC(8 + 12+13 + 12+zlen + 12); + if (!out) return 0; + *out_len = 8 + 12+13 + 12+zlen + 12; + + o=out; + STBIW_MEMMOVE(o,sig,8); o+= 8; + stbiw__wp32(o, 13); // header length + stbiw__wptag(o, "IHDR"); + stbiw__wp32(o, x); + stbiw__wp32(o, y); + *o++ = 8; + *o++ = STBIW_UCHAR(ctype[n]); + *o++ = 0; + *o++ = 0; + *o++ = 0; + stbiw__wpcrc(&o,13); + + stbiw__wp32(o, zlen); + stbiw__wptag(o, "IDAT"); + STBIW_MEMMOVE(o, zlib, zlen); + o += zlen; + STBIW_FREE(zlib); + stbiw__wpcrc(&o, zlen); + + stbiw__wp32(o,0); + stbiw__wptag(o, "IEND"); + stbiw__wpcrc(&o,0); + + STBIW_ASSERT(o == out + *out_len); + + return out; +} + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes) +{ + FILE *f; + int len; + unsigned char *png = stbi_write_png_to_mem((unsigned char *) data, stride_bytes, x, y, comp, &len); + if (png == NULL) return 0; + f = fopen(filename, "wb"); + if (!f) { STBIW_FREE(png); return 0; } + fwrite(png, 1, len, f); + fclose(f); + STBIW_FREE(png); + return 1; +} +#endif + +STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int stride_bytes) +{ + int len; + unsigned char *png = stbi_write_png_to_mem((unsigned char *) data, stride_bytes, x, y, comp, &len); + if (png == NULL) return 0; + func(context, png, len); + STBIW_FREE(png); + return 1; +} + +#endif // STB_IMAGE_WRITE_IMPLEMENTATION + +/* Revision history + 1.04 (2017-03-03) + monochrome BMP expansion + 1.03 ??? + 1.02 (2016-04-02) + avoid allocating large structures on the stack + 1.01 (2016-01-16) + STBIW_REALLOC_SIZED: support allocators with no realloc support + avoid race-condition in crc initialization + minor compile issues + 1.00 (2015-09-14) + installable file IO function + 0.99 (2015-09-13) + warning fixes; TGA rle support + 0.98 (2015-04-08) + added STBIW_MALLOC, STBIW_ASSERT etc + 0.97 (2015-01-18) + fixed HDR asserts, rewrote HDR rle logic + 0.96 (2015-01-17) + add HDR output + fix monochrome BMP + 0.95 (2014-08-17) + add monochrome TGA output + 0.94 (2014-05-31) + rename private functions to avoid conflicts with stb_image.h + 0.93 (2014-05-27) + warning fixes + 0.92 (2010-08-01) + casts to unsigned char to fix warnings + 0.91 (2010-07-17) + first public release + 0.90 first internal release +*/ + +/* +------------------------------------------------------------------------------ +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/slang.h b/slang.h new file mode 100644 index 000000000..a4fef24ba --- /dev/null +++ b/slang.h @@ -0,0 +1,897 @@ +#ifndef SLANG_H +#define SLANG_H + +#ifdef _MSC_VER +#ifdef SLANG_COMPILING_DLL +#define SLANG_API __declspec(dllexport) +#else +#ifdef SLANG_DYNAMIC +#define SLANG_API __declspec(dllimport) +#else +#define SLANG_API +#endif +#endif +#else +#define SLANG_API +#endif + +#ifndef SLANG_NO_INTTYPES +#include +#endif // ! SLANG_NO_INTTYPES + + +#ifdef __cplusplus +extern "C" +{ +#endif + /*! + @mainpage Introduction + + API Reference: slang.h + + @file slang.h + */ + + typedef uint32_t SlangUInt32; + typedef intptr_t SlangInt; + typedef uintptr_t SlangUInt; + + /*! + @brief Severity of a diagnostic generated by the compiler. + Values come from the enum below, with higher values representing more severe + conditions, and all values >= SLANG_SEVERITY_ERROR indicating compilation + failure. + */ + typedef int SlangSeverity; + enum + { + SLANG_SEVERITY_NOTE = 0, /**< An informative message. */ + SLANG_SEVERITY_WARNING, /**< A warning, which indicates a possible proble. */ + SLANG_SEVERITY_ERROR, /**< An error, indicating that compilation failed. */ + SLANG_SEVERITY_FATAL, /**< An unrecoverable error, which forced compilation to abort. */ + SLANG_SEVERITY_INTERNAL, /**< An internal error, indicating a logic error in the compiler. */ + }; + + typedef int SlangBindableResourceType; + enum + { + SLANG_NON_BINDABLE = 0, + SLANG_TEXTURE, + SLANG_SAMPLER, + SLANG_UNIFORM_BUFFER, + SLANG_STORAGE_BUFFER, + }; + + typedef int SlangCompileTarget; + enum + { + SLANG_TARGET_UNKNOWN, + SLANG_GLSL, + SLANG_GLSL_VULKAN, + SLANG_GLSL_VULKAN_ONE_DESC, + SLANG_HLSL, + SLANG_SPIRV, + SLANG_SPIRV_ASM, + SLANG_DXBC, + SLANG_DXBC_ASM, + SLANG_REFLECTION_JSON, + }; + + typedef int SlangPassThrough; + enum + { + SLANG_PASS_THROUGH_NONE, + SLANG_PASS_THROUGH_FXC, + SLANG_PASS_THROUGH_DXC, + SLANG_PASS_THROUGH_GLSLANG, + }; + + /*! + Flags to control compilation behavior. + */ + typedef unsigned int SlangCompileFlags; + enum + { + SLANG_COMPILE_FLAG_NO_CHECKING = 1 << 0, /**< Disable semantic checking as much as possible. */ + }; + + typedef int SlangSourceLanguage; + enum + { + SLANG_SOURCE_LANGUAGE_UNKNOWN, + SLANG_SOURCE_LANGUAGE_SLANG, + SLANG_SOURCE_LANGUAGE_HLSL, + SLANG_SOURCE_LANGUAGE_GLSL, + }; + + typedef unsigned int SlangProfileID; + enum + { + SLANG_PROFILE_UNKNOWN, + }; + +//#define SLANG_LAYOUT_UNIFORM 0 +//#define SLANG_LAYOUT_PACKED 1 +//#define SLANG_LAYOUT_STORAGE 2 + +#define SLANG_ERROR_INSUFFICIENT_BUFFER -1 +#define SLANG_ERROR_INVALID_PARAMETER -2 + + /*! + @brief An instance of the Slang library. + */ + typedef struct SlangSession SlangSession; + + /*! + @bref A request for one or more compilation actions to be performed. + */ + typedef struct SlangCompileRequest SlangCompileRequest; + + /*! + @brief Initialize an instance of the Slang library. + @param cacheDir The directory used to store cached compilation results. Pass NULL to disable caching. + */ + SLANG_API SlangSession* spCreateSession(const char * cacheDir); + + /*! + @brief Clean up after an instance of the Slang library. + */ + SLANG_API void spDestroySession( + SlangSession* session); + + + /*! + @brief Add new builtin declarations to be used in subsequent compiles. + */ + SLANG_API void spAddBuiltins( + SlangSession* session, + char const* sourcePath, + char const* sourceString); + + /*! + @brief Create a compile request. + */ + SLANG_API SlangCompileRequest* spCreateCompileRequest( + SlangSession* session); + + /*! + @brief Destroy a compile request. + */ + SLANG_API void spDestroyCompileRequest( + SlangCompileRequest* request); + + + /*! + @brief Set flags to be used for compilation. + */ + SLANG_API void spSetCompileFlags( + SlangCompileRequest* request, + SlangCompileFlags flags); + + /*! + @brief Sets the target for code generation. + @param ctx The compilation context. + @param target The code generation target. Possible values are: + - SLANG_GLSL. Generates GLSL code. + - SLANG_HLSL. Generates HLSL code. + - SLANG_SPIRV. Generates SPIR-V code. + */ + SLANG_API void spSetCodeGenTarget( + SlangCompileRequest* request, + int target); + + SLANG_API void spSetPassThrough( + SlangCompileRequest* request, + SlangPassThrough passThrough); + + typedef void(*SlangDiagnosticCallback)( + char const* message, + void* userData); + + SLANG_API void spSetDiagnosticCallback( + SlangCompileRequest* request, + SlangDiagnosticCallback callback, + void const* userData); + + /*! + @brief Add a path in which source files are being search. When the programmer specifies @code using @endcode in code, the compiler searches the file + in all search pathes in order. + @param ctx The compilation context. + @param searchDir The additional search directory. + */ + SLANG_API void spAddSearchPath( + SlangCompileRequest* request, + const char* searchDir); + + /*! + @brief Add a macro definition to be used during preprocessing. + @param key The name of the macro to define. + @param value The value of the macro to define. + */ + SLANG_API void spAddPreprocessorDefine( + SlangCompileRequest* request, + const char* key, + const char* value); + + + /** Add a distinct translation unit to the compilation request + + `name` is optional. + Returns the zero-based index of the translation unit created. + */ + SLANG_API int spAddTranslationUnit( + SlangCompileRequest* request, + SlangSourceLanguage language, + char const* name); + + /** Add a source file to the given translation unit + */ + SLANG_API void spAddTranslationUnitSourceFile( + SlangCompileRequest* request, + int translationUnitIndex, + char const* path); + + /** Add a source string to the given translation unit + + The `path` will be used in any diagnostic output. + */ + SLANG_API void spAddTranslationUnitSourceString( + SlangCompileRequest* request, + int translationUnitIndex, + char const* path, + char const* source); + + /** Look up a compilation profile by name. + + For example, one could look up the string `"ps_5_0"` to find the corresponding target ID. + */ + SLANG_API SlangProfileID spFindProfile( + SlangSession* session, + char const* name); + + /** Add an entry point in a particular translation unit + */ + SLANG_API int spAddTranslationUnitEntryPoint( + SlangCompileRequest* request, + int translationUnitIndex, + char const* name, + SlangProfileID profile); + + /** Execute the compilation request. + + Returns zero on success, non-zero on failure. + */ + SLANG_API int spCompile( + SlangCompileRequest* request); + + + /** Get any diagnostic messages reported by the compiler. + */ + SLANG_API char const* spGetDiagnosticOutput( + SlangCompileRequest* request); + + /** Get the number of files that this compilation depended on. + + This includes both the explicit source files, as well as any + additional files that were transitively referenced (e.g., via + a `#include` directive). + */ + SLANG_API int + spGetDependencyFileCount( + SlangCompileRequest* request); + + /** Get the path to a file this compilation dependend on. + */ + SLANG_API char const* + spGetDependencyFilePath( + SlangCompileRequest* request, + int index); + + /** Get the number of tranlsation units associated with the compilation request + */ + SLANG_API int + spGetTranslationUnitCount( + SlangCompileRequest* request); + + /** Get the output code associated with a specific translation unit + + The lifetime of the output pointer is the same as `request`. + */ + SLANG_API char const* spGetTranslationUnitSource( + SlangCompileRequest* request, + int translationUnitIndex); + + /** Get the output code associated with a specific entry point. + + The lifetime of the output pointer is the same as `request`. + */ + SLANG_API char const* spGetEntryPointSource( + SlangCompileRequest* request, + int translationUnitIndex, + int entryPointIndex); + + + /* Note(tfoley): working on new reflection interface... + */ + + typedef struct SlangReflection SlangReflection; + typedef struct SlangReflectionEntryPoint SlangReflectionEntryPoint; + typedef struct SlangReflectionType SlangReflectionType; + typedef struct SlangReflectionTypeLayout SlangReflectionTypeLayout; + typedef struct SlangReflectionVariable SlangReflectionVariable; + typedef struct SlangReflectionVariableLayout SlangReflectionVariableLayout; + + // get reflection data from a compilation request + SLANG_API SlangReflection* spGetReflection( + SlangCompileRequest* request); + + // type reflection + + typedef unsigned int SlangTypeKind; + enum + { + SLANG_TYPE_KIND_NONE, + SLANG_TYPE_KIND_STRUCT, + SLANG_TYPE_KIND_ARRAY, + SLANG_TYPE_KIND_MATRIX, + SLANG_TYPE_KIND_VECTOR, + SLANG_TYPE_KIND_SCALAR, + SLANG_TYPE_KIND_CONSTANT_BUFFER, + SLANG_TYPE_KIND_RESOURCE, + SLANG_TYPE_KIND_SAMPLER_STATE, + + SLANG_TYPE_KIND_COUNT, + }; + + typedef unsigned int SlangScalarType; + enum + { + SLANG_SCALAR_TYPE_NONE, + SLANG_SCALAR_TYPE_VOID, + SLANG_SCALAR_TYPE_BOOL, + SLANG_SCALAR_TYPE_INT32, + SLANG_SCALAR_TYPE_UINT32, + SLANG_SCALAR_TYPE_INT64, + SLANG_SCALAR_TYPE_UINT64, + SLANG_SCALAR_TYPE_FLOAT16, + SLANG_SCALAR_TYPE_FLOAT32, + SLANG_SCALAR_TYPE_FLOAT64, + }; + + typedef unsigned int SlangResourceShape; + enum + { + SLANG_RESOURCE_BASE_SHAPE_MASK = 0x0F, + + SLANG_RESOURCE_NONE = 0x00, + + SLANG_TEXTURE_1D = 0x01, + SLANG_TEXTURE_2D = 0x02, + SLANG_TEXTURE_3D = 0x03, + SLANG_TEXTURE_CUBE = 0x04, + SLANG_TEXTURE_BUFFER = 0x05, + + SLANG_STRUCTURED_BUFFER = 0x06, + SLANG_BYTE_ADDRESS_BUFFER = 0x07, + SLANG_RESOURCE_UNKNOWN = 0x08, + + SLANG_RESOURCE_EXT_SHAPE_MASK = 0xF0, + SLANG_TEXTURE_ARRAY_FLAG = 0x40, + SLANG_TEXTURE_MULTISAMPLE_FLAG = 0x80, + + SLANG_TEXTURE_1D_ARRAY = SLANG_TEXTURE_1D | SLANG_TEXTURE_ARRAY_FLAG, + SLANG_TEXTURE_2D_ARRAY = SLANG_TEXTURE_2D | SLANG_TEXTURE_ARRAY_FLAG, + SLANG_TEXTURE_CUBE_ARRAY = SLANG_TEXTURE_CUBE | SLANG_TEXTURE_ARRAY_FLAG, + + SLANG_TEXTURE_2D_MULTISAMPLE = SLANG_TEXTURE_2D | SLANG_TEXTURE_MULTISAMPLE_FLAG, + SLANG_TEXTURE_2D_MULTISAMPLE_ARRAY = SLANG_TEXTURE_2D | SLANG_TEXTURE_MULTISAMPLE_FLAG | SLANG_TEXTURE_ARRAY_FLAG, + }; + + typedef unsigned int SlangResourceAccess; + enum + { + SLANG_RESOURCE_ACCESS_NONE, + SLANG_RESOURCE_ACCESS_READ, + SLANG_RESOURCE_ACCESS_READ_WRITE, + SLANG_RESOURCE_ACCESS_RASTER_ORDERED, + SLANG_RESOURCE_ACCESS_APPEND, + SLANG_RESOURCE_ACCESS_CONSUME, + }; + + typedef unsigned int SlangParameterCategory; + enum + { + SLANG_PARAMETER_CATEGORY_NONE, + SLANG_PARAMETER_CATEGORY_CONSTANT_BUFFER, + SLANG_PARAMETER_CATEGORY_SHADER_RESOURCE, + SLANG_PARAMETER_CATEGORY_UNORDERED_ACCESS, + SLANG_PARAMETER_CATEGORY_VERTEX_INPUT, + SLANG_PARAMETER_CATEGORY_FRAGMENT_OUTPUT, + SLANG_PARAMETER_CATEGORY_SAMPLER_STATE, + SLANG_PARAMETER_CATEGORY_UNIFORM, + SLANG_PARAMETER_CATEGORY_DESCRIPTOR_TABLE_SLOT, + SLANG_PARAMETER_CATEGORY_SPECIALIZTION_CONSTANT, + SLANG_PARAMETER_CATEGORY_MIXED, + }; + + typedef SlangUInt32 SlangStage; + enum + { + SLANG_STAGE_NONE, + SLANG_STAGE_VERTEX, + SLANG_STAGE_HULL, + SLANG_STAGE_DOMAIN, + SLANG_STAGE_GEOMETRY, + SLANG_STAGE_FRAGMENT, + SLANG_STAGE_COMPUTE, + + SLANG_STAGE_PIXEL = SLANG_STAGE_FRAGMENT, + }; + + // Type Reflection + + SLANG_API SlangTypeKind spReflectionType_GetKind(SlangReflectionType* type); + SLANG_API unsigned int spReflectionType_GetFieldCount(SlangReflectionType* type); + SLANG_API SlangReflectionVariable* spReflectionType_GetFieldByIndex(SlangReflectionType* type, unsigned index); + + SLANG_API size_t spReflectionType_GetElementCount(SlangReflectionType* type); + SLANG_API SlangReflectionType* spReflectionType_GetElementType(SlangReflectionType* type); + + SLANG_API unsigned int spReflectionType_GetRowCount(SlangReflectionType* type); + SLANG_API unsigned int spReflectionType_GetColumnCount(SlangReflectionType* type); + SLANG_API SlangScalarType spReflectionType_GetScalarType(SlangReflectionType* type); + + SLANG_API SlangResourceShape spReflectionType_GetResourceShape(SlangReflectionType* type); + SLANG_API SlangResourceAccess spReflectionType_GetResourceAccess(SlangReflectionType* type); + SLANG_API SlangReflectionType* spReflectionType_GetResourceResultType(SlangReflectionType* type); + + // Type Layout Reflection + + SLANG_API SlangReflectionType* spReflectionTypeLayout_GetType(SlangReflectionTypeLayout* type); + SLANG_API size_t spReflectionTypeLayout_GetSize(SlangReflectionTypeLayout* type, SlangParameterCategory category); + + SLANG_API SlangReflectionVariableLayout* spReflectionTypeLayout_GetFieldByIndex(SlangReflectionTypeLayout* type, unsigned index); + + SLANG_API size_t spReflectionTypeLayout_GetElementStride(SlangReflectionTypeLayout* type, SlangParameterCategory category); + SLANG_API SlangReflectionTypeLayout* spReflectionTypeLayout_GetElementTypeLayout(SlangReflectionTypeLayout* type); + + SLANG_API SlangParameterCategory spReflectionTypeLayout_GetParameterCategory(SlangReflectionTypeLayout* type); + + SLANG_API unsigned spReflectionTypeLayout_GetCategoryCount(SlangReflectionTypeLayout* type); + SLANG_API SlangParameterCategory spReflectionTypeLayout_GetCategoryByIndex(SlangReflectionTypeLayout* type, unsigned index); + + // Variable Reflection + + SLANG_API char const* spReflectionVariable_GetName(SlangReflectionVariable* var); + SLANG_API SlangReflectionType* spReflectionVariable_GetType(SlangReflectionVariable* var); + + // Variable Layout Reflection + + SLANG_API SlangReflectionVariable* spReflectionVariableLayout_GetVariable(SlangReflectionVariableLayout* var); + + SLANG_API SlangReflectionTypeLayout* spReflectionVariableLayout_GetTypeLayout(SlangReflectionVariableLayout* var); + + SLANG_API size_t spReflectionVariableLayout_GetOffset(SlangReflectionVariableLayout* var, SlangParameterCategory category); + SLANG_API size_t spReflectionVariableLayout_GetSpace(SlangReflectionVariableLayout* var, SlangParameterCategory category); + + // Shader Parameter Reflection + + typedef SlangReflectionVariableLayout SlangReflectionParameter; + + SLANG_API unsigned spReflectionParameter_GetBindingIndex(SlangReflectionParameter* parameter); + SLANG_API unsigned spReflectionParameter_GetBindingSpace(SlangReflectionParameter* parameter); + + // Entry Point Reflection + + SLANG_API SlangStage spReflectionEntryPoint_getStage(SlangReflectionEntryPoint* entryPoint); + + SLANG_API void spReflectionEntryPoint_getComputeThreadGroupSize( + SlangReflectionEntryPoint* entryPoint, + SlangUInt axisCount, + SlangUInt* outSizeAlongAxis); + + // Shader Reflection + + SLANG_API unsigned spReflection_GetParameterCount(SlangReflection* reflection); + SLANG_API SlangReflectionParameter* spReflection_GetParameterByIndex(SlangReflection* reflection, unsigned index); + + + SLANG_API SlangUInt spReflection_getEntryPointCount(SlangReflection* reflection); + + SLANG_API SlangReflectionEntryPoint* spReflection_getEntryPointByIndex(SlangReflection* reflection, SlangUInt index); + +#ifdef __cplusplus +} + +/* Helper interfaces for C++ users */ +namespace slang +{ +#define SLANG_SAFE_BOOL(expr) \ + operator bool() const { return expr; } + + struct BufferReflection; + struct TypeLayoutReflection; + struct TypeReflection; + struct VariableLayoutReflection; + struct VariableReflection; + + struct TypeReflection + { + enum class Kind + { + None = SLANG_TYPE_KIND_NONE, + Struct = SLANG_TYPE_KIND_STRUCT, + Array = SLANG_TYPE_KIND_ARRAY, + Matrix = SLANG_TYPE_KIND_MATRIX, + Vector = SLANG_TYPE_KIND_VECTOR, + Scalar = SLANG_TYPE_KIND_SCALAR, + ConstantBuffer = SLANG_TYPE_KIND_CONSTANT_BUFFER, + Resource = SLANG_TYPE_KIND_RESOURCE, + SamplerState = SLANG_TYPE_KIND_SAMPLER_STATE, + }; + + enum ScalarType : SlangScalarType + { + None = SLANG_SCALAR_TYPE_NONE, + Void = SLANG_SCALAR_TYPE_VOID, + Bool = SLANG_SCALAR_TYPE_BOOL, + Int32 = SLANG_SCALAR_TYPE_INT32, + UInt32 = SLANG_SCALAR_TYPE_UINT32, + Int64 = SLANG_SCALAR_TYPE_INT64, + UInt64 = SLANG_SCALAR_TYPE_UINT64, + Float16 = SLANG_SCALAR_TYPE_FLOAT16, + Float32 = SLANG_SCALAR_TYPE_FLOAT32, + Float64 = SLANG_SCALAR_TYPE_FLOAT64, + }; + + Kind getKind() + { + return (Kind) spReflectionType_GetKind((SlangReflectionType*) this); + } + + // only useful if `getKind() == Kind::Struct` + unsigned int getFieldCount() + { + return spReflectionType_GetFieldCount((SlangReflectionType*) this); + } + + VariableReflection* getFieldByIndex(unsigned int index) + { + return (VariableReflection*) spReflectionType_GetFieldByIndex((SlangReflectionType*) this, index); + } + + bool isArray() { return getKind() == TypeReflection::Kind::Array; } + + TypeReflection* unwrapArray() + { + TypeReflection* type = this; + while( type->isArray() ) + { + type = type->getElementType(); + } + return type; + } + + // only useful if `getKind() == Kind::Array` + size_t getElementCount() + { + return spReflectionType_GetElementCount((SlangReflectionType*) this); + } + + size_t getTotalArrayElementCount() + { + if(!isArray()) return 0; + size_t result = 1; + TypeReflection* type = this; + for(;;) + { + if(!type->isArray()) + return result; + + result *= type->getElementCount(); + type = type->getElementType(); + } + } + + TypeReflection* getElementType() + { + return (TypeReflection*) spReflectionType_GetElementType((SlangReflectionType*) this); + } + + unsigned getRowCount() + { + return spReflectionType_GetRowCount((SlangReflectionType*) this); + } + + unsigned getColumnCount() + { + return spReflectionType_GetColumnCount((SlangReflectionType*) this); + } + + ScalarType getScalarType() + { + return (ScalarType) spReflectionType_GetScalarType((SlangReflectionType*) this); + } + + TypeReflection* getResourceResultType() + { + return (TypeReflection*) spReflectionType_GetResourceResultType((SlangReflectionType*) this); + } + + SlangResourceShape getResourceShape() + { + return spReflectionType_GetResourceShape((SlangReflectionType*) this); + } + + SlangResourceAccess getResourceAccess() + { + return spReflectionType_GetResourceAccess((SlangReflectionType*) this); + } + }; + + enum ParameterCategory : SlangParameterCategory + { + // TODO: these aren't scoped... + None = SLANG_PARAMETER_CATEGORY_NONE, + ConstantBuffer = SLANG_PARAMETER_CATEGORY_CONSTANT_BUFFER, + ShaderResource = SLANG_PARAMETER_CATEGORY_SHADER_RESOURCE, + UnorderedAccess = SLANG_PARAMETER_CATEGORY_UNORDERED_ACCESS, + VertexInput = SLANG_PARAMETER_CATEGORY_VERTEX_INPUT, + FragmentOutput = SLANG_PARAMETER_CATEGORY_FRAGMENT_OUTPUT, + SamplerState = SLANG_PARAMETER_CATEGORY_SAMPLER_STATE, + Uniform = SLANG_PARAMETER_CATEGORY_UNIFORM, + DescriptorTableSlot = SLANG_PARAMETER_CATEGORY_DESCRIPTOR_TABLE_SLOT, + SpecializationConstant = SLANG_PARAMETER_CATEGORY_SPECIALIZTION_CONSTANT, + Mixed = SLANG_PARAMETER_CATEGORY_MIXED, + }; + + struct TypeLayoutReflection + { + TypeReflection* getType() + { + return (TypeReflection*) spReflectionTypeLayout_GetType((SlangReflectionTypeLayout*) this); + } + + TypeReflection::Kind getKind() { return getType()->getKind(); } + + size_t getSize(SlangParameterCategory category = SLANG_PARAMETER_CATEGORY_UNIFORM) + { + return spReflectionTypeLayout_GetSize((SlangReflectionTypeLayout*) this, category); + } + + unsigned int getFieldCount() + { + return getType()->getFieldCount(); + } + + VariableLayoutReflection* getFieldByIndex(unsigned int index) + { + return (VariableLayoutReflection*) spReflectionTypeLayout_GetFieldByIndex((SlangReflectionTypeLayout*) this, index); + } + + bool isArray() { return getType()->isArray(); } + + TypeLayoutReflection* unwrapArray() + { + TypeLayoutReflection* typeLayout = this; + while( typeLayout->isArray() ) + { + typeLayout = typeLayout->getElementTypeLayout(); + } + return typeLayout; + } + + // only useful if `getKind() == Kind::Array` + size_t getElementCount() + { + return getType()->getElementCount(); + } + + size_t getTotalArrayElementCount() + { + return getType()->getTotalArrayElementCount(); + } + + size_t getElementStride(SlangParameterCategory category) + { + return spReflectionTypeLayout_GetElementStride((SlangReflectionTypeLayout*) this, category); + } + + TypeLayoutReflection* getElementTypeLayout() + { + return (TypeLayoutReflection*) spReflectionTypeLayout_GetElementTypeLayout((SlangReflectionTypeLayout*) this); + } + + // How is this type supposed to be bound? + ParameterCategory getParameterCategory() + { + return (ParameterCategory) spReflectionTypeLayout_GetParameterCategory((SlangReflectionTypeLayout*) this); + } + + unsigned int getCategoryCount() + { + return spReflectionTypeLayout_GetCategoryCount((SlangReflectionTypeLayout*) this); + } + + ParameterCategory getCategoryByIndex(unsigned int index) + { + return (ParameterCategory) spReflectionTypeLayout_GetCategoryByIndex((SlangReflectionTypeLayout*) this, index); + } + + unsigned getRowCount() + { + return getType()->getRowCount(); + } + + unsigned getColumnCount() + { + return getType()->getColumnCount(); + } + + TypeReflection::ScalarType getScalarType() + { + return getType()->getScalarType(); + } + + TypeReflection* getResourceResultType() + { + return getType()->getResourceResultType(); + } + + SlangResourceShape getResourceShape() + { + return getType()->getResourceShape(); + } + + SlangResourceAccess getResourceAccess() + { + return getType()->getResourceAccess(); + } + + }; + + struct VariableReflection + { + char const* getName() + { + return spReflectionVariable_GetName((SlangReflectionVariable*) this); + } + + TypeReflection* getType() + { + return (TypeReflection*) spReflectionVariable_GetType((SlangReflectionVariable*) this); + } + }; + + struct VariableLayoutReflection + { + VariableReflection* getVariable() + { + return (VariableReflection*) spReflectionVariableLayout_GetVariable((SlangReflectionVariableLayout*) this); + } + + char const* getName() + { + return getVariable()->getName(); + } + + TypeLayoutReflection* getTypeLayout() + { + return (TypeLayoutReflection*) spReflectionVariableLayout_GetTypeLayout((SlangReflectionVariableLayout*) this); + } + + ParameterCategory getCategory() + { + return getTypeLayout()->getParameterCategory(); + } + + unsigned int getCategoryCount() + { + return getTypeLayout()->getCategoryCount(); + } + + ParameterCategory getCategoryByIndex(unsigned int index) + { + return getTypeLayout()->getCategoryByIndex(index); + } + + + size_t getOffset(SlangParameterCategory category = SLANG_PARAMETER_CATEGORY_UNIFORM) + { + return spReflectionVariableLayout_GetOffset((SlangReflectionVariableLayout*) this, category); + } + + TypeReflection* getType() + { + return getVariable()->getType(); + } + + unsigned getBindingIndex() + { + return spReflectionParameter_GetBindingIndex((SlangReflectionVariableLayout*) this); + } + + unsigned getBindingSpace() + { + return spReflectionParameter_GetBindingSpace((SlangReflectionVariableLayout*) this); + } + + size_t getBindingSpace(SlangParameterCategory category) + { + return spReflectionVariableLayout_GetSpace((SlangReflectionVariableLayout*) this, category); + } + }; + + struct EntryPointReflection + { + SlangStage getStage() + { + return spReflectionEntryPoint_getStage((SlangReflectionEntryPoint*) this); + } + + void getComputeThreadGroupSize( + SlangUInt axisCount, + SlangUInt* outSizeAlongAxis) + { + return spReflectionEntryPoint_getComputeThreadGroupSize((SlangReflectionEntryPoint*) this, axisCount, outSizeAlongAxis); + } + }; + + struct ShaderReflection + { + unsigned getParameterCount() + { + return spReflection_GetParameterCount((SlangReflection*) this); + } + + VariableLayoutReflection* getParameterByIndex(unsigned index) + { + return (VariableLayoutReflection*) spReflection_GetParameterByIndex((SlangReflection*) this, index); + } + + static ShaderReflection* get(SlangCompileRequest* request) + { + return (ShaderReflection*) spGetReflection(request); + } + + SlangUInt getEntryPointCount() + { + return spReflection_getEntryPointCount((SlangReflection*) this); + } + + EntryPointReflection* getEntryPointByIndex(SlangUInt index) + { + return (EntryPointReflection*) spReflection_getEntryPointByIndex((SlangReflection*) this, index); + } + }; +} + +#endif + +#ifdef SLANG_INCLUDE_IMPLEMENTATION + +#include "source/core/slang-io.cpp" +#include "source/core/slang-math.cpp" +#include "source/core/slang-string.cpp" +#include "source/core/stream.cpp" +#include "source/core/text-io.cpp" +#include "source/slang/diagnostics.cpp" +#include "source/slang/emit.cpp" +#include "source/slang/lexer.cpp" +#include "source/slang/parameter-binding.cpp" +#include "source/slang/parser.cpp" +#include "source/slang/preprocessor.cpp" +#include "source/slang/lookup.cpp" +#include "source/slang/check.cpp" +#include "source/slang/compiler.cpp" +#include "source/slang/slang-stdlib.cpp" +#include "source/slang/syntax.cpp" +#include "source/slang/token.cpp" +#include "source/slang/type-layout.cpp" +#include "source/slang/reflection.cpp" +#include "source/slang/slang.cpp" + + +#endif + +#endif diff --git a/slang.sln b/slang.sln new file mode 100644 index 000000000..70fc8aaa9 --- /dev/null +++ b/slang.sln @@ -0,0 +1,460 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "slang", "slang", "{362538E0-CA8A-4F9A-AC99-15CC9A715A43}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "examples", "examples", "{B625E3E2-3B0B-4A01-9D10-957F84092E10}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "hello", "examples\hello\hello.vcxproj", "{E6385042-1649-4803-9EBD-168F8B7EF131}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "core", "source\core\core.vcxproj", "{F9BE7957-8399-899E-0C49-E714FDDD4B65}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "utils", "utils", "{37016FF6-E6AF-4316-BC2B-0152FC0C969E}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{74C5F0DC-93BB-4BF3-AC65-8C65491570F7}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "slang", "source\slang\slang.vcxproj", "{DB00DA62-0533-4AFD-B59F-A67D5B3A0808}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "slangc", "source\slangc\slangc.vcxproj", "{D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "slang-test", "tools\slang-test\slang-test.vcxproj", "{0C768A18-1D25-4000-9F37-DA5FE99E3B64}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "render-test", "tools\render-test\render-test.vcxproj", "{96610759-07B9-4EEB-A974-5C634A2E742B}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "glslang", "tools\glslang\glslang.vcxproj", "{C495878A-832C-485B-B347-0998A90CC936}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug_VS2013|Any CPU = Debug_VS2013|Any CPU + Debug_VS2013|ARM = Debug_VS2013|ARM + Debug_VS2013|Win32 = Debug_VS2013|Win32 + Debug_VS2013|x64 = Debug_VS2013|x64 + Debug|Any CPU = Debug|Any CPU + Debug|ARM = Debug|ARM + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + DebugClang|Any CPU = DebugClang|Any CPU + DebugClang|ARM = DebugClang|ARM + DebugClang|Win32 = DebugClang|Win32 + DebugClang|x64 = DebugClang|x64 + Release_VS2013|Any CPU = Release_VS2013|Any CPU + Release_VS2013|ARM = Release_VS2013|ARM + Release_VS2013|Win32 = Release_VS2013|Win32 + Release_VS2013|x64 = Release_VS2013|x64 + Release|Any CPU = Release|Any CPU + Release|ARM = Release|ARM + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + TracingDebug|Any CPU = TracingDebug|Any CPU + TracingDebug|ARM = TracingDebug|ARM + TracingDebug|Win32 = TracingDebug|Win32 + TracingDebug|x64 = TracingDebug|x64 + TracingRelease|Any CPU = TracingRelease|Any CPU + TracingRelease|ARM = TracingRelease|ARM + TracingRelease|Win32 = TracingRelease|Win32 + TracingRelease|x64 = TracingRelease|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {E6385042-1649-4803-9EBD-168F8B7EF131}.Debug_VS2013|Any CPU.ActiveCfg = Debug_VS2013|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Debug_VS2013|ARM.ActiveCfg = Debug_VS2013|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Debug_VS2013|Win32.ActiveCfg = Debug_VS2013|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Debug_VS2013|Win32.Build.0 = Debug_VS2013|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Debug_VS2013|x64.ActiveCfg = Debug_VS2013|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Debug_VS2013|x64.Build.0 = Debug_VS2013|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Debug|Any CPU.ActiveCfg = Debug|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Debug|ARM.ActiveCfg = Debug|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Debug|Win32.ActiveCfg = Debug|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Debug|Win32.Build.0 = Debug|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Debug|x64.ActiveCfg = Debug|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Debug|x64.Build.0 = Debug|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.DebugClang|Any CPU.ActiveCfg = Release_VS2013|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.DebugClang|Any CPU.Build.0 = Release_VS2013|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.DebugClang|ARM.ActiveCfg = Release_VS2013|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.DebugClang|ARM.Build.0 = Release_VS2013|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.DebugClang|Win32.ActiveCfg = Debug|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.DebugClang|Win32.Build.0 = Debug|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.DebugClang|x64.ActiveCfg = Debug|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.DebugClang|x64.Build.0 = Debug|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Release_VS2013|Any CPU.ActiveCfg = Release_VS2013|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Release_VS2013|ARM.ActiveCfg = Release_VS2013|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Release_VS2013|Win32.ActiveCfg = Release_VS2013|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Release_VS2013|Win32.Build.0 = Release_VS2013|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Release_VS2013|x64.ActiveCfg = Release_VS2013|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Release_VS2013|x64.Build.0 = Release_VS2013|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Release|Any CPU.ActiveCfg = Release|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Release|ARM.ActiveCfg = Release|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Release|Win32.ActiveCfg = Release|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Release|Win32.Build.0 = Release|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Release|x64.ActiveCfg = Release|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.Release|x64.Build.0 = Release|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.TracingDebug|Any CPU.ActiveCfg = Release_VS2013|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.TracingDebug|Any CPU.Build.0 = Release_VS2013|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.TracingDebug|ARM.ActiveCfg = Release_VS2013|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.TracingDebug|ARM.Build.0 = Release_VS2013|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.TracingDebug|Win32.ActiveCfg = Debug|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.TracingDebug|Win32.Build.0 = Debug|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.TracingDebug|x64.ActiveCfg = Debug|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.TracingDebug|x64.Build.0 = Debug|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.TracingRelease|Any CPU.ActiveCfg = Release_VS2013|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.TracingRelease|Any CPU.Build.0 = Release_VS2013|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.TracingRelease|ARM.ActiveCfg = Release_VS2013|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.TracingRelease|ARM.Build.0 = Release_VS2013|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.TracingRelease|Win32.ActiveCfg = Release|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.TracingRelease|Win32.Build.0 = Release|Win32 + {E6385042-1649-4803-9EBD-168F8B7EF131}.TracingRelease|x64.ActiveCfg = Release|x64 + {E6385042-1649-4803-9EBD-168F8B7EF131}.TracingRelease|x64.Build.0 = Release|x64 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Debug_VS2013|Any CPU.ActiveCfg = Debug_VS2013|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Debug_VS2013|ARM.ActiveCfg = Debug_VS2013|ARM + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Debug_VS2013|ARM.Build.0 = Debug_VS2013|ARM + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Debug_VS2013|Win32.ActiveCfg = Debug_VS2013|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Debug_VS2013|Win32.Build.0 = Debug_VS2013|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Debug_VS2013|x64.ActiveCfg = Debug_VS2013|x64 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Debug_VS2013|x64.Build.0 = Debug_VS2013|x64 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Debug|Any CPU.ActiveCfg = Debug|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Debug|ARM.ActiveCfg = Debug|ARM + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Debug|ARM.Build.0 = Debug|ARM + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Debug|Win32.ActiveCfg = Debug|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Debug|Win32.Build.0 = Debug|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Debug|x64.ActiveCfg = Debug|x64 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Debug|x64.Build.0 = Debug|x64 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.DebugClang|Any CPU.ActiveCfg = DebugClang|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.DebugClang|ARM.ActiveCfg = DebugClang|ARM + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.DebugClang|ARM.Build.0 = DebugClang|ARM + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.DebugClang|Win32.ActiveCfg = DebugClang|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.DebugClang|Win32.Build.0 = DebugClang|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.DebugClang|x64.ActiveCfg = DebugClang|x64 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.DebugClang|x64.Build.0 = DebugClang|x64 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Release_VS2013|Any CPU.ActiveCfg = Release_VS2013|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Release_VS2013|ARM.ActiveCfg = Release_VS2013|ARM + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Release_VS2013|ARM.Build.0 = Release_VS2013|ARM + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Release_VS2013|Win32.ActiveCfg = Release_VS2013|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Release_VS2013|Win32.Build.0 = Release_VS2013|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Release_VS2013|x64.ActiveCfg = Release_VS2013|x64 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Release_VS2013|x64.Build.0 = Release_VS2013|x64 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Release|Any CPU.ActiveCfg = Release|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Release|ARM.ActiveCfg = Release|ARM + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Release|ARM.Build.0 = Release|ARM + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Release|Win32.ActiveCfg = Release|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Release|Win32.Build.0 = Release|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Release|x64.ActiveCfg = Release|x64 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.Release|x64.Build.0 = Release|x64 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.TracingDebug|Any CPU.ActiveCfg = TracingDebug|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.TracingDebug|ARM.ActiveCfg = TracingDebug|ARM + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.TracingDebug|ARM.Build.0 = TracingDebug|ARM + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.TracingDebug|Win32.ActiveCfg = TracingDebug|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.TracingDebug|Win32.Build.0 = TracingDebug|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.TracingDebug|x64.ActiveCfg = TracingDebug|x64 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.TracingDebug|x64.Build.0 = TracingDebug|x64 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.TracingRelease|Any CPU.ActiveCfg = TracingRelease|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.TracingRelease|ARM.ActiveCfg = TracingRelease|ARM + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.TracingRelease|ARM.Build.0 = TracingRelease|ARM + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.TracingRelease|Win32.ActiveCfg = TracingRelease|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.TracingRelease|Win32.Build.0 = TracingRelease|Win32 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.TracingRelease|x64.ActiveCfg = TracingRelease|x64 + {F9BE7957-8399-899E-0C49-E714FDDD4B65}.TracingRelease|x64.Build.0 = TracingRelease|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Debug_VS2013|Any CPU.ActiveCfg = Debug_VS2013|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Debug_VS2013|ARM.ActiveCfg = Debug_VS2013|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Debug_VS2013|Win32.ActiveCfg = Debug_VS2013|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Debug_VS2013|Win32.Build.0 = Debug_VS2013|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Debug_VS2013|x64.ActiveCfg = Debug_VS2013|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Debug_VS2013|x64.Build.0 = Debug_VS2013|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Debug|Any CPU.ActiveCfg = Debug|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Debug|ARM.ActiveCfg = Debug|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Debug|Win32.ActiveCfg = Debug|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Debug|Win32.Build.0 = Debug|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Debug|x64.ActiveCfg = Debug|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Debug|x64.Build.0 = Debug|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.DebugClang|Any CPU.ActiveCfg = DebugClang|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.DebugClang|ARM.ActiveCfg = DebugClang|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.DebugClang|Win32.ActiveCfg = DebugClang|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.DebugClang|Win32.Build.0 = DebugClang|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.DebugClang|x64.ActiveCfg = DebugClang|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.DebugClang|x64.Build.0 = DebugClang|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Release_VS2013|Any CPU.ActiveCfg = Release_VS2013|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Release_VS2013|ARM.ActiveCfg = Release_VS2013|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Release_VS2013|Win32.ActiveCfg = Release_VS2013|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Release_VS2013|Win32.Build.0 = Release_VS2013|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Release_VS2013|x64.ActiveCfg = Release_VS2013|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Release_VS2013|x64.Build.0 = Release_VS2013|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Release|Any CPU.ActiveCfg = Release|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Release|ARM.ActiveCfg = Release|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Release|Win32.ActiveCfg = Release|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Release|Win32.Build.0 = Release|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Release|x64.ActiveCfg = Release|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.Release|x64.Build.0 = Release|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.TracingDebug|Any CPU.ActiveCfg = Release_VS2013|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.TracingDebug|Any CPU.Build.0 = Release_VS2013|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.TracingDebug|ARM.ActiveCfg = Release_VS2013|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.TracingDebug|ARM.Build.0 = Release_VS2013|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.TracingDebug|Win32.ActiveCfg = Debug|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.TracingDebug|Win32.Build.0 = Debug|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.TracingDebug|x64.ActiveCfg = Debug|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.TracingDebug|x64.Build.0 = Debug|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.TracingRelease|Any CPU.ActiveCfg = Release_VS2013|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.TracingRelease|Any CPU.Build.0 = Release_VS2013|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.TracingRelease|ARM.ActiveCfg = Release_VS2013|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.TracingRelease|ARM.Build.0 = Release_VS2013|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.TracingRelease|Win32.ActiveCfg = Release|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.TracingRelease|Win32.Build.0 = Release|Win32 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.TracingRelease|x64.ActiveCfg = Release|x64 + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808}.TracingRelease|x64.Build.0 = Release|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Debug_VS2013|Any CPU.ActiveCfg = Debug_VS2013|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Debug_VS2013|ARM.ActiveCfg = Debug_VS2013|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Debug_VS2013|Win32.ActiveCfg = Debug_VS2013|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Debug_VS2013|Win32.Build.0 = Debug_VS2013|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Debug_VS2013|x64.ActiveCfg = Debug_VS2013|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Debug_VS2013|x64.Build.0 = Debug_VS2013|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Debug|Any CPU.ActiveCfg = Debug|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Debug|ARM.ActiveCfg = Debug|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Debug|Win32.ActiveCfg = Debug|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Debug|Win32.Build.0 = Debug|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Debug|x64.ActiveCfg = Debug|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Debug|x64.Build.0 = Debug|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.DebugClang|Any CPU.ActiveCfg = DebugClang|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.DebugClang|ARM.ActiveCfg = DebugClang|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.DebugClang|Win32.ActiveCfg = DebugClang|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.DebugClang|Win32.Build.0 = DebugClang|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.DebugClang|x64.ActiveCfg = DebugClang|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.DebugClang|x64.Build.0 = DebugClang|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Release_VS2013|Any CPU.ActiveCfg = Release_VS2013|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Release_VS2013|ARM.ActiveCfg = Release_VS2013|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Release_VS2013|Win32.ActiveCfg = Release_VS2013|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Release_VS2013|Win32.Build.0 = Release_VS2013|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Release_VS2013|x64.ActiveCfg = Release_VS2013|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Release_VS2013|x64.Build.0 = Release_VS2013|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Release|Any CPU.ActiveCfg = Release|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Release|ARM.ActiveCfg = Release|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Release|Win32.ActiveCfg = Release|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Release|Win32.Build.0 = Release|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Release|x64.ActiveCfg = Release|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.Release|x64.Build.0 = Release|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.TracingDebug|Any CPU.ActiveCfg = Release_VS2013|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.TracingDebug|Any CPU.Build.0 = Release_VS2013|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.TracingDebug|ARM.ActiveCfg = Release_VS2013|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.TracingDebug|ARM.Build.0 = Release_VS2013|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.TracingDebug|Win32.ActiveCfg = Debug|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.TracingDebug|Win32.Build.0 = Debug|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.TracingDebug|x64.ActiveCfg = Debug|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.TracingDebug|x64.Build.0 = Debug|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.TracingRelease|Any CPU.ActiveCfg = Release_VS2013|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.TracingRelease|Any CPU.Build.0 = Release_VS2013|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.TracingRelease|ARM.ActiveCfg = Release_VS2013|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.TracingRelease|ARM.Build.0 = Release_VS2013|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.TracingRelease|Win32.ActiveCfg = Release|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.TracingRelease|Win32.Build.0 = Release|Win32 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.TracingRelease|x64.ActiveCfg = Release|x64 + {1168C449-66A5-4D23-80E2-2C1A07E58F83}.TracingRelease|x64.Build.0 = Release|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Debug_VS2013|Any CPU.ActiveCfg = Debug_VS2013|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Debug_VS2013|ARM.ActiveCfg = Debug_VS2013|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Debug_VS2013|Win32.ActiveCfg = Debug_VS2013|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Debug_VS2013|Win32.Build.0 = Debug_VS2013|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Debug_VS2013|x64.ActiveCfg = Debug_VS2013|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Debug_VS2013|x64.Build.0 = Debug_VS2013|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Debug|Any CPU.ActiveCfg = Debug|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Debug|ARM.ActiveCfg = Debug|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Debug|Win32.ActiveCfg = Debug|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Debug|Win32.Build.0 = Debug|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Debug|x64.ActiveCfg = Debug|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Debug|x64.Build.0 = Debug|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.DebugClang|Any CPU.ActiveCfg = DebugClang|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.DebugClang|ARM.ActiveCfg = DebugClang|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.DebugClang|Win32.ActiveCfg = DebugClang|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.DebugClang|Win32.Build.0 = DebugClang|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.DebugClang|x64.ActiveCfg = DebugClang|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.DebugClang|x64.Build.0 = DebugClang|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Release_VS2013|Any CPU.ActiveCfg = Release_VS2013|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Release_VS2013|ARM.ActiveCfg = Release_VS2013|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Release_VS2013|Win32.ActiveCfg = Release_VS2013|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Release_VS2013|Win32.Build.0 = Release_VS2013|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Release_VS2013|x64.ActiveCfg = Release_VS2013|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Release_VS2013|x64.Build.0 = Release_VS2013|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Release|Any CPU.ActiveCfg = Release|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Release|ARM.ActiveCfg = Release|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Release|Win32.ActiveCfg = Release|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Release|Win32.Build.0 = Release|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Release|x64.ActiveCfg = Release|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.Release|x64.Build.0 = Release|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.TracingDebug|Any CPU.ActiveCfg = Release_VS2013|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.TracingDebug|Any CPU.Build.0 = Release_VS2013|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.TracingDebug|ARM.ActiveCfg = Release_VS2013|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.TracingDebug|ARM.Build.0 = Release_VS2013|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.TracingDebug|Win32.ActiveCfg = Debug|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.TracingDebug|Win32.Build.0 = Debug|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.TracingDebug|x64.ActiveCfg = Debug|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.TracingDebug|x64.Build.0 = Debug|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.TracingRelease|Any CPU.ActiveCfg = Release_VS2013|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.TracingRelease|Any CPU.Build.0 = Release_VS2013|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.TracingRelease|ARM.ActiveCfg = Release_VS2013|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.TracingRelease|ARM.Build.0 = Release_VS2013|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.TracingRelease|Win32.ActiveCfg = Release|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.TracingRelease|Win32.Build.0 = Release|Win32 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.TracingRelease|x64.ActiveCfg = Release|x64 + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7}.TracingRelease|x64.Build.0 = Release|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Debug_VS2013|Any CPU.ActiveCfg = Debug_VS2013|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Debug_VS2013|ARM.ActiveCfg = Debug_VS2013|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Debug_VS2013|Win32.ActiveCfg = Debug_VS2013|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Debug_VS2013|Win32.Build.0 = Debug_VS2013|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Debug_VS2013|x64.ActiveCfg = Debug_VS2013|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Debug_VS2013|x64.Build.0 = Debug_VS2013|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Debug|Any CPU.ActiveCfg = Debug|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Debug|ARM.ActiveCfg = Debug|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Debug|Win32.ActiveCfg = Debug|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Debug|Win32.Build.0 = Debug|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Debug|x64.ActiveCfg = Debug|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Debug|x64.Build.0 = Debug|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.DebugClang|Any CPU.ActiveCfg = Release_VS2013|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.DebugClang|Any CPU.Build.0 = Release_VS2013|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.DebugClang|ARM.ActiveCfg = Release_VS2013|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.DebugClang|ARM.Build.0 = Release_VS2013|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.DebugClang|Win32.ActiveCfg = Debug|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.DebugClang|Win32.Build.0 = Debug|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.DebugClang|x64.ActiveCfg = Debug|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.DebugClang|x64.Build.0 = Debug|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Release_VS2013|Any CPU.ActiveCfg = Release_VS2013|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Release_VS2013|ARM.ActiveCfg = Release_VS2013|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Release_VS2013|Win32.ActiveCfg = Release_VS2013|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Release_VS2013|Win32.Build.0 = Release_VS2013|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Release_VS2013|x64.ActiveCfg = Release_VS2013|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Release_VS2013|x64.Build.0 = Release_VS2013|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Release|Any CPU.ActiveCfg = Release|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Release|ARM.ActiveCfg = Release|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Release|Win32.ActiveCfg = Release|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Release|Win32.Build.0 = Release|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Release|x64.ActiveCfg = Release|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.Release|x64.Build.0 = Release|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.TracingDebug|Any CPU.ActiveCfg = Release_VS2013|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.TracingDebug|Any CPU.Build.0 = Release_VS2013|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.TracingDebug|ARM.ActiveCfg = Release_VS2013|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.TracingDebug|ARM.Build.0 = Release_VS2013|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.TracingDebug|Win32.ActiveCfg = Debug|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.TracingDebug|Win32.Build.0 = Debug|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.TracingDebug|x64.ActiveCfg = Debug|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.TracingDebug|x64.Build.0 = Debug|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.TracingRelease|Any CPU.ActiveCfg = Release_VS2013|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.TracingRelease|Any CPU.Build.0 = Release_VS2013|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.TracingRelease|ARM.ActiveCfg = Release_VS2013|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.TracingRelease|ARM.Build.0 = Release_VS2013|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.TracingRelease|Win32.ActiveCfg = Release|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.TracingRelease|Win32.Build.0 = Release|Win32 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.TracingRelease|x64.ActiveCfg = Release|x64 + {0C768A18-1D25-4000-9F37-DA5FE99E3B64}.TracingRelease|x64.Build.0 = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Debug_VS2013|Any CPU.ActiveCfg = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Debug_VS2013|Any CPU.Build.0 = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Debug_VS2013|ARM.ActiveCfg = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Debug_VS2013|ARM.Build.0 = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Debug_VS2013|Win32.ActiveCfg = Debug|Win32 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Debug_VS2013|Win32.Build.0 = Debug|Win32 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Debug_VS2013|x64.ActiveCfg = Debug|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Debug_VS2013|x64.Build.0 = Debug|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Debug|Any CPU.ActiveCfg = Debug|Win32 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Debug|ARM.ActiveCfg = Debug|Win32 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Debug|Win32.ActiveCfg = Debug|Win32 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Debug|Win32.Build.0 = Debug|Win32 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Debug|x64.ActiveCfg = Debug|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Debug|x64.Build.0 = Debug|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.DebugClang|Any CPU.ActiveCfg = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.DebugClang|Any CPU.Build.0 = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.DebugClang|ARM.ActiveCfg = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.DebugClang|ARM.Build.0 = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.DebugClang|Win32.ActiveCfg = Debug|Win32 + {96610759-07B9-4EEB-A974-5C634A2E742B}.DebugClang|Win32.Build.0 = Debug|Win32 + {96610759-07B9-4EEB-A974-5C634A2E742B}.DebugClang|x64.ActiveCfg = Debug|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.DebugClang|x64.Build.0 = Debug|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Release_VS2013|Any CPU.ActiveCfg = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Release_VS2013|Any CPU.Build.0 = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Release_VS2013|ARM.ActiveCfg = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Release_VS2013|ARM.Build.0 = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Release_VS2013|Win32.ActiveCfg = Release|Win32 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Release_VS2013|Win32.Build.0 = Release|Win32 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Release_VS2013|x64.ActiveCfg = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Release_VS2013|x64.Build.0 = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Release|Any CPU.ActiveCfg = Release|Win32 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Release|ARM.ActiveCfg = Release|Win32 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Release|Win32.ActiveCfg = Release|Win32 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Release|Win32.Build.0 = Release|Win32 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Release|x64.ActiveCfg = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.Release|x64.Build.0 = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.TracingDebug|Any CPU.ActiveCfg = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.TracingDebug|Any CPU.Build.0 = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.TracingDebug|ARM.ActiveCfg = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.TracingDebug|ARM.Build.0 = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.TracingDebug|Win32.ActiveCfg = Debug|Win32 + {96610759-07B9-4EEB-A974-5C634A2E742B}.TracingDebug|Win32.Build.0 = Debug|Win32 + {96610759-07B9-4EEB-A974-5C634A2E742B}.TracingDebug|x64.ActiveCfg = Debug|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.TracingDebug|x64.Build.0 = Debug|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.TracingRelease|Any CPU.ActiveCfg = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.TracingRelease|Any CPU.Build.0 = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.TracingRelease|ARM.ActiveCfg = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.TracingRelease|ARM.Build.0 = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.TracingRelease|Win32.ActiveCfg = Release|Win32 + {96610759-07B9-4EEB-A974-5C634A2E742B}.TracingRelease|Win32.Build.0 = Release|Win32 + {96610759-07B9-4EEB-A974-5C634A2E742B}.TracingRelease|x64.ActiveCfg = Release|x64 + {96610759-07B9-4EEB-A974-5C634A2E742B}.TracingRelease|x64.Build.0 = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.Debug_VS2013|Any CPU.ActiveCfg = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.Debug_VS2013|Any CPU.Build.0 = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.Debug_VS2013|ARM.ActiveCfg = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.Debug_VS2013|ARM.Build.0 = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.Debug_VS2013|Win32.ActiveCfg = Debug|Win32 + {C495878A-832C-485B-B347-0998A90CC936}.Debug_VS2013|Win32.Build.0 = Debug|Win32 + {C495878A-832C-485B-B347-0998A90CC936}.Debug_VS2013|x64.ActiveCfg = Debug|x64 + {C495878A-832C-485B-B347-0998A90CC936}.Debug_VS2013|x64.Build.0 = Debug|x64 + {C495878A-832C-485B-B347-0998A90CC936}.Debug|Any CPU.ActiveCfg = Debug|Win32 + {C495878A-832C-485B-B347-0998A90CC936}.Debug|ARM.ActiveCfg = Debug|Win32 + {C495878A-832C-485B-B347-0998A90CC936}.Debug|Win32.ActiveCfg = Debug|Win32 + {C495878A-832C-485B-B347-0998A90CC936}.Debug|Win32.Build.0 = Debug|Win32 + {C495878A-832C-485B-B347-0998A90CC936}.Debug|x64.ActiveCfg = Debug|x64 + {C495878A-832C-485B-B347-0998A90CC936}.Debug|x64.Build.0 = Debug|x64 + {C495878A-832C-485B-B347-0998A90CC936}.DebugClang|Any CPU.ActiveCfg = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.DebugClang|Any CPU.Build.0 = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.DebugClang|ARM.ActiveCfg = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.DebugClang|ARM.Build.0 = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.DebugClang|Win32.ActiveCfg = Debug|Win32 + {C495878A-832C-485B-B347-0998A90CC936}.DebugClang|Win32.Build.0 = Debug|Win32 + {C495878A-832C-485B-B347-0998A90CC936}.DebugClang|x64.ActiveCfg = Debug|x64 + {C495878A-832C-485B-B347-0998A90CC936}.DebugClang|x64.Build.0 = Debug|x64 + {C495878A-832C-485B-B347-0998A90CC936}.Release_VS2013|Any CPU.ActiveCfg = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.Release_VS2013|Any CPU.Build.0 = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.Release_VS2013|ARM.ActiveCfg = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.Release_VS2013|ARM.Build.0 = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.Release_VS2013|Win32.ActiveCfg = Release|Win32 + {C495878A-832C-485B-B347-0998A90CC936}.Release_VS2013|Win32.Build.0 = Release|Win32 + {C495878A-832C-485B-B347-0998A90CC936}.Release_VS2013|x64.ActiveCfg = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.Release_VS2013|x64.Build.0 = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.Release|Any CPU.ActiveCfg = Release|Win32 + {C495878A-832C-485B-B347-0998A90CC936}.Release|ARM.ActiveCfg = Release|Win32 + {C495878A-832C-485B-B347-0998A90CC936}.Release|Win32.ActiveCfg = Release|Win32 + {C495878A-832C-485B-B347-0998A90CC936}.Release|Win32.Build.0 = Release|Win32 + {C495878A-832C-485B-B347-0998A90CC936}.Release|x64.ActiveCfg = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.Release|x64.Build.0 = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.TracingDebug|Any CPU.ActiveCfg = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.TracingDebug|Any CPU.Build.0 = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.TracingDebug|ARM.ActiveCfg = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.TracingDebug|ARM.Build.0 = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.TracingDebug|Win32.ActiveCfg = Debug|Win32 + {C495878A-832C-485B-B347-0998A90CC936}.TracingDebug|Win32.Build.0 = Debug|Win32 + {C495878A-832C-485B-B347-0998A90CC936}.TracingDebug|x64.ActiveCfg = Debug|x64 + {C495878A-832C-485B-B347-0998A90CC936}.TracingDebug|x64.Build.0 = Debug|x64 + {C495878A-832C-485B-B347-0998A90CC936}.TracingRelease|Any CPU.ActiveCfg = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.TracingRelease|Any CPU.Build.0 = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.TracingRelease|ARM.ActiveCfg = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.TracingRelease|ARM.Build.0 = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.TracingRelease|Win32.ActiveCfg = Release|Win32 + {C495878A-832C-485B-B347-0998A90CC936}.TracingRelease|Win32.Build.0 = Release|Win32 + {C495878A-832C-485B-B347-0998A90CC936}.TracingRelease|x64.ActiveCfg = Release|x64 + {C495878A-832C-485B-B347-0998A90CC936}.TracingRelease|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {E6385042-1649-4803-9EBD-168F8B7EF131} = {B625E3E2-3B0B-4A01-9D10-957F84092E10} + {F9BE7957-8399-899E-0C49-E714FDDD4B65} = {362538E0-CA8A-4F9A-AC99-15CC9A715A43} + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808} = {362538E0-CA8A-4F9A-AC99-15CC9A715A43} + {1168C449-66A5-4D23-80E2-2C1A07E58F83} = {362538E0-CA8A-4F9A-AC99-15CC9A715A43} + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7} = {362538E0-CA8A-4F9A-AC99-15CC9A715A43} + {0C768A18-1D25-4000-9F37-DA5FE99E3B64} = {74C5F0DC-93BB-4BF3-AC65-8C65491570F7} + {96610759-07B9-4EEB-A974-5C634A2E742B} = {74C5F0DC-93BB-4BF3-AC65-8C65491570F7} + {C495878A-832C-485B-B347-0998A90CC936} = {74C5F0DC-93BB-4BF3-AC65-8C65491570F7} + EndGlobalSection +EndGlobal diff --git a/source/core/allocator.h b/source/core/allocator.h new file mode 100644 index 000000000..d4dfcf5a9 --- /dev/null +++ b/source/core/allocator.h @@ -0,0 +1,62 @@ +#ifndef CORE_LIB_ALLOCATOR_H +#define CORE_LIB_ALLOCATOR_H + +#include + +namespace CoreLib +{ + namespace Basic + { + inline void * AlignedAlloc(size_t size, size_t alignment) + { +#ifdef _MSC_VER + return _aligned_malloc(size, alignment); +#else + void * rs = 0; + int succ = posix_memalign(&rs, alignment, size); + if (succ!=0) + rs = 0; + return rs; +#endif + } + + inline void AlignedFree(void * ptr) + { +#ifdef _MSC_VER + _aligned_free(ptr); +#else + free(ptr); +#endif + } + + class StandardAllocator + { + public: + // not really called + void * Alloc(size_t size) + { + return malloc(size); + } + void Free(void * ptr) + { + return free(ptr); + } + }; + + template + class AlignedAllocator + { + public: + void * Alloc(size_t size) + { + return AlignedAlloc(size, alignment); + } + void Free(void * ptr) + { + return AlignedFree(ptr); + } + }; + } +} + +#endif \ No newline at end of file diff --git a/source/core/array-view.h b/source/core/array-view.h new file mode 100644 index 000000000..201ef2a79 --- /dev/null +++ b/source/core/array-view.h @@ -0,0 +1,131 @@ +#ifndef CORE_LIB_ARRAY_VIEW_H +#define CORE_LIB_ARRAY_VIEW_H + +#include "Exception.h" + +namespace CoreLib +{ + namespace Basic + { + template + class ArrayView + { + private: + T * _buffer; + int _count; + int stride; + public: + T* begin() const + { + return _buffer; + } + T* end() const + { + return (T*)((char*)_buffer + _count*stride); + } + public: + ArrayView() + { + _buffer = 0; + _count = 0; + } + ArrayView(const T & singleObj) + { + SetData((T*)&singleObj, 1, sizeof(T)); + } + ArrayView(T * buffer, int count) + { + SetData(buffer, count, sizeof(T)); + } + ArrayView(void * buffer, int count, int _stride) + { + SetData(buffer, count, _stride); + } + void SetData(void * buffer, int count, int _stride) + { + this->_buffer = (T*)buffer; + this->_count = count; + this->stride = _stride; + } + inline int GetCapacity() const + { + return _count; + } + inline int Count() const + { + return _count; + } + + inline T & operator [](int id) const + { +#if _DEBUG + if (id >= _count || id < 0) + throw IndexOutofRangeException("Operator[]: Index out of Range."); +#endif + return *(T*)((char*)_buffer+id*stride); + } + + inline T* Buffer() const + { + return _buffer; + } + + template + int IndexOf(const T2 & val) const + { + for (int i = 0; i < _count; i++) + { + if (*(T*)((char*)_buffer + i*stride) == val) + return i; + } + return -1; + } + + template + int LastIndexOf(const T2 & val) const + { + for (int i = _count - 1; i >= 0; i--) + { + if (*(T*)((char*)_buffer + i*stride) == val) + return i; + } + return -1; + } + + template + int FindFirst(const Func & predicate) const + { + for (int i = 0; i < _count; i++) + { + if (predicate(_buffer[i])) + return i; + } + return -1; + } + + template + int FindLast(const Func & predicate) const + { + for (int i = _count - 1; i >= 0; i--) + { + if (predicate(_buffer[i])) + return i; + } + return -1; + } + }; + + template + ArrayView MakeArrayView(const T & obj) + { + return ArrayView(obj); + } + + template + ArrayView MakeArrayView(T * buffer, int count) + { + return ArrayView(buffer, count); + } + } +} +#endif \ No newline at end of file diff --git a/source/core/array.h b/source/core/array.h new file mode 100644 index 000000000..b6dbeab07 --- /dev/null +++ b/source/core/array.h @@ -0,0 +1,146 @@ +#ifndef CORE_LIB_ARRAY_H +#define CORE_LIB_ARRAY_H + +#include "exception.h" +#include "array-view.h" + +namespace CoreLib +{ + namespace Basic + { + template + class Array + { + private: + T _buffer[size]; + int _count = 0; + public: + T* begin() const + { + return (T*)_buffer; + } + T* end() const + { + return (T*)_buffer + _count; + } + public: + inline int GetCapacity() const + { + return size; + } + inline int Count() const + { + return _count; + } + inline T & First() const + { + return const_cast(_buffer[0]); + } + inline T & Last() const + { + return const_cast(_buffer[_count - 1]); + } + inline void SetSize(int newSize) + { +#ifdef _DEBUG + if (newSize > size) + throw IndexOutofRangeException("size too large."); +#endif + _count = newSize; + } + inline void Add(const T & item) + { +#ifdef _DEBUG + if (_count == size) + throw IndexOutofRangeException("out of range access to static array."); +#endif + _buffer[_count++] = item; + } + inline void Add(T && item) + { +#ifdef _DEBUG + if (_count == size) + throw IndexOutofRangeException("out of range access to static array."); +#endif + _buffer[_count++] = _Move(item); + } + + inline T & operator [](int id) const + { +#if _DEBUG + if (id >= _count || id < 0) + throw IndexOutofRangeException("Operator[]: Index out of Range."); +#endif + return ((T*)_buffer)[id]; + } + + inline T* Buffer() const + { + return (T*)_buffer; + } + + inline void Clear() + { + _count = 0; + } + + template + int IndexOf(const T2 & val) const + { + for (int i = 0; i < _count; i++) + { + if (_buffer[i] == val) + return i; + } + return -1; + } + + template + int LastIndexOf(const T2 & val) const + { + for (int i = _count - 1; i >= 0; i--) + { + if (_buffer[i] == val) + return i; + } + return -1; + } + + inline ArrayView GetArrayView() const + { + return ArrayView((T*)_buffer, _count); + } + inline ArrayView GetArrayView(int start, int count) const + { + return ArrayView((T*)_buffer + start, count); + } + }; + + template + struct FirstType + { + typedef T type; + }; + + + template + void InsertArray(Array &) {} + + template + void InsertArray(Array & arr, const T & val, TArgs... args) + { + arr.Add(val); + InsertArray(arr, args...); + } + + template + auto MakeArray(TArgs ...args) -> Array::type, sizeof...(args)> + { + Array::type, sizeof...(args)> rs; + InsertArray(rs, args...); + return rs; + } + } +} + +#endif \ No newline at end of file diff --git a/source/core/basic.h b/source/core/basic.h new file mode 100644 index 000000000..5b0e05e7b --- /dev/null +++ b/source/core/basic.h @@ -0,0 +1,21 @@ +#ifndef CORE_LIB_BASIC_H +#define CORE_LIB_BASIC_H + +#include "common.h" +#include "slang-math.h" +#include "slang-string.h" +#include "array.h" +#include "list.h" +#include "link.h" +#include "smart-pointer.h" +#include "exception.h" +#include "dictionary.h" +#include "func.h" +#include "linq.h" + +namespace CoreLib +{ + using namespace Basic; +} + +#endif \ No newline at end of file diff --git a/source/core/common.h b/source/core/common.h new file mode 100644 index 000000000..517b018a7 --- /dev/null +++ b/source/core/common.h @@ -0,0 +1,48 @@ +#ifndef CORE_LIB_COMMON_H +#define CORE_LIB_COMMON_H + +#include + +#ifdef __GNUC__ +#define CORE_LIB_ALIGN_16(x) x __attribute__((aligned(16))) +#else +#define CORE_LIB_ALIGN_16(x) __declspec(align(16)) x +#endif + +#define VARIADIC_TEMPLATE + +namespace CoreLib +{ + typedef int64_t Int64; + typedef unsigned short Word; +#ifdef _M_X64 + typedef int64_t PtrInt; +#else + typedef int PtrInt; +#endif + namespace Basic + { + class Object + { + public: + virtual ~Object() + {} + }; + + template + inline T&& _Move(T & obj) + { + return static_cast(obj); + } + + template + inline void Swap(T & v0, T & v1) + { + T tmp = _Move(v0); + v0 = _Move(v1); + v1 = _Move(tmp); + } + } +} + +#endif diff --git a/source/core/core.natvis b/source/core/core.natvis new file mode 100644 index 000000000..b856d31db --- /dev/null +++ b/source/core/core.natvis @@ -0,0 +1,105 @@ + + + + + + {buffer.pointer,s} + buffer.pointer,s + + + + {{ size={_count} }} + + _count + + _count + _buffer + + + + + + {{ size={_count} }} + + _count + bufferSize + + _count + buffer + + + + + + + {{ size={_count} }} + + _count + + _count + _buffer + + + + + + {{ size={FCount} }} + + + FCount + FHead + pNext + Value + + + + + + {{ size={_count} }} + + _count + bucketSizeMinusOne + 1 + + bucketSizeMinusOne + 1 + hashMap + + + + + + {{ size={_count} }} + + _count + bucketSizeMinusOne + 1 + + kvPairs.FCount + kvPairs.FHead + pNext + Value + + + + + + {{ size={dict._count} }} + + dict._count + dict.bucketSizeMinusOne + 1 + + dict.kvPairs.FCount + dict.kvPairs.FHead + pNext + Value + + + + + + pointer + empty + RefPtr {*pointer} + + pointer + + + diff --git a/source/core/core.vcxproj b/source/core/core.vcxproj new file mode 100644 index 000000000..6b8496080 --- /dev/null +++ b/source/core/core.vcxproj @@ -0,0 +1,802 @@ + + + + + DebugClang + ARM + + + DebugClang + Win32 + + + DebugClang + x64 + + + Debug_VS2013 + ARM + + + Debug_VS2013 + Win32 + + + Debug_VS2013 + x64 + + + Debug + ARM + + + Debug + Win32 + + + Debug + x64 + + + Release_VS2013 + ARM + + + Release_VS2013 + Win32 + + + Release_VS2013 + x64 + + + Release + ARM + + + Release + Win32 + + + Release + x64 + + + TracingDebug + ARM + + + TracingDebug + Win32 + + + TracingDebug + x64 + + + TracingRelease + ARM + + + TracingRelease + Win32 + + + TracingRelease + x64 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Win32Proj + CoreLib + {F9BE7957-8399-899E-0C49-E714FDDD4B65} + 8.1 + + + + StaticLibrary + true + v140 + Unicode + + + StaticLibrary + true + v120 + Unicode + + + StaticLibrary + true + v140_clang_3_7 + Unicode + + + StaticLibrary + true + v140 + Unicode + + + StaticLibrary + true + v140 + Unicode + + + StaticLibrary + true + v120 + Unicode + + + StaticLibrary + true + v140_Clang_3_7 + Unicode + + + StaticLibrary + true + v140 + Unicode + + + StaticLibrary + true + v140 + Unicode + + + StaticLibrary + true + v120 + Unicode + + + StaticLibrary + true + v140_clang_3_7 + Unicode + + + StaticLibrary + true + v140 + Unicode + + + StaticLibrary + false + v140 + true + Unicode + + + StaticLibrary + false + v120 + true + Unicode + + + StaticLibrary + false + v140 + true + Unicode + + + StaticLibrary + false + v140 + true + Unicode + + + StaticLibrary + false + v120 + true + Unicode + + + StaticLibrary + false + v140 + true + Unicode + + + StaticLibrary + false + v140 + true + Unicode + + + StaticLibrary + false + v120 + true + Unicode + + + StaticLibrary + false + v140 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreadedDebug + false + Default + + + Windows + true + + + Shlwapi.lib + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreadedDebug + false + Default + + + Windows + true + + + Shlwapi.lib + + + + + + + EnableAllWarnings + Disabled + WIN32;_DEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreadedDebug + false + Default + true + + + Windows + true + + + Shlwapi.lib + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreadedDebug + false + + + Windows + true + + + Shlwapi.lib + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreadedDebug + true + false + Default + + + Windows + true + + + Shlwapi.lib + + + true + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreadedDebug + true + false + Default + + + Windows + true + + + Shlwapi.lib + + + true + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreadedDebug + true + false + Default + + + Windows + true + + + Shlwapi.lib + + + true + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreadedDebug + false + + + Windows + true + + + Shlwapi.lib + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreadedDebug + false + Default + + + Windows + true + + + Shlwapi.lib + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreadedDebug + false + Default + + + Windows + true + + + Shlwapi.lib + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreadedDebug + false + Default + + + Windows + true + + + Shlwapi.lib + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreadedDebug + false + + + Windows + true + + + Shlwapi.lib + + + + + Level4 + + + MaxSpeed + true + true + WIN32;NDEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreaded + false + + + Windows + true + true + true + + + Shlwapi.lib + + + + + Level4 + + + MaxSpeed + true + true + WIN32;NDEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreaded + false + + + Windows + true + true + true + + + Shlwapi.lib + + + + + Level4 + + + MaxSpeed + true + true + WIN32;NDEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreaded + false + + + Windows + true + true + true + + + Shlwapi.lib + + + + + Level4 + + + MaxSpeed + true + true + WIN32;NDEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreaded + false + + + Windows + true + true + true + + + Shlwapi.lib + + + + + Level4 + + + MaxSpeed + true + true + WIN32;NDEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreaded + false + + + Windows + true + true + true + + + Shlwapi.lib + + + + + Level4 + + + MaxSpeed + true + true + WIN32;NDEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreaded + false + false + + + Windows + true + true + true + + + Shlwapi.lib + + + + + Level4 + + + MaxSpeed + true + true + WIN32;NDEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreaded + false + + + Windows + true + true + true + + + Shlwapi.lib + + + + + Level4 + + + MaxSpeed + true + true + WIN32;NDEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreaded + false + + + Windows + true + true + true + + + Shlwapi.lib + + + + + Level4 + + + MaxSpeed + true + true + WIN32;NDEBUG;_LIB;WINDOWS_PLATFORM;%(PreprocessorDefinitions);GLEW_STATIC + MultiThreaded + false + + + Windows + true + true + true + + + Shlwapi.lib + + + + + + \ No newline at end of file diff --git a/source/core/dictionary.h b/source/core/dictionary.h new file mode 100644 index 000000000..77f0df515 --- /dev/null +++ b/source/core/dictionary.h @@ -0,0 +1,1018 @@ +#ifndef CORE_LIB_DICTIONARY_H +#define CORE_LIB_DICTIONARY_H +#include "list.h" +#include "common.h" +#include "int-set.h" +#include "exception.h" +#include "slang-math.h" +#include "hash.h" + +namespace CoreLib +{ + namespace Basic + { + template + class KeyValuePair + { + public: + TKey Key; + TValue Value; + KeyValuePair() + {} + KeyValuePair(const TKey & key, const TValue & value) + { + Key = key; + Value = value; + } + KeyValuePair(TKey && key, TValue && value) + { + Key = _Move(key); + Value = _Move(value); + } + KeyValuePair(TKey && key, const TValue & value) + { + Key = _Move(key); + Value = value; + } + KeyValuePair(const KeyValuePair & _that) + { + Key = _that.Key; + Value = _that.Value; + } + KeyValuePair(KeyValuePair && _that) + { + operator=(_Move(_that)); + } + KeyValuePair & operator=(KeyValuePair && that) + { + Key = _Move(that.Key); + Value = _Move(that.Value); + return *this; + } + KeyValuePair & operator=(const KeyValuePair & that) + { + Key = that.Key; + Value = that.Value; + return *this; + } + int GetHashCode() + { + return GetHashCode(Key); + } + }; + + template + inline KeyValuePair KVPair(const TKey & k, const TValue & v) + { + return KeyValuePair(k, v); + } + + const float MaxLoadFactor = 0.7f; + + template + class Dictionary + { + friend class Iterator; + friend class ItemProxy; + private: + inline int GetProbeOffset(int /*probeId*/) const + { + // quadratic probing + return 1; + } + private: + int bucketSizeMinusOne, shiftBits; + int _count; + IntSet marks; + KeyValuePair* hashMap; + void Free() + { + if (hashMap) + delete[] hashMap; + hashMap = 0; + } + inline bool IsDeleted(int pos) const + { + return marks.Contains((pos << 1) + 1); + } + inline bool IsEmpty(int pos) const + { + return !marks.Contains((pos << 1)); + } + inline void SetDeleted(int pos, bool val) + { + if (val) + marks.Add((pos << 1) + 1); + else + marks.Remove((pos << 1) + 1); + } + inline void SetEmpty(int pos, bool val) + { + if (val) + marks.Remove((pos << 1)); + else + marks.Add((pos << 1)); + } + struct FindPositionResult + { + int ObjectPosition; + int InsertionPosition; + FindPositionResult() + { + ObjectPosition = -1; + InsertionPosition = -1; + } + FindPositionResult(int objPos, int insertPos) + { + ObjectPosition = objPos; + InsertionPosition = insertPos; + } + + }; + template + inline int GetHashPos(T & key) const + { + return ((unsigned int)(GetHashCode(key) * 2654435761)) >> shiftBits; + } + template + FindPositionResult FindPosition(const T & key) const + { + int hashPos = GetHashPos((T&)key); + int insertPos = -1; + int numProbes = 0; + while (numProbes <= bucketSizeMinusOne) + { + if (IsEmpty(hashPos)) + { + if (insertPos == -1) + return FindPositionResult(-1, hashPos); + else + return FindPositionResult(-1, insertPos); + } + else if (IsDeleted(hashPos)) + { + if (insertPos == -1) + insertPos = hashPos; + } + else if (hashMap[hashPos].Key == key) + { + return FindPositionResult(hashPos, -1); + } + numProbes++; + hashPos = (hashPos + GetProbeOffset(numProbes)) & bucketSizeMinusOne; + } + if (insertPos != -1) + return FindPositionResult(-1, insertPos); + throw InvalidOperationException("Hash map is full. This indicates an error in Key::Equal or Key::GetHashCode."); + } + TValue & _Insert(KeyValuePair && kvPair, int pos) + { + hashMap[pos] = _Move(kvPair); + SetEmpty(pos, false); + SetDeleted(pos, false); + return hashMap[pos].Value; + } + void Rehash() + { + if (bucketSizeMinusOne == -1 || _count / (float)bucketSizeMinusOne >= MaxLoadFactor) + { + int newSize = (bucketSizeMinusOne + 1) * 2; + int newShiftBits = shiftBits - 1; + if (newSize == 0) + { + newSize = 16; + newShiftBits = 28; + } + Dictionary newDict; + newDict.shiftBits = newShiftBits; + newDict.bucketSizeMinusOne = newSize - 1; + newDict.hashMap = new KeyValuePair[newSize]; + newDict.marks.SetMax(newSize * 2); + if (hashMap) + { + for (auto & kvPair : *this) + { + newDict.Add(_Move(kvPair)); + } + } + *this = _Move(newDict); + } + } + + bool AddIfNotExists(KeyValuePair && kvPair) + { + Rehash(); + auto pos = FindPosition(kvPair.Key); + if (pos.ObjectPosition != -1) + return false; + else if (pos.InsertionPosition != -1) + { + _count++; + _Insert(_Move(kvPair), pos.InsertionPosition); + return true; + } + else + throw InvalidOperationException("Inconsistent find result returned. This is a bug in Dictionary implementation."); + } + void Add(KeyValuePair && kvPair) + { + if (!AddIfNotExists(_Move(kvPair))) + throw KeyExistsException("The key already exists in Dictionary."); + } + TValue & Set(KeyValuePair && kvPair) + { + Rehash(); + auto pos = FindPosition(kvPair.Key); + if (pos.ObjectPosition != -1) + return _Insert(_Move(kvPair), pos.ObjectPosition); + else if (pos.InsertionPosition != -1) + { + _count++; + return _Insert(_Move(kvPair), pos.InsertionPosition); + } + else + throw InvalidOperationException("Inconsistent find result returned. This is a bug in Dictionary implementation."); + } + public: + class Iterator + { + private: + const Dictionary * dict; + int pos; + public: + KeyValuePair & operator *() const + { + return dict->hashMap[pos]; + } + KeyValuePair * operator ->() const + { + return dict->hashMap + pos; + } + Iterator & operator ++() + { + if (pos > dict->bucketSizeMinusOne) + return *this; + pos++; + while (pos <= dict->bucketSizeMinusOne && (dict->IsDeleted(pos) || dict->IsEmpty(pos))) + { + pos++; + } + return *this; + } + Iterator operator ++(int) + { + Iterator rs = *this; + operator++(); + return rs; + } + bool operator != (const Iterator & _that) const + { + return pos != _that.pos || dict != _that.dict; + } + bool operator == (const Iterator & _that) const + { + return pos == _that.pos && dict == _that.dict; + } + Iterator(const Dictionary * _dict, int _pos) + { + this->dict = _dict; + this->pos = _pos; + } + Iterator() + { + this->dict = 0; + this->pos = 0; + } + }; + + Iterator begin() const + { + int pos = 0; + while (pos < bucketSizeMinusOne + 1) + { + if (IsEmpty(pos) || IsDeleted(pos)) + pos++; + else + break; + } + return Iterator(this, pos); + } + Iterator end() const + { + return Iterator(this, bucketSizeMinusOne + 1); + } + public: + void Add(const TKey & key, const TValue & value) + { + Add(KeyValuePair(key, value)); + } + void Add(TKey && key, TValue && value) + { + Add(KeyValuePair(_Move(key), _Move(value))); + } + bool AddIfNotExists(const TKey & key, const TValue & value) + { + return AddIfNotExists(KeyValuePair(key, value)); + } + bool AddIfNotExists(TKey && key, TValue && value) + { + return AddIfNotExists(KeyValuePair(_Move(key), _Move(value))); + } + void Remove(const TKey & key) + { + if (_count == 0) + return; + auto pos = FindPosition(key); + if (pos.ObjectPosition != -1) + { + SetDeleted(pos.ObjectPosition, true); + _count--; + } + } + void Clear() + { + _count = 0; + + marks.Clear(); + } + + template + bool ContainsKey(const T & key) const + { + if (bucketSizeMinusOne == -1) + return false; + auto pos = FindPosition(key); + return pos.ObjectPosition != -1; + } + template + bool TryGetValue(const T & key, TValue & value) const + { + if (bucketSizeMinusOne == -1) + return false; + auto pos = FindPosition(key); + if (pos.ObjectPosition != -1) + { + value = hashMap[pos.ObjectPosition].Value; + return true; + } + return false; + } + template + TValue * TryGetValue(const T & key) const + { + if (bucketSizeMinusOne == -1) + return nullptr; + auto pos = FindPosition(key); + if (pos.ObjectPosition != -1) + { + return &hashMap[pos.ObjectPosition].Value; + } + return nullptr; + } + class ItemProxy + { + private: + const Dictionary * dict; + TKey key; + public: + ItemProxy(const TKey & _key, const Dictionary * _dict) + { + this->dict = _dict; + this->key = _key; + } + ItemProxy(TKey && _key, const Dictionary * _dict) + { + this->dict = _dict; + this->key = _Move(_key); + } + TValue & GetValue() const + { + auto pos = dict->FindPosition(key); + if (pos.ObjectPosition != -1) + { + return dict->hashMap[pos.ObjectPosition].Value; + } + else + throw KeyNotFoundException("The key does not exists in dictionary."); + } + inline TValue & operator()() const + { + return GetValue(); + } + operator TValue&() const + { + return GetValue(); + } + TValue & operator = (const TValue & val) const + { + return ((Dictionary*)dict)->Set(KeyValuePair(_Move(key), val)); + } + TValue & operator = (TValue && val) const + { + return ((Dictionary*)dict)->Set(KeyValuePair(_Move(key), _Move(val))); + } + }; + ItemProxy operator [](const TKey & key) const + { + return ItemProxy(key, this); + } + ItemProxy operator [](TKey && key) const + { + return ItemProxy(_Move(key), this); + } + int Count() const + { + return _count; + } + private: + template + void Init(const KeyValuePair & kvPair, Args... args) + { + Add(kvPair); + Init(args...); + } + public: + Dictionary() + { + bucketSizeMinusOne = -1; + shiftBits = 32; + _count = 0; + hashMap = 0; + } + template + Dictionary(Arg arg, Args... args) + { + Init(arg, args...); + } + Dictionary(const Dictionary & other) + : bucketSizeMinusOne(-1), _count(0), hashMap(0) + { + *this = other; + } + Dictionary(Dictionary && other) + : bucketSizeMinusOne(-1), _count(0), hashMap(0) + { + *this = (_Move(other)); + } + Dictionary & operator = (const Dictionary & other) + { + if (this == &other) + return *this; + Free(); + bucketSizeMinusOne = other.bucketSizeMinusOne; + _count = other._count; + shiftBits = other.shiftBits; + hashMap = new KeyValuePair[other.bucketSizeMinusOne + 1]; + marks = other.marks; + for (int i = 0; i <= bucketSizeMinusOne; i++) + hashMap[i] = other.hashMap[i]; + return *this; + } + Dictionary & operator = (Dictionary && other) + { + if (this == &other) + return *this; + Free(); + bucketSizeMinusOne = other.bucketSizeMinusOne; + _count = other._count; + hashMap = other.hashMap; + shiftBits = other.shiftBits; + marks = _Move(other.marks); + other.hashMap = 0; + other._count = 0; + other.bucketSizeMinusOne = -1; + return *this; + } + ~Dictionary() + { + Free(); + } + }; + + template + class EnumerableDictionary + { + friend class Iterator; + friend class ItemProxy; + private: + inline int GetProbeOffset(int /*probeIdx*/) const + { + // quadratic probing + return 1; + } + private: + int bucketSizeMinusOne, shiftBits; + int _count; + IntSet marks; + + // debug op + struct Op + { + TKey key; + int opType; + Op() + {} + Op(const TKey & key, int t) + { + this->key = key; + opType = t; + } + }; + LinkedList> kvPairs; + LinkedNode>** hashMap; + void Free() + { + if (hashMap) + delete[] hashMap; + hashMap = 0; + kvPairs.Clear(); + } + inline bool IsDeleted(int pos) const + { + return marks.Contains((pos << 1) + 1); + } + inline bool IsEmpty(int pos) const + { + return !marks.Contains((pos << 1)); + } + inline void SetDeleted(int pos, bool val) + { + if (val) + marks.Add((pos << 1) + 1); + else + marks.Remove((pos << 1) + 1); + } + inline void SetEmpty(int pos, bool val) + { + if (val) + marks.Remove((pos << 1)); + else + marks.Add((pos << 1)); + } + struct FindPositionResult + { + int ObjectPosition; + int InsertionPosition; + FindPositionResult() + { + ObjectPosition = -1; + InsertionPosition = -1; + } + FindPositionResult(int objPos, int insertPos) + { + ObjectPosition = objPos; + InsertionPosition = insertPos; + } + + }; + template + inline int GetHashPos(T & key) const + { + return ((unsigned int)(GetHashCode(key) * 2654435761)) >> shiftBits; + } + template + FindPositionResult FindPosition(const T & key) const + { + int hashPos = GetHashPos((T&)key); + int insertPos = -1; + int numProbes = 0; + while (numProbes <= bucketSizeMinusOne) + { + if (IsEmpty(hashPos)) + { + if (insertPos == -1) + return FindPositionResult(-1, hashPos); + else + return FindPositionResult(-1, insertPos); + } + else if (IsDeleted(hashPos)) + { + if (insertPos == -1) + insertPos = hashPos; + } + else if (hashMap[hashPos]->Value.Key == key) + { + return FindPositionResult(hashPos, -1); + } + numProbes++; + hashPos = (hashPos + GetProbeOffset(numProbes)) & bucketSizeMinusOne; + } + if (insertPos != -1) + return FindPositionResult(-1, insertPos); + throw InvalidOperationException("Hash map is full. This indicates an error in Key::Equal or Key::GetHashCode."); + } + TValue & _Insert(KeyValuePair && kvPair, int pos) + { + auto node = kvPairs.AddLast(); + node->Value = _Move(kvPair); + hashMap[pos] = node; + SetEmpty(pos, false); + SetDeleted(pos, false); + return node->Value.Value; + } + void Rehash() + { + if (bucketSizeMinusOne == -1 || _count / (float)bucketSizeMinusOne >= MaxLoadFactor) + { + int newSize = (bucketSizeMinusOne + 1) * 2; + int newShiftBits = shiftBits - 1; + if (newSize == 0) + { + newSize = 16; + newShiftBits = 28; + } + EnumerableDictionary newDict; + newDict.shiftBits = newShiftBits; + newDict.bucketSizeMinusOne = newSize - 1; + newDict.hashMap = new LinkedNode>*[newSize]; + newDict.marks.SetMax(newSize * 2); + if (hashMap) + { + for (auto & kvPair : *this) + { + newDict.Add(_Move(kvPair)); + } + } + *this = _Move(newDict); + } + } + + bool AddIfNotExists(KeyValuePair && kvPair) + { + Rehash(); + auto pos = FindPosition(kvPair.Key); + if (pos.ObjectPosition != -1) + return false; + else if (pos.InsertionPosition != -1) + { + _count++; + _Insert(_Move(kvPair), pos.InsertionPosition); + return true; + } + else + throw InvalidOperationException("Inconsistent find result returned. This is a bug in Dictionary implementation."); + } + void Add(KeyValuePair && kvPair) + { + if (!AddIfNotExists(_Move(kvPair))) + throw KeyExistsException("The key already exists in Dictionary."); + } + TValue & Set(KeyValuePair && kvPair) + { + Rehash(); + auto pos = FindPosition(kvPair.Key); + if (pos.ObjectPosition != -1) + { + hashMap[pos.ObjectPosition]->Delete(); + return _Insert(_Move(kvPair), pos.ObjectPosition); + } + else if (pos.InsertionPosition != -1) + { + _count++; + return _Insert(_Move(kvPair), pos.InsertionPosition); + } + else + throw InvalidOperationException("Inconsistent find result returned. This is a bug in Dictionary implementation."); + } + public: + typedef typename LinkedList>::Iterator Iterator; + + typename LinkedList>::Iterator begin() const + { + return kvPairs.begin(); + } + typename LinkedList>::Iterator end() const + { + return kvPairs.end(); + } + public: + void Add(const TKey & key, const TValue & value) + { + Add(KeyValuePair(key, value)); + } + void Add(TKey && key, TValue && value) + { + Add(KeyValuePair(_Move(key), _Move(value))); + } + bool AddIfNotExists(const TKey & key, const TValue & value) + { + return AddIfNotExists(KeyValuePair(key, value)); + } + bool AddIfNotExists(TKey && key, TValue && value) + { + return AddIfNotExists(KeyValuePair(_Move(key), _Move(value))); + } + void Remove(const TKey & key) + { + if (_count > 0) + { + auto pos = FindPosition(key); + if (pos.ObjectPosition != -1) + { + kvPairs.Delete(hashMap[pos.ObjectPosition]); + hashMap[pos.ObjectPosition] = 0; + SetDeleted(pos.ObjectPosition, true); + _count--; + } + } + } + void Clear() + { + _count = 0; + kvPairs.Clear(); + marks.Clear(); + } + template + bool ContainsKey(const T & key) const + { + if (bucketSizeMinusOne == -1) + return false; + auto pos = FindPosition(key); + return pos.ObjectPosition != -1; + } + template + TValue * TryGetValue(const T & key) const + { + if (bucketSizeMinusOne == -1) + return nullptr; + auto pos = FindPosition(key); + if (pos.ObjectPosition != -1) + { + return &(hashMap[pos.ObjectPosition]->Value.Value); + } + return nullptr; + } + template + bool TryGetValue(const T & key, TValue & value) const + { + if (bucketSizeMinusOne == -1) + return false; + auto pos = FindPosition(key); + if (pos.ObjectPosition != -1) + { + value = hashMap[pos.ObjectPosition]->Value.Value; + return true; + } + return false; + } + class ItemProxy + { + private: + const EnumerableDictionary * dict; + TKey key; + public: + ItemProxy(const TKey & _key, const EnumerableDictionary * _dict) + { + this->dict = _dict; + this->key = _key; + } + ItemProxy(TKey && _key, const EnumerableDictionary * _dict) + { + this->dict = _dict; + this->key = _Move(_key); + } + TValue & GetValue() const + { + auto pos = dict->FindPosition(key); + if (pos.ObjectPosition != -1) + { + return dict->hashMap[pos.ObjectPosition]->Value.Value; + } + else + { + throw KeyNotFoundException("The key does not exists in dictionary."); + } + } + inline TValue & operator()() const + { + return GetValue(); + } + operator TValue&() const + { + return GetValue(); + } + TValue & operator = (const TValue & val) + { + return ((EnumerableDictionary*)dict)->Set(KeyValuePair(_Move(key), val)); + } + TValue & operator = (TValue && val) + { + return ((EnumerableDictionary*)dict)->Set(KeyValuePair(_Move(key), _Move(val))); + } + }; + ItemProxy operator [](const TKey & key) const + { + return ItemProxy(key, this); + } + ItemProxy operator [](TKey && key) const + { + return ItemProxy(_Move(key), this); + } + int Count() const + { + return _count; + } + KeyValuePair & First() const + { + return kvPairs.First(); + } + KeyValuePair & Last() const + { + return kvPairs.Last(); + } + private: + template + void Init(const KeyValuePair & kvPair, Args... args) + { + Add(kvPair); + Init(args...); + } + public: + EnumerableDictionary() + { + bucketSizeMinusOne = -1; + shiftBits = 32; + _count = 0; + hashMap = 0; + } + template + EnumerableDictionary(Arg arg, Args... args) + { + Init(arg, args...); + } + EnumerableDictionary(const EnumerableDictionary & other) + : bucketSizeMinusOne(-1), _count(0), hashMap(0) + { + *this = other; + } + EnumerableDictionary(EnumerableDictionary && other) + : bucketSizeMinusOne(-1), _count(0), hashMap(0) + { + *this = (_Move(other)); + } + EnumerableDictionary & operator = (const EnumerableDictionary & other) + { + if (this == &other) + return *this; + Clear(); + for (auto & item : other) + Add(item.Key, item.Value); + return *this; + } + EnumerableDictionary & operator = (EnumerableDictionary && other) + { + if (this == &other) + return *this; + Free(); + bucketSizeMinusOne = other.bucketSizeMinusOne; + _count = other._count; + hashMap = other.hashMap; + shiftBits = other.shiftBits; + marks = _Move(other.marks); + other.hashMap = 0; + other._count = 0; + other.bucketSizeMinusOne = -1; + kvPairs = _Move(other.kvPairs); + return *this; + } + ~EnumerableDictionary() + { + Free(); + } + }; + + class _DummyClass + {}; + + template + class HashSetBase + { + protected: + DictionaryType dict; + private: + template + void Init(const T & v, Args... args) + { + Add(v); + Init(args...); + } + public: + HashSetBase() + {} + template + HashSetBase(Arg arg, Args... args) + { + Init(arg, args...); + } + HashSetBase(const HashSetBase & set) + { + operator=(set); + } + HashSetBase(HashSetBase && set) + { + operator=(_Move(set)); + } + HashSetBase & operator = (const HashSetBase & set) + { + dict = set.dict; + return *this; + } + HashSetBase & operator = (HashSetBase && set) + { + dict = _Move(set.dict); + return *this; + } + public: + class Iterator + { + private: + typename DictionaryType::Iterator iter; + public: + Iterator() = default; + T & operator *() const + { + return (*iter).Key; + } + T * operator ->() const + { + return &(*iter).Key; + } + Iterator & operator ++() + { + ++iter; + return *this; + } + Iterator operator ++(int) + { + Iterator rs = *this; + operator++(); + return rs; + } + bool operator != (const Iterator & _that) const + { + return iter != _that.iter; + } + bool operator == (const Iterator & _that) const + { + return iter == _that.iter; + } + Iterator(const typename DictionaryType::Iterator & _iter) + { + this->iter = _iter; + } + }; + Iterator begin() const + { + return Iterator(dict.begin()); + } + Iterator end() const + { + return Iterator(dict.end()); + } + public: + int Count() const + { + return dict.Count(); + } + void Clear() + { + dict.Clear(); + } + bool Add(const T& obj) + { + return dict.AddIfNotExists(obj, _DummyClass()); + } + bool Add(T && obj) + { + return dict.AddIfNotExists(_Move(obj), _DummyClass()); + } + void Remove(const T & obj) + { + dict.Remove(obj); + } + bool Contains(const T & obj) const + { + return dict.ContainsKey(obj); + } + }; + template + class HashSet : public HashSetBase> + {}; + + template + class EnumerableHashSet : public HashSetBase> + { + public: + T & First() const + { + return this->dict.First().Key; + } + T & Last() const + { + return this->dict.Last().Key; + } + }; + } +} + +#endif diff --git a/source/core/exception.h b/source/core/exception.h new file mode 100644 index 000000000..652cafca7 --- /dev/null +++ b/source/core/exception.h @@ -0,0 +1,115 @@ +#ifndef CORE_LIB_EXCEPTION_H +#define CORE_LIB_EXCEPTION_H + +#include "common.h" +#include "slang-string.h" + +namespace CoreLib +{ + namespace Basic + { + class Exception : public Object + { + public: + String Message; + Exception() + {} + Exception(const String & message) + : Message(message) + { + } + }; + + class IndexOutofRangeException : public Exception + { + public: + IndexOutofRangeException() + {} + IndexOutofRangeException(const String & message) + : Exception(message) + { + } + + }; + + class InvalidOperationException : public Exception + { + public: + InvalidOperationException() + {} + InvalidOperationException(const String & message) + : Exception(message) + { + } + + }; + + class ArgumentException : public Exception + { + public: + ArgumentException() + {} + ArgumentException(const String & message) + : Exception(message) + { + } + + }; + + class KeyNotFoundException : public Exception + { + public: + KeyNotFoundException() + {} + KeyNotFoundException(const String & message) + : Exception(message) + { + } + }; + class KeyExistsException : public Exception + { + public: + KeyExistsException() + {} + KeyExistsException(const String & message) + : Exception(message) + { + } + }; + + class NotSupportedException : public Exception + { + public: + NotSupportedException() + {} + NotSupportedException(const String & message) + : Exception(message) + { + } + }; + + class NotImplementedException : public Exception + { + public: + NotImplementedException() + {} + NotImplementedException(const String & message) + : Exception(message) + { + } + }; + + class InvalidProgramException : public Exception + { + public: + InvalidProgramException() + {} + InvalidProgramException(const String & message) + : Exception(message) + { + } + }; + } +} + +#endif \ No newline at end of file diff --git a/source/core/func.h b/source/core/func.h new file mode 100644 index 000000000..8ec2ba8a5 --- /dev/null +++ b/source/core/func.h @@ -0,0 +1,216 @@ +#ifndef CORELIB_FUNC_H +#define CORELIB_FUNC_H + +#if 0 + +#include "SmartPointer.h" + +namespace CoreLib +{ + namespace Basic + { + template + class FuncPtr + { + public: + virtual TResult operator()(Arguments...) = 0; + virtual bool operator == (const FuncPtr *) + { + return false; + } + virtual ~FuncPtr() {} + }; + + template + class CdeclFuncPtr : public FuncPtr + { + public: + typedef TResult (*FuncType)(Arguments...); + private: + FuncType funcPtr; + public: + CdeclFuncPtr(FuncType func) + :funcPtr(func) + { + } + + virtual TResult operator()(Arguments... params) override + { + return funcPtr(params...); + } + + virtual bool operator == (const FuncPtr * ptr) override + { + auto cptr = dynamic_cast*>(ptr); + if (cptr) + return funcPtr == cptr->funcPtr; + else + return false; + } + }; + + template + class MemberFuncPtr : public FuncPtr + { + public: + typedef TResult (Class::*FuncType)(Arguments...); + private: + FuncType funcPtr; + Class * object; + public: + MemberFuncPtr(Class * obj, FuncType func) + : funcPtr(func), object(obj) + { + } + + virtual TResult operator()(Arguments... params) override + { + return (object->*funcPtr)(params...); + } + + virtual bool operator == (const FuncPtr * ptr) override + { + auto cptr = dynamic_cast*>(ptr); + if (cptr) + return funcPtr == cptr->funcPtr && object == cptr->object; + else + return false; + } + }; + + template + class LambdaFuncPtr : public FuncPtr + { + private: + F func; + public: + LambdaFuncPtr(const F & _func) + : func(_func) + {} + virtual TResult operator()(Arguments... params) override + { + return func(params...); + } + virtual bool operator == (const FuncPtr * /*ptr*/) override + { + return false; + } + }; + + template + class Func + { + private: + RefPtr> funcPtr; + public: + Func(){} + Func(typename CdeclFuncPtr::FuncType func) + { + funcPtr = new CdeclFuncPtr(func); + } + template + Func(Class * object, typename MemberFuncPtr::FuncType func) + { + funcPtr = new MemberFuncPtr(object, func); + } + template + Func(const TFuncObj & func) + { + funcPtr = new LambdaFuncPtr(func); + } + Func & operator = (typename CdeclFuncPtr::FuncType func) + { + funcPtr = new CdeclFuncPtr(func); + return *this; + } + template + Func & operator = (const MemberFuncPtr & func) + { + funcPtr = new MemberFuncPtr(func); + return *this; + } + template + Func & operator = (const TFuncObj & func) + { + funcPtr = new LambdaFuncPtr(func); + return *this; + } + bool operator == (const Func & f) + { + return *funcPtr == f.funcPtr.Ptr(); + } + bool operator != (const Func & f) + { + return !(*this == f); + } + TResult operator()(Arguments... params) + { + return (*funcPtr)(params...); + } + }; + + // template + // using Procedure = Func; + + template + class Procedure : public Func + { + private: + RefPtr> funcPtr; + public: + Procedure(){} + Procedure(const Procedure & proc) + { + funcPtr = proc.funcPtr; + } + Procedure(typename CdeclFuncPtr::FuncType func) + { + funcPtr = new CdeclFuncPtr(func); + } + template + Procedure(Class * object, typename MemberFuncPtr::FuncType func) + { + funcPtr = new MemberFuncPtr(object, func); + } + template + Procedure(const TFuncObj & func) + { + funcPtr = new LambdaFuncPtr(func); + } + Procedure & operator = (typename CdeclFuncPtr::FuncType func) + { + funcPtr = new CdeclFuncPtr(func); + return *this; + } + template + Procedure & operator = (const MemberFuncPtr & func) + { + funcPtr = new MemberFuncPtr(func); + return *this; + } + template + Procedure & operator = (const TFuncObj & func) + { + funcPtr = new LambdaFuncPtr(func); + return *this; + } + Procedure & operator = (const Procedure & proc) + { + funcPtr = proc.funcPtr; + } + void Clear() + { + funcPtr = nullptr; + } + void operator()(Arguments... params) + { + if (funcPtr) + (*funcPtr)(params...); + } + }; + } +} + +#endif + +#endif \ No newline at end of file diff --git a/source/core/hash.h b/source/core/hash.h new file mode 100644 index 000000000..07327a415 --- /dev/null +++ b/source/core/hash.h @@ -0,0 +1,105 @@ +#ifndef CORELIB_HASH_H +#define CORELIB_HASH_H + +#include "slang-math.h" +#include + +namespace CoreLib +{ + namespace Basic + { + + inline int GetHashCode(double key) + { + return FloatAsInt((float)key); + } + inline int GetHashCode(float key) + { + return FloatAsInt(key); + } + inline int GetHashCode(const char * buffer) + { + if (!buffer) + return 0; + int hash = 0; + int c; + auto str = buffer; + c = *str++; + while (c) + { + hash = c + (hash << 6) + (hash << 16) - hash; + c = *str++; + } + return hash; + } + inline int GetHashCode(char * buffer) + { + return GetHashCode(const_cast(buffer)); + } + + template + class Hash + { + public: + }; + template<> + class Hash<1> + { + public: + template + static int GetHashCode(TKey & key) + { + return (int)key; + } + }; + template<> + class Hash<0> + { + public: + template + static int GetHashCode(TKey & key) + { + return key.GetHashCode(); + } + }; + template + class PointerHash + {}; + template<> + class PointerHash<1> + { + public: + template + static int GetHashCode(TKey const& key) + { + return (int)((CoreLib::PtrInt)key) / 16; // sizeof(typename std::remove_pointer::type); + } + }; + template<> + class PointerHash<0> + { + public: + template + static int GetHashCode(TKey & key) + { + return Hash::value || std::is_enum::value>::GetHashCode(key); + } + }; + + template + int GetHashCode(const TKey & key) + { + return PointerHash::value>::GetHashCode(key); + } + + template + int GetHashCode(TKey & key) + { + return PointerHash::value>::GetHashCode(key); + } + + + } +} + +#endif \ No newline at end of file diff --git a/source/core/int-set.h b/source/core/int-set.h new file mode 100644 index 000000000..cb8f788f2 --- /dev/null +++ b/source/core/int-set.h @@ -0,0 +1,166 @@ +#ifndef BIT_VECTOR_INT_SET_H +#define BIT_VECTOR_INT_SET_H + +#include "list.h" +#include "slang-math.h" +#include "common.h" +#include "exception.h" + +#include + +namespace CoreLib +{ + namespace Basic + { + class IntSet + { + private: + List buffer; + public: + IntSet() + {} + IntSet(const IntSet & other) + { + buffer = other.buffer; + } + IntSet(IntSet && other) + { + *this = (_Move(other)); + } + IntSet & operator = (IntSet && other) + { + buffer = _Move(other.buffer); + return *this; + } + IntSet & operator = (const IntSet & other) + { + buffer = other.buffer; + return *this; + } + int GetHashCode() + { + int rs = 0; + for (auto val : buffer) + rs ^= val; + return rs; + } + IntSet(int maxVal) + { + SetMax(maxVal); + } + int Size() const + { + return buffer.Count()*32; + } + void SetMax(int val) + { + Resize(val); + Clear(); + } + void SetAll() + { + for (int i = 0; i>5); + if (buffer.Count() > oldBufferSize) + memset(buffer.Buffer()+oldBufferSize, 0, (buffer.Count()-oldBufferSize) * sizeof(int)); + } + void Clear() + { + for (int i = 0; i>5; + if (id < buffer.Count()) + buffer[id] |= (1<<(val&31)); + else + { + int oldSize = buffer.Count(); + buffer.SetSize(id+1); + memset(buffer.Buffer() + oldSize, 0, (buffer.Count()-oldSize)*sizeof(int)); + buffer[id] |= (1<<(val&31)); + } + } + void Remove(int val) + { + if ((val>>5) < buffer.Count()) + buffer[(val>>5)] &= ~(1<<(val&31)); + } + bool Contains(int val) const + { + if ((val>>5) >= buffer.Count()) + return false; + return (buffer[(val>>5)] & (1<<(val&31))) != 0; + } + void UnionWith(const IntSet & set) + { + for (int i = 0; i buffer.Count()) + buffer.AddRange(set.buffer.Buffer()+buffer.Count(), set.buffer.Count()-buffer.Count()); + } + bool operator == (const IntSet & set) + { + if (buffer.Count() != set.buffer.Count()) + return false; + for (int i = 0; i + class LinkedList; + + template + class LinkedNode + { + template + friend class LinkedList; + private: + LinkedNode *pPrev, *pNext; + LinkedList * FLink; + public: + T Value; + LinkedNode (LinkedList * lnk):FLink(lnk) + { + pPrev = pNext = 0; + }; + LinkedNode * GetPrevious() + { + return pPrev; + }; + LinkedNode * GetNext() + { + return pNext; + }; + LinkedNode * InsertAfter(const T & nData) + { + LinkedNode * n = new LinkedNode(FLink); + n->Value = nData; + n->pPrev = this; + n->pNext = this->pNext; + LinkedNode *npp = n->pNext; + if (npp) + { + npp->pPrev = n; + } + pNext = n; + if (!n->pNext) + FLink->FTail = n; + FLink->FCount ++; + return n; + }; + LinkedNode * InsertBefore(const T & nData) + { + LinkedNode * n = new LinkedNode(FLink); + n->Value = nData; + n->pPrev = pPrev; + n->pNext = this; + pPrev = n; + LinkedNode *npp = n->pPrev; + if (npp) + npp->pNext = n; + if (!n->pPrev) + FLink->FHead = n; + FLink->FCount ++; + return n; + }; + void Delete() + { + if (pPrev) + pPrev->pNext = pNext; + if (pNext) + pNext->pPrev = pPrev; + FLink->FCount --; + if (FLink->FHead == this) + { + FLink->FHead = pNext; + } + if (FLink->FTail == this) + { + FLink->FTail = pPrev; + } + delete this; + } + }; + template + class LinkedList + { + template + friend class LinkedNode; + private: + LinkedNode * FHead, *FTail; + int FCount; + public: + class Iterator + { + public: + LinkedNode * Current, *Next; + void SetCurrent(LinkedNode * cur) + { + Current = cur; + if (Current) + Next = Current->GetNext(); + else + Next = 0; + } + Iterator() + { + Current = Next = 0; + } + Iterator(LinkedNode * cur) + { + SetCurrent(cur); + } + T & operator *() const + { + return Current->Value; + } + Iterator& operator ++() + { + SetCurrent(Next); + return *this; + } + Iterator operator ++(int) + { + Iterator rs = *this; + SetCurrent(Next); + return rs; + } + bool operator != (const Iterator & iter) const + { + return Current != iter.Current; + } + bool operator == (const Iterator & iter) const + { + return Current == iter.Current; + } + }; + Iterator begin() const + { + return Iterator(FHead); + } + Iterator end() const + { + return Iterator(0); + } + public: + LinkedList() : FHead(0), FTail(0), FCount(0) + { + } + ~LinkedList() + { + Clear(); + } + LinkedList(const LinkedList & link) : FHead(0), FTail(0), FCount(0) + { + this->operator=(link); + } + LinkedList(LinkedList && link) : FHead(0), FTail(0), FCount(0) + { + this->operator=(_Move(link)); + } + LinkedList & operator = (LinkedList && link) + { + if (FHead != 0) + Clear(); + FHead = link.FHead; + FTail = link.FTail; + FCount = link.FCount; + link.FHead = 0; + link.FTail = 0; + link.FCount = 0; + for (auto node = FHead; node; node = node->GetNext()) + node->FLink = this; + return *this; + } + LinkedList & operator = (const LinkedList & link) + { + if (FHead != 0) + Clear(); + auto p = link.FHead; + while (p) + { + AddLast(p->Value); + p = p->GetNext(); + } + return *this; + } + template + void ForEach(const IteratorFunc & f) + { + auto p = FHead; + while (p) + { + f(p->Value); + p = p->GetNext(); + } + } + LinkedNode * GetNode(int x) + { + LinkedNode *pCur = FHead; + for (int i=0;ipNext; + else + throw "Index out of range"; + } + return pCur; + }; + LinkedNode * Find(const T& fData) + { + for (LinkedNode * pCur = FHead; pCur; pCur = pCur->pNext) + { + if (pCur->Value == fData) + return pCur; + } + return 0; + }; + LinkedNode * FirstNode() const + { + return FHead; + }; + T & First() const + { + if (!FHead) + throw IndexOutofRangeException("LinkedList: index out of range."); + return FHead->Value; + } + T & Last() const + { + if (!FTail) + throw IndexOutofRangeException("LinkedList: index out of range."); + return FTail->Value; + } + LinkedNode * LastNode() const + { + return FTail; + }; + LinkedNode * AddLast(const T & nData) + { + LinkedNode * n = new LinkedNode(this); + n->Value = nData; + n->pPrev = FTail; + if (FTail) + FTail->pNext = n; + n->pNext = 0; + FTail = n; + if (!FHead) + FHead = n; + FCount ++; + return n; + }; + // Insert a blank node + LinkedNode * AddLast() + { + LinkedNode * n = new LinkedNode(this); + n->pPrev = FTail; + if (FTail) + FTail->pNext = n; + n->pNext = 0; + FTail = n; + if (!FHead) + FHead = n; + FCount ++; + return n; + }; + LinkedNode * AddFirst(const T& nData) + { + LinkedNode *n = new LinkedNode(this); + n->Value = nData; + n->pPrev = 0; + n->pNext = FHead; + if (FHead) + FHead->pPrev = n; + FHead = n; + if (!FTail) + FTail = n; + FCount ++; + return n; + }; + void Delete(LinkedNode*n, int Count = 1) + { + LinkedNode *n1,*n2 = 0, *tn; + n1 = n->pPrev; + tn = n; + int numDeleted = 0; + for (int i=0; ipNext; + delete tn; + tn = n2; + numDeleted++; + if (tn == 0) + break; + } + if (n1) + n1->pNext = n2; + else + FHead = n2; + if (n2) + n2->pPrev = n1; + else + FTail = n1; + FCount -= numDeleted; + } + void Clear() + { + for (LinkedNode *n = FHead; n; ) + { + LinkedNode * tmp = n->pNext; + delete n; + n = tmp; + } + FHead = 0; + FTail = 0; + FCount = 0; + } + List ToList() const + { + List rs; + rs.Reserve(FCount); + for (auto & item : *this) + { + rs.Add(item); + } + return rs; + } + int Count() + { + return FCount; + } + }; + } +} +#endif diff --git a/source/core/linq.h b/source/core/linq.h new file mode 100644 index 000000000..bd40f1bc2 --- /dev/null +++ b/source/core/linq.h @@ -0,0 +1,669 @@ +#ifndef FUNDAMENTAL_LIB_LINQ_H +#define FUNDAMENTAL_LIB_LINQ_H + +#include "List.h" + +namespace CoreLib +{ + namespace Basic + { + + template + T ConstructT(); + + template + class RemoveReference + { + public: + typedef T Type; + }; + + template + class RemoveReference + { + public: + typedef T Type; + }; + + template + class RemoveReference + { + public: + typedef T Type; + }; + + template + struct RemovePointer + { + typedef T Type; + }; + + template + struct RemovePointer + { + typedef T Type; + }; + + template + class ConcatQuery + { + private: + TQueryable1 items1; + TQueryable2 items2; + public: + ConcatQuery(const TQueryable1 & queryable1, const TQueryable2 & queryable2) + : items1(queryable1), items2(queryable2) + {} + class Enumerator + { + private: + TEnumerator1 ptr1; + TEnumerator1 end1; + TEnumerator2 ptr2; + TEnumerator2 end2; + public: + Enumerator(const Enumerator &) = default; + Enumerator(TEnumerator1 pptr, TEnumerator1 pend, TEnumerator2 pptr2, TEnumerator2 pend2) + : ptr1(pptr), end1(pend), ptr2(pptr2), end2(pend2) + {} + T operator *() const + { + if (ptr1 != end1) + return *(ptr1); + else + return *(ptr2); + } + Enumerator& operator ++() + { + if (ptr1 != end1) + ++ptr1; + else + ++ptr2; + return *this; + } + Enumerator operator ++(int) + { + Enumerator rs = *this; + ++rs; + return rs; + } + bool operator != (const Enumerator & iter) const + { + return ptr1 != iter.ptr1 || ptr2 != iter.ptr2; + } + bool operator == (const Enumerator & iter) const + { + return ptr1 == iter.ptr1 && ptr2 == iter.ptr2; + } + }; + Enumerator begin() const + { + return Enumerator(items1.begin(), items1.end(), items2.begin(), items2.end()); + } + Enumerator end() const + { + return Enumerator(items1.end(), items1.end(), items2.end(), items2.end()); + } + }; + + template + class WhereQuery + { + private: + TQueryable items; + TFunc func; + public: + WhereQuery(const TQueryable & queryable, const TFunc & f) + : items(queryable), func(f) + {} + class Enumerator + { + private: + TEnumerator ptr; + TEnumerator end; + const TFunc * func; + public: + Enumerator(const Enumerator &) = default; + Enumerator(TEnumerator ptr, TEnumerator end, const TFunc & f) + : ptr(ptr), end(end), func(&f) + {} + T operator *() const + { + return *(ptr); + } + Enumerator& operator ++() + { + ++ptr; + while (ptr != end) + { + if ((*func)(*ptr)) + break; + else + ++ptr; + } + return *this; + } + Enumerator operator ++(int) + { + Enumerator rs = *this; + while (rs.ptr != end) + { + if ((*func)(*rs.ptr)) + break; + ++rs.ptr; + } + return rs; + } + bool operator != (const Enumerator & iter) const + { + return ptr != iter.ptr; + } + bool operator == (const Enumerator & iter) const + { + return ptr == iter.ptr; + } + }; + Enumerator begin() const + { + auto ptr = items.begin(); + auto end = items.end(); + while (ptr != end) + { + if (func(*ptr)) + break; + ++ptr; + } + return Enumerator(ptr, end, func); + } + Enumerator end() const + { + return Enumerator(items.end(), items.end(), func); + } + }; + + template + class SkipQuery + { + private: + TQueryable items; + int count = 0; + public: + SkipQuery(const TQueryable & queryable, int pCount) + : items(queryable), count(pCount) + {} + class Enumerator + { + private: + TEnumerator ptr; + TEnumerator end; + public: + Enumerator(const Enumerator &) = default; + Enumerator(TEnumerator pptr, TEnumerator pend) + : ptr(pptr), end(pend) + { + } + T operator *() const + { + return *(ptr); + } + Enumerator& operator ++() + { + ++ptr; + return *this; + } + Enumerator operator ++(int) + { + Enumerator rs = *this; + ++ptr; + return rs; + } + bool operator != (const Enumerator & iter) const + { + return ptr != iter.ptr; + } + bool operator == (const Enumerator & iter) const + { + return ptr == iter.ptr; + } + }; + Enumerator begin() const + { + auto ptr = items.begin(); + auto end = items.end(); + for (int i = 0; i < count; i++) + if (ptr != end) + ++ptr; + return Enumerator(ptr, end); + } + Enumerator end() const + { + return Enumerator(items.end(), items.end()); + } + }; + + template + class SelectQuery + { + private: + TQueryable items; + TFunc func; + public: + SelectQuery(const TQueryable & queryable, const TFunc & f) + : items(queryable), func(f) + {} + class Enumerator + { + private: + TEnumerator ptr; + TEnumerator end; + const TFunc * func; + public: + Enumerator(const Enumerator &) = default; + Enumerator(TEnumerator ptr, TEnumerator end, const TFunc & f) + : ptr(ptr), end(end), func(&f) + {} + auto operator *() const -> decltype((*func)(*ptr)) + { + return (*func)(*ptr); + } + Enumerator& operator ++() + { + ++ptr; + return *this; + } + Enumerator operator ++(int) + { + Enumerator rs = *this; + ++rs; + return rs; + } + bool operator != (const Enumerator & iter) const + { + return !(ptr == iter.ptr); + } + bool operator == (const Enumerator & iter) const + { + return ptr == iter.ptr; + } + }; + Enumerator begin() const + { + return Enumerator(items.begin(), items.end(), func); + } + Enumerator end() const + { + return Enumerator(items.end(), items.end(), func); + } + }; + + template + class SelectManyQuery + { + private: + TQueryable items; + TFunc func; + SelectManyQuery() + {} + public: + SelectManyQuery(const TQueryable & queryable, const TFunc & f) + : items(queryable), func(f) + {} + template + class Enumerator + { + private: + TEnumerator ptr; + TEnumerator end; + const TFunc * func; + TItems items; + TItemPtr subPtr; + public: + Enumerator(const Enumerator &) = default; + Enumerator(TEnumerator ptr, TEnumerator end, const TFunc & f) + : ptr(ptr), end(end), func(&f) + { + if (ptr != end) + { + items = f(*ptr); + subPtr = items.begin(); + } + } + auto operator *() const -> decltype(*subPtr) + { + return *subPtr; + } + Enumerator& operator ++() + { + ++subPtr; + while (subPtr == items.end() && ptr != end) + { + ++ptr; + if (ptr != end) + { + items = (*func)(*ptr); + subPtr = items.begin(); + } + else + break; + } + + return *this; + } + Enumerator operator ++(int) + { + Enumerator rs = *this; + ++rs; + return rs; + } + bool operator != (const Enumerator & iter) const + { + return !operator==(iter); + } + bool operator == (const Enumerator & iter) const + { + if (ptr == iter.ptr) + { + if (ptr == end) + return true; + else + return subPtr == iter.subPtr; + } + else + return false; + } + }; + auto begin() const ->Enumerator())), decltype(func(ConstructT()).begin())> + { + return Enumerator())), decltype(func(ConstructT()).begin())>(items.begin(), items.end(), func); + } + auto end() const ->Enumerator())), decltype(func(ConstructT()).begin())> + { + return Enumerator())), decltype(func(ConstructT()).begin())>(items.end(), items.end(), func); + } + }; + + template + struct EnumeratorType + { + typedef decltype(ConstructT().begin()) Type; + }; + + template + class ExtractReturnType + { + public: + static TFunc * f; + static TArg ConstructArg() {}; + typedef decltype((*f)(ConstructArg())) ReturnType; + }; + + template + class ExtractItemType + { + public: + typedef typename RemovePointer().begin())>::Type Type; + }; + + template + class Queryable + { + private: + TQueryable items; + public: + auto begin() const -> decltype(items.begin()) + { + return items.begin(); + } + auto end() const -> decltype(items.end()) + { + return items.end(); + } + public: + const TQueryable & GetItems() const + { + return items; + } + Queryable(const TQueryable & items) + : items(items) + {} + + Queryable, typename SkipQuery::Enumerator, T> Skip(int count) const + { + return Queryable, typename SkipQuery::Enumerator, T>(SkipQuery(items, count)); + } + + template + Queryable, typename ConcatQuery::Enumerator, T> Concat(const Queryable & other) const + { + return Queryable, typename ConcatQuery::Enumerator, T>(ConcatQuery(this->items, other.GetItems())); + } + + template + Queryable, typename WhereQuery::Enumerator, T> Where(const TFunc & f) const + { + return Queryable, typename WhereQuery::Enumerator, T>(WhereQuery(items, f)); + } + + template + Queryable, typename SelectQuery::Enumerator, typename RemoveReference::ReturnType>::Type> Select(const TFunc & f) const + { + return Queryable, typename SelectQuery::Enumerator, typename RemoveReference::ReturnType>::Type>(SelectQuery(items, f)); + } + + template + auto SelectMany(const TFunc & f) const ->Queryable, typename EnumeratorType>::Type, typename ExtractItemType()))>::Type> + { + return Queryable, typename EnumeratorType>::Type, typename ExtractItemType()))>::Type>(SelectManyQuery(items, f)); + } + + template + auto Aggregate(const TAggregateResult & initial, const TFunc & f) const -> decltype(f(initial, *items.begin())) + { + TAggregateResult rs = initial; + for (auto && x : items) + rs = f(rs, x); + return rs; + } + + template + bool Any(const TFunc & condition) const + { + for (auto && x : items) + if (condition(x)) + return true; + return false; + } + + template + T & First(const TFunc & condition) const + { + for (auto && x : items) + if (condition(x)) + return x; + } + + template + T Max(const TFunc & selector) const + { + return Aggregate(*items.begin(), [&](const T & v0, const T & v1) + { + return selector(v0) > selector(v1) ? v0 : v1; + }); + } + + template + T Min(const TFunc & selector) const + { + return Aggregate(*items.begin(), [&](const T & v0, const T & v1) + { + return selector(v0) < selector(v1) ? v0 : v1; + }); + } + + template + auto Sum(const TFunc & selector) const -> decltype(selector(ConstructT())) + { + decltype(selector(ConstructT())) rs(0); + for (auto && x : items) + rs = rs + selector(x); + return rs; + } + + T Max() const + { + return Aggregate(*items.begin(), [](const T & v0, const T & v1) {return v0 > v1 ? v0 : v1; }); + } + + T Min() const + { + return Aggregate(*items.begin(), [](const T & v0, const T & v1) {return v0 < v1 ? v0 : v1; }); + } + + T Sum() const + { + T rs = T(0); + for (auto && x : items) + rs = rs + x; + return rs; + } + + T Avg() const + { + T rs = T(0); + int count = 0; + for (auto && x : items) + { + rs = rs + x; + count++; + } + return rs / count; + } + + int Count() const + { + int rs = 0; + for (auto && x : items) + rs++; + return rs; + } + + List ToList() const + { + List rs; + for (auto && val : items) + rs.Add(val); + return rs; + } + }; + + + template + inline Queryable, T*, T> From(const List & list) + { + return Queryable, T*, T>(list.GetArrayView()); + } + + template + inline Queryable, T*, T> From(List && list) + { + return Queryable, T*, T>(_Move(list)); + } + + template + inline Queryable, T*, T> From(const ArrayView & list) + { + return Queryable, T*, T>(list); + } + + template + inline Queryable, T*, T> From(const Array & list) + { + return Queryable, T*, T>(list); + } + + template + inline auto From(const T & list) -> Queryable + { + return Queryable(list); + } + + template + inline Queryable, T*, T> FromSingle(const T & obj) + { + Array arr; + arr.Add(obj); + return From(arr); + } + + template + struct LinkedListView + { + typename LinkedList::Iterator start, last; + typename LinkedList::Iterator begin() const + { + return start; + } + typename LinkedList::Iterator end() const + { + return last; + } + }; + + template + inline Queryable, LinkedNode, T> From(const LinkedList & list) + { + LinkedListView view; + view.start = list.begin(); + view.last = list.end(); + return Queryable, LinkedNode, T>(view); + } + + template + struct EnumerableDictView + { + typename EnumerableDictionary::Iterator start, last; + typename EnumerableDictionary::Iterator begin() const + { + return start; + } + typename EnumerableDictionary::Iterator end() const + { + return last; + } + }; + + template + inline Queryable, typename EnumerableDictionary::Iterator, KeyValuePair> From(const EnumerableDictionary & dict) + { + EnumerableDictView view; + view.start = dict.begin(); + view.last = dict.end(); + return Queryable, typename EnumerableDictionary::Iterator, KeyValuePair>(view); + } + + template + struct EnumerableHashSetView + { + typename HashSetBase>::Iterator start, last; + typename EnumerableHashSet::Iterator begin() const + { + return start; + } + typename EnumerableHashSet::Iterator end() const + { + return last; + } + }; + + template + inline Queryable, typename HashSetBase>::Iterator, TKey> From(const EnumerableHashSet & dict) + { + EnumerableHashSetView view; + view.start = dict.begin(); + view.last = dict.end(); + return Queryable, typename HashSetBase>::Iterator, TKey>(view); + } + } +} + +#endif \ No newline at end of file diff --git a/source/core/list.h b/source/core/list.h new file mode 100644 index 000000000..6ff68ed7d --- /dev/null +++ b/source/core/list.h @@ -0,0 +1,674 @@ +#ifndef FUNDAMENTAL_LIB_LIST_H +#define FUNDAMENTAL_LIB_LIST_H + +#include "allocator.h" +#include "slang-math.h" +#include "array-view.h" + +#include +#include +#include + +const int MIN_QSORT_SIZE = 32; + +namespace CoreLib +{ + namespace Basic + { + template + class Initializer + { + + }; + + template + class Initializer + { + public: + static void Initialize(T * buffer, int size) + { + for (int i = 0; i + class AllocateMethod + { + public: + static inline T* Alloc(int size) + { + TAllocator allocator; + T * rs = (T*)allocator.Alloc(size*sizeof(T)); + Initializer::value>::Initialize(rs, size); + return rs; + } + static inline void Free(T * ptr, int bufferSize) + { + TAllocator allocator; + if (!std::is_trivially_destructible::value) + { + for (int i = 0; i + class AllocateMethod + { + public: + static inline T* Alloc(int size) + { + return new T[size]; + } + static inline void Free(T* ptr, int /*bufferSize*/) + { + delete [] ptr; + } + }; + + template + class Initializer + { + public: + static void Initialize(T * buffer, int size) + { + for (int i = 0; i + class List + { + private: + + inline T * Allocate(int size) + { + return AllocateMethod::Alloc(size); + + } + private: + static const int InitialSize = 16; + TAllocator allocator; + private: + T * buffer; + int _count; + int bufferSize; + void FreeBuffer() + { + AllocateMethod::Free(buffer, bufferSize); + buffer = 0; + } + void Free() + { + if (buffer) + { + FreeBuffer(); + } + buffer = 0; + _count = bufferSize = 0; + } + public: + T* begin() const + { + return buffer; + } + T* end() const + { + return buffer+_count; + } + private: + template + void Init(const T & val, Args... args) + { + Add(val); + Init(args...); + } + public: + List() + : buffer(0), _count(0), bufferSize(0) + { + } + template + List(const T & val, Args... args) + { + Init(val, args...); + } + List(const List & list) + : buffer(0), _count(0), bufferSize(0) + { + this->operator=(list); + } + List(List && list) + : buffer(0), _count(0), bufferSize(0) + { + this->operator=(static_cast&&>(list)); + } + static List Create(const T & val, int count) + { + List rs; + rs.SetSize(count); + for (int i = 0; i < count; i++) + rs[i] = val; + return rs; + } + ~List() + { + Free(); + } + List & operator=(const List & list) + { + Free(); + AddRange(list); + + return *this; + } + + List & operator=(List && list) + { + Free(); + _count = list._count; + bufferSize = list.bufferSize; + buffer = list.buffer; + + list.buffer = 0; + list._count = 0; + list.bufferSize = 0; + return *this; + } + + T & First() const + { +#ifdef _DEBUG + if (_count == 0) + throw "Index out of range."; +#endif + return buffer[0]; + } + + T & Last() const + { +#ifdef _DEBUG + if (_count == 0) + throw "Index out of range."; +#endif + return buffer[_count-1]; + } + + inline void SwapWith(List & other) + { + T* tmpBuffer = this->buffer; + this->buffer = other.buffer; + other.buffer = tmpBuffer; + int tmpBufferSize = this->bufferSize; + this->bufferSize = other.bufferSize; + other.bufferSize = tmpBufferSize; + int tmpCount = this->_count; + this->_count = other._count; + other._count = tmpCount; + TAllocator tmpAlloc = _Move(this->allocator); + this->allocator = _Move(other.allocator); + other.allocator = _Move(tmpAlloc); + } + + T* ReleaseBuffer() + { + T* rs = buffer; + buffer = nullptr; + _count = 0; + bufferSize = 0; + return rs; + } + + inline ArrayView GetArrayView() const + { + return ArrayView(buffer, _count); + } + + inline ArrayView GetArrayView(int start, int count) const + { +#ifdef _DEBUG + if (start + count > _count || start < 0 || count < 0) + throw "Index out of range."; +#endif + return ArrayView(buffer + start, count); + } + + void Add(T && obj) + { + if (bufferSize < _count + 1) + { + int newBufferSize = InitialSize; + if (bufferSize) + newBufferSize = (bufferSize << 1); + + Reserve(newBufferSize); + } + buffer[_count++] = static_cast(obj); + } + + void Add(const T & obj) + { + if (bufferSize < _count + 1) + { + int newBufferSize = InitialSize; + if (bufferSize) + newBufferSize = (bufferSize << 1); + + Reserve(newBufferSize); + } + buffer[_count++] = obj; + + } + + int Count() const + { + return _count; + } + + T * Buffer() const + { + return buffer; + } + + int Capacity() const + { + return bufferSize; + } + + void Insert(int id, const T & val) + { + InsertRange(id, &val, 1); + } + + void InsertRange(int id, const T * vals, int n) + { + if (bufferSize < _count + n) + { + int newBufferSize = InitialSize; + while (newBufferSize < _count + n) + newBufferSize = newBufferSize << 1; + + T * newBuffer = Allocate(newBufferSize); + if (bufferSize) + { + /*if (std::has_trivial_copy_assign::value && std::has_trivial_destructor::value) + { + memcpy(newBuffer, buffer, sizeof(T) * id); + memcpy(newBuffer + id + n, buffer + id, sizeof(T) * (_count - id)); + } + else*/ + { + for (int i = 0; i < id; i++) + newBuffer[i] = buffer[i]; + for (int i = id; i < _count; i++) + newBuffer[i + n] = T(static_cast(buffer[i])); + } + FreeBuffer(); + } + buffer = newBuffer; + bufferSize = newBufferSize; + } + else + { + /*if (std::has_trivial_copy_assign::value && std::has_trivial_destructor::value) + memmove(buffer + id + n, buffer + id, sizeof(T) * (_count - id)); + else*/ + { + for (int i = _count - 1; i >= id; i--) + buffer[i + n] = static_cast(buffer[i]); + } + } + /*if (std::has_trivial_copy_assign::value && std::has_trivial_destructor::value) + memcpy(buffer + id, vals, sizeof(T) * n); + else*/ + for (int i = 0; i < n; i++) + buffer[id + i] = vals[i]; + + _count += n; + } + + //slower than original edition + //void Add(const T & val) + //{ + // InsertRange(_count, &val, 1); + //} + + void InsertRange(int id, const List & list) + { + InsertRange(id, list.buffer, list._count); + } + + void AddRange(ArrayView list) + { + InsertRange(_count, list.Buffer(), list.Count()); + } + + void AddRange(const T * vals, int n) + { + InsertRange(_count, vals, n); + } + + void AddRange(const List & list) + { + InsertRange(_count, list.buffer, list._count); + } + + void RemoveRange(int id, int deleteCount) + { +#if _DEBUG + if (id >= _count || id < 0) + throw "Remove: Index out of range."; + if(deleteCount < 0) + throw "Remove: deleteCount smaller than zero."; +#endif + int actualDeleteCount = ((id + deleteCount) >= _count)? (_count - id) : deleteCount; + for (int i = id + actualDeleteCount; i < _count; i++) + buffer[i - actualDeleteCount] = static_cast(buffer[i]); + _count -= actualDeleteCount; + } + + void RemoveAt(int id) + { + RemoveRange(id, 1); + } + + void Remove(const T & val) + { + int idx = IndexOf(val); + if (idx != -1) + RemoveAt(idx); + } + + void Reverse() + { + for (int i = 0; i < (_count >> 1); i++) + { + Swap(buffer, i, _count - i - 1); + } + } + + void FastRemove(const T & val) + { + int idx = IndexOf(val); + FastRemoveAt(idx); + } + + void FastRemoveAt(int idx) + { + if (idx != -1 && _count - 1 != idx) + { + buffer[idx] = _Move(buffer[_count - 1]); + } + _count--; + } + + void Clear() + { + _count = 0; + } + + void Reserve(int size) + { + if(size > bufferSize) + { + T * newBuffer = Allocate(size); + if (bufferSize) + { + /*if (std::has_trivial_copy_assign::value && std::has_trivial_destructor::value) + memcpy(newBuffer, buffer, _count * sizeof(T)); + else*/ + { + for (int i = 0; i < _count; i++) + newBuffer[i] = static_cast(buffer[i]); + } + FreeBuffer(); + } + buffer = newBuffer; + bufferSize = size; + } + } + + void GrowToSize(int size) + { + int newBufferSize = 1<_count = size; + } + + void SetSize(int size) + { + Reserve(size); + _count = size; + } + + void UnsafeShrinkToSize(int size) + { + _count = size; + } + + void Compress() + { + if (bufferSize > _count && _count > 0) + { + T * newBuffer = Allocate(_count); + for (int i = 0; i < _count; i++) + newBuffer[i] = static_cast(buffer[i]); + FreeBuffer(); + buffer = newBuffer; + bufferSize = _count; + } + } + +#ifndef FORCE_INLINE +#ifdef _MSC_VER +#define FORCE_INLINE __forceinline +#else +#define FORCE_INLINE inline +#endif +#endif + + FORCE_INLINE T & operator [](int id) const + { +#if _DEBUG + if(id >= _count || id < 0) + throw IndexOutofRangeException("Operator[]: Index out of Range."); +#endif + return buffer[id]; + } + + template + int FindFirst(const Func & predicate) const + { + for (int i = 0; i < _count; i++) + { + if (predicate(buffer[i])) + return i; + } + return -1; + } + + template + int FindLast(const Func & predicate) const + { + for (int i = _count - 1; i >= 0; i--) + { + if (predicate(buffer[i])) + return i; + } + return -1; + } + + template + int IndexOf(const T2 & val) const + { + for (int i = 0; i < _count; i++) + { + if (buffer[i] == val) + return i; + } + return -1; + } + + template + int LastIndexOf(const T2 & val) const + { + for (int i = _count - 1; i >= 0; i--) + { + if(buffer[i] == val) + return i; + } + return -1; + } + + void Sort() + { + Sort([](T& t1, T& t2){return t1 + void Sort(Comparer compare) + { + //InsertionSort(buffer, 0, _count - 1); + //QuickSort(buffer, 0, _count - 1, compare); + std::sort(buffer, buffer + _count, compare); + } + + template + void ForEach(IterateFunc f) const + { + for (int i = 0; i<_count; i++) + f(buffer[i]); + } + + template + void QuickSort(T * vals, int startIndex, int endIndex, Comparer comparer) + { + if(startIndex < endIndex) + { + if (endIndex - startIndex < MIN_QSORT_SIZE) + InsertionSort(vals, startIndex, endIndex, comparer); + else + { + int pivotIndex = (startIndex + endIndex) >> 1; + int pivotNewIndex = Partition(vals, startIndex, endIndex, pivotIndex, comparer); + QuickSort(vals, startIndex, pivotNewIndex - 1, comparer); + QuickSort(vals, pivotNewIndex + 1, endIndex, comparer); + } + } + + } + template + int Partition(T * vals, int left, int right, int pivotIndex, Comparer comparer) + { + T pivotValue = vals[pivotIndex]; + Swap(vals, right, pivotIndex); + int storeIndex = left; + for (int i = left; i < right; i++) + { + if (comparer(vals[i], pivotValue)) + { + Swap(vals, i, storeIndex); + storeIndex++; + } + } + Swap(vals, storeIndex, right); + return storeIndex; + } + template + void InsertionSort(T * vals, int startIndex, int endIndex, Comparer comparer) + { + for (int i = startIndex + 1; i <= endIndex; i++) + { + T insertValue = static_cast(vals[i]); + int insertIndex = i - 1; + while (insertIndex >= startIndex && comparer(insertValue, vals[insertIndex])) + { + vals[insertIndex + 1] = static_cast(vals[insertIndex]); + insertIndex--; + } + vals[insertIndex + 1] = static_cast(insertValue); + } + } + + inline void Swap(T * vals, int index1, int index2) + { + if (index1 != index2) + { + T tmp = static_cast(vals[index1]); + vals[index1] = static_cast(vals[index2]); + vals[index2] = static_cast(tmp); + } + } + + template + int BinarySearch(const T2 & obj, Comparer comparer) + { + int imin = 0, imax = _count - 1; + while (imax >= imin) + { + int imid = (imin + imax) >> 1; + int compareResult = comparer(buffer[imid], obj); + if (compareResult == 0) + return imid; + else if (compareResult < 0) + imin = imid + 1; + else + imax = imid - 1; + } + return -1; + } + + template + int BinarySearch(const T2 & obj) + { + return BinarySearch(obj, + [](T & curObj, const T2 & thatObj)->int + { + if (curObj < thatObj) + return -1; + else if (curObj == thatObj) + return 0; + else + return 1; + }); + } + }; + + template + T Min(const List & list) + { + T minVal = list.First(); + for (int i = 1; i + T Max(const List & list) + { + T maxVal = list.First(); + for (int i = 1; i maxVal) + maxVal = list[i]; + return maxVal; + } + } +} + +#endif diff --git a/source/core/memory-pool.cpp b/source/core/memory-pool.cpp new file mode 100644 index 000000000..f9d29636b --- /dev/null +++ b/source/core/memory-pool.cpp @@ -0,0 +1,135 @@ +#include "memory-pool.h" +#include + +namespace CoreLib +{ + namespace Basic + { + MemoryPool::MemoryPool(unsigned char * pBuffer, int pLog2BlockSize, int numBlocks) + { + Init(pBuffer, pLog2BlockSize, numBlocks); + } + void MemoryPool::Init(unsigned char * pBuffer, int pLog2BlockSize, int numBlocks) + { + assert(pLog2BlockSize >= 1 && pLog2BlockSize <= 30); + assert(numBlocks >= 4); + buffer = pBuffer; + blockSize = 1 << pLog2BlockSize; + log2BlockSize = pLog2BlockSize; + numLevels = Math::Log2Floor(numBlocks); + freeList[0] = (FreeListNode*)buffer; + freeList[0]->NextPtr = nullptr; + freeList[0]->PrevPtr = nullptr; + used.SetMax(1 << (numLevels)); + for (int i = 1; i < MaxLevels; i++) + { + freeList[i] = nullptr; + } + } + int MemoryPool::AllocBlock(int level) + { + if (level < 0) + return -1; + if (freeList[level] == nullptr) + { + auto largeBlockAddr = AllocBlock(level - 1); + if (largeBlockAddr != -1) + { + auto block1 = (FreeListNode*)(buffer + ((largeBlockAddr ^ (1 << (numLevels - level))) << log2BlockSize)); + block1->NextPtr = nullptr; + block1->PrevPtr = nullptr; + freeList[level] = block1; + + int blockIndex = (1 << level) + (largeBlockAddr >> (numLevels-level)) - 1; + used.Add(blockIndex); + return largeBlockAddr; + } + else + return -1; + } + else + { + auto node = freeList[level]; + if (node->NextPtr) + { + node->NextPtr->PrevPtr = node->PrevPtr; + } + freeList[level] = freeList[level]->NextPtr; + int rs = (int)((unsigned char *)node - buffer) >> log2BlockSize; + int blockIndex = (1 << level) + (rs >> (numLevels - level)) - 1; + used.Add(blockIndex); + return rs; + } + } + unsigned char * MemoryPool::Alloc(int size) + { + if (size == 0) + return nullptr; + int originalSize = size; + if (size < blockSize) + size = blockSize; + int order = numLevels - (Math::Log2Ceil(size) - log2BlockSize); + assert(order >= 0 && order < MaxLevels); + + bytesAllocated += (1 << ((numLevels-order) + log2BlockSize)); + bytesWasted += (1 << ((numLevels - order) + log2BlockSize)) - originalSize; + + int blockId = AllocBlock(order); + if (blockId != -1) + return buffer + (blockId << log2BlockSize); + else + return nullptr; + } + void MemoryPool::FreeBlock(unsigned char * ptr, int level) + { + int indexInLevel = (int)(ptr - buffer) >> (numLevels - level + log2BlockSize); + int blockIndex = (1 << level) + indexInLevel - 1; + assert(used.Contains(blockIndex)); + int buddyIndex = (blockIndex & 1) ? blockIndex + 1 : blockIndex - 1; + used.Remove(blockIndex); + if (level > 0 && !used.Contains(buddyIndex)) + { + auto buddyPtr = (FreeListNode *)(buffer + ((((int)(ptr - buffer) >> log2BlockSize) ^ (1 << (numLevels - level))) << log2BlockSize)); + if (buddyPtr->PrevPtr) + { + buddyPtr->PrevPtr->NextPtr = buddyPtr->NextPtr; + } + if (buddyPtr->NextPtr) + { + buddyPtr->NextPtr->PrevPtr = buddyPtr->PrevPtr; + } + if (freeList[level] == buddyPtr) + { + freeList[level] = buddyPtr->NextPtr; + } + // recursively free parent blocks + auto parentPtr = Math::Min(buddyPtr, (FreeListNode*)ptr); + if (level > 0) + FreeBlock((unsigned char*)parentPtr, level - 1); + } + else + { + // insert to freelist + auto freeNode = (FreeListNode *)ptr; + freeNode->NextPtr = freeList[level]; + freeNode->PrevPtr = nullptr; + if (freeList[level]) + freeList[level]->PrevPtr = freeNode; + freeList[level] = freeNode; + } + } + void MemoryPool::Free(unsigned char * ptr, int size) + { + if (size == 0) + return; + int originalSize = size; + if (size < blockSize) + size = blockSize; + int level = numLevels - (Math::Log2Ceil(size) - log2BlockSize); + bytesAllocated -= (1 << ((numLevels-level) + log2BlockSize)); + bytesWasted -= (1 << ((numLevels - level) + log2BlockSize)) - originalSize; + FreeBlock(ptr, level); + } + } +} + diff --git a/source/core/memory-pool.h b/source/core/memory-pool.h new file mode 100644 index 000000000..6bfded060 --- /dev/null +++ b/source/core/memory-pool.h @@ -0,0 +1,126 @@ +#ifndef CORE_LIB_MEMORY_POOL_H +#define CORE_LIB_MEMORY_POOL_H + +#include "basic.h" +#include "int-set.h" + +namespace CoreLib +{ + namespace Basic + { + struct MemoryBlockFields + { + unsigned int Occupied : 1; + unsigned int Order : 31; + }; + struct FreeListNode + { + FreeListNode * PrevPtr = nullptr, *NextPtr = nullptr; + }; + class MemoryPool + { + private: + static const int MaxLevels = 32; + int blockSize = 0, log2BlockSize = 0; + int numLevels = 0; + int bytesAllocated = 0; + int bytesWasted = 0; + unsigned char * buffer = nullptr; + FreeListNode * freeList[MaxLevels]; + IntSet used; + int AllocBlock(int level); + void FreeBlock(unsigned char * ptr, int level); + public: + MemoryPool(unsigned char * buffer, int log2BlockSize, int numBlocks); + MemoryPool() = default; + void Init(unsigned char * buffer, int log2BlockSize, int numBlocks); + unsigned char * Alloc(int size); + void Free(unsigned char * ptr, int size); + }; + + class OutofPoolMemoryException : public Exception + {}; + + template + class ObjectPool + { + static const int ObjectSize = sizeof(T) < 8 ? 8 : sizeof(T); + private: + struct FreeList + { + FreeList* Next; + }; + FreeList * freeList = nullptr; + int allocPtr = 0; + int poolSize = 0; + void * buffer = 0; + T * GetFreeObject() + { + if (freeList) + { + auto rs = (T*)freeList; + freeList = freeList->Next; + return rs; + } + return nullptr; + } + public: + ObjectPool() + { + freeList = nullptr; + allocPtr = 0; + buffer = malloc(PoolSize * ObjectSize); + } + + void Close() + { + free(buffer); + } + + void Free(T * obj) + { + auto newList = (FreeList*)obj; + newList->Next = freeList; + freeList = newList; + } + + void * Buffer() + { + return buffer; + } + + T * Alloc() + { + auto rs = GetFreeObject(); + if (!rs) + { + if (allocPtr < PoolSize) + { + rs = (T*)buffer + allocPtr; + allocPtr++; + } + } + if (!rs) + { + throw OutofPoolMemoryException(); + } + return rs; + } + }; + }; + +#define USE_POOL_ALLOCATOR(T, PoolSize) \ + private:\ + static CoreLib::ObjectPool _pool;\ + public:\ + void * operator new(std::size_t) { return _pool.Alloc(); } \ + void operator delete(void * ptr) {_pool.Free((T*)ptr); }\ + int GetObjectId() { return (int)(this - (T*)_pool.Buffer()); }\ + static void ClosePool(); +#define IMPL_POOL_ALLOCATOR(T, PoolSize) \ + CoreLib::ObjectPool T::_pool;\ + void T::ClosePool() { _pool.Close(); } + +} + +#endif \ No newline at end of file diff --git a/source/core/secure-crt.h b/source/core/secure-crt.h new file mode 100644 index 000000000..12927cc24 --- /dev/null +++ b/source/core/secure-crt.h @@ -0,0 +1,75 @@ +#ifndef _MSC_VER +#ifndef CORE_LIB_SECURE_CRT_H +#define CORE_LIB_SECURE_CRT_H +#include +#include +#include +#include + +inline void memcpy_s(void *dest, size_t numberOfElements, const void * src, size_t count) +{ + memcpy(dest, src, count); +} + +#define _TRUNCATE ((size_t)-1) +#define _stricmp strcasecmp + +inline void fopen_s(FILE**f, const char * fileName, const char * mode) +{ + *f = fopen(fileName, mode); +} + +inline size_t fread_s(void * buffer, size_t bufferSize, size_t elementSize, size_t count, FILE * stream) +{ + return fread(buffer, elementSize, count, stream); +} + +inline size_t wcsnlen_s(const wchar_t * str, size_t /*numberofElements*/) +{ + return wcslen(str); +} + +inline size_t strnlen_s(const char * str, size_t numberofElements) +{ + return strnlen(str, numberofElements); +} + +inline int sprintf_s(char * buffer, size_t sizeOfBuffer, const char * format, ...) +{ + va_list argptr; + va_start(argptr, format); + int rs = snprintf(buffer, sizeOfBuffer, format, argptr); + va_end(argptr); + return rs; +} + +inline int swprintf_s(wchar_t * buffer, size_t sizeOfBuffer, const wchar_t * format, ...) +{ + va_list argptr; + va_start(argptr, format); + int rs = swprintf(buffer, sizeOfBuffer, format, argptr); + va_end(argptr); + return rs; +} + +inline void wcscpy_s(wchar_t * strDestination, size_t /*numberOfElements*/, const wchar_t * strSource) +{ + wcscpy(strDestination, strSource); +} +inline void strcpy_s(char * strDestination, size_t /*numberOfElements*/, const char * strSource) +{ + strcpy(strDestination, strSource); +} + +inline void wcsncpy_s(wchar_t * strDestination, size_t /*numberOfElements*/, const wchar_t * strSource, size_t count) +{ + wcscpy(strDestination, strSource); + //wcsncpy(strDestination, strSource, count); +} +inline void strncpy_s(char * strDestination, size_t /*numberOfElements*/, const char * strSource, size_t count) +{ + strncpy(strDestination, strSource, count); + //wcsncpy(strDestination, strSource, count); +} +#endif +#endif diff --git a/source/core/slang-io.cpp b/source/core/slang-io.cpp new file mode 100644 index 000000000..da36edbbf --- /dev/null +++ b/source/core/slang-io.cpp @@ -0,0 +1,145 @@ +#include "slang-io.h" +#include "exception.h" +#ifndef __STDC__ +#define __STDC__ 1 +#endif +#include +#ifdef _WIN32 +#include +#endif +namespace CoreLib +{ + namespace IO + { + using namespace CoreLib::Basic; + + CommandLineWriter * currentCommandWriter = nullptr; + + void SetCommandLineWriter(CommandLineWriter * writer) + { + currentCommandWriter = writer; + } + + bool File::Exists(const String & fileName) + { +#ifdef _WIN32 + struct _stat32 statVar; + return ::_wstat32(((String)fileName).ToWString(), &statVar) != -1; +#else + struct stat statVar; + return ::stat(fileName.Buffer(), &statVar) == 0; +#endif + } + + String Path::TruncateExt(const String & path) + { + int dotPos = path.LastIndexOf('.'); + if (dotPos != -1) + return path.SubString(0, dotPos); + else + return path; + } + String Path::ReplaceExt(const String & path, const char * newExt) + { + StringBuilder sb(path.Length()+10); + int dotPos = path.LastIndexOf('.'); + if (dotPos == -1) + dotPos = path.Length(); + sb.Append(path.Buffer(), dotPos); + sb.Append('.'); + sb.Append(newExt); + return sb.ProduceString(); + } + String Path::GetFileName(const String & path) + { + int pos = path.LastIndexOf('/'); + pos = Math::Max(path.LastIndexOf('\\'), pos) + 1; + return path.SubString(pos, path.Length()-pos); + } + String Path::GetFileNameWithoutEXT(const String & path) + { + int pos = path.LastIndexOf('/'); + pos = Math::Max(path.LastIndexOf('\\'), pos) + 1; + int dotPos = path.LastIndexOf('.'); + if (dotPos <= pos) + dotPos = path.Length(); + return path.SubString(pos, dotPos - pos); + } + String Path::GetFileExt(const String & path) + { + int dotPos = path.LastIndexOf('.'); + if (dotPos != -1) + return path.SubString(dotPos+1, path.Length()-dotPos-1); + else + return ""; + } + String Path::GetDirectoryName(const String & path) + { + int pos = path.LastIndexOf('/'); + pos = Math::Max(path.LastIndexOf('\\'), pos); + if (pos != -1) + return path.SubString(0, pos); + else + return ""; + } + String Path::Combine(const String & path1, const String & path2) + { + if (path1.Length() == 0) return path2; + StringBuilder sb(path1.Length()+path2.Length()+2); + sb.Append(path1); + if (!path1.EndsWith('\\') && !path1.EndsWith('/')) + sb.Append(PathDelimiter); + sb.Append(path2); + return sb.ProduceString(); + } + String Path::Combine(const String & path1, const String & path2, const String & path3) + { + StringBuilder sb(path1.Length()+path2.Length()+path3.Length()+3); + sb.Append(path1); + if (!path1.EndsWith('\\') && !path1.EndsWith('/')) + sb.Append(PathDelimiter); + sb.Append(path2); + if (!path2.EndsWith('\\') && !path2.EndsWith('/')) + sb.Append(PathDelimiter); + sb.Append(path3); + return sb.ProduceString(); + } + + bool Path::CreateDir(const String & path) + { +#if defined(_WIN32) + return _wmkdir(path.ToWString()) == 0; +#else + return mkdir(path.Buffer(), 0777) == 0; +#endif + } + + CoreLib::Basic::String File::ReadAllText(const CoreLib::Basic::String & fileName) + { + StreamReader reader(new FileStream(fileName, FileMode::Open, FileAccess::Read, FileShare::ReadWrite)); + return reader.ReadToEnd(); + } + + CoreLib::Basic::List File::ReadAllBytes(const CoreLib::Basic::String & fileName) + { + RefPtr fs = new FileStream(fileName, FileMode::Open, FileAccess::Read, FileShare::ReadWrite); + List buffer; + while (!fs->IsEnd()) + { + unsigned char ch; + int read = (int)fs->Read(&ch, 1); + if (read) + buffer.Add(ch); + else + break; + } + return _Move(buffer); + } + + void File::WriteAllText(const CoreLib::Basic::String & fileName, const CoreLib::Basic::String & text) + { + StreamWriter writer(new FileStream(fileName, FileMode::Create)); + writer.Write(text); + } + } +} \ No newline at end of file diff --git a/source/core/slang-io.h b/source/core/slang-io.h new file mode 100644 index 000000000..0471cd965 --- /dev/null +++ b/source/core/slang-io.h @@ -0,0 +1,63 @@ +#ifndef CORE_LIB_IO_H +#define CORE_LIB_IO_H + +#include "slang-string.h" +#include "stream.h" +#include "text-io.h" +#include "secure-crt.h" + +namespace CoreLib +{ + namespace IO + { + class File + { + public: + static bool Exists(const CoreLib::Basic::String & fileName); + static CoreLib::Basic::String ReadAllText(const CoreLib::Basic::String & fileName); + static CoreLib::Basic::List ReadAllBytes(const CoreLib::Basic::String & fileName); + static void WriteAllText(const CoreLib::Basic::String & fileName, const CoreLib::Basic::String & text); + }; + + class Path + { + public: +#ifdef _WIN32 + static const char PathDelimiter = '\\'; +#else + static const char PathDelimiter = '/'; +#endif + static String TruncateExt(const String & path); + static String ReplaceExt(const String & path, const char * newExt); + static String GetFileName(const String & path); + static String GetFileNameWithoutEXT(const String & path); + static String GetFileExt(const String & path); + static String GetDirectoryName(const String & path); + static String Combine(const String & path1, const String & path2); + static String Combine(const String & path1, const String & path2, const String & path3); + static bool CreateDir(const String & path); + }; + + class CommandLineWriter : public Object + { + public: + virtual void Write(const String & text) = 0; + }; + + void SetCommandLineWriter(CommandLineWriter * writer); + + extern CommandLineWriter * currentCommandWriter; + template + void uiprintf(const wchar_t * format, Args... args) + { + if (currentCommandWriter) + { + char buffer[1024]; + snprintf(buffer, 1024, format, args...); + currentCommandWriter->Write(buffer); + } + } + } +} + +#endif \ No newline at end of file diff --git a/source/core/slang-math.cpp b/source/core/slang-math.cpp new file mode 100644 index 000000000..a57b0dac2 --- /dev/null +++ b/source/core/slang-math.cpp @@ -0,0 +1,9 @@ +#include "slang-math.h" + +namespace CoreLib +{ + namespace Basic + { + const float Math::Pi = 3.141592654f; + } +} \ No newline at end of file diff --git a/source/core/slang-math.h b/source/core/slang-math.h new file mode 100644 index 000000000..454dfbfdf --- /dev/null +++ b/source/core/slang-math.h @@ -0,0 +1,220 @@ +#ifndef CORE_LIB_MATH_H +#define CORE_LIB_MATH_H + +#include + +namespace CoreLib +{ + namespace Basic + { + class Math + { + public: + static const float Pi; + template + static T Min(const T& v1, const T&v2) + { + return v1 + static T Max(const T& v1, const T&v2) + { + return v1>v2?v1:v2; + } + template + static T Min(const T& v1, const T&v2, const T&v3) + { + return Min(v1, Min(v2, v3)); + } + template + static T Max(const T& v1, const T&v2, const T&v3) + { + return Max(v1, Max(v2, v3)); + } + template + static T Clamp(const T& val, const T& vmin, const T&vmax) + { + if (val < vmin) return vmin; + else if (val > vmax) return vmax; + else return val; + } + + static inline int FastFloor(float x) + { + int i = (int)x; + return i - (i > x); + } + + static inline int FastFloor(double x) + { + int i = (int)x; + return i - (i > x); + } + + static inline int IsNaN(float x) + { +#ifdef _M_X64 + return _isnanf(x); +#else + return isnan(x); +#endif + } + + static inline int IsInf(float x) + { + return isinf(x); + } + + static inline unsigned int Ones32(register unsigned int x) + { + /* 32-bit recursive reduction using SWAR... + but first step is mapping 2-bit values + into sum of 2 1-bit values in sneaky way + */ + x -= ((x >> 1) & 0x55555555); + x = (((x >> 2) & 0x33333333) + (x & 0x33333333)); + x = (((x >> 4) + x) & 0x0f0f0f0f); + x += (x >> 8); + x += (x >> 16); + return(x & 0x0000003f); + } + + static inline unsigned int Log2Floor(register unsigned int x) + { + x |= (x >> 1); + x |= (x >> 2); + x |= (x >> 4); + x |= (x >> 8); + x |= (x >> 16); + return(Ones32(x >> 1)); + } + + static inline unsigned int Log2Ceil(register unsigned int x) + { + int y = (x & (x - 1)); + y |= -y; + y >>= (32 - 1); + x |= (x >> 1); + x |= (x >> 2); + x |= (x >> 4); + x |= (x >> 8); + x |= (x >> 16); + return(Ones32(x >> 1) - y); + } + /* + static inline int Log2(float x) + { + unsigned int ix = (unsigned int&)x; + unsigned int exp = (ix >> 23) & 0xFF; + int log2 = (unsigned int)(exp) - 127; + + return log2; + } + */ + }; + inline int FloatAsInt(float val) + { + union InterCast + { + float fvalue; + int ivalue; + } cast; + cast.fvalue = val; + return cast.ivalue; + } + inline float IntAsFloat(int val) + { + union InterCast + { + float fvalue; + int ivalue; + } cast; + cast.ivalue = val; + return cast.fvalue; + } + + inline unsigned short FloatToHalf(float val) + { + int x = *(int*)&val; + unsigned short bits = (x >> 16) & 0x8000; + unsigned short m = (x >> 12) & 0x07ff; + unsigned int e = (x >> 23) & 0xff; + if (e < 103) + return bits; + if (e > 142) + { + bits |= 0x7c00u; + bits |= e == 255 && (x & 0x007fffffu); + return bits; + } + if (e < 113) + { + m |= 0x0800u; + bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1); + return bits; + } + bits |= ((e - 112) << 10) | (m >> 1); + bits += m & 1; + return bits; + } + + inline float HalfToFloat(unsigned short input) + { + union InterCast + { + float fvalue; + int ivalue; + InterCast() = default; + InterCast(int ival) + { + ivalue = ival; + } + }; + static const InterCast magic = InterCast((127 + (127 - 15)) << 23); + static const InterCast was_infnan = InterCast((127 + 16) << 23); + InterCast o; + o.ivalue = (input & 0x7fff) << 13; // exponent/mantissa bits + o.fvalue *= magic.fvalue; // exponent adjust + if (o.fvalue >= was_infnan.fvalue) // make sure Inf/NaN survive + o.ivalue |= 255 << 23; + o.ivalue |= (input & 0x8000) << 16; // sign bit + return o.fvalue; + } + + class Random + { + private: + unsigned int seed; + public: + Random(int seed) + { + this->seed = seed; + } + int Next() // random between 0 and RandMax (currently 0x7fff) + { + return ((seed = ((seed << 12) + 150889L) % 714025) & 0x7fff); + } + int Next(int min, int max) // inclusive min, exclusive max + { + unsigned int a = ((seed = ((seed << 12) + 150889L) % 714025) & 0xFFFF); + unsigned int b = ((seed = ((seed << 12) + 150889L) % 714025) & 0xFFFF); + unsigned int r = (a << 16) + b; + return min + r % (max - min); + } + float NextFloat() + { + return ((Next() << 15) + Next()) / ((float)(1 << 30)); + } + float NextFloat(float valMin, float valMax) + { + return valMin + (valMax - valMin) * NextFloat(); + } + static int RandMax() + { + return 0x7fff; + } + }; + } +} + +#endif diff --git a/source/core/slang-string.cpp b/source/core/slang-string.cpp new file mode 100644 index 000000000..1337ceaec --- /dev/null +++ b/source/core/slang-string.cpp @@ -0,0 +1,166 @@ +#include "slang-string.h" +#include "text-io.h" + +namespace CoreLib +{ + namespace Basic + { + _EndLine EndLine; + String StringConcat(const char * lhs, int leftLen, const char * rhs, int rightLen) + { + String res; + res.length = leftLen + rightLen; + res.buffer = new char[res.length + 1]; + strcpy_s(res.buffer.Ptr(), res.length + 1, lhs); + strcpy_s(res.buffer + leftLen, res.length + 1 - leftLen, rhs); + return res; + } + String operator+(const char * op1, const String & op2) + { + if(!op2.buffer) + return String(op1); + + return StringConcat(op1, (int)strlen(op1), op2.buffer.Ptr(), op2.length); + } + + String operator+(const String & op1, const char * op2) + { + if(!op1.buffer) + return String(op2); + + return StringConcat(op1.buffer.Ptr(), op1.length, op2, (int)strlen(op2)); + } + + String operator+(const String & op1, const String & op2) + { + if(!op1.buffer && !op2.buffer) + return String(); + else if(!op1.buffer) + return String(op2); + else if(!op2.buffer) + return String(op1); + + return StringConcat(op1.buffer.Ptr(), op1.length, op2.buffer.Ptr(), op2.length); + } + + int StringToInt(const String & str, int radix) + { + if (str.StartsWith("0x")) + return (int)strtoll(str.Buffer(), NULL, 16); + else + return (int)strtoll(str.Buffer(), NULL, radix); + } + unsigned int StringToUInt(const String & str, int radix) + { + if (str.StartsWith("0x")) + return (unsigned int)strtoull(str.Buffer(), NULL, 16); + else + return (unsigned int)strtoull(str.Buffer(), NULL, radix); + } + double StringToDouble(const String & str) + { + return (double)strtod(str.Buffer(), NULL); + } + float StringToFloat(const String & str) + { + return strtof(str.Buffer(), NULL); + } + + String String::ReplaceAll(String src, String dst) const + { + String rs = *this; + int index = 0; + int srcLen = src.length; + int len = rs.length; + while ((index = rs.IndexOf(src, index)) != -1) + { + rs = rs.SubString(0, index) + dst + rs.SubString(index + srcLen, len - index - srcLen); + len = rs.length; + } + return rs; + } + + String String::FromWString(const wchar_t * wstr) + { +#ifdef _WIN32 + return CoreLib::IO::Encoding::UTF16->ToString((const char*)wstr, (int)(wcslen(wstr) * sizeof(wchar_t))); +#else + return CoreLib::IO::Encoding::UTF32->ToString((const char*)wstr, (int)(wcslen(wstr) * sizeof(wchar_t))); +#endif + } + + String String::FromWString(const wchar_t * wstr, const wchar_t * wend) + { +#ifdef _WIN32 + return CoreLib::IO::Encoding::UTF16->ToString((const char*)wstr, (int)((wend - wstr) * sizeof(wchar_t))); +#else + return CoreLib::IO::Encoding::UTF32->ToString((const char*)wstr, (int)((wend - wstr) * sizeof(wchar_t))); +#endif + } + + String String::FromWChar(const wchar_t ch) + { +#ifdef _WIN32 + return CoreLib::IO::Encoding::UTF16->ToString((const char*)&ch, (int)(sizeof(wchar_t))); +#else + return CoreLib::IO::Encoding::UTF32->ToString((const char*)&ch, (int)(sizeof(wchar_t))); +#endif + } + + String String::FromUnicodePoint(unsigned int codePoint) + { + char buf[6]; + int len = CoreLib::IO::EncodeUnicodePointToUTF8(buf, (int)codePoint); + buf[len] = 0; + return String(buf); + } + + const wchar_t * String::ToWString(int * len) const + { + if (!buffer) + { + if (len) + *len = 0; + return L""; + } + else + { + if (wcharBuffer) + { + if (len) + *len = (int)wcslen(wcharBuffer); + return wcharBuffer; + } + List buf; + CoreLib::IO::Encoding::UTF16->GetBytes(buf, *this); + if (len) + *len = buf.Count() / sizeof(wchar_t); + buf.Add(0); + buf.Add(0); + const_cast(this)->wcharBuffer = (wchar_t*)buf.Buffer(); + buf.ReleaseBuffer(); + return wcharBuffer; + } + } + + String String::PadLeft(char ch, int pLen) + { + StringBuilder sb; + for (int i = 0; i < pLen - this->length; i++) + sb << ch; + for (int i = 0; i < this->length; i++) + sb << buffer[i]; + return sb.ProduceString(); + } + + String String::PadRight(char ch, int pLen) + { + StringBuilder sb; + for (int i = 0; i < this->length; i++) + sb << buffer[i]; + for (int i = 0; i < pLen - this->length; i++) + sb << ch; + return sb.ProduceString(); + } + } +} diff --git a/source/core/slang-string.h b/source/core/slang-string.h new file mode 100644 index 000000000..3eb99e8e3 --- /dev/null +++ b/source/core/slang-string.h @@ -0,0 +1,740 @@ +#ifndef FUNDAMENTAL_LIB_STRING_H +#define FUNDAMENTAL_LIB_STRING_H +#include +#include +#include +#include "smart-pointer.h" +#include "common.h" +#include "hash.h" +#include "secure-crt.h" + +namespace CoreLib +{ + namespace Basic + { + class _EndLine + {}; + extern _EndLine EndLine; + + // in-place reversion, works only for ascii string + inline void ReverseInternalAscii(char * buffer, int length) + { + int i, j; + char c; + for (i = 0, j = length - 1; i + inline int IntToAscii(char * buffer, IntType val, int radix) + { + int i = 0; + IntType sign; + sign = val; + if (sign < 0) + val = (IntType)(0 - val); + do + { + int digit = (val % radix); + if (digit <= 9) + buffer[i++] = (char)(digit + '0'); + else + buffer[i++] = (char)(digit - 10 + 'A'); + } while ((val /= radix) > 0); + if (sign < 0) + buffer[i++] = '-'; + buffer[i] = '\0'; + return i; + } + + inline bool IsUtf8LeadingByte(char ch) + { + return (((unsigned char)ch) & 0xC0) == 0xC0; + } + + inline bool IsUtf8ContinuationByte(char ch) + { + return (((unsigned char)ch) & 0xC0) == 0x80; + } + + /*! + @brief Represents a UTF-8 encoded string. + */ + + class String + { + friend class StringBuilder; + private: + RefPtr buffer; + wchar_t * wcharBuffer = nullptr; + int length = 0; + void Free() + { + if (buffer) + buffer = 0; + if (wcharBuffer) + delete[] wcharBuffer; + buffer = 0; + wcharBuffer = 0; + length = 0; + } + public: + static String FromBuffer(RefPtr buffer, int len) + { + String rs; + rs.buffer = buffer; + rs.length = len; + return rs; + } + static String FromWString(const wchar_t * wstr); + static String FromWString(const wchar_t * wstr, const wchar_t * wend); + static String FromWChar(const wchar_t ch); + static String FromUnicodePoint(unsigned int codePoint); + String() + { + } + const char * begin() const + { + return buffer.Ptr(); + } + const char * end() const + { + return buffer.Ptr() + length; + } + String(int val, int radix = 10) + { + buffer = new char[33]; + length = IntToAscii(buffer.Ptr(), val, radix); + ReverseInternalAscii(buffer.Ptr(), length); + } + String(unsigned int val, int radix = 10) + { + buffer = new char[33]; + length = IntToAscii(buffer.Ptr(), val, radix); + ReverseInternalAscii(buffer.Ptr(), length); + } + String(long long val, int radix = 10) + { + buffer = new char[65]; + length = IntToAscii(buffer.Ptr(), val, radix); + ReverseInternalAscii(buffer.Ptr(), length); + } + String(float val, const char * format = "%g") + { + buffer = new char[128]; + sprintf_s(buffer.Ptr(), 128, format, val); + length = (int)strnlen_s(buffer.Ptr(), 128); + } + String(double val, const char * format = "%g") + { + buffer = new char[128]; + sprintf_s(buffer.Ptr(), 128, format, val); + length = (int)strnlen_s(buffer.Ptr(), 128); + } + String(const char * str) + { + if (str) + { + length = (int)strlen(str); + buffer = new char[length + 1]; + memcpy(buffer.Ptr(), str, length + 1); + } + } + String(char chr) + { + if (chr) + { + length = 1; + buffer = new char[2]; + buffer[0] = chr; + buffer[1] = '\0'; + } + } + String(const String & str) + { + this->operator=(str); + } + String(String&& other) + { + this->operator=(static_cast(other)); + } + ~String() + { + Free(); + } + String & operator=(const String & str) + { + if (str.buffer == buffer) + return *this; + Free(); + if (str.buffer) + { + length = str.length; + buffer = str.buffer; + wcharBuffer = 0; + } + return *this; + } + String & operator=(String&& other) + { + if (this != &other) + { + Free(); + buffer = _Move(other.buffer); + length = other.length; + wcharBuffer = other.wcharBuffer; + other.buffer = 0; + other.length = 0; + other.wcharBuffer = 0; + } + return *this; + } + char operator[](int id) const + { +#if _DEBUG + if (id < 0 || id >= length) + throw "Operator[]: index out of range."; +#endif + return buffer.Ptr()[id]; + } + + friend String StringConcat(const char * lhs, int leftLen, const char * rhs, int rightLen); + friend String operator+(const char*op1, const String & op2); + friend String operator+(const String & op1, const char * op2); + friend String operator+(const String & op1, const String & op2); + + String TrimStart() const + { + if (!buffer) + return *this; + int startIndex = 0; + while (startIndex < length && + (buffer[startIndex] == ' ' || buffer[startIndex] == '\t' || buffer[startIndex] == '\r' || buffer[startIndex] == '\n')) + startIndex++; + return String(buffer + startIndex); + } + + String TrimEnd() const + { + if (!buffer) + return *this; + + int endIndex = length - 1; + while (endIndex >= 0 && + (buffer[endIndex] == ' ' || buffer[endIndex] == '\t' || buffer[endIndex] == '\r' || buffer[endIndex] == '\n')) + endIndex--; + String res; + res.length = endIndex + 1; + res.buffer = new char[endIndex + 2]; + strncpy_s(res.buffer.Ptr(), endIndex + 2, buffer.Ptr(), endIndex + 1); + return res; + } + + String Trim() const + { + if (!buffer) + return *this; + + int startIndex = 0; + while (startIndex < length && + (buffer[startIndex] == ' ' || buffer[startIndex] == '\t')) + startIndex++; + int endIndex = length - 1; + while (endIndex >= startIndex && + (buffer[endIndex] == ' ' || buffer[endIndex] == '\t')) + endIndex--; + + String res; + res.length = endIndex - startIndex + 1; + res.buffer = new char[res.length + 1]; + memcpy(res.buffer.Ptr(), buffer + startIndex, res.length); + res.buffer[res.length] = '\0'; + return res; + } + + String SubString(int id, int len) const + { + if (len == 0) + return ""; + if (id + len > length) + len = length - id; +#if _DEBUG + if (id < 0 || id >= length || (id + len) > length) + throw "SubString: index out of range."; + if (len < 0) + throw "SubString: length less than zero."; +#endif + String res; + res.buffer = new char[len + 1]; + res.length = len; + strncpy_s(res.buffer.Ptr(), len + 1, buffer + id, len); + res.buffer[len] = 0; + return res; + } + + const char * Buffer() const + { + if (buffer) + return buffer.Ptr(); + else + return ""; + } + + const wchar_t * ToWString(int * len = 0) const; + + bool Equals(const String & str, bool caseSensitive = true) + { + if (!buffer) + return (str.buffer == 0); + if (caseSensitive) + return (strcmp(buffer.Ptr(), str.buffer.Ptr()) == 0); + else + { +#ifdef _MSC_VER + return (_stricmp(buffer.Ptr(), str.buffer.Ptr()) == 0); +#else + return (strcasecmp(buffer.Ptr(), str.buffer.Ptr()) == 0); +#endif + } + } + bool operator==(const char * strbuffer) const + { + if (!buffer) + return (strbuffer == 0 || strcmp(strbuffer, "") == 0); + if (!strbuffer) + return buffer == nullptr || strcmp(buffer.Ptr(), "") == 0; + return (strcmp(buffer.Ptr(), strbuffer) == 0); + } + + bool operator==(const String & str) const + { + if (!buffer) + return (str.buffer == 0 || strcmp(str.buffer.Ptr(), "") == 0); + if (!str.buffer) + return buffer == nullptr || strcmp(buffer.Ptr(), "") == 0; + return (strcmp(buffer.Ptr(), str.buffer.Ptr()) == 0); + } + bool operator!=(const char * strbuffer) const + { + if (!buffer) + return (strbuffer != 0 && strcmp(strbuffer, "") != 0); + if (strbuffer == 0) + return length != 0; + return (strcmp(buffer.Ptr(), strbuffer) != 0); + } + bool operator!=(const String & str) const + { + if (!buffer) + return (str.buffer != 0 && strcmp(str.buffer.Ptr(), "") != 0); + if (str.buffer.Ptr() == 0) + return length != 0; + return (strcmp(buffer.Ptr(), str.buffer.Ptr()) != 0); + } + bool operator>(const String & str) const + { + if (!buffer) + return false; + if (!str.buffer) + return buffer.Ptr() != nullptr && length != 0; + return (strcmp(buffer.Ptr(), str.buffer.Ptr()) > 0); + } + bool operator<(const String & str) const + { + if (!buffer) + return (str.buffer != 0); + if (!str.buffer) + return false; + return (strcmp(buffer.Ptr(), str.buffer.Ptr()) < 0); + } + bool operator>=(const String & str) const + { + if (!buffer) + return (str.buffer == 0); + if (!str.buffer) + return length == 0; + int res = strcmp(buffer.Ptr(), str.buffer.Ptr()); + return (res > 0 || res == 0); + } + bool operator<=(const String & str) const + { + if (!buffer) + return true; + if (!str.buffer) + return length > 0; + int res = strcmp(buffer.Ptr(), str.buffer.Ptr()); + return (res < 0 || res == 0); + } + + String ToUpper() const + { + if (!buffer) + return *this; + String res; + res.length = length; + res.buffer = new char[length + 1]; + for (int i = 0; i <= length; i++) + res.buffer[i] = (buffer[i] >= 'a' && buffer[i] <= 'z') ? + (buffer[i] - 'a' + 'A') : buffer[i]; + return res; + } + + String ToLower() const + { + if (!buffer) + return *this; + String res; + res.length = length; + res.buffer = new char[length + 1]; + for (int i = 0; i <= length; i++) + res.buffer[i] = (buffer[i] >= 'A' && buffer[i] <= 'Z') ? + (buffer[i] - 'A' + 'a') : buffer[i]; + return res; + } + + int Length() const + { + return length; + } + + int IndexOf(const char * str, int id) const // String str + { + if (!buffer) + return -1; + if (id < 0 || id >= length) + return -1; + auto findRs = strstr(buffer + id, str); + int res = findRs ? (int)(findRs - buffer.Ptr()) : -1; + if (res >= 0) + return res; + else + return -1; + } + + int IndexOf(const String & str, int id) const + { + return IndexOf(str.buffer.Ptr(), id); + } + + int IndexOf(const char * str) const + { + return IndexOf(str, 0); + } + + int IndexOf(const String & str) const + { + return IndexOf(str.buffer.Ptr(), 0); + } + + int IndexOf(char ch, int id) const + { +#if _DEBUG + if (id < 0 || id >= length) + throw "SubString: index out of range."; +#endif + if (!buffer) + return -1; + for (int i = id; i < length; i++) + if (buffer[i] == ch) + return i; + return -1; + } + + int IndexOf(char ch) const + { + return IndexOf(ch, 0); + } + + int LastIndexOf(char ch) const + { + for (int i = length - 1; i >= 0; i--) + if (buffer[i] == ch) + return i; + return -1; + } + + bool StartsWith(const char * str) const // String str + { + if (!buffer) + return false; + int strLen = (int)strlen(str); + if (strLen > length) + return false; + for (int i = 0; i < strLen; i++) + if (str[i] != buffer[i]) + return false; + return true; + } + + bool StartsWith(const String & str) const + { + return StartsWith(str.buffer.Ptr()); + } + + bool EndsWith(char * str) const // String str + { + if (!buffer) + return false; + int strLen = (int)strlen(str); + if (strLen > length) + return false; + for (int i = strLen - 1; i >= 0; i--) + if (str[i] != buffer[length - strLen + i]) + return false; + return true; + } + + bool EndsWith(const String & str) const + { + return EndsWith(str.buffer.Ptr()); + } + + bool Contains(const char * str) const // String str + { + if (!buffer) + return false; + return (IndexOf(str) >= 0) ? true : false; + } + + bool Contains(const String & str) const + { + return Contains(str.buffer.Ptr()); + } + + int GetHashCode() const + { + return CoreLib::Basic::GetHashCode((const char*)buffer.Ptr()); + } + String PadLeft(char ch, int length); + String PadRight(char ch, int length); + String ReplaceAll(String src, String dst) const; + }; + + class StringBuilder + { + private: + char * buffer; + int length; + int bufferSize; + static const int InitialSize = 512; + public: + StringBuilder(int bufferSize = 1024) + :buffer(0), length(0), bufferSize(0) + { + buffer = new char[InitialSize]; // new a larger buffer + buffer[0] = '\0'; + length = 0; + bufferSize = InitialSize; + } + ~StringBuilder() + { + if (buffer) + delete[] buffer; + } + void EnsureCapacity(int size) + { + if (bufferSize < size) + { + char * newBuffer = new char[size + 1]; + if (buffer) + { + strcpy_s(newBuffer, size + 1, buffer); + delete[] buffer; + } + buffer = newBuffer; + bufferSize = size; + } + } + StringBuilder & operator << (char ch) + { + Append(&ch, 1); + return *this; + } + StringBuilder & operator << (int val) + { + Append(val); + return *this; + } + StringBuilder & operator << (unsigned int val) + { + Append(val); + return *this; + } + StringBuilder & operator << (long long val) + { + Append(val); + return *this; + } + StringBuilder & operator << (float val) + { + Append(val); + return *this; + } + StringBuilder & operator << (double val) + { + Append(val); + return *this; + } + StringBuilder & operator << (const char * str) + { + Append(str, (int)strlen(str)); + return *this; + } + StringBuilder & operator << (const String & str) + { + Append(str); + return *this; + } + StringBuilder & operator << (const _EndLine) + { + Append('\n'); + return *this; + } + void Append(char ch) + { + Append(&ch, 1); + } + void Append(float val) + { + char buf[128]; + sprintf_s(buf, 128, "%g", val); + int len = (int)strnlen_s(buf, 128); + Append(buf, len); + } + void Append(double val) + { + char buf[128]; + sprintf_s(buf, 128, "%g", val); + int len = (int)strnlen_s(buf, 128); + Append(buf, len); + } + void Append(unsigned int value, int radix = 10) + { + char vBuffer[33]; + int len = IntToAscii(vBuffer, value, radix); + ReverseInternalAscii(vBuffer, len); + Append(vBuffer); + } + void Append(int value, int radix = 10) + { + char vBuffer[33]; + int len = IntToAscii(vBuffer, value, radix); + ReverseInternalAscii(vBuffer, len); + Append(vBuffer); + } + void Append(long long value, int radix = 10) + { + char vBuffer[65]; + int len = IntToAscii(vBuffer, value, radix); + ReverseInternalAscii(vBuffer, len); + Append(vBuffer); + } + void Append(const String & str) + { + Append(str.Buffer(), str.Length()); + } + void Append(const char * str) + { + Append(str, (int)strlen(str)); + } + void Append(const char * str, int strLen) + { + int newLength = length + strLen; + if (bufferSize < newLength + 1) + { + int newBufferSize = InitialSize; + while (newBufferSize < newLength + 1) + newBufferSize <<= 1; + char * newBuffer = new char[newBufferSize]; + if (buffer) + { + memcpy(newBuffer, buffer, length); + delete[] buffer; + } + memcpy(newBuffer + length, str, strLen); + newBuffer[newLength] = '\0'; + buffer = newBuffer; + bufferSize = newBufferSize; + } + else + { + memcpy(buffer + length, str, strLen); + buffer[newLength] = '\0'; + } + length = newLength; + } + + int Capacity() + { + return bufferSize; + } + + char * Buffer() + { + return buffer; + } + + int Length() + { + return length; + } + + String ToString() + { + return String(buffer); + } + + String ProduceString() + { + String rs; + rs.buffer = buffer; + rs.length = length; + buffer = 0; + bufferSize = 0; + length = 0; + return rs; + + } + + String GetSubString(int start, int count) + { + String rs; + rs.buffer = new char[count + 1]; + rs.length = count; + strncpy_s(rs.buffer.Ptr(), count + 1, buffer + start, count); + rs.buffer[count] = 0; + return rs; + } + + void Remove(int id, int len) + { +#if _DEBUG + if (id >= length || id < 0) + throw "Remove: Index out of range."; + if (len < 0) + throw "Remove: remove length smaller than zero."; +#endif + int actualDelLength = ((id + len) >= length) ? (length - id) : len; + for (int i = id + actualDelLength; i <= length; i++) + buffer[i - actualDelLength] = buffer[i]; + length -= actualDelLength; + } + + void Clear() + { + length = 0; + if (buffer) + buffer[0] = 0; + } + }; + + int StringToInt(const String & str, int radix = 10); + unsigned int StringToUInt(const String & str, int radix = 10); + double StringToDouble(const String & str); + float StringToFloat(const String & str); + } +} + +#endif diff --git a/source/core/smart-pointer.h b/source/core/smart-pointer.h new file mode 100644 index 000000000..f1fece2e5 --- /dev/null +++ b/source/core/smart-pointer.h @@ -0,0 +1,468 @@ +#ifndef FUNDAMENTAL_LIB_SMART_POINTER_H +#define FUNDAMENTAL_LIB_SMART_POINTER_H + +#include "type-traits.h" + +namespace CoreLib +{ + namespace Basic + { + class RefPtrDefaultDestructor + { + public: + template + void operator ()(T * ptr) + { + delete ptr; + } + }; + + class RefPtrArrayDestructor + { + public: + template + void operator() (T * ptr) + { + delete [] ptr; + } + }; + + class ReferenceCounted + { + template + friend class RefPtrImpl; + private: + int _refCount = 0; + public: + ReferenceCounted() {} + ReferenceCounted(const ReferenceCounted &) + { + _refCount = 0; + } + }; + + + class RefObject : public ReferenceCounted + { + public: + virtual ~RefObject() + {} + }; + + template + class RefPtrImpl + { + }; + + template + using RefPtr = RefPtrImpl::Value, Destructor>; + + template + class RefPtrImpl + { + template + friend class RefPtrImpl; + private: + T * pointer; + int * refCount; + + public: + RefPtrImpl() + { + pointer = 0; + refCount = 0; + } + RefPtrImpl(T * ptr) + : pointer(0), refCount(0) + { + this->operator=(ptr); + } + RefPtrImpl(const RefPtrImpl & ptr) + : pointer(0), refCount(0) + { + this->operator=(ptr); + } + RefPtrImpl(RefPtrImpl && str) + : pointer(0), refCount(0) + { + this->operator=(static_cast &&>(str)); + } + + template + RefPtrImpl(const RefPtrImpl& ptr, + typename EnableIf::Value, void>::type * = 0) + : pointer(0), refCount(0) + { + pointer = ptr.pointer; + if (ptr) + { + refCount = ptr.refCount; + (*refCount)++; + } + else + refCount = 0; + } + + template + typename EnableIf::value, RefPtrImpl>::type& + operator=(const RefPtrImpl & ptr) + { + Unreference(); + + pointer = ptr; + if (ptr) + { + refCount = ptr.refCount; + (*refCount)++; + } + else + refCount = 0; + return *this; + } + + RefPtrImpl& operator=(const RefPtrImpl & ptr) + { + Unreference(); + pointer = ptr.pointer; + if (ptr) + { + refCount = ptr.refCount; + (*refCount)++; + } + else + refCount = 0; + return *this; + } + + RefPtrImpl& operator=(T * ptr) + { + if (ptr != pointer) + { + Unreference(); + + pointer = ptr; + if (ptr) + { + refCount = new int; + (*refCount) = 1; + } + else + refCount = 0; + } + return *this; + } + int GetHashCode() + { + return (int)(long long)(void*)pointer; + } + bool operator == (const T * ptr) const + { + return pointer == ptr; + } + bool operator != (const T * ptr) const + { + return pointer != ptr; + } + template + bool operator == (const RefPtr & ptr) const + { + return pointer == ptr.pointer; + } + template + bool operator != (const RefPtr & ptr) const + { + return pointer != ptr.pointer; + } + template + RefPtrImpl As() const + { + RefPtrImpl result; + if (pointer) + { + result.pointer = dynamic_cast(pointer); + if (result.pointer) + { + result.refCount = refCount; + (*refCount)++; + } + } + return result; + } + + T* operator +(int offset) const + { + return pointer+offset; + } + T& operator [](int idx) const + { + return *(pointer + idx); + } + RefPtrImpl& operator=(RefPtrImpl && ptr) + { + if(ptr.pointer != pointer) + { + Unreference(); + pointer = ptr.pointer; + refCount = ptr.refCount; + ptr.pointer = 0; + ptr.refCount = 0; + } + return *this; + } + T* Release() + { + if(pointer) + { + if((*refCount) > 1) + { + (*refCount)--; + } + else + { + delete refCount; + } + } + auto rs = pointer; + refCount = 0; + pointer = 0; + return rs; + } + ~RefPtrImpl() + { + Unreference(); + } + + void Unreference() + { + if(pointer) + { + if((*refCount) > 1) + { + (*refCount)--; + } + else + { + Destructor destructor; + destructor(pointer); + delete refCount; + } + } + } + T & operator *() const + { + return *pointer; + } + T * operator->() const + { + return pointer; + } + T * Ptr() const + { + return pointer; + } + public: + explicit operator bool() const + { + if (pointer) + return true; + else + return false; + } + }; + + + template + class RefPtrImpl + { + template + friend class RefPtrImpl; + + private: + T * pointer; + public: + RefPtrImpl() + { + pointer = 0; + } + RefPtrImpl(T * ptr) + : pointer(0) + { + this->operator=(ptr); + } + RefPtrImpl(const RefPtrImpl & ptr) + : pointer(0) + { + this->operator=(ptr); + } + RefPtrImpl(RefPtrImpl && str) + : pointer(0) + { + this->operator=(static_cast &&>(str)); + } + template + RefPtrImpl(const RefPtrImpl& ptr, + typename EnableIf::Value, void>::type * = 0) + : pointer(0) + { + pointer = ptr.pointer; + if (ptr) + { + ptr->_refCount++; + } + } + + template + typename EnableIf::value, RefPtrImpl&>::type + operator=(const RefPtrImpl & ptr) + { + Unreference(); + + pointer = ptr.pointer; + if (ptr) + { + ptr->_refCount++; + } + return *this; + } + RefPtrImpl& operator=(T * ptr) + { + if (ptr != pointer) + { + Unreference(); + + pointer = ptr; + if (ptr) + { + ptr->_refCount++; + } + } + return *this; + } + RefPtrImpl& operator=(const RefPtrImpl & ptr) + { + // Note: It is possible that the object this pointer references owns + // (directly or indirectly) the storage for the argument `ptr`. If + // that is the case and the `Unreference()` call below frees this + // object, then the argument would become invalid. + // + // We copy the pointer value out of the argument first, in order + // to protected against this case. + T* ptrPointer = ptr.pointer; + if (ptrPointer != pointer) + { + if (ptrPointer) + ptrPointer->_refCount++; + Unreference(); + pointer = ptrPointer; + } + return *this; + } + int GetHashCode() + { + return (int)(long long)(void*)pointer; + } + bool operator == (const T * ptr) const + { + return pointer == ptr; + } + bool operator != (const T * ptr) const + { + return pointer != ptr; + } + template + bool operator == (const RefPtr & ptr) const + { + return pointer == ptr.pointer; + } + template + bool operator != (const RefPtr & ptr) const + { + return pointer != ptr.pointer; + } + template + RefPtrImpl As() const + { + RefPtrImpl result; + if (pointer) + { + result.pointer = dynamic_cast(pointer); + if (result.pointer) + { + result.pointer->_refCount++; + } + } + return result; + } + T* operator +(int offset) const + { + return pointer + offset; + } + T& operator [](int idx) const + { + return *(pointer + idx); + } + RefPtrImpl& operator=(RefPtrImpl && ptr) + { + if (ptr.pointer != pointer) + { + Unreference(); + pointer = ptr.pointer; + ptr.pointer = nullptr; + } + return *this; + } + T* Release() + { + if (pointer) + { + pointer->_refCount--; + } + auto rs = pointer; + pointer = 0; + return rs; + } + ~RefPtrImpl() + { + Unreference(); + } + + void Unreference() + { + if (pointer) + { + if (pointer->_refCount > 1) + { + pointer->_refCount--; + } + else + { + Destructor destructor; + destructor(pointer); + } + } + } + T & operator *() const + { + return *pointer; + } + T * operator->() const + { + return pointer; + } + T * Ptr() const + { + return pointer; + } + public: + explicit operator bool() const + { + if (pointer) + return true; + else + return false; + } + }; + } +} + +#endif \ No newline at end of file diff --git a/source/core/stream.cpp b/source/core/stream.cpp new file mode 100644 index 000000000..580ea5884 --- /dev/null +++ b/source/core/stream.cpp @@ -0,0 +1,220 @@ +#include "Stream.h" +#ifdef _WIN32 +#include +#endif +#include "slang-io.h" + +namespace CoreLib +{ + namespace IO + { + using namespace CoreLib::Basic; + FileStream::FileStream(const CoreLib::Basic::String & fileName, FileMode fileMode) + { + Init(fileName, fileMode, fileMode==FileMode::Open?FileAccess::Read:FileAccess::Write, FileShare::None); + } + FileStream::FileStream(const CoreLib::Basic::String & fileName, FileMode fileMode, FileAccess access, FileShare share) + { + Init(fileName, fileMode, access, share); + } + void FileStream::Init(const CoreLib::Basic::String & fileName, FileMode fileMode, FileAccess access, FileShare share) + { + const wchar_t * mode = L"rt"; + const char* modeMBCS = "rt"; + switch (fileMode) + { + case CoreLib::IO::FileMode::Create: + if (access == FileAccess::Read) + throw ArgumentException("Read-only access is incompatible with Create mode."); + else if (access == FileAccess::ReadWrite) + { + mode = L"w+b"; + modeMBCS = "w+b"; + this->fileAccess = FileAccess::ReadWrite; + } + else + { + mode = L"wb"; + modeMBCS = "wb"; + this->fileAccess = FileAccess::Write; + } + break; + case CoreLib::IO::FileMode::Open: + if (access == FileAccess::Read) + { + mode = L"rb"; + modeMBCS = "rb"; + this->fileAccess = FileAccess::Read; + } + else if (access == FileAccess::ReadWrite) + { + mode = L"r+b"; + modeMBCS = "r+b"; + this->fileAccess = FileAccess::ReadWrite; + } + else + { + mode = L"wb"; + modeMBCS = "wb"; + this->fileAccess = FileAccess::Write; + } + break; + case CoreLib::IO::FileMode::CreateNew: + if (File::Exists(fileName)) + { + throw IOException("Failed opening '" + fileName + "', file already exists."); + } + if (access == FileAccess::Read) + throw ArgumentException("Read-only access is incompatible with Create mode."); + else if (access == FileAccess::ReadWrite) + { + mode = L"w+b"; + this->fileAccess = FileAccess::ReadWrite; + } + else + { + mode = L"wb"; + this->fileAccess = FileAccess::Write; + } + break; + case CoreLib::IO::FileMode::Append: + if (access == FileAccess::Read) + throw ArgumentException("Read-only access is incompatible with Append mode."); + else if (access == FileAccess::ReadWrite) + { + mode = L"a+b"; + this->fileAccess = FileAccess::ReadWrite; + } + else + { + mode = L"ab"; + this->fileAccess = FileAccess::Write; + } + break; + default: + break; + } + int shFlag; +#ifdef _WIN32 + switch (share) + { + case CoreLib::IO::FileShare::None: + shFlag = _SH_DENYRW; + break; + case CoreLib::IO::FileShare::ReadOnly: + shFlag = _SH_DENYWR; + break; + case CoreLib::IO::FileShare::WriteOnly: + shFlag = _SH_DENYRD; + break; + case CoreLib::IO::FileShare::ReadWrite: + shFlag = _SH_DENYNO; + break; + default: + throw ArgumentException("Invalid file share mode."); + break; + } + if (share == CoreLib::IO::FileShare::None) +#pragma warning(suppress:4996) + handle = _wfopen(fileName.ToWString(), mode); + else + handle = _wfsopen(fileName.ToWString(), mode, shFlag); +#else + handle = fopen(fileName.Buffer(), modeMBCS); +#endif + if (!handle) + { + throw IOException("Cannot open file '" + fileName + "'"); + } + } + FileStream::~FileStream() + { + Close(); + } + Int64 FileStream::GetPosition() + { +#ifdef _WIN32 + fpos_t pos; + fgetpos(handle, &pos); + return pos; +#else + fpos64_t pos; + fgetpos64(handle, &pos); + return *(Int64*)(&pos); +#endif + } + void FileStream::Seek(SeekOrigin origin, Int64 offset) + { + int _origin; + switch (origin) + { + case CoreLib::IO::SeekOrigin::Start: + _origin = SEEK_SET; + endReached = false; + break; + case CoreLib::IO::SeekOrigin::End: + _origin = SEEK_END; + endReached = true; + break; + case CoreLib::IO::SeekOrigin::Current: + _origin = SEEK_CUR; + endReached = false; + break; + default: + throw NotSupportedException("Unsupported seek origin."); + break; + } +#ifdef _WIN32 + int rs = _fseeki64(handle, offset, _origin); +#else + int rs = fseek(handle, (int)offset, _origin); +#endif + if (rs != 0) + { + throw IOException("FileStream seek failed."); + } + } + Int64 FileStream::Read(void * buffer, Int64 length) + { + auto bytes = fread_s(buffer, (size_t)length, 1, (size_t)length, handle); + if (bytes == 0 && length > 0) + { + if (!feof(handle)) + throw IOException("FileStream read failed."); + else if (endReached) + throw EndOfStreamException("End of file is reached."); + endReached = true; + } + return (int)bytes; + } + Int64 FileStream::Write(const void * buffer, Int64 length) + { + auto bytes = (Int64)fwrite(buffer, 1, (size_t)length, handle); + if (bytes < length) + { + throw IOException("FileStream write failed."); + } + return bytes; + } + bool FileStream::CanRead() + { + return ((int)fileAccess & (int)FileAccess::Read) != 0; + } + bool FileStream::CanWrite() + { + return ((int)fileAccess & (int)FileAccess::Write) != 0; + } + void FileStream::Close() + { + if (handle) + { + fclose(handle); + handle = 0; + } + } + bool FileStream::IsEnd() + { + return endReached; + } + } +} diff --git a/source/core/stream.h b/source/core/stream.h new file mode 100644 index 000000000..30d1cc992 --- /dev/null +++ b/source/core/stream.h @@ -0,0 +1,333 @@ +#ifndef CORE_LIB_STREAM_H +#define CORE_LIB_STREAM_H + +#include "Basic.h" + +namespace CoreLib +{ + namespace IO + { + using CoreLib::Basic::Exception; + using CoreLib::Basic::String; + using CoreLib::Basic::RefPtr; + + class IOException : public Exception + { + public: + IOException() + {} + IOException(const String & message) + : CoreLib::Basic::Exception(message) + { + } + }; + + class EndOfStreamException : public IOException + { + public: + EndOfStreamException() + {} + EndOfStreamException(const String & message) + : IOException(message) + { + } + }; + + enum class SeekOrigin + { + Start, End, Current + }; + + class Stream : public CoreLib::Basic::Object + { + public: + virtual Int64 GetPosition()=0; + virtual void Seek(SeekOrigin origin, Int64 offset)=0; + virtual Int64 Read(void * buffer, Int64 length) = 0; + virtual Int64 Write(const void * buffer, Int64 length) = 0; + virtual bool IsEnd() = 0; + virtual bool CanRead() = 0; + virtual bool CanWrite() = 0; + virtual void Close() = 0; + }; + + class BinaryReader + { + private: + RefPtr stream; + inline void Throw(Int64 val) + { + if (val == 0) + throw IOException("read operation failed."); + } + public: + BinaryReader(RefPtr stream) + { + this->stream = stream; + } + Stream * GetStream() + { + return stream.Ptr(); + } + void ReleaseStream() + { + stream.Release(); + } + template + void Read(T * buffer, int count) + { + stream->Read(buffer, sizeof(T)*(Int64)count); + } + template + void Read(T & buffer) + { + Throw(stream->Read(&buffer, sizeof(T))); + } + template + void Read(List & buffer) + { + int count = ReadInt32(); + buffer.SetSize(count); + Read(buffer.Buffer(), count); + } + void Read(String & buffer) + { + buffer = ReadString(); + } + int ReadInt32() + { + int rs; + Throw(stream->Read(&rs, sizeof(int))); + return rs; + } + short ReadInt16() + { + short rs; + Throw(stream->Read(&rs, sizeof(short))); + return rs; + } + Int64 ReadInt64() + { + Int64 rs; + Throw(stream->Read(&rs, sizeof(Int64))); + return rs; + } + float ReadFloat() + { + float rs; + Throw(stream->Read(&rs, sizeof(float))); + return rs; + } + double ReadDouble() + { + double rs; + Throw(stream->Read(&rs, sizeof(double))); + return rs; + } + char ReadChar() + { + char rs; + Throw(stream->Read(&rs, sizeof(char))); + return rs; + } + String ReadString() + { + int len = ReadInt32(); + char * buffer = new char[len+1]; + try + { + Throw(stream->Read(buffer, len)); + } + catch(IOException & e) + { + delete [] buffer; + throw e; + } + buffer[len] = 0; + return String::FromBuffer(buffer, len); + } + }; + + class BinaryWriter + { + private: + RefPtr stream; + public: + BinaryWriter(RefPtr stream) + { + this->stream = stream; + } + Stream * GetStream() + { + return stream.Ptr(); + } + template + void Write(const T& val) + { + stream->Write(&val, sizeof(T)); + } + template + void Write(T * buffer, int count) + { + stream->Write(buffer, sizeof(T)*(Int64)count); + } + template + void Write(const List & list) + { + Write(list.Count()); + stream->Write(list.Buffer(), sizeof(T)*list.Count()); + } + void Write(const String & str) + { + Write(str.Length()); + Write(str.Buffer(), str.Length()); + } + void ReleaseStream() + { + stream.Release(); + } + void Close() + { + stream->Close(); + } + }; + + enum class FileMode + { + Create, Open, CreateNew, Append + }; + + enum class FileAccess + { + Read = 1, Write = 2, ReadWrite = 3 + }; + + enum class FileShare + { + None, ReadOnly, WriteOnly, ReadWrite + }; + + class FileStream : public Stream + { + private: + FILE * handle; + FileAccess fileAccess; + bool endReached = false; + void Init(const CoreLib::Basic::String & fileName, FileMode fileMode, FileAccess access, FileShare share); + public: + FileStream(const CoreLib::Basic::String & fileName, FileMode fileMode = FileMode::Open); + FileStream(const CoreLib::Basic::String & fileName, FileMode fileMode, FileAccess access, FileShare share); + ~FileStream(); + public: + virtual Int64 GetPosition(); + virtual void Seek(SeekOrigin origin, Int64 offset); + virtual Int64 Read(void * buffer, Int64 length); + virtual Int64 Write(const void * buffer, Int64 length); + virtual bool CanRead(); + virtual bool CanWrite(); + virtual void Close(); + virtual bool IsEnd(); + }; + + class MemoryStream : public Stream + { + private: + CoreLib::List writeBuffer; + CoreLib::ArrayView readBuffer; + int ptr = 0; + bool isReadStream; + public: + MemoryStream() + { + isReadStream = false; + } + MemoryStream(unsigned char * mem, int length) + { + isReadStream = true; + readBuffer = MakeArrayView(mem, length); + } + MemoryStream(CoreLib::ArrayView source) + { + isReadStream = true; + readBuffer = source; + } + virtual Int64 GetPosition() + { + return ptr; + } + virtual void Seek(SeekOrigin origin, Int64 offset) + { + if (origin == SeekOrigin::Start) + ptr = (int)offset; + else if (origin == SeekOrigin::End) + { + if (isReadStream) + ptr = readBuffer.Count() + (int)offset; + else + ptr = writeBuffer.Count() + (int)offset; + } + } + virtual Int64 Read(void * pbuffer, Int64 length) + { + Int64 i; + for (i = 0; i < length; i++) + { + if (ptr + i < readBuffer.Count()) + { + ((unsigned char*)pbuffer)[i] = readBuffer[(int)(ptr + i)]; + } + else + break; + } + return i; + } + virtual Int64 Write(const void * pbuffer, Int64 length) + { + writeBuffer.SetSize(ptr); + if (pbuffer) + writeBuffer.AddRange((unsigned char *)pbuffer, (int)length); + else + for (auto i = 0; i < length; i++) + writeBuffer.Add(0); + ptr = writeBuffer.Count(); + return length; + } + virtual bool CanRead() + { + return isReadStream; + } + virtual bool CanWrite() + { + return !isReadStream; + } + virtual void Close() + { + writeBuffer.SetSize(0); + writeBuffer.Compress(); + } + virtual bool IsEnd() + { + if (isReadStream) + return ptr >= readBuffer.Count(); + else + return ptr == writeBuffer.Count(); + } + void * GetBuffer() + { + if (isReadStream) + return readBuffer.Buffer(); + else + return writeBuffer.Buffer(); + } + int GetBufferSize() + { + if (isReadStream) + return readBuffer.Count(); + else + return writeBuffer.Count(); + } + }; + } +} + +#endif diff --git a/source/core/text-io.cpp b/source/core/text-io.cpp new file mode 100644 index 000000000..cf75c4762 --- /dev/null +++ b/source/core/text-io.cpp @@ -0,0 +1,344 @@ +#include "text-io.h" +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#undef WIN32_LEAN_AND_MEAN +#undef NOMINMAX +#define CONVERT_END_OF_LINE +#endif + +namespace CoreLib +{ + namespace IO + { + using namespace CoreLib::Basic; + + class Utf8Encoding : public Encoding + { + public: + virtual void GetBytes(List & result, const String & str) override + { + result.AddRange(str.Buffer(), str.Length()); + } + virtual String ToString(const char * bytes, int /*length*/) override + { + return String(bytes); + } + }; + + class Utf32Encoding : public Encoding + { + public: + virtual void GetBytes(List & result, const String & str) override + { + int ptr = 0; + while (ptr < str.Length()) + { + int codePoint = GetUnicodePointFromUTF8([&](int) + { + if (ptr < str.Length()) + return str[ptr++]; + else + return '\0'; + }); + result.AddRange((char*)&codePoint, 4); + } + } + virtual String ToString(const char * bytes, int length) override + { + StringBuilder sb; + int * content = (int*)bytes; + for (int i = 0; i < (length >> 2); i++) + { + char buf[5]; + int count = EncodeUnicodePointToUTF8(buf, content[i]); + for (int j = 0; j < count; j++) + sb.Append(buf[j]); + } + return sb.ProduceString(); + } + }; + + class Utf16Encoding : public Encoding //UTF16 + { + private: + bool reverseOrder = false; + public: + Utf16Encoding(bool pReverseOrder) + : reverseOrder(pReverseOrder) + {} + virtual void GetBytes(List & result, const String & str) override + { + int ptr = 0; + while (ptr < str.Length()) + { + int codePoint = GetUnicodePointFromUTF8([&](int) + { + if (ptr < str.Length()) + return str[ptr++]; + else + return '\0'; + }); + unsigned short buffer[2]; + int count; + if (!reverseOrder) + count = EncodeUnicodePointToUTF16(buffer, codePoint); + else + count = EncodeUnicodePointToUTF16Reversed(buffer, codePoint); + result.AddRange((char*)buffer, count * 2); + } + } + virtual String ToString(const char * bytes, int length) override + { + int ptr = 0; + StringBuilder sb; + while (ptr < length) + { + int codePoint = GetUnicodePointFromUTF16([&](int) + { + if (ptr < length) + return bytes[ptr++]; + else + return '\0'; + }); + char buf[5]; + int count = EncodeUnicodePointToUTF8(buf, codePoint); + for (int i = 0; i < count; i++) + sb.Append(buf[i]); + } + return sb.ProduceString(); + } + }; + + Utf8Encoding __utf8Encoding; + Utf16Encoding __utf16Encoding(false); + Utf16Encoding __utf16EncodingReversed(true); + Utf32Encoding __utf32Encoding; + + Encoding * Encoding::UTF8 = &__utf8Encoding; + Encoding * Encoding::UTF16 = &__utf16Encoding; + Encoding * Encoding::UTF16Reversed = &__utf16EncodingReversed; + Encoding * Encoding::UTF32 = &__utf32Encoding; + + const unsigned short Utf16Header = 0xFEFF; + const unsigned short Utf16ReversedHeader = 0xFFFE; + + StreamWriter::StreamWriter(const String & path, Encoding * encoding) + { + this->stream = new FileStream(path, FileMode::Create); + this->encoding = encoding; + if (encoding == Encoding::UTF16) + { + this->stream->Write(&Utf16Header, 2); + } + else if (encoding == Encoding::UTF16Reversed) + { + this->stream->Write(&Utf16ReversedHeader, 2); + } + } + StreamWriter::StreamWriter(RefPtr stream, Encoding * encoding) + { + this->stream = stream; + this->encoding = encoding; + if (encoding == Encoding::UTF16) + { + this->stream->Write(&Utf16Header, 2); + } + else if (encoding == Encoding::UTF16Reversed) + { + this->stream->Write(&Utf16ReversedHeader, 2); + } + } + void StreamWriter::Write(const String & str) + { + encodingBuffer.Clear(); + StringBuilder sb; + String newLine; +#ifdef _WIN32 + newLine = "\r\n"; +#else + newLine = "\n"; +#endif + for (int i = 0; i < str.Length(); i++) + { + if (str[i] == '\r') + sb << newLine; + else if (str[i] == '\n') + { + if (i > 0 && str[i - 1] != '\r') + sb << newLine; + } + else + sb << str[i]; + } + encoding->GetBytes(encodingBuffer, sb.ProduceString()); + stream->Write(encodingBuffer.Buffer(), encodingBuffer.Count()); + } + void StreamWriter::Write(const char * str) + { + Write(String(str)); + } + + StreamReader::StreamReader(const String & path) + { + stream = new FileStream(path, FileMode::Open); + ReadBuffer(); + encoding = DetermineEncoding(); + if (encoding == 0) + encoding = Encoding::UTF8; + } + StreamReader::StreamReader(RefPtr stream, Encoding * encoding) + { + this->stream = stream; + this->encoding = encoding; + ReadBuffer(); + auto determinedEncoding = DetermineEncoding(); + if (this->encoding == nullptr) + this->encoding = determinedEncoding; + } + + Encoding * StreamReader::DetermineEncoding() + { + if (buffer.Count() >= 3 && (unsigned char)(buffer[0]) == 0xEF && (unsigned char)(buffer[1]) == 0xBB && (unsigned char)(buffer[2]) == 0xBF) + { + ptr += 3; + return Encoding::UTF8; + } + else if (*((unsigned short*)(buffer.Buffer())) == 0xFEFF) + { + ptr += 2; + return Encoding::UTF16; + } + else if (*((unsigned short*)(buffer.Buffer())) == 0xFFFE) + { + ptr += 2; + return Encoding::UTF16Reversed; + } + else + { +#ifdef _WIN32 + int flag = IS_TEXT_UNICODE_SIGNATURE | IS_TEXT_UNICODE_REVERSE_SIGNATURE | IS_TEXT_UNICODE_STATISTICS | IS_TEXT_UNICODE_ASCII16; + int rs = IsTextUnicode(buffer.Buffer(), buffer.Count(), &flag); + if (rs) + { + if (flag & (IS_TEXT_UNICODE_SIGNATURE | IS_TEXT_UNICODE_STATISTICS)) + return Encoding::UTF16; + else if (flag & (IS_TEXT_UNICODE_SIGNATURE | IS_TEXT_UNICODE_STATISTICS)) + return Encoding::UTF16Reversed; + else if (flag & IS_TEXT_UNICODE_ASCII16) + return Encoding::UTF8; + } +#endif + return Encoding::UTF8; + } + } + + void StreamReader::ReadBuffer() + { + buffer.SetSize(4096); + auto len = stream->Read(buffer.Buffer(), buffer.Count()); + buffer.SetSize((int)len); + ptr = 0; + } + + char StreamReader::ReadBufferChar() + { + if (ptrIsEnd()) + ReadBuffer(); + if (ptr + TextWriter & operator << (const T& val) + { + Write(val.ToString()); + return *this; + } + TextWriter & operator << (int value) + { + Write(String(value)); + return *this; + } + TextWriter & operator << (float value) + { + Write(String(value)); + return *this; + } + TextWriter & operator << (double value) + { + Write(String(value)); + return *this; + } + TextWriter & operator << (const char* value) + { + Write(value); + return *this; + } + TextWriter & operator << (const String & val) + { + Write(val); + return *this; + } + TextWriter & operator << (const _EndLine &) + { +#ifdef _WIN32 + Write("\r\n"); +#else + Write("\n"); +#endif + return *this; + } + }; + + template + int GetUnicodePointFromUTF8(const ReadCharFunc & get) + { + int codePoint = 0; + int leading = get(0); + int mask = 0x80; + int count = 0; + while (leading & mask) + { + count++; + mask >>= 1; + } + codePoint = (leading & (mask - 1)); + for (int i = 1; i <= count - 1; i++) + { + codePoint <<= 6; + codePoint += (get(i) & 0x3F); + } + return codePoint; + } + + template + int GetUnicodePointFromUTF16(const ReadCharFunc & get) + { + int byte0 = (unsigned char)get(0); + int byte1 = (unsigned char)get(1); + int word0 = byte0 + (byte1 << 8); + if (word0 >= 0xD800 && word0 <= 0xDFFF) + { + int byte2 = (unsigned char)get(2); + int byte3 = (unsigned char)get(3); + int word1 = byte2 + (byte3 << 8); + return ((word0 & 0x3FF) << 10) + (word1 & 0x3FF) + 0x10000; + } + else + return word0; + } + + template + int GetUnicodePointFromUTF16Reversed(const ReadCharFunc & get) + { + int byte0 = (unsigned char)get(0); + int byte1 = (unsigned char)get(1); + int word0 = (byte0 << 8) + byte1; + if (word0 >= 0xD800 && word0 <= 0xDFFF) + { + int byte2 = (unsigned char)get(2); + int byte3 = (unsigned char)get(3); + int word1 = (byte2 << 8) + byte3; + return ((word0 & 0x3FF) << 10) + (word1 & 0x3FF); + } + else + return word0; + } + + template + int GetUnicodePointFromUTF32(const ReadCharFunc & get) + { + int byte0 = (unsigned char)get(0); + int byte1 = (unsigned char)get(1); + int byte2 = (unsigned char)get(2); + int byte3 = (unsigned char)get(3); + return byte0 + (byte1 << 8) + (byte2 << 16) + (byte3 << 24); + } + + inline int EncodeUnicodePointToUTF8(char * buffer, int codePoint) + { + int count = 0; + if (codePoint <= 0x7F) + buffer[count++] = ((char)codePoint); + else if (codePoint <= 0x7FF) + { + unsigned char byte = (unsigned char)(0xC0 + (codePoint >> 6)); + buffer[count++] = ((char)byte); + byte = 0x80 + (codePoint & 0x3F); + buffer[count++] = ((char)byte); + } + else if (codePoint <= 0xFFFF) + { + unsigned char byte = (unsigned char)(0xE0 + (codePoint >> 12)); + buffer[count++] = ((char)byte); + byte = (unsigned char)(0x80 + ((codePoint >> 6) & (0x3F))); + buffer[count++] = ((char)byte); + byte = (unsigned char)(0x80 + (codePoint & 0x3F)); + buffer[count++] = ((char)byte); + } + else + { + unsigned char byte = (unsigned char)(0xF0 + (codePoint >> 18)); + buffer[count++] = ((char)byte); + byte = (unsigned char)(0x80 + ((codePoint >> 12) & 0x3F)); + buffer[count++] = ((char)byte); + byte = (unsigned char)(0x80 + ((codePoint >> 6) & 0x3F)); + buffer[count++] = ((char)byte); + byte = (unsigned char)(0x80 + (codePoint & 0x3F)); + buffer[count++] = ((char)byte); + } + return count; + } + + inline int EncodeUnicodePointToUTF16(unsigned short * buffer, int codePoint) + { + int count = 0; + if (codePoint <= 0xD7FF || (codePoint >= 0xE000 && codePoint <= 0xFFFF)) + buffer[count++] = (unsigned short)codePoint; + else + { + int sub = codePoint - 0x10000; + int high = (sub >> 10) + 0xD800; + int low = (sub & 0x3FF) + 0xDC00; + buffer[count++] = (unsigned short)high; + buffer[count++] = (unsigned short)low; + } + return count; + } + + inline unsigned short ReverseBitOrder(unsigned short val) + { + int byte0 = val & 0xFF; + int byte1 = val >> 8; + return (unsigned short)(byte1 + (byte0 << 8)); + } + + inline int EncodeUnicodePointToUTF16Reversed(unsigned short * buffer, int codePoint) + { + int count = 0; + if (codePoint <= 0xD7FF || (codePoint >= 0xE000 && codePoint <= 0xFFFF)) + buffer[count++] = ReverseBitOrder((unsigned short)codePoint); + else + { + int sub = codePoint - 0x10000; + int high = (sub >> 10) + 0xD800; + int low = (sub & 0x3FF) + 0xDC00; + buffer[count++] = ReverseBitOrder((unsigned short)high); + buffer[count++] = ReverseBitOrder((unsigned short)low); + } + return count; + } + + class Encoding + { + public: + static Encoding * UTF8, * UTF16, *UTF16Reversed, * UTF32; + virtual void GetBytes(List& buffer, const String & str) = 0; + virtual String ToString(const char * buffer, int length) = 0; + virtual ~Encoding() + {} + }; + + class StreamWriter : public TextWriter + { + private: + List encodingBuffer; + RefPtr stream; + Encoding * encoding; + public: + StreamWriter(const String & path, Encoding * encoding = Encoding::UTF8); + StreamWriter(RefPtr stream, Encoding * encoding = Encoding::UTF8); + virtual void Write(const String & str); + virtual void Write(const char * str); + virtual void Close() + { + stream->Close(); + } + void ReleaseStream() + { + stream.Release(); + } + }; + + class StreamReader : public TextReader + { + private: + RefPtr stream; + List buffer; + Encoding * encoding; + int ptr; + char ReadBufferChar(); + void ReadBuffer(); + + Encoding * DetermineEncoding(); + protected: + virtual void ReadChar() + { + decodedCharPtr = 0; + int codePoint = 0; + if (encoding == Encoding::UTF8) + codePoint = GetUnicodePointFromUTF8([&](int) {return ReadBufferChar(); }); + else if (encoding == Encoding::UTF16) + codePoint = GetUnicodePointFromUTF16([&](int) {return ReadBufferChar(); }); + else if (encoding == Encoding::UTF16Reversed) + codePoint = GetUnicodePointFromUTF16Reversed([&](int) {return ReadBufferChar(); }); + else if (encoding == Encoding::UTF32) + codePoint = GetUnicodePointFromUTF32([&](int) {return ReadBufferChar(); }); + decodedCharSize = EncodeUnicodePointToUTF8(decodedChar, codePoint); + } + public: + StreamReader(const String & path); + StreamReader(RefPtr stream, Encoding * encoding = nullptr); + virtual String ReadLine(); + virtual String ReadToEnd(); + virtual bool IsEnd() + { + return ptr == buffer.Count() && stream->IsEnd(); + } + virtual void Close() + { + stream->Close(); + } + void ReleaseStream() + { + stream.Release(); + } + }; + + } +} + +#endif diff --git a/source/core/type-traits.h b/source/core/type-traits.h new file mode 100644 index 000000000..5dd81965d --- /dev/null +++ b/source/core/type-traits.h @@ -0,0 +1,49 @@ +#ifndef CORELIB_TYPETRAITS_H +#define CORELIB_TYPETRAITS_H + +namespace CoreLib +{ + namespace Basic + { + struct TraitResultYes + { + char x; + }; + struct TraitResultNo + { + char x[2]; + }; + + template + struct IsBaseOfTraitHost + { + operator B*() const { return nullptr; } + operator D*() { return nullptr; } + }; + + template + struct IsBaseOf + { + template + static TraitResultYes Check(D*, T) { return TraitResultYes(); } + static TraitResultNo Check(B*, int) { return TraitResultNo(); } + enum { Value = sizeof(Check(IsBaseOfTraitHost(), int())) == sizeof(TraitResultYes) }; + }; + + template + struct EnableIf {}; + + template + struct EnableIf { typedef T type; }; + + template + struct IsConvertible + { + static TraitResultYes Use(B) {}; + static TraitResultNo Use(...) {}; + enum { Value = sizeof(Use(*(D*)(nullptr))) == sizeof(TraitResultYes) }; + }; + } +} + +#endif diff --git a/source/slang/check.cpp b/source/slang/check.cpp new file mode 100644 index 000000000..7d50c5978 --- /dev/null +++ b/source/slang/check.cpp @@ -0,0 +1,4973 @@ +#include "syntax-visitors.h" + +#include "lookup.h" +#include "compiler.h" + +#include + +namespace Slang +{ + namespace Compiler + { + bool IsNumeric(BaseType t) + { + return t == BaseType::Int || t == BaseType::Float || t == BaseType::UInt; + } + + String TranslateHLSLTypeNames(String name) + { + if (name == "float2" || name == "half2") + return "vec2"; + else if (name == "float3" || name == "half3") + return "vec3"; + else if (name == "float4" || name == "half4") + return "vec4"; + else if (name == "half") + return "float"; + else if (name == "int2") + return "ivec2"; + else if (name == "int3") + return "ivec3"; + else if (name == "int4") + return "ivec4"; + else if (name == "uint2") + return "uvec2"; + else if (name == "uint3") + return "uvec3"; + else if (name == "uint4") + return "uvec4"; + else if (name == "float3x3" || name == "half3x3") + return "mat3"; + else if (name == "float4x4" || name == "half4x4") + return "mat4"; + else + return name; + } + + class SemanticsVisitor : public SyntaxVisitor + { + ProgramSyntaxNode * program = nullptr; + FunctionSyntaxNode * function = nullptr; + CompileOptions const* options = nullptr; + + // lexical outer statements + List outerStmts; + public: + SemanticsVisitor( + DiagnosticSink * pErr, + CompileOptions const& options) + : SyntaxVisitor(pErr) + , options(&options) + { + } + + CompileOptions const& getOptions() { return *options; } + + public: + // Translate Types + RefPtr typeResult; + RefPtr TranslateTypeNodeImpl(const RefPtr & node) + { + if (!node) return nullptr; + auto expr = node->Accept(this).As(); + expr = ExpectATypeRepr(expr); + return expr; + } + RefPtr ExtractTypeFromTypeRepr(const RefPtr& typeRepr) + { + if (!typeRepr) return nullptr; + if (auto typeType = typeRepr->Type->As()) + { + return typeType->type; + } + return ExpressionType::Error; + } + RefPtr TranslateTypeNode(const RefPtr & node) + { + if (!node) return nullptr; + auto typeRepr = TranslateTypeNodeImpl(node); + return ExtractTypeFromTypeRepr(typeRepr); + } + TypeExp TranslateTypeNode(TypeExp const& typeExp) + { + // HACK(tfoley): It seems that in some cases we end up re-checking + // syntax that we've already checked. We need to root-cause that + // issue, but for now a quick fix in this case is to early + // exist if we've already got a type associated here: + if (typeExp.type) + { + return typeExp; + } + + + auto typeRepr = TranslateTypeNodeImpl(typeExp.exp); + + TypeExp result; + result.exp = typeRepr; + result.type = ExtractTypeFromTypeRepr(typeRepr); + return result; + } + + RefPtr ConstructDeclRefExpr( + DeclRef declRef, + RefPtr baseExpr, + RefPtr originalExpr) + { + if (baseExpr) + { + auto expr = new MemberExpressionSyntaxNode(); + expr->Position = originalExpr->Position; + expr->BaseExpression = baseExpr; + expr->MemberName = declRef.GetName(); + expr->Type = GetTypeForDeclRef(declRef); + expr->declRef = declRef; + return expr; + } + else + { + auto expr = new VarExpressionSyntaxNode(); + expr->Position = originalExpr->Position; + expr->Variable = declRef.GetName(); + expr->Type = GetTypeForDeclRef(declRef); + expr->declRef = declRef; + return expr; + } + } + + RefPtr ConstructDerefExpr( + RefPtr base, + RefPtr originalExpr) + { + auto ptrLikeType = base->Type->As(); + assert(ptrLikeType); + + auto derefExpr = new DerefExpr(); + derefExpr->Position = originalExpr->Position; + derefExpr->base = base; + derefExpr->Type = ptrLikeType->elementType; + + // TODO(tfoley): handle l-value status here + + return derefExpr; + } + + RefPtr ConstructLookupResultExpr( + LookupResultItem const& item, + RefPtr baseExpr, + RefPtr originalExpr) + { + // If we collected any breadcrumbs, then these represent + // additional segments of the lookup path that we need + // to expand here. + auto bb = baseExpr; + for (auto breadcrumb = item.breadcrumbs; breadcrumb; breadcrumb = breadcrumb->next) + { + switch (breadcrumb->kind) + { + case LookupResultItem::Breadcrumb::Kind::Member: + bb = ConstructDeclRefExpr(breadcrumb->declRef, bb, originalExpr); + break; + case LookupResultItem::Breadcrumb::Kind::Deref: + bb = ConstructDerefExpr(bb, originalExpr); + break; + default: + SLANG_UNREACHABLE("all cases handle"); + } + } + + return ConstructDeclRefExpr(item.declRef, bb, originalExpr); + } + + RefPtr createLookupResultExpr( + LookupResult const& lookupResult, + RefPtr baseExpr, + RefPtr originalExpr) + { + if (lookupResult.isOverloaded()) + { + auto overloadedExpr = new OverloadedExpr(); + overloadedExpr->Position = originalExpr->Position; + overloadedExpr->Type = ExpressionType::Overloaded; + overloadedExpr->base = baseExpr; + overloadedExpr->lookupResult2 = lookupResult; + return overloadedExpr; + } + else + { + return ConstructLookupResultExpr(lookupResult.item, baseExpr, originalExpr); + } + } + + RefPtr ResolveOverloadedExpr(RefPtr overloadedExpr, LookupMask mask) + { + auto lookupResult = overloadedExpr->lookupResult2; + assert(lookupResult.isValid() && lookupResult.isOverloaded()); + + // Take the lookup result we had, and refine it based on what is expected in context. + lookupResult = refineLookup(lookupResult, mask); + + if (!lookupResult.isValid()) + { + // If we didn't find any symbols after filtering, then just + // use the original and report errors that way + return overloadedExpr; + } + + if (lookupResult.isOverloaded()) + { + // We had an ambiguity anyway, so report it. + getSink()->diagnose(overloadedExpr, Diagnostics::ambiguousReference, lookupResult.items[0].declRef.GetName()); + + for(auto item : lookupResult.items) + { + String declString = getDeclSignatureString(item); + getSink()->diagnose(item.declRef, Diagnostics::overloadCandidate, declString); + } + + // TODO(tfoley): should we construct a new ErrorExpr here? + overloadedExpr->Type = ExpressionType::Error; + return overloadedExpr; + } + + // otherwise, we had a single decl and it was valid, hooray! + return ConstructLookupResultExpr(lookupResult.item, overloadedExpr->base, overloadedExpr); + } + + RefPtr ExpectATypeRepr(RefPtr expr) + { + if (auto overloadedExpr = expr.As()) + { + expr = ResolveOverloadedExpr(overloadedExpr, LookupMask::Type); + } + + if (auto typeType = expr->Type.type->As()) + { + return expr; + } + else if (expr->Type.type->Equals(ExpressionType::Error)) + { + return expr; + } + + getSink()->diagnose(expr, Diagnostics::unimplemented, "expected a type"); + // TODO: construct some kind of `ErrorExpr`? + return expr; + } + + RefPtr ExpectAType(RefPtr expr) + { + auto typeRepr = ExpectATypeRepr(expr); + if (auto typeType = typeRepr->Type->As()) + { + return typeType->type; + } + return ExpressionType::Error; + } + + RefPtr ExtractGenericArgType(RefPtr exp) + { + return ExpectAType(exp); + } + + RefPtr ExtractGenericArgInteger(RefPtr exp) + { + return CheckIntegerConstantExpression(exp.Ptr()); + } + + RefPtr ExtractGenericArgVal(RefPtr exp) + { + if (auto overloadedExpr = exp.As()) + { + // assume that if it is overloaded, we want a type + exp = ResolveOverloadedExpr(overloadedExpr, LookupMask::Type); + } + + if (auto typeType = exp->Type->As()) + { + return typeType->type; + } + else if (exp->Type->Equals(ExpressionType::Error)) + { + return exp->Type.type; + } + else + { + return ExtractGenericArgInteger(exp); + } + } + + // Construct a type reprsenting the instantiation of + // the given generic declaration for the given arguments. + // The arguments should already be checked against + // the declaration. + RefPtr InstantiateGenericType( + GenericDeclRef genericDeclRef, + List> const& args) + { + RefPtr subst = new Substitutions(); + subst->genericDecl = genericDeclRef.GetDecl(); + subst->outer = genericDeclRef.substitutions; + + for (auto argExpr : args) + { + subst->args.Add(ExtractGenericArgVal(argExpr)); + } + + DeclRef innerDeclRef; + innerDeclRef.decl = genericDeclRef.GetInner(); + innerDeclRef.substitutions = subst; + + return DeclRefType::Create(innerDeclRef); + } + + // Make sure a declaration has been checked, so we can refer to it. + // Note that this may lead to us recursively invoking checking, + // so this may not be the best way to handle things. + void EnsureDecl(RefPtr decl, DeclCheckState state = DeclCheckState::CheckedHeader) + { + if (decl->IsChecked(state)) return; + if (decl->checkState == DeclCheckState::CheckingHeader) + { + // We tried to reference the same declaration while checking it! + throw "circularity"; + } + + if (DeclCheckState::CheckingHeader > decl->checkState) + { + decl->SetCheckState(DeclCheckState::CheckingHeader); + } + + // TODO: not all of the `Visit` cases are ready to + // handle this being called on-the-fly + decl->Accept(this); + + decl->SetCheckState(DeclCheckState::Checked); + } + + void EnusreAllDeclsRec(RefPtr decl) + { + EnsureDecl(decl, DeclCheckState::Checked); + if (auto containerDecl = decl.As()) + { + for (auto m : containerDecl->Members) + { + EnusreAllDeclsRec(m); + } + } + } + + // A "proper" type is one that can be used as the type of an expression. + // Put simply, it can be a concrete type like `int`, or a generic + // type that is applied to arguments, like `Texture2D`. + // The type `void` is also a proper type, since we can have expressions + // that return a `void` result (e.g., many function calls). + // + // A "non-proper" type is any type that can't actually have values. + // A simple example of this in C++ is `std::vector` - you can't have + // a value of this type. + // + // Part of what this function does is give errors if somebody tries + // to use a non-proper type as the type of a variable (or anything + // else that needs a proper type). + // + // The other thing it handles is the fact that HLSL lets you use + // the name of a non-proper type, and then have the compiler fill + // in the default values for its type arguments (e.g., a variable + // given type `Texture2D` will actually have type `Texture2D`). + bool CoerceToProperTypeImpl(TypeExp const& typeExp, RefPtr* outProperType) + { + ExpressionType* type = typeExp.type.Ptr(); + if (auto genericDeclRefType = type->As()) + { + // We are using a reference to a generic declaration as a concrete + // type. This means we should substitute in any default parameter values + // if they are available. + // + // TODO(tfoley): A more expressive type system would substitute in + // "fresh" variables and then solve for their values... + // + + auto genericDeclRef = genericDeclRefType->GetDeclRef(); + EnsureDecl(genericDeclRef.decl); + List> args; + for (RefPtr member : genericDeclRef.GetDecl()->Members) + { + if (auto typeParam = member.As()) + { + if (!typeParam->initType.exp) + { + if (outProperType) + { + getSink()->diagnose(typeExp.exp.Ptr(), Diagnostics::unimplemented, "can't fill in default for generic type parameter"); + *outProperType = ExpressionType::Error; + } + return false; + } + + // TODO: this is one place where syntax should get cloned! + if(outProperType) + args.Add(typeParam->initType.exp); + } + else if (auto valParam = member.As()) + { + if (!valParam->Expr) + { + if (outProperType) + { + getSink()->diagnose(typeExp.exp.Ptr(), Diagnostics::unimplemented, "can't fill in default for generic type parameter"); + *outProperType = ExpressionType::Error; + } + return false; + } + + // TODO: this is one place where syntax should get cloned! + if(outProperType) + args.Add(valParam->Expr); + } + else + { + // ignore non-parameter members + } + } + + if (outProperType) + { + *outProperType = InstantiateGenericType(genericDeclRef, args); + } + return true; + } + else + { + // default case: we expect this to already be a proper type + if (outProperType) + { + *outProperType = type; + } + return true; + } + } + + + + TypeExp CoerceToProperType(TypeExp const& typeExp) + { + TypeExp result = typeExp; + CoerceToProperTypeImpl(typeExp, &result.type); + return result; + } + + bool CanCoerceToProperType(TypeExp const& typeExp) + { + return CoerceToProperTypeImpl(typeExp, nullptr); + } + + // Check a type, and coerce it to be proper + TypeExp CheckProperType(TypeExp typeExp) + { + return CoerceToProperType(TranslateTypeNode(typeExp)); + } + + // For our purposes, a "usable" type is one that can be + // used to declare a function parameter, variable, etc. + // These turn out to be all the proper types except + // `void`. + // + // TODO(tfoley): consider just allowing `void` as a + // simple example of a "unit" type, and get rid of + // this check. + TypeExp CoerceToUsableType(TypeExp const& typeExp) + { + TypeExp result = CoerceToProperType(typeExp); + ExpressionType* type = result.type.Ptr(); + if (auto basicType = type->As()) + { + // TODO: `void` shouldn't be a basic type, to make this easier to avoid + if (basicType->BaseType == BaseType::Void) + { + // TODO(tfoley): pick the right diagnostic message + getSink()->diagnose(result.exp.Ptr(), Diagnostics::invalidTypeVoid); + result.type = ExpressionType::Error; + return result; + } + } + return result; + } + + // Check a type, and coerce it to be usable + TypeExp CheckUsableType(TypeExp typeExp) + { + return CoerceToUsableType(TranslateTypeNode(typeExp)); + } + + RefPtr CheckTerm(RefPtr term) + { + if (!term) return nullptr; + return term->Accept(this).As(); + } + + RefPtr CreateErrorExpr(ExpressionSyntaxNode* expr) + { + expr->Type = ExpressionType::Error; + return expr; + } + + bool IsErrorExpr(RefPtr expr) + { + // TODO: we may want other cases here... + + if (expr->Type->Equals(ExpressionType::Error)) + return true; + + return false; + } + + // Capture the "base" expression in case this is a member reference + RefPtr GetBaseExpr(RefPtr expr) + { + if (auto memberExpr = expr.As()) + { + return memberExpr->BaseExpression; + } + else if(auto overloadedExpr = expr.As()) + { + return overloadedExpr->base; + } + return nullptr; + } + + public: + + typedef unsigned int ConversionCost; + enum : ConversionCost + { + // No conversion at all + kConversionCost_None = 0, + + // Conversion that is lossless and keeps the "kind" of the value the same + kConversionCost_RankPromotion = 100, + + // Conversions that are lossless, but change "kind" + kConversionCost_UnsignedToSignedPromotion = 200, + + // Conversion from signed->unsigned integer of same or greater size + kConversionCost_SignedToUnsignedConversion = 300, + + // Cost of converting an integer to a floating-point type + kConversionCost_IntegerToFloatConversion = 400, + + // Catch-all for conversions that should be discouraged + // (i.e., that really shouldn't be made implicitly) + // + // TODO: make these conversions not be allowed implicitly in "Slang mode" + kConversionCost_GeneralConversion = 900, + + // Additional conversion cost to add when promoting from a scalar to + // a vector (this will be added to the cost, if any, of converting + // the element type of the vector) + kConversionCost_ScalarToVector = 1, + }; + + enum BaseTypeConversionKind : uint8_t + { + kBaseTypeConversionKind_Signed, + kBaseTypeConversionKind_Unsigned, + kBaseTypeConversionKind_Float, + kBaseTypeConversionKind_Error, + }; + + enum BaseTypeConversionRank : uint8_t + { + kBaseTypeConversionRank_Bool, + kBaseTypeConversionRank_Int8, + kBaseTypeConversionRank_Int16, + kBaseTypeConversionRank_Int32, + kBaseTypeConversionRank_IntPtr, + kBaseTypeConversionRank_Int64, + kBaseTypeConversionRank_Error, + }; + + struct BaseTypeConversionInfo + { + BaseTypeConversionKind kind; + BaseTypeConversionRank rank; + }; + static BaseTypeConversionInfo GetBaseTypeConversionInfo(BaseType baseType) + { + switch (baseType) + { + #define CASE(TAG, KIND, RANK) \ + case BaseType::TAG: { BaseTypeConversionInfo info = {kBaseTypeConversionKind_##KIND, kBaseTypeConversionRank_##RANK}; return info; } break + + CASE(Bool, Unsigned, Bool); + CASE(Int, Signed, Int32); + CASE(UInt, Unsigned, Int32); + CASE(UInt64, Unsigned, Int64); + CASE(Float, Float, Int32); + CASE(Void, Error, Error); + + #undef CASE + + default: + break; + } + SLANG_UNREACHABLE("all cases handled"); + } + + bool ValuesAreEqual( + RefPtr left, + RefPtr right) + { + if(left == right) return true; + + if(auto leftConst = left.As()) + { + if(auto rightConst = right.As()) + { + return leftConst->value == rightConst->value; + } + } + + if(auto leftVar = left.As()) + { + if(auto rightVar = right.As()) + { + return leftVar->declRef.Equals(rightVar->declRef); + } + } + + return false; + } + + // Central engine for implementing implicit coercion logic + bool TryCoerceImpl( + RefPtr toType, // the target type for conversion + RefPtr* outToExpr, // (optional) a place to stuff the target expression + RefPtr fromType, // the source type for the conversion + RefPtr fromExpr, // the source expression + ConversionCost* outCost) // (optional) a place to stuff the conversion cost + { + // Easy case: the types are equal + if (toType->Equals(fromType)) + { + if (outToExpr) + *outToExpr = fromExpr; + if (outCost) + *outCost = kConversionCost_None; + return true; + } + + // If either type is an error, then let things pass. + if (toType->As() || fromType->As()) + { + if (outToExpr) + *outToExpr = CreateImplicitCastExpr(toType, fromExpr); + if (outCost) + *outCost = kConversionCost_None; + return true; + } + + // Coercion from an initializer list is allowed for many types + if( auto fromInitializerListExpr = fromExpr.As()) + { + auto argCount = fromInitializerListExpr->args.Count(); + + // In the case where we need to build a reuslt expression, + // we will collect the new arguments here + List> coercedArgs; + + if(auto toDeclRefType = toType->As()) + { + auto toTypeDeclRef = toDeclRefType->declRef; + if(auto toStructDeclRef = toTypeDeclRef.As()) + { + // Trying to initialize a `struct` type given an initializer list. + // We will go through the fields in order and try to match them + // up with initializer arguments. + + + int argIndex = 0; + for(auto& fieldDeclRef : toStructDeclRef.GetMembersOfType()) + { + if(argIndex >= argCount) + { + // We've consumed all the arguments, so we should stop + break; + } + + auto arg = fromInitializerListExpr->args[argIndex++]; + + // + RefPtr coercedArg; + ConversionCost argCost; + + bool argResult = TryCoerceImpl( + fieldDeclRef.GetType(), + outToExpr ? &coercedArg : nullptr, + arg->Type, + arg, + outCost ? &argCost : nullptr); + + // No point in trying further if any argument fails + if(!argResult) + return false; + + // TODO(tfoley): what to do with cost? + // This only matters if/when we allow an initializer list as an argument to + // an overloaded call. + + if( outToExpr ) + { + coercedArgs.Add(coercedArg); + } + } + } + } + else if(auto toArrayType = toType->As()) + { + // TODO(tfoley): If we can compute the size of the array statically, + // then we want to check that there aren't too many initializers present + + auto toElementType = toArrayType->BaseType; + + for(auto& arg : fromInitializerListExpr->args) + { + RefPtr coercedArg; + ConversionCost argCost; + + bool argResult = TryCoerceImpl( + toElementType, + outToExpr ? &coercedArg : nullptr, + arg->Type, + arg, + outCost ? &argCost : nullptr); + + // No point in trying further if any argument fails + if(!argResult) + return false; + + if( outToExpr ) + { + coercedArgs.Add(coercedArg); + } + } + } + else + { + // By default, we don't allow a type to be initialized using + // an initializer list. + return false; + } + + // For now, coercion from an initializer list has no cost + if(outCost) + { + *outCost = kConversionCost_None; + } + + // We were able to coerce all the arguments given, and so + // we need to construct a suitable expression to remember the result + if(outToExpr) + { + auto toInitializerListExpr = new InitializerListExpr(); + toInitializerListExpr->Position = fromInitializerListExpr->Position; + toInitializerListExpr->Type = toType; + toInitializerListExpr->args = coercedArgs; + + + *outToExpr = toInitializerListExpr; + } + + return true; + } + + // + + if (auto toBasicType = toType->AsBasicType()) + { + if (auto fromBasicType = fromType->AsBasicType()) + { + // Conversions between base types are always allowed, + // and the only question is what the cost will be. + + auto toInfo = GetBaseTypeConversionInfo(toBasicType->BaseType); + auto fromInfo = GetBaseTypeConversionInfo(fromBasicType->BaseType); + + // We expect identical types to have been dealt with already. + assert(toInfo.kind != fromInfo.kind || toInfo.rank != fromInfo.rank); + + if (outToExpr) + *outToExpr = CreateImplicitCastExpr(toType, fromExpr); + + + if (outCost) + { + // Conversions within the same kind are easist to handle + if (toInfo.kind == fromInfo.kind) + { + // If we are converting to a "larger" type, then + // we are doing a lossless promotion, and otherwise + // we are doing a demotion. + if( toInfo.rank > fromInfo.rank) + *outCost = kConversionCost_RankPromotion; + else + *outCost = kConversionCost_GeneralConversion; + } + // If we are converting from an unsigned integer type to + // a signed integer type that is guaranteed to be larger, + // then that is also a lossless promotion. + else if(toInfo.kind == kBaseTypeConversionKind_Signed + && fromInfo.kind == kBaseTypeConversionKind_Unsigned + && toInfo.rank > fromInfo.rank) + { + // TODO: probably need to weed out cases involving + // "pointer-sized" integers if these are treated + // as distinct from 32- and 64-bit types. + // E.g., there is no guarantee that conversion + // from 32-bit unsigned to pointer-sized signed + // is lossless, because pointers could be 32-bit, + // and the same applies for conversion from + // `uintptr` to `uint64`. + *outCost = kConversionCost_UnsignedToSignedPromotion; + } + // Conversion from signed to unsigned is always lossy, + // but it is preferred over conversions from unsigned + // to signed, for same-size types. + else if(toInfo.kind == kBaseTypeConversionKind_Unsigned + && fromInfo.kind == kBaseTypeConversionKind_Signed + && toInfo.rank >= fromInfo.rank) + { + *outCost = kConversionCost_SignedToUnsignedConversion; + } + // Conversion from an integer to a floating-point type + // is never considered a promotion (even when the value + // would fit in the available bits). + // If the destination type is at least 32 bits we consider + // this a reasonably good conversion, though. + else if (toInfo.kind == kBaseTypeConversionKind_Float + && toInfo.rank >= kBaseTypeConversionRank_Int32) + { + *outCost = kConversionCost_IntegerToFloatConversion; + } + // All other cases are considered as "general" conversions, + // where we don't consider any one conversion better than + // any others. + else + { + *outCost = kConversionCost_GeneralConversion; + } + } + + return true; + } + } + + if (auto toVectorType = toType->AsVectorType()) + { + if (auto fromVectorType = fromType->AsVectorType()) + { + // Conversion between vector types. + + // If element counts don't match, then bail: + if (!ValuesAreEqual(toVectorType->elementCount, fromVectorType->elementCount)) + return false; + + // Otherwise, if we can convert the element types, we are golden + ConversionCost elementCost; + if (CanCoerce(toVectorType->elementType, fromVectorType->elementType, &elementCost)) + { + if (outToExpr) + *outToExpr = CreateImplicitCastExpr(toType, fromExpr); + if (outCost) + *outCost = elementCost; + return true; + } + } + else if (auto fromScalarType = fromType->AsBasicType()) + { + // Conversion from scalar to vector. + // Should allow as long as we can coerce the scalar to our element type. + ConversionCost elementCost; + if (CanCoerce(toVectorType->elementType, fromScalarType, &elementCost)) + { + if (outToExpr) + *outToExpr = CreateImplicitCastExpr(toType, fromExpr); + if (outCost) + *outCost = elementCost + kConversionCost_ScalarToVector; + return true; + } + } + } + + // TODO: more cases! + + return false; + } + + // Check whether a type coercion is possible + bool CanCoerce( + RefPtr toType, // the target type for conversion + RefPtr fromType, // the source type for the conversion + ConversionCost* outCost = 0) // (optional) a place to stuff the conversion cost + { + return TryCoerceImpl( + toType, + nullptr, + fromType, + nullptr, + outCost); + } + + RefPtr CreateImplicitCastExpr( + RefPtr toType, + RefPtr fromExpr) + { + auto castExpr = new TypeCastExpressionSyntaxNode(); + castExpr->Position = fromExpr->Position; + castExpr->TargetType.type = toType; + castExpr->Type = toType; + castExpr->Expression = fromExpr; + return castExpr; + } + + + // Perform type coercion, and emit errors if it isn't possible + RefPtr Coerce( + RefPtr toType, + RefPtr fromExpr) + { + // If semantic checking is being suppressed, then we might see + // expressions without a type, and we need to ignore them. + if( !fromExpr->Type.type ) + { + if(getOptions().flags & SLANG_COMPILE_FLAG_NO_CHECKING ) + return fromExpr; + } + + RefPtr expr; + if (!TryCoerceImpl( + toType, + &expr, + fromExpr->Type.Ptr(), + fromExpr.Ptr(), + nullptr)) + { + if(!(getOptions().flags & SLANG_COMPILE_FLAG_NO_CHECKING)) + { + getSink()->diagnose(fromExpr->Position, Diagnostics::typeMismatch, toType, fromExpr->Type); + } + + // Note(tfoley): We don't call `CreateErrorExpr` here, because that would + // clobber the type on `fromExpr`, and an invariant here is that coercion + // really shouldn't *change* the expression that is passed in, but should + // introduce new AST nodes to coerce its value to a different type... + return CreateImplicitCastExpr(ExpressionType::Error, fromExpr); + } + return expr; + } + + void CheckVarDeclCommon(RefPtr varDecl) + { + // Check the type, if one was given + TypeExp type = CheckUsableType(varDecl->Type); + + // TODO: Additional validation rules on types should go here, + // but we need to deal with the fact that some cases might be + // allowed in one context (e.g., an unsized array parameter) + // but not in othters (e.g., an unsized array field in a struct). + + // Check the initializers, if one was given + RefPtr initExpr = CheckTerm(varDecl->Expr); + + // If a type was given, ... + if (type.Ptr()) + { + // then coerce any initializer to the type + if (initExpr) + { + initExpr = Coerce(type, initExpr); + } + } + else + { + // TODO: infer a type from the initializers + if (!initExpr) + { + getSink()->diagnose(varDecl, Diagnostics::unimplemented, "variable declaration with no type must have initializer"); + } + else + { + getSink()->diagnose(varDecl, Diagnostics::unimplemented, "type inference for variable declaration"); + } + } + + varDecl->Type = type; + varDecl->Expr = initExpr; + } + + void CheckGenericConstraintDecl(GenericTypeConstraintDecl* decl) + { + // TODO: are there any other validations we can do at this point? + // + // There probably needs to be a kind of "occurs check" to make + // sure that the constraint actually applies to at least one + // of the parameters of the generic. + + decl->sub = TranslateTypeNode(decl->sub); + decl->sup = TranslateTypeNode(decl->sup); + } + + virtual RefPtr VisitGenericDecl(GenericDecl* genericDecl) override + { + // check the parameters + for (auto m : genericDecl->Members) + { + if (auto typeParam = m.As()) + { + typeParam->initType = CheckProperType(typeParam->initType); + } + else if (auto valParam = m.As()) + { + // TODO: some real checking here... + CheckVarDeclCommon(valParam); + } + else if(auto constraint = m.As()) + { + CheckGenericConstraintDecl(constraint.Ptr()); + } + } + + // check the nested declaration + // TODO: this needs to be done in an appropriate environment... + genericDecl->inner->Accept(this); + return genericDecl; + } + + virtual void VisitTraitConformanceDecl(TraitConformanceDecl* conformanceDecl) override + { + // check the type being conformed to + auto base = conformanceDecl->base; + base = TranslateTypeNode(base); + conformanceDecl->base = base; + + if(auto declRefType = base.type->As()) + { + if(auto traitDeclRef = declRefType->declRef.As()) + { + conformanceDecl->traitDeclRef = traitDeclRef; + return; + } + } + + // We expected a trait here + getSink()->diagnose( conformanceDecl, Diagnostics::expectedATraitGot, base.type); + } + + RefPtr checkConstantIntVal( + RefPtr expr) + { + // First type-check the expression as normal + expr = CheckExpr(expr); + + auto intVal = CheckIntegerConstantExpression(expr.Ptr()); + if(!intVal) + return nullptr; + + auto constIntVal = intVal.As(); + if(!constIntVal) + { + getSink()->diagnose(expr->Position, Diagnostics::expectedIntegerConstantNotLiteral); + return nullptr; + } + return constIntVal; + } + + RefPtr checkModifier( + RefPtr m, + Decl* decl) + { + if(auto hlslUncheckedAttribute = m.As()) + { + // We have an HLSL `[name(arg,...)]` attribute, and we'd like + // to check that it is provides all the expected arguments + // + // For now we will do this in a completely ad hoc fashion, + // but it would be nice to have some generic routine to + // do the needed type checking/coercion. + if(hlslUncheckedAttribute->nameToken.Content == "numthreads") + { + if(hlslUncheckedAttribute->args.Count() != 3) + return m; + + auto xVal = checkConstantIntVal(hlslUncheckedAttribute->args[0]); + auto yVal = checkConstantIntVal(hlslUncheckedAttribute->args[1]); + auto zVal = checkConstantIntVal(hlslUncheckedAttribute->args[2]); + + if(!xVal) return m; + if(!yVal) return m; + if(!zVal) return m; + + auto hlslNumThreadsAttribute = new HLSLNumThreadsAttribute(); + + hlslNumThreadsAttribute->Position = hlslUncheckedAttribute->Position; + hlslNumThreadsAttribute->nameToken = hlslUncheckedAttribute->nameToken; + hlslNumThreadsAttribute->args = hlslUncheckedAttribute->args; + hlslNumThreadsAttribute->x = xVal->value; + hlslNumThreadsAttribute->y = yVal->value; + hlslNumThreadsAttribute->z = zVal->value; + + return hlslNumThreadsAttribute; + } + } + + // Default behavior is to leave things as they are, + // and assume that modifiers are mostly already checked. + // + // TODO: This would be a good place to validate that + // a modifier is actually valid for the thing it is + // being applied to, and potentially to check that + // it isn't in conflict with any other modifiers + // on the same declaration. + + return m; + } + + + void checkModifiers(Decl* decl) + { + // TODO(tfoley): need to make sure this only + // performs semantic checks on a `SharedModifier` once... + + // The process of checking a modifier may produce a new modifier in its place, + // so we will build up a new linked list of modifiers that will replace + // the old list. + RefPtr resultModifiers; + RefPtr* resultModifierLink = &resultModifiers; + + RefPtr modifier = decl->modifiers.first; + while(modifier) + { + // Because we are rewriting the list in place, we need to extract + // the next modifier here (not at the end of the loop). + auto next = modifier->next; + + // We also go ahead and clobber the `next` field on the modifier + // itself, so that the default behavior of `checkModifier()` can + // be to return a single unlinked modifier. + modifier->next = nullptr; + + auto checkedModifier = checkModifier(modifier, decl); + if(checkedModifier) + { + // If checking gave us a modifier to add, then we + // had better add it. + + // Just in case `checkModifier` ever returns multiple + // modifiers, lets advance to the end of the list we + // are building. + while(*resultModifierLink) + resultModifierLink = &(*resultModifierLink)->next; + + // attach the new modifier at the end of the list, + // and now set the "link" to point to its `next` field + *resultModifierLink = checkedModifier; + resultModifierLink = &checkedModifier->next; + } + + // Move along to the next modifier + modifier = next; + } + + // Whether we actually re-wrote anything or note, lets + // install the new list of modifiers on the declaration + decl->modifiers.first = resultModifiers; + } + + virtual RefPtr VisitProgram(ProgramSyntaxNode * programNode) override + { + // Try to register all the builtin decls + for (auto decl : programNode->Members) + { + auto inner = decl; + if (auto genericDecl = decl.As()) + { + inner = genericDecl->inner; + } + + if (auto builtinMod = inner->FindModifier()) + { + RegisterBuiltinDecl(decl, builtinMod); + } + if (auto magicMod = inner->FindModifier()) + { + RegisterMagicDecl(decl, magicMod); + } + } + + // + + HashSet funcNames; + this->program = programNode; + this->function = nullptr; + + for (auto & s : program->GetTypeDefs()) + VisitTypeDefDecl(s.Ptr()); + for (auto & s : program->GetStructs()) + { + VisitStruct(s.Ptr()); + } + for (auto & s : program->GetClasses()) + { + VisitClass(s.Ptr()); + } + // HACK(tfoley): Visiting all generic declarations here, + // because otherwise they won't get visited. + for (auto & g : program->GetMembersOfType()) + { + VisitGenericDecl(g.Ptr()); + } + + for (auto & func : program->GetFunctions()) + { + if (!func->IsChecked(DeclCheckState::Checked)) + { + VisitFunctionDeclaration(func.Ptr()); + } + } + for (auto & func : program->GetFunctions()) + { + EnsureDecl(func); + } + + if (sink->GetErrorCount() != 0) + return programNode; + + // Force everything to be fully checked, just in case + // Note that we don't just call this on the program, + // because we'd end up recursing into this very code path... + for (auto d : programNode->Members) + { + EnusreAllDeclsRec(d); + } + + // Do any semantic checking required on modifiers? + for (auto d : programNode->Members) + { + checkModifiers(d.Ptr()); + } + + return programNode; + } + + virtual RefPtr VisitClass(ClassSyntaxNode * classNode) override + { + if (classNode->IsChecked(DeclCheckState::Checked)) + return classNode; + classNode->SetCheckState(DeclCheckState::Checked); + + for (auto field : classNode->GetFields()) + { + field->Type = CheckUsableType(field->Type); + field->SetCheckState(DeclCheckState::Checked); + } + return classNode; + } + + virtual RefPtr VisitStruct(StructSyntaxNode * structNode) override + { + if (structNode->IsChecked(DeclCheckState::Checked)) + return structNode; + structNode->SetCheckState(DeclCheckState::Checked); + + for (auto field : structNode->GetFields()) + { + field->Type = CheckUsableType(field->Type); + field->SetCheckState(DeclCheckState::Checked); + } + return structNode; + } + + virtual RefPtr VisitTypeDefDecl(TypeDefDecl* decl) override + { + if (decl->IsChecked(DeclCheckState::Checked)) return decl; + + decl->SetCheckState(DeclCheckState::CheckingHeader); + decl->Type = CheckProperType(decl->Type); + decl->SetCheckState(DeclCheckState::Checked); + return decl; + } + + virtual RefPtr VisitFunction(FunctionSyntaxNode *functionNode) override + { + if (functionNode->IsChecked(DeclCheckState::Checked)) + return functionNode; + + VisitFunctionDeclaration(functionNode); + functionNode->SetCheckState(DeclCheckState::Checked); + + if (!functionNode->IsExtern()) + { + this->function = functionNode; + if (functionNode->Body) + { + functionNode->Body->Accept(this); + } + this->function = nullptr; + } + return functionNode; + } + + // Check if two functions have the same signature for the purposes + // of overload resolution. + bool DoFunctionSignaturesMatch( + FunctionSyntaxNode* fst, + FunctionSyntaxNode* snd) + { + // TODO(tfoley): This function won't do anything sensible for generics, + // so we need to figure out a plan for that... + + // TODO(tfoley): This copies the parameter array, which is bad for performance. + auto fstParams = fst->GetParameters().ToArray(); + auto sndParams = snd->GetParameters().ToArray(); + + // If the functions have different numbers of parameters, then + // their signatures trivially don't match. + auto fstParamCount = fstParams.Count(); + auto sndParamCount = sndParams.Count(); + if (fstParamCount != sndParamCount) + return false; + + for (int ii = 0; ii < fstParamCount; ++ii) + { + auto fstParam = fstParams[ii]; + auto sndParam = sndParams[ii]; + + // If a given parameter type doesn't match, then signatures don't match + if (!fstParam->Type.Equals(sndParam->Type)) + return false; + + // If one parameter is `out` and the other isn't, then they don't match + // + // Note(tfoley): we don't consider `out` and `inout` as distinct here, + // because there is no way for overload resolution to pick between them. + if (fstParam->HasModifier() != sndParam->HasModifier()) + return false; + } + + // Note(tfoley): return type doesn't enter into it, because we can't take + // calling context into account during overload resolution. + + return true; + } + + void ValidateFunctionRedeclaration(FunctionSyntaxNode* funcDecl) + { + auto parentDecl = funcDecl->ParentDecl; + assert(parentDecl); + if (!parentDecl) return; + + // Look at previously-declared functions with the same name, + // in the same container + buildMemberDictionary(parentDecl); + + for (auto prevDecl = funcDecl->nextInContainerWithSameName; prevDecl; prevDecl = prevDecl->nextInContainerWithSameName) + { + // Look through generics to the declaration underneath + auto prevGenericDecl = dynamic_cast(prevDecl); + if (prevGenericDecl) + prevDecl = prevGenericDecl->inner.Ptr(); + + // We only care about previously-declared functions + // Note(tfoley): although we should really error out if the + // name is already in use for something else, like a variable... + auto prevFuncDecl = dynamic_cast(prevDecl); + if (!prevFuncDecl) + continue; + + // If the parameter signatures don't match, then don't worry + if (!DoFunctionSignaturesMatch(funcDecl, prevFuncDecl)) + continue; + + // If we get this far, then we've got two declarations in the same + // scope, with the same name and signature. + // + // They might just be redeclarations, which we would want to allow. + + // First, check if the return types match. + // TODO(tfolye): this code won't work for generics + if (!funcDecl->ReturnType.Equals(prevFuncDecl->ReturnType)) + { + // Bad dedeclaration + getSink()->diagnose(funcDecl, Diagnostics::unimplemented, "redeclaration has a different return type"); + + // Don't bother emitting other errors at this point + break; + } + + // TODO(tfoley): track the fact that there is redeclaration going on, + // so that we can detect it and react accordingly during overload resolution + // (e.g., by only considering one declaration as the canonical one...) + + // If both have a body, then there is trouble + if (funcDecl->Body && prevFuncDecl->Body) + { + // Redefinition + getSink()->diagnose(funcDecl, Diagnostics::unimplemented, "function redefinition"); + + // Don't bother emitting other errors + break; + } + + // TODO(tfoley): If both specific default argument expressions + // for the same value, then that is an error too... + } + } + + void VisitFunctionDeclaration(FunctionSyntaxNode *functionNode) + { + if (functionNode->IsChecked(DeclCheckState::CheckedHeader)) return; + functionNode->SetCheckState(DeclCheckState::CheckingHeader); + + this->function = functionNode; + auto returnType = CheckProperType(functionNode->ReturnType); + functionNode->ReturnType = returnType; + HashSet paraNames; + for (auto & para : functionNode->GetParameters()) + { + if (paraNames.Contains(para->Name.Content)) + getSink()->diagnose(para, Diagnostics::parameterAlreadyDefined, para->Name); + else + paraNames.Add(para->Name.Content); + para->Type = CheckUsableType(para->Type); + if (para->Type.Equals(ExpressionType::GetVoid())) + getSink()->diagnose(para, Diagnostics::parameterCannotBeVoid); + } + this->function = NULL; + functionNode->SetCheckState(DeclCheckState::CheckedHeader); + + // One last bit of validation: check if we are redeclaring an existing function + ValidateFunctionRedeclaration(functionNode); + } + + virtual RefPtr VisitBlockStatement(BlockStatementSyntaxNode *stmt) override + { + for (auto & node : stmt->Statements) + { + node->Accept(this); + } + return stmt; + } + + template + T* FindOuterStmt() + { + int outerStmtCount = outerStmts.Count(); + for (int ii = outerStmtCount - 1; ii >= 0; --ii) + { + auto outerStmt = outerStmts[ii]; + auto found = dynamic_cast(outerStmt); + if (found) + return found; + } + return nullptr; + } + + virtual RefPtr VisitBreakStatement(BreakStatementSyntaxNode *stmt) override + { + auto outer = FindOuterStmt(); + if (!outer) + { + getSink()->diagnose(stmt, Diagnostics::breakOutsideLoop); + } + stmt->parentStmt = outer; + return stmt; + } + virtual RefPtr VisitContinueStatement(ContinueStatementSyntaxNode *stmt) override + { + auto outer = FindOuterStmt(); + if (!outer) + { + getSink()->diagnose(stmt, Diagnostics::continueOutsideLoop); + } + stmt->parentStmt = outer; + return stmt; + } + + void PushOuterStmt(StatementSyntaxNode* stmt) + { + outerStmts.Add(stmt); + } + + void PopOuterStmt(StatementSyntaxNode* /*stmt*/) + { + outerStmts.RemoveAt(outerStmts.Count() - 1); + } + + virtual RefPtr VisitDoWhileStatement(DoWhileStatementSyntaxNode *stmt) override + { + PushOuterStmt(stmt); + if (stmt->Predicate != NULL) + stmt->Predicate = stmt->Predicate->Accept(this).As(); + if (!stmt->Predicate->Type->Equals(ExpressionType::GetError()) && + !stmt->Predicate->Type->Equals(ExpressionType::GetInt()) && + !stmt->Predicate->Type->Equals(ExpressionType::GetBool())) + { + getSink()->diagnose(stmt, Diagnostics::whilePredicateTypeError); + } + stmt->Statement->Accept(this); + + PopOuterStmt(stmt); + return stmt; + } + virtual RefPtr VisitForStatement(ForStatementSyntaxNode *stmt) override + { + PushOuterStmt(stmt); + if (stmt->InitialStatement) + { + stmt->InitialStatement = stmt->InitialStatement->Accept(this).As(); + } + if (stmt->PredicateExpression) + { + stmt->PredicateExpression = stmt->PredicateExpression->Accept(this).As(); + if (!stmt->PredicateExpression->Type->Equals(ExpressionType::GetBool()) && + !stmt->PredicateExpression->Type->Equals(ExpressionType::GetInt()) && + !stmt->PredicateExpression->Type->Equals(ExpressionType::GetUInt())) + { + getSink()->diagnose(stmt->PredicateExpression.Ptr(), Diagnostics::forPredicateTypeError); + } + } + if (stmt->SideEffectExpression) + { + stmt->SideEffectExpression = stmt->SideEffectExpression->Accept(this).As(); + } + stmt->Statement->Accept(this); + + PopOuterStmt(stmt); + return stmt; + } + virtual RefPtr VisitSwitchStmt(SwitchStmt* stmt) override + { + PushOuterStmt(stmt); + // TODO(tfoley): need to coerce condition to an integral type... + stmt->condition = CheckExpr(stmt->condition); + stmt->body->Accept(this); + PopOuterStmt(stmt); + return stmt; + } + virtual RefPtr VisitCaseStmt(CaseStmt* stmt) override + { + auto expr = CheckExpr(stmt->expr); + auto switchStmt = FindOuterStmt(); + + if (!switchStmt) + { + getSink()->diagnose(stmt, Diagnostics::caseOutsideSwitch); + } + else + { + // TODO: need to do some basic matching to ensure the type + // for the `case` is consistent with the type for the `switch`... + } + + stmt->expr = expr; + stmt->parentStmt = switchStmt; + + return stmt; + } + virtual RefPtr VisitDefaultStmt(DefaultStmt* stmt) override + { + auto switchStmt = FindOuterStmt(); + if (!switchStmt) + { + getSink()->diagnose(stmt, Diagnostics::defaultOutsideSwitch); + } + stmt->parentStmt = switchStmt; + return stmt; + } + virtual RefPtr VisitIfStatement(IfStatementSyntaxNode *stmt) override + { + auto condition = stmt->Predicate; + condition = CheckTerm(condition); + condition = Coerce(ExpressionType::GetBool(), condition); + + stmt->Predicate = condition; + +#if 0 + if (stmt->Predicate != NULL) + stmt->Predicate = stmt->Predicate->Accept(this).As(); + if (!stmt->Predicate->Type->Equals(ExpressionType::GetError()) + && (!stmt->Predicate->Type->Equals(ExpressionType::GetInt()) && + !stmt->Predicate->Type->Equals(ExpressionType::GetBool()))) + getSink()->diagnose(stmt, Diagnostics::ifPredicateTypeError); +#endif + + if (stmt->PositiveStatement != NULL) + stmt->PositiveStatement->Accept(this); + + if (stmt->NegativeStatement != NULL) + stmt->NegativeStatement->Accept(this); + return stmt; + } + virtual RefPtr VisitReturnStatement(ReturnStatementSyntaxNode *stmt) override + { + if (!stmt->Expression) + { + if (function && !function->ReturnType.Equals(ExpressionType::GetVoid())) + getSink()->diagnose(stmt, Diagnostics::returnNeedsExpression); + } + else + { + stmt->Expression = stmt->Expression->Accept(this).As(); + if (!stmt->Expression->Type->Equals(ExpressionType::Error.Ptr())) + { + if (function) + { + stmt->Expression = Coerce(function->ReturnType, stmt->Expression); + } + else + { + // TODO(tfoley): this case currently gets triggered for member functions, + // which aren't being checked consistently (because of the whole symbol + // table idea getting in the way). + +// getSink()->diagnose(stmt, Diagnostics::unimplemented, "case for return stmt"); + } + } + } + return stmt; + } + + int GetMinBound(RefPtr val) + { + if (auto constantVal = val.As()) + return constantVal->value; + + // TODO(tfoley): Need to track intervals so that this isn't just a lie... + return 1; + } + + void maybeInferArraySizeForVariable(Variable* varDecl) + { + // Not an array? + auto arrayType = varDecl->Type->AsArrayType(); + if (!arrayType) return; + + // Explicit element count given? + auto elementCount = arrayType->ArrayLength; + if (elementCount) return; + + // No initializer? + auto initExpr = varDecl->Expr; + if(!initExpr) return; + + // Is the initializer an initializer list? + if(auto initializerListExpr = initExpr.As()) + { + auto argCount = initializerListExpr->args.Count(); + elementCount = new ConstantIntVal(argCount); + } + // Is the type of the initializer an array type? + else if(auto arrayInitType = initExpr->Type->As()) + { + elementCount = arrayInitType->ArrayLength; + } + else + { + // Nothing to do: we couldn't infer a size + return; + } + + // Create a new array type based on the size we found, + // and install it into our type. + auto newArrayType = new ArrayExpressionType(); + newArrayType->BaseType = arrayType->BaseType; + newArrayType->ArrayLength = elementCount; + + // Okay we are good to go! + varDecl->Type.type = newArrayType; + } + + void ValidateArraySizeForVariable(Variable* varDecl) + { + auto arrayType = varDecl->Type->AsArrayType(); + if (!arrayType) return; + + auto elementCount = arrayType->ArrayLength; + if (!elementCount) + { + // Note(tfoley): For now we allow arrays of unspecified size + // everywhere, because some source languages (e.g., GLSL) + // allow them in specific cases. +#if 0 + getSink()->diagnose(varDecl, Diagnostics::invalidArraySize); +#endif + return; + } + + // TODO(tfoley): How to handle the case where bound isn't known? + if (GetMinBound(elementCount) <= 0) + { + getSink()->diagnose(varDecl, Diagnostics::invalidArraySize); + return; + } + } + + virtual RefPtr VisitDeclrVariable(Variable* varDecl) + { + TypeExp typeExp = CheckUsableType(varDecl->Type); +#if 0 + if (typeExp.type->GetBindableResourceType() != BindableResourceType::NonBindable) + { + // We don't want to allow bindable resource types as local variables (at least for now). + auto parentDecl = varDecl->ParentDecl; + if (auto parentScopeDecl = dynamic_cast(parentDecl)) + { + getSink()->diagnose(varDecl->Type, Diagnostics::invalidTypeForLocalVariable); + } + } +#endif + varDecl->Type = typeExp; + if (varDecl->Type.Equals(ExpressionType::GetVoid())) + getSink()->diagnose(varDecl, Diagnostics::invalidTypeVoid); + + if(auto initExpr = varDecl->Expr) + { + initExpr = CheckTerm(initExpr); + varDecl->Expr = initExpr; + } + + // If this is an array variable, then we first want to give + // it a chance to infer an array size from its initializer + // + // TODO(tfoley): May need to extend this to handle the + // multi-dimensional case... + maybeInferArraySizeForVariable(varDecl); + // + // Next we want to make sure that the declared (or inferred) + // size for the array meets whatever language-specific + // constraints we want to enforce (e.g., disallow empty + // arrays in specific cases) + ValidateArraySizeForVariable(varDecl); + + + if(auto initExpr = varDecl->Expr) + { + // TODO(tfoley): should coercion of initializer lists be special-cased + // here, or handled as a general case for coercion? + + initExpr = Coerce(varDecl->Type, initExpr); + varDecl->Expr = initExpr; + } + + varDecl->SetCheckState(DeclCheckState::Checked); + + return varDecl; + } + + virtual RefPtr VisitWhileStatement(WhileStatementSyntaxNode *stmt) override + { + PushOuterStmt(stmt); + stmt->Predicate = stmt->Predicate->Accept(this).As(); + if (!stmt->Predicate->Type->Equals(ExpressionType::GetError()) && + !stmt->Predicate->Type->Equals(ExpressionType::GetInt()) && + !stmt->Predicate->Type->Equals(ExpressionType::GetBool())) + getSink()->diagnose(stmt, Diagnostics::whilePredicateTypeError2); + + stmt->Statement->Accept(this); + PopOuterStmt(stmt); + return stmt; + } + virtual RefPtr VisitExpressionStatement(ExpressionStatementSyntaxNode *stmt) override + { + stmt->Expression = stmt->Expression->Accept(this).As(); + return stmt; + } + virtual RefPtr VisitOperatorExpression(OperatorExpressionSyntaxNode *expr) override + { +#if 0 + + for (int i = 0; i < expr->Arguments.Count(); i++) + expr->Arguments[i] = expr->Arguments[i]->Accept(this).As(); + auto & leftType = expr->Arguments[0]->Type; + QualType rightType; + if (expr->Arguments.Count() == 2) + rightType = expr->Arguments[1]->Type; + RefPtr matchedType; + auto checkAssign = [&]() + { + if (!leftType.IsLeftValue && + !leftType->Equals(ExpressionType::Error.Ptr())) + getSink()->diagnose(expr->Arguments[0].Ptr(), Diagnostics::assignNonLValue); + if (expr->Operator == Operator::AndAssign || + expr->Operator == Operator::OrAssign || + expr->Operator == Operator::XorAssign || + expr->Operator == Operator::LshAssign || + expr->Operator == Operator::RshAssign) + { +#if 0 + if (!(leftType->IsIntegral() && rightType->IsIntegral())) + { + // TODO(tfoley): This diagnostic shouldn't be handled here +// getSink()->diagnose(expr, Diagnostics::bitOperationNonIntegral); + } +#endif + } + + // TODO(tfoley): Need to actual insert coercion here... + if(CanCoerce(leftType, expr->Type)) + expr->Type = leftType; + else + expr->Type = ExpressionType::Error; + }; +#if 0 + if (expr->Operator == Operator::Assign) + { + expr->Type = rightType; + checkAssign(); + } + else +#endif + { + expr->FunctionExpr = CheckExpr(expr->FunctionExpr); + CheckInvokeExprWithCheckedOperands(expr); + if (expr->Operator > Operator::Assign) + checkAssign(); + } + return expr; +#endif + + // Treat operator application just like a function call + return VisitInvokeExpression(expr); + } + virtual RefPtr VisitConstantExpression(ConstantExpressionSyntaxNode *expr) override + { + switch (expr->ConstType) + { + case ConstantExpressionSyntaxNode::ConstantType::Int: + expr->Type = ExpressionType::GetInt(); + break; + case ConstantExpressionSyntaxNode::ConstantType::Bool: + expr->Type = ExpressionType::GetBool(); + break; + case ConstantExpressionSyntaxNode::ConstantType::Float: + expr->Type = ExpressionType::GetFloat(); + break; + default: + expr->Type = ExpressionType::Error; + throw "Invalid constant type."; + break; + } + return expr; + } + + IntVal* GetIntVal(ConstantExpressionSyntaxNode* expr) + { + // TODO(tfoley): don't keep allocating here! + return new ConstantIntVal(expr->IntValue); + } + + RefPtr TryConstantFoldExpr( + InvokeExpressionSyntaxNode* invokeExpr) + { + // We need all the operands to the expression + + // Check if the callee is an operation that is amenable to constant-folding. + // + // For right now we will look for calls to intrinsic functions, and then inspect + // their names (this is bad and slow). + auto funcDeclRefExpr = invokeExpr->FunctionExpr.As(); + if (!funcDeclRefExpr) return nullptr; + + auto funcDeclRef = funcDeclRefExpr->declRef; + auto intrinsicMod = funcDeclRef.GetDecl()->FindModifier(); + if (!intrinsicMod) return nullptr; + + // Let's not constant-fold operations with more than a certain number of arguments, for simplicity + static const int kMaxArgs = 8; + if (invokeExpr->Arguments.Count() > kMaxArgs) + return nullptr; + + // Before checking the operation name, let's look at the arguments + RefPtr argVals[kMaxArgs]; + int constArgVals[kMaxArgs]; + int argCount = 0; + bool allConst = true; + for (auto argExpr : invokeExpr->Arguments) + { + auto argVal = TryCheckIntegerConstantExpression(argExpr.Ptr()); + if (!argVal) + return nullptr; + + argVals[argCount] = argVal; + + if (auto constArgVal = argVal.As()) + { + constArgVals[argCount] = constArgVal->value; + } + else + { + allConst = false; + } + argCount++; + } + + if (!allConst) + { + // TODO(tfoley): We probably want to support a very limited number of operations + // on "constants" that aren't actually known, to be able to handle a generic + // that takes an integer `N` but then constructs a vector of size `N+1`. + // + // The hard part there is implementing the rules for value unification in the + // presence of more complicated `IntVal` subclasses, like `SumIntVal`. You'd + // need inference to be smart enough to know that `2 + N` and `N + 2` are the + // same value, as are `N + M + 1 + 1` and `M + 2 + N`. + // + // For now we can just bail in this case. + return nullptr; + } + + // At this point, all the operands had simple integer values, so we are golden. + int resultValue = 0; + auto opName = funcDeclRef.GetName(); + + // handle binary operators + if (opName == "-") + { + if (argCount == 1) + { + resultValue = -constArgVals[0]; + } + else if (argCount == 2) + { + resultValue = constArgVals[0] - constArgVals[1]; + } + } + + // simple binary operators +#define CASE(OP) \ + else if(opName == #OP) do { \ + if(argCount != 2) return nullptr; \ + resultValue = constArgVals[0] OP constArgVals[1]; \ + } while(0) + + CASE(+); // TODO: this can also be unary... + CASE(*); +#undef CASE + + // binary operators with chance of divide-by-zero + // TODO: issue a suitable error in that case +#define CASE(OP) \ + else if(opName == #OP) do { \ + if(argCount != 2) return nullptr; \ + if(!constArgVals[1]) return nullptr; \ + resultValue = constArgVals[0] OP constArgVals[1]; \ + } while(0) + + CASE(/); + CASE(%); +#undef CASE + + // TODO(tfoley): more cases + else + { + return nullptr; + } + + RefPtr result = new ConstantIntVal(resultValue); + return result; + } + + RefPtr TryConstantFoldExpr( + ExpressionSyntaxNode* expr) + { + // TODO(tfoley): more serious constant folding here + if (auto constExp = dynamic_cast(expr)) + { + return GetIntVal(constExp); + } + + // it is possible that we are referring to a generic value param + if (auto declRefExpr = dynamic_cast(expr)) + { + auto declRef = declRefExpr->declRef; + + if (auto genericValParamRef = declRef.As()) + { + // TODO(tfoley): handle the case of non-`int` value parameters... + return new GenericParamIntVal(genericValParamRef); + } + + // We may also need to check for references to variables that + // are defined in a way that can be used as a constant expression: + if(auto varRef = declRef.As()) + { + auto varDecl = varRef.GetDecl(); + + switch(sourceLanguage) + { + case SourceLanguage::Slang: + case SourceLanguage::HLSL: + // HLSL: `static const` is used to mark compile-time constant expressions + if(auto staticAttr = varDecl->FindModifier()) + { + if(auto constAttr = varDecl->FindModifier()) + { + // HLSL `static const` can be used as a constant expression + if(auto initExpr = varRef.getInitExpr()) + { + return TryConstantFoldExpr(initExpr.Ptr()); + } + } + } + break; + + case SourceLanguage::GLSL: + // GLSL: `const` indicates compile-time constant expression + // + // TODO(tfoley): The current logic here isn't robust against + // GLSL "specialization constants" - we will extract the + // initializer for a `const` variable and use it to extract + // a value, when we really should be using an opaque + // reference to the variable. + if(auto constAttr = varDecl->FindModifier()) + { + // We need to handle a "specialization constant" (with a `constant_id` layout modifier) + // differently from an ordinary compile-time constant. The latter can/should be reduced + // to a value, while the former should be kept as a symbolic reference + + if(auto constantIDModifier = varDecl->FindModifier()) + { + // Retain the specialization constant as a symbolic reference + // + // TODO(tfoley): handle the case of non-`int` value parameters... + // + // TODO(tfoley): this is cloned from the case above that handles generic value parameters + return new GenericParamIntVal(varRef); + } + else if(auto initExpr = varRef.getInitExpr()) + { + // This is an ordinary constant, and not a specialization constant, so we + // can try to fold its value right now. + return TryConstantFoldExpr(initExpr.Ptr()); + } + } + break; + } + + } + } + + if (auto invokeExpr = dynamic_cast(expr)) + { + auto val = TryConstantFoldExpr(invokeExpr); + if (val) + return val; + } + else if(auto castExpr = dynamic_cast(expr)) + { + auto val = TryConstantFoldExpr(castExpr->Expression.Ptr()); + if(val) + return val; + } + + return nullptr; + } + + // Try to check an integer constant expression, either returning the value, + // or NULL if the expression isn't recognized as a constant. + RefPtr TryCheckIntegerConstantExpression(ExpressionSyntaxNode* exp) + { + if (!exp->Type.type->Equals(ExpressionType::GetInt())) + { + return nullptr; + } + + + + // Otherwise, we need to consider operations that we might be able to constant-fold... + return TryConstantFoldExpr(exp); + } + + // Enforce that an expression resolves to an integer constant, and get its value + RefPtr CheckIntegerConstantExpression(ExpressionSyntaxNode* inExpr) + { + // First coerce the expression to the expected type + auto expr = Coerce(ExpressionType::GetInt(),inExpr); + auto result = TryCheckIntegerConstantExpression(expr.Ptr()); + if (!result) + { + getSink()->diagnose(expr, Diagnostics::expectedIntegerConstantNotConstant); + } + return result; + } + + + + RefPtr CheckSimpleSubscriptExpr( + RefPtr subscriptExpr, + RefPtr elementType) + { + auto baseExpr = subscriptExpr->BaseExpression; + auto indexExpr = subscriptExpr->IndexExpression; + + if (!indexExpr->Type->Equals(ExpressionType::GetInt()) && + !indexExpr->Type->Equals(ExpressionType::GetUInt())) + { + getSink()->diagnose(indexExpr, Diagnostics::subscriptIndexNonInteger); + return CreateErrorExpr(subscriptExpr.Ptr()); + } + + subscriptExpr->Type = elementType; + + // TODO(tfoley): need to be more careful about this stuff + subscriptExpr->Type.IsLeftValue = baseExpr->Type.IsLeftValue; + + return subscriptExpr; + } + + // The way that we have designed out type system, pretyt much *every* + // type is a reference to some declaration in the standard library. + // That means that when we construct a new type on the fly, we need + // to make sure that it is wired up to reference the appropriate + // declaration, or else it won't compare as equal to other types + // that *do* reference the declaration. + // + // This function is used to construct a `vector` type + // programmatically, so that it will work just like a type of + // that form constructed by the user. + RefPtr createVectorType( + RefPtr elementType, + RefPtr elementCount) + { + auto vectorGenericDecl = findMagicDecl("Vector").As(); + auto vectorTypeDecl = vectorGenericDecl->inner; + + auto substitutions = new Substitutions(); + substitutions->genericDecl = vectorGenericDecl.Ptr(); + substitutions->args.Add(elementType); + substitutions->args.Add(elementCount); + + auto declRef = DeclRef(vectorTypeDecl.Ptr(), substitutions); + + return DeclRefType::Create(declRef)->As(); + } + + virtual RefPtr VisitIndexExpression(IndexExpressionSyntaxNode* subscriptExpr) override + { + auto baseExpr = subscriptExpr->BaseExpression; + baseExpr = CheckExpr(baseExpr); + + RefPtr indexExpr = subscriptExpr->IndexExpression; + if (indexExpr) + { + indexExpr = CheckExpr(indexExpr); + } + + subscriptExpr->BaseExpression = baseExpr; + subscriptExpr->IndexExpression = indexExpr; + + // If anything went wrong in the base expression, + // then just move along... + if (IsErrorExpr(baseExpr)) + return CreateErrorExpr(subscriptExpr); + + // Otherwise, we need to look at the type of the base expression, + // to figure out how subscripting should work. + auto baseType = baseExpr->Type.Ptr(); + if (auto baseTypeType = baseType->As()) + { + // We are trying to "index" into a type, so we have an expression like `float[2]` + // which should be interpreted as resolving to an array type. + + RefPtr elementCount = nullptr; + if (indexExpr) + { + elementCount = CheckIntegerConstantExpression(indexExpr.Ptr()); + } + + auto elementType = CoerceToUsableType(TypeExp(baseExpr, baseTypeType->type)); + auto arrayType = new ArrayExpressionType(); + arrayType->BaseType = elementType; + arrayType->ArrayLength = elementCount; + + typeResult = arrayType; + subscriptExpr->Type = new TypeType(arrayType); + return subscriptExpr; + } + else if (auto baseArrayType = baseType->As()) + { + return CheckSimpleSubscriptExpr( + subscriptExpr, + baseArrayType->BaseType); + } + else if (auto vecType = baseType->As()) + { + return CheckSimpleSubscriptExpr( + subscriptExpr, + vecType->elementType); + } + else if (auto matType = baseType->As()) + { + // TODO(tfoley): We shouldn't go and recompute + // row types over and over like this... :( + auto rowType = createVectorType( + matType->getElementType(), + matType->getColumnCount()); + + return CheckSimpleSubscriptExpr( + subscriptExpr, + rowType); + } + + // Default behavior is to look at all available `__subscript` + // declarations on the type and try to call one of them. + + if (auto declRefType = baseType->AsDeclRefType()) + { + if (auto aggTypeDeclRef = declRefType->declRef.As()) + { + // Checking of the type must be complete before we can reference its members safely + EnsureDecl(aggTypeDeclRef.GetDecl(), DeclCheckState::Checked); + + // Note(tfoley): The name used for lookup here is a bit magical, since + // it must match what the parser installed in subscript declarations. + LookupResult lookupResult = LookUpLocal("operator[]", aggTypeDeclRef); + if (!lookupResult.isValid()) + { + goto fail; + } + + RefPtr subscriptFuncExpr = createLookupResultExpr( + lookupResult, subscriptExpr->BaseExpression, subscriptExpr); + + // Now that we know there is at least one subscript member, + // we will construct a reference to it and try to call it + + RefPtr subscriptCallExpr = new InvokeExpressionSyntaxNode(); + subscriptCallExpr->Position = subscriptExpr->Position; + subscriptCallExpr->FunctionExpr = subscriptFuncExpr; + + // TODO(tfoley): This path can support multiple arguments easily + subscriptCallExpr->Arguments.Add(subscriptExpr->IndexExpression); + + return CheckInvokeExprWithCheckedOperands(subscriptCallExpr.Ptr()); + } + } + + fail: + { + getSink()->diagnose(subscriptExpr, Diagnostics::subscriptNonArray, baseType); + return CreateErrorExpr(subscriptExpr); + } + } + + bool MatchArguments(FunctionSyntaxNode * functionNode, List > &args) + { + if (functionNode->GetParameters().Count() != args.Count()) + return false; + int i = 0; + for (auto param : functionNode->GetParameters()) + { + if (!param->Type.Equals(args[i]->Type.Ptr())) + return false; + i++; + } + return true; + } + + // Coerce an expression to a specific type that it is expected to have in context + RefPtr CoerceExprToType( + RefPtr expr, + RefPtr type) + { + // TODO(tfoley): clean this up so there is only one version... + return Coerce(type, expr); + } + + // Resolve a call to a function, represented here + // by a symbol with a `FuncType` type. + RefPtr ResolveFunctionApp( + RefPtr funcType, + InvokeExpressionSyntaxNode* /*appExpr*/) + { + // TODO(tfoley): Actual checking logic needs to go here... +#if 0 + auto& args = appExpr->Arguments; + List> params; + RefPtr resultType; + if (auto funcDeclRef = funcType->declRef) + { + EnsureDecl(funcDeclRef.GetDecl()); + + params = funcDeclRef->GetParameters().ToArray(); + resultType = funcDecl->ReturnType; + } + else if (auto funcSym = funcType->Func) + { + auto funcDecl = funcSym->SyntaxNode; + EnsureDecl(funcDecl); + + params = funcDecl->GetParameters().ToArray(); + resultType = funcDecl->ReturnType; + } + else if (auto componentFuncSym = funcType->Component) + { + auto componentFuncDecl = componentFuncSym->Implementations.First()->SyntaxNode; + params = componentFuncDecl->GetParameters().ToArray(); + resultType = componentFuncDecl->Type; + } + + auto argCount = args.Count(); + auto paramCount = params.Count(); + if (argCount != paramCount) + { + getSink()->diagnose(appExpr, Diagnostics::unimplemented, "wrong number of arguments for call"); + appExpr->Type = ExpressionType::Error; + return appExpr; + } + + for (int ii = 0; ii < argCount; ++ii) + { + auto arg = args[ii]; + auto param = params[ii]; + + arg = CoerceExprToType(arg, param->Type); + + args[ii] = arg; + } + + assert(resultType); + appExpr->Type = resultType; + return appExpr; +#else + throw "unimplemented"; +#endif + } + + // Resolve a constructor call, formed by apply a type to arguments + RefPtr ResolveConstructorApp( + RefPtr type, + InvokeExpressionSyntaxNode* appExpr) + { + // TODO(tfoley): Actual checking logic needs to go here... + + appExpr->Type = type; + return appExpr; + } + + + // + + virtual void VisitExtensionDecl(ExtensionDecl* decl) override + { + if (decl->IsChecked(DeclCheckState::Checked)) return; + + decl->SetCheckState(DeclCheckState::CheckingHeader); + decl->targetType = CheckProperType(decl->targetType); + + // TODO: need to check that the target type names a declaration... + + if (auto targetDeclRefType = decl->targetType->As()) + { + // Attach our extension to that type as a candidate... + if (auto aggTypeDeclRef = targetDeclRefType->declRef.As()) + { + auto aggTypeDecl = aggTypeDeclRef.GetDecl(); + decl->nextCandidateExtension = aggTypeDecl->candidateExtensions; + aggTypeDecl->candidateExtensions = decl; + } + else + { + getSink()->diagnose(decl->targetType.exp, Diagnostics::unimplemented, "expected a nominal type here"); + } + } + else if (decl->targetType->Equals(ExpressionType::Error)) + { + // there was an error, so ignore + } + else + { + getSink()->diagnose(decl->targetType.exp, Diagnostics::unimplemented, "expected a nominal type here"); + } + + decl->SetCheckState(DeclCheckState::CheckedHeader); + + // now check the members of the extension + for (auto m : decl->Members) + { + EnsureDecl(m); + } + + decl->SetCheckState(DeclCheckState::Checked); + } + + virtual void VisitConstructorDecl(ConstructorDecl* decl) override + { + if (decl->IsChecked(DeclCheckState::Checked)) return; + decl->SetCheckState(DeclCheckState::CheckingHeader); + + for (auto& paramDecl : decl->GetParameters()) + { + paramDecl->Type = CheckUsableType(paramDecl->Type); + } + decl->SetCheckState(DeclCheckState::CheckedHeader); + + // TODO(tfoley): check body + decl->SetCheckState(DeclCheckState::Checked); + } + + + virtual void visitSubscriptDecl(SubscriptDecl* decl) override + { + if (decl->IsChecked(DeclCheckState::Checked)) return; + decl->SetCheckState(DeclCheckState::CheckingHeader); + + for (auto& paramDecl : decl->GetParameters()) + { + paramDecl->Type = CheckUsableType(paramDecl->Type); + } + + decl->ReturnType = CheckUsableType(decl->ReturnType); + + decl->SetCheckState(DeclCheckState::CheckedHeader); + + decl->SetCheckState(DeclCheckState::Checked); + } + + virtual void visitAccessorDecl(AccessorDecl* decl) override + { + // TODO: check the body! + + decl->SetCheckState(DeclCheckState::Checked); + } + + + // + + struct Constraint + { + Decl* decl; // the declaration of the thing being constraints + RefPtr val; // the value to which we are constraining it + bool satisfied = false; // Has this constraint been met? + }; + + // A collection of constraints that will need to be satisified (solved) + // in order for checking to suceed. + struct ConstraintSystem + { + List constraints; + }; + + RefPtr TryJoinVectorAndScalarType( + RefPtr vectorType, + RefPtr scalarType) + { + // Join( vector, S ) -> vetor + // + // That is, the join of a vector and a scalar type is + // a vector type with a joined element type. + auto joinElementType = TryJoinTypes( + vectorType->elementType, + scalarType); + if(!joinElementType) + return nullptr; + + return createVectorType( + joinElementType, + vectorType->elementCount); + } + + bool DoesTypeConformToTrait( + RefPtr type, + TraitDeclRef traitDeclRef) + { + // for now look up a conformance member... + if(auto declRefType = type->As()) + { + if( auto aggTypeDeclRef = declRefType->declRef.As() ) + { + for( auto conformanceRef : aggTypeDeclRef.GetMembersOfType()) + { + EnsureDecl(conformanceRef.GetDecl()); + + if(traitDeclRef.Equals(conformanceRef.GetTraitDeclRef())) + return true; + } + } + } + + // default is failure + return false; + } + + RefPtr TryJoinTypeWithTrait( + RefPtr type, + TraitDeclRef traitDeclRef) + { + // The most basic test here should be: does the type declare conformance to the trait. + if(DoesTypeConformToTrait(type, traitDeclRef)) + return type; + + // There is a more nuanced case if `type` is a builtin type, and we need to make it + // conform to a trait that some but not all builtin types support (the main problem + // here is when an operation wants an integer type, but one of our operands is a `float`. + // The HLSL rules will allow that, with implicit conversion, but our default join rules + // will end up picking `float` and we don't want that...). + + // For now we don't handle the hard case and just bail + return nullptr; + } + + // Try to compute the "join" between two types + RefPtr TryJoinTypes( + RefPtr left, + RefPtr right) + { + // Easy case: they are the same type! + if (left->Equals(right)) + return left; + + // We can join two basic types by picking the "better" of the two + if (auto leftBasic = left->As()) + { + if (auto rightBasic = right->As()) + { + auto leftFlavor = leftBasic->BaseType; + auto rightFlavor = rightBasic->BaseType; + + // TODO(tfoley): Need a special-case rule here that if + // either operand is of type `half`, then we promote + // to at least `float` + + // Return the one that had higher rank... + if (leftFlavor > rightFlavor) + return left; + else + { + assert(rightFlavor > leftFlavor); + return right; + } + } + + // We can also join a vector and a scalar + if(auto rightVector = right->As()) + { + return TryJoinVectorAndScalarType(rightVector, leftBasic); + } + } + + // We can join two vector types by joining their element types + // (and also their sizes...) + if( auto leftVector = left->As()) + { + if(auto rightVector = right->As()) + { + // Check if the vector sizes match + if(!leftVector->elementCount->EqualsVal(rightVector->elementCount.Ptr())) + return nullptr; + + // Try to join the element types + auto joinElementType = TryJoinTypes( + leftVector->elementType, + rightVector->elementType); + if(!joinElementType) + return nullptr; + + return createVectorType( + joinElementType, + leftVector->elementCount); + } + + // We can also join a vector and a scalar + if(auto rightBasic = right->As()) + { + return TryJoinVectorAndScalarType(leftVector, rightBasic); + } + } + + // HACK: trying to work trait types in here... + if(auto leftDeclRefType = left->As()) + { + if( auto leftTraitRef = leftDeclRefType->declRef.As() ) + { + // + return TryJoinTypeWithTrait(right, leftTraitRef); + } + } + if(auto rightDeclRefType = right->As()) + { + if( auto rightTraitRef = rightDeclRefType->declRef.As() ) + { + // + return TryJoinTypeWithTrait(left, rightTraitRef); + } + } + + // TODO: all the cases for vectors apply to matrices too! + + // Default case is that we just fail. + return nullptr; + } + + // Try to solve a system of generic constraints. + // The `system` argument provides the constraints. + // The `varSubst` argument provides the list of constraint + // variables that were created for the system. + // + // Returns a new substitution representing the values that + // we solved for along the way. + RefPtr TrySolveConstraintSystem( + ConstraintSystem* system, + GenericDeclRef genericDeclRef) + { + // For now the "solver" is going to be ridiculously simplistic. + + // The generic itself will have some constraints, so we need to try and solve those too + for( auto constraintDeclRef : genericDeclRef.GetMembersOfType() ) + { + if(!TryUnifyTypes(*system, constraintDeclRef.GetSub(), constraintDeclRef.GetSup())) + return nullptr; + } + + // We will loop over the generic parameters, and for + // each we will try to find a way to satisfy all + // the constraints for that parameter + List> args; + for (auto m : genericDeclRef.GetMembers()) + { + if (auto typeParam = m.As()) + { + RefPtr type = nullptr; + for (auto& c : system->constraints) + { + if (c.decl != typeParam.GetDecl()) + continue; + + auto cType = c.val.As(); + assert(cType.Ptr()); + + if (!type) + { + type = cType; + } + else + { + auto joinType = TryJoinTypes(type, cType); + if (!joinType) + { + // failure! + return nullptr; + } + type = joinType; + } + + c.satisfied = true; + } + + if (!type) + { + // failure! + return nullptr; + } + args.Add(type); + } + else if (auto valParam = m.As()) + { + // TODO(tfoley): maybe support more than integers some day? + // TODO(tfoley): figure out how this needs to interact with + // compile-time integers that aren't just constants... + RefPtr val = nullptr; + for (auto& c : system->constraints) + { + if (c.decl != valParam.GetDecl()) + continue; + + auto cVal = c.val.As(); + assert(cVal.Ptr()); + + if (!val) + { + val = cVal; + } + else + { + if(!val->EqualsVal(cVal.Ptr())) + { + // failure! + return nullptr; + } + } + + c.satisfied = true; + } + + if (!val) + { + // failure! + return nullptr; + } + args.Add(val); + } + else + { + // ignore anything that isn't a generic parameter + } + } + + // Make sure we haven't constructed any spurious constraints + // that we aren't able to satisfy: + for (auto c : system->constraints) + { + if (!c.satisfied) + { + return nullptr; + } + } + + // Consruct a reference to the extension with our constraint variables + // as the + RefPtr solvedSubst = new Substitutions(); + solvedSubst->genericDecl = genericDeclRef.GetDecl(); + solvedSubst->outer = genericDeclRef.substitutions; + solvedSubst->args = args; + + return solvedSubst; + + +#if 0 + List> solvedArgs; + for (auto varArg : varSubst->args) + { + if (auto typeVar = dynamic_cast(varArg.Ptr())) + { + RefPtr type = nullptr; + for (auto& c : system->constraints) + { + if (c.decl != typeVar->declRef.GetDecl()) + continue; + + auto cType = c.val.As(); + assert(cType.Ptr()); + + if (!type) + { + type = cType; + } + else + { + if (!type->Equals(cType)) + { + // failure! + return nullptr; + } + } + + c.satisfied = true; + } + + if (!type) + { + // failure! + return nullptr; + } + solvedArgs.Add(type); + } + else if (auto valueVar = dynamic_cast(varArg.Ptr())) + { + // TODO(tfoley): maybe support more than integers some day? + RefPtr val = nullptr; + for (auto& c : system->constraints) + { + if (c.decl != valueVar->declRef.GetDecl()) + continue; + + auto cVal = c.val.As(); + assert(cVal.Ptr()); + + if (!val) + { + val = cVal; + } + else + { + if (val->value != cVal->value) + { + // failure! + return nullptr; + } + } + + c.satisfied = true; + } + + if (!val) + { + // failure! + return nullptr; + } + solvedArgs.Add(val); + } + else + { + // ignore anything that isn't a generic parameter + } + } + + // Make sure we haven't constructed any spurious constraints + // that we aren't able to satisfy: + for (auto c : system->constraints) + { + if (!c.satisfied) + { + return nullptr; + } + } + + RefPtr newSubst = new Substitutions(); + newSubst->genericDecl = varSubst->genericDecl; + newSubst->outer = varSubst->outer; + newSubst->args = solvedArgs; + return newSubst; + +#endif + } + + // + + struct OverloadCandidate + { + enum class Flavor + { + Func, + Generic, + UnspecializedGeneric, + }; + Flavor flavor; + + enum class Status + { + GenericArgumentInferenceFailed, + Unchecked, + ArityChecked, + FixityChecked, + TypeChecked, + Appicable, + }; + Status status = Status::Unchecked; + + // Reference to the declaration being applied + LookupResultItem item; + + // The type of the result expression if this candidate is selected + RefPtr resultType; + + // A system for tracking constraints introduced on generic parameters + ConstraintSystem constraintSystem; + + // How much conversion cost should be considered for this overload, + // when ranking candidates. + ConversionCost conversionCostSum = kConversionCost_None; + }; + + + + // State related to overload resolution for a call + // to an overloaded symbol + struct OverloadResolveContext + { + enum class Mode + { + // We are just checking if a candidate works or not + JustTrying, + + // We want to actually update the AST for a chosen candidate + ForReal, + }; + + RefPtr appExpr; + RefPtr baseExpr; + + // Are we still trying out candidates, or are we + // checking the chosen one for real? + Mode mode = Mode::JustTrying; + + // We store one candidate directly, so that we don't + // need to do dynamic allocation on the list every time + OverloadCandidate bestCandidateStorage; + OverloadCandidate* bestCandidate = nullptr; + + // Full list of all candidates being considered, in the ambiguous case + List bestCandidates; + }; + + struct ParamCounts + { + int required; + int allowed; + }; + + // count the number of parameters required/allowed for a callable + ParamCounts CountParameters(FilteredMemberRefList params) + { + ParamCounts counts = { 0, 0 }; + for (auto param : params) + { + counts.allowed++; + + // No initializer means no default value + // + // TODO(tfoley): The logic here is currently broken in two ways: + // + // 1. We are assuming that once one parameter has a default, then all do. + // This can/should be validated earlier, so that we can assume it here. + // + // 2. We are not handling the possibility of multiple declarations for + // a single function, where we'd need to merge default parameters across + // all the declarations. + if (!param.GetDecl()->Expr) + { + counts.required++; + } + } + return counts; + } + + // count the number of parameters required/allowed for a generic + ParamCounts CountParameters(GenericDeclRef genericRef) + { + ParamCounts counts = { 0, 0 }; + for (auto m : genericRef.GetDecl()->Members) + { + if (auto typeParam = m.As()) + { + counts.allowed++; + if (!typeParam->initType.Ptr()) + { + counts.required++; + } + } + else if (auto valParam = m.As()) + { + counts.allowed++; + if (!valParam->Expr) + { + counts.required++; + } + } + } + return counts; + } + + bool TryCheckOverloadCandidateArity( + OverloadResolveContext& context, + OverloadCandidate const& candidate) + { + int argCount = context.appExpr->Arguments.Count(); + ParamCounts paramCounts = { 0, 0 }; + switch (candidate.flavor) + { + case OverloadCandidate::Flavor::Func: + paramCounts = CountParameters(candidate.item.declRef.As().GetParameters()); + break; + + case OverloadCandidate::Flavor::Generic: + paramCounts = CountParameters(candidate.item.declRef.As()); + break; + + default: + assert(!"unexpected"); + break; + } + + if (argCount >= paramCounts.required && argCount <= paramCounts.allowed) + return true; + + // Emit an error message if we are checking this call for real + if (context.mode != OverloadResolveContext::Mode::JustTrying) + { + if (argCount < paramCounts.required) + { + getSink()->diagnose(context.appExpr, Diagnostics::notEnoughArguments, argCount, paramCounts.required); + } + else + { + assert(argCount > paramCounts.allowed); + getSink()->diagnose(context.appExpr, Diagnostics::tooManyArguments, argCount, paramCounts.allowed); + } + } + + return false; + } + + bool TryCheckOverloadCandidateFixity( + OverloadResolveContext& context, + OverloadCandidate const& candidate) + { + auto expr = context.appExpr; + + auto decl = candidate.item.declRef.decl; + + if(auto prefixExpr = expr.As()) + { + if(decl->HasModifier()) + return true; + + if (context.mode != OverloadResolveContext::Mode::JustTrying) + { + getSink()->diagnose(context.appExpr, Diagnostics::expectedPrefixOperator); + getSink()->diagnose(decl, Diagnostics::seeDefinitionOf, decl->getName()); + } + + return false; + } + else if(auto postfixExpr = expr.As()) + { + if(decl->HasModifier()) + return true; + + if (context.mode != OverloadResolveContext::Mode::JustTrying) + { + getSink()->diagnose(context.appExpr, Diagnostics::expectedPostfixOperator); + getSink()->diagnose(decl, Diagnostics::seeDefinitionOf, decl->getName()); + } + + return false; + } + else + { + return true; + } + + return false; + } + + bool TryCheckGenericOverloadCandidateTypes( + OverloadResolveContext& context, + OverloadCandidate& candidate) + { + auto& args = context.appExpr->Arguments; + + auto genericDeclRef = candidate.item.declRef.As(); + + int aa = 0; + for (auto memberRef : genericDeclRef.GetMembers()) + { + if (auto typeParamRef = memberRef.As()) + { + auto arg = args[aa++]; + + if (context.mode == OverloadResolveContext::Mode::JustTrying) + { + if (!CanCoerceToProperType(TypeExp(arg))) + { + return false; + } + } + else + { + TypeExp typeExp = CoerceToProperType(TypeExp(arg)); + } + } + else if (auto valParamRef = memberRef.As()) + { + auto arg = args[aa++]; + + if (context.mode == OverloadResolveContext::Mode::JustTrying) + { + ConversionCost cost = kConversionCost_None; + if (!CanCoerce(valParamRef.GetType(), arg->Type, &cost)) + { + return false; + } + candidate.conversionCostSum += cost; + } + else + { + arg = Coerce(valParamRef.GetType(), arg); + auto val = ExtractGenericArgInteger(arg); + } + } + else + { + continue; + } + } + + return true; + } + + bool TryCheckOverloadCandidateTypes( + OverloadResolveContext& context, + OverloadCandidate& candidate) + { + auto& args = context.appExpr->Arguments; + int argCount = args.Count(); + + List params; + switch (candidate.flavor) + { + case OverloadCandidate::Flavor::Func: + params = candidate.item.declRef.As().GetParameters().ToArray(); + break; + + case OverloadCandidate::Flavor::Generic: + return TryCheckGenericOverloadCandidateTypes(context, candidate); + + default: + assert(!"unexpected"); + break; + } + + // Note(tfoley): We might have fewer arguments than parameters in the + // case where one or more parameters had defaults. + assert(argCount <= params.Count()); + + for (int ii = 0; ii < argCount; ++ii) + { + auto& arg = args[ii]; + auto param = params[ii]; + + if (context.mode == OverloadResolveContext::Mode::JustTrying) + { + ConversionCost cost = kConversionCost_None; + if (!CanCoerce(param.GetType(), arg->Type, &cost)) + { + return false; + } + candidate.conversionCostSum += cost; + } + else + { + arg = Coerce(param.GetType(), arg); + } + } + return true; + } + + bool TryCheckOverloadCandidateDirections( + OverloadResolveContext& /*context*/, + OverloadCandidate const& /*candidate*/) + { + // TODO(tfoley): check `in` and `out` markers, as needed. + return true; + } + + // Try to check an overload candidate, but bail out + // if any step fails + void TryCheckOverloadCandidate( + OverloadResolveContext& context, + OverloadCandidate& candidate) + { + if (!TryCheckOverloadCandidateArity(context, candidate)) + return; + + candidate.status = OverloadCandidate::Status::ArityChecked; + if (!TryCheckOverloadCandidateFixity(context, candidate)) + return; + + candidate.status = OverloadCandidate::Status::FixityChecked; + if (!TryCheckOverloadCandidateTypes(context, candidate)) + return; + + candidate.status = OverloadCandidate::Status::TypeChecked; + if (!TryCheckOverloadCandidateDirections(context, candidate)) + return; + + candidate.status = OverloadCandidate::Status::Appicable; + } + + // Create the representation of a given generic applied to some arguments + RefPtr CreateGenericDeclRef( + RefPtr baseExpr, + RefPtr appExpr) + { + auto baseDeclRefExpr = baseExpr.As(); + if (!baseDeclRefExpr) + { + assert(!"unexpected"); + return CreateErrorExpr(appExpr.Ptr()); + } + auto baseGenericRef = baseDeclRefExpr->declRef.As(); + if (!baseGenericRef) + { + assert(!"unexpected"); + return CreateErrorExpr(appExpr.Ptr()); + } + + RefPtr subst = new Substitutions(); + subst->genericDecl = baseGenericRef.GetDecl(); + subst->outer = baseGenericRef.substitutions; + + for (auto arg : appExpr->Arguments) + { + subst->args.Add(ExtractGenericArgVal(arg)); + } + + DeclRef innerDeclRef(baseGenericRef.GetInner(), subst); + + return ConstructDeclRefExpr( + innerDeclRef, + nullptr, + appExpr); + } + + // Take an overload candidate that previously got through + // `TryCheckOverloadCandidate` above, and try to finish + // up the work and turn it into a real expression. + // + // If the candidate isn't actually applicable, this is + // where we'd start reporting the issue(s). + RefPtr CompleteOverloadCandidate( + OverloadResolveContext& context, + OverloadCandidate& candidate) + { + // special case for generic argument inference failure + if (candidate.status == OverloadCandidate::Status::GenericArgumentInferenceFailed) + { + String callString = GetCallSignatureString(context.appExpr); + getSink()->diagnose( + context.appExpr, + Diagnostics::genericArgumentInferenceFailed, + callString); + + String declString = getDeclSignatureString(candidate.item); + getSink()->diagnose(candidate.item.declRef, Diagnostics::genericSignatureTried, declString); + goto error; + } + + context.mode = OverloadResolveContext::Mode::ForReal; + context.appExpr->Type = ExpressionType::Error; + + if (!TryCheckOverloadCandidateArity(context, candidate)) + goto error; + + if (!TryCheckOverloadCandidateFixity(context, candidate)) + goto error; + + if (!TryCheckOverloadCandidateTypes(context, candidate)) + goto error; + + if (!TryCheckOverloadCandidateDirections(context, candidate)) + goto error; + + { + auto baseExpr = ConstructLookupResultExpr( + candidate.item, context.baseExpr, context.appExpr->FunctionExpr); + + switch(candidate.flavor) + { + case OverloadCandidate::Flavor::Func: + context.appExpr->FunctionExpr = baseExpr; + context.appExpr->Type = candidate.resultType; + + // A call may yield an l-value, and we should take a look at the candidate to be sure + if(auto subscriptDeclRef = candidate.item.declRef.As()) + { + for(auto setter : subscriptDeclRef.GetDecl()->GetMembersOfType()) + { + context.appExpr->Type.IsLeftValue = true; + } + } + + // TODO: there may be other cases that confer l-value-ness + + return context.appExpr; + break; + + case OverloadCandidate::Flavor::Generic: + return CreateGenericDeclRef(baseExpr, context.appExpr); + break; + + default: + assert(!"unexpected"); + break; + } + } + + + error: + return CreateErrorExpr(context.appExpr.Ptr()); + } + + // Implement a comparison operation between overload candidates, + // so that the better candidate compares as less-than the other + int CompareOverloadCandidates( + OverloadCandidate* left, + OverloadCandidate* right) + { + // If one candidate got further along in validation, pick it + if (left->status != right->status) + return int(right->status) - int(left->status); + + // If both candidates are applicable, then we need to compare + // the costs of their type conversion sequences + if(left->status == OverloadCandidate::Status::Appicable) + { + if (left->conversionCostSum != right->conversionCostSum) + return left->conversionCostSum - right->conversionCostSum; + } + + return 0; + } + + void AddOverloadCandidateInner( + OverloadResolveContext& context, + OverloadCandidate& candidate) + { + // Filter our existing candidates, to remove any that are worse than our new one + + bool keepThisCandidate = true; // should this candidate be kept? + + if (context.bestCandidates.Count() != 0) + { + // We have multiple candidates right now, so filter them. + bool anyFiltered = false; + // Note that we are querying the list length on every iteration, + // because we might remove things. + for (int cc = 0; cc < context.bestCandidates.Count(); ++cc) + { + int cmp = CompareOverloadCandidates(&candidate, &context.bestCandidates[cc]); + if (cmp < 0) + { + // our new candidate is better! + + // remove it from the list (by swapping in a later one) + context.bestCandidates.FastRemoveAt(cc); + // and then reduce our index so that we re-visit the same index + --cc; + + anyFiltered = true; + } + else if(cmp > 0) + { + // our candidate is worse! + keepThisCandidate = false; + } + } + // It should not be possible that we removed some existing candidate *and* + // chose not to keep this candidate (otherwise the better-ness relation + // isn't transitive). Therefore we confirm that we either chose to keep + // this candidate (in which case filtering is okay), or we didn't filter + // anything. + assert(keepThisCandidate || !anyFiltered); + } + else if(context.bestCandidate) + { + // There's only one candidate so far + int cmp = CompareOverloadCandidates(&candidate, context.bestCandidate); + if(cmp < 0) + { + // our new candidate is better! + context.bestCandidate = nullptr; + } + else if (cmp > 0) + { + // our candidate is worse! + keepThisCandidate = false; + } + } + + // If our candidate isn't good enough, then drop it + if (!keepThisCandidate) + return; + + // Otherwise we want to keep the candidate + if (context.bestCandidates.Count() > 0) + { + // There were already multiple candidates, and we are adding one more + context.bestCandidates.Add(candidate); + } + else if (context.bestCandidate) + { + // There was a unique best candidate, but now we are ambiguous + context.bestCandidates.Add(*context.bestCandidate); + context.bestCandidates.Add(candidate); + context.bestCandidate = nullptr; + } + else + { + // This is the only candidate worthe keeping track of right now + context.bestCandidateStorage = candidate; + context.bestCandidate = &context.bestCandidateStorage; + } + } + + void AddOverloadCandidate( + OverloadResolveContext& context, + OverloadCandidate& candidate) + { + // Try the candidate out, to see if it is applicable at all. + TryCheckOverloadCandidate(context, candidate); + + // Now (potentially) add it to the set of candidate overloads to consider. + AddOverloadCandidateInner(context, candidate); + } + + void AddFuncOverloadCandidate( + LookupResultItem item, + CallableDeclRef funcDeclRef, + OverloadResolveContext& context) + { + EnsureDecl(funcDeclRef.GetDecl()); + + OverloadCandidate candidate; + candidate.flavor = OverloadCandidate::Flavor::Func; + candidate.item = item; + candidate.resultType = funcDeclRef.GetResultType(); + + AddOverloadCandidate(context, candidate); + } + + void AddFuncOverloadCandidate( + RefPtr /*funcType*/, + OverloadResolveContext& /*context*/) + { +#if 0 + if (funcType->decl) + { + AddFuncOverloadCandidate(funcType->decl, context); + } + else if (funcType->Func) + { + AddFuncOverloadCandidate(funcType->Func->SyntaxNode, context); + } + else if (funcType->Component) + { + AddComponentFuncOverloadCandidate(funcType->Component, context); + } +#else + throw "unimplemented"; +#endif + } + + void AddCtorOverloadCandidate( + LookupResultItem typeItem, + RefPtr type, + ConstructorDeclRef ctorDeclRef, + OverloadResolveContext& context) + { + EnsureDecl(ctorDeclRef.GetDecl()); + + // `typeItem` refers to the type being constructed (the thing + // that was applied as a function) so we need to construct + // a `LookupResultItem` that refers to the constructor instead + + LookupResultItem ctorItem; + ctorItem.declRef = ctorDeclRef; + ctorItem.breadcrumbs = new LookupResultItem::Breadcrumb(LookupResultItem::Breadcrumb::Kind::Member, typeItem.declRef, typeItem.breadcrumbs); + + OverloadCandidate candidate; + candidate.flavor = OverloadCandidate::Flavor::Func; + candidate.item = ctorItem; + candidate.resultType = type; + + AddOverloadCandidate(context, candidate); + } + + // If the given declaration has generic parameters, then + // return the corresponding `GenericDecl` that holds the + // parameters, etc. + GenericDecl* GetOuterGeneric(Decl* decl) + { + auto parentDecl = decl->ParentDecl; + if (!parentDecl) return nullptr; + auto parentGeneric = dynamic_cast(parentDecl); + return parentGeneric; + } + + // Try to find a unification for two values + bool TryUnifyVals( + ConstraintSystem& constraints, + RefPtr fst, + RefPtr snd) + { + // if both values are types, then unify types + if (auto fstType = fst.As()) + { + if (auto sndType = snd.As()) + { + return TryUnifyTypes(constraints, fstType, sndType); + } + } + + // if both values are constant integers, then compare them + if (auto fstIntVal = fst.As()) + { + if (auto sndIntVal = snd.As()) + { + return fstIntVal->value == sndIntVal->value; + } + } + + // Check if both are integer values in general + if (auto fstInt = fst.As()) + { + if (auto sndInt = snd.As()) + { + auto fstParam = fstInt.As(); + auto sndParam = sndInt.As(); + + if (fstParam) + TryUnifyIntParam(constraints, fstParam->declRef, sndInt); + if (sndParam) + TryUnifyIntParam(constraints, sndParam->declRef, fstInt); + + if (fstParam || sndParam) + return true; + } + } + + throw "unimplemented"; + + // default: fail + return false; + } + + bool TryUnifySubstitutions( + ConstraintSystem& constraints, + RefPtr fst, + RefPtr snd) + { + // They must both be NULL or non-NULL + if (!fst || !snd) + return fst == snd; + + // They must be specializing the same generic + if (fst->genericDecl != snd->genericDecl) + return false; + + // Their arguments must unify + assert(fst->args.Count() == snd->args.Count()); + int argCount = fst->args.Count(); + for (int aa = 0; aa < argCount; ++aa) + { + if (!TryUnifyVals(constraints, fst->args[aa], snd->args[aa])) + return false; + } + + // Their "base" specializations must unify + if (!TryUnifySubstitutions(constraints, fst->outer, snd->outer)) + return false; + + return true; + } + + bool TryUnifyTypeParam( + ConstraintSystem& constraints, + RefPtr typeParamDecl, + RefPtr type) + { + // We want to constrain the given type parameter + // to equal the given type. + Constraint constraint; + constraint.decl = typeParamDecl.Ptr(); + constraint.val = type; + + constraints.constraints.Add(constraint); + + return true; + } + + bool TryUnifyIntParam( + ConstraintSystem& constraints, + RefPtr paramDecl, + RefPtr val) + { + // We want to constrain the given parameter to equal the given value. + Constraint constraint; + constraint.decl = paramDecl.Ptr(); + constraint.val = val; + + constraints.constraints.Add(constraint); + + return true; + } + + bool TryUnifyIntParam( + ConstraintSystem& constraints, + VarDeclBaseRef const& varRef, + RefPtr val) + { + if(auto genericValueParamRef = varRef.As()) + { + return TryUnifyIntParam(constraints, genericValueParamRef.GetDecl(), val); + } + else + { + return false; + } + } + + bool TryUnifyTypesByStructuralMatch( + ConstraintSystem& constraints, + RefPtr fst, + RefPtr snd) + { + if (auto fstDeclRefType = fst->As()) + { + auto fstDeclRef = fstDeclRefType->declRef; + + if (auto typeParamDecl = dynamic_cast(fstDeclRef.GetDecl())) + return TryUnifyTypeParam(constraints, typeParamDecl, snd); + + if (auto sndDeclRefType = snd->As()) + { + auto sndDeclRef = sndDeclRefType->declRef; + + if (auto typeParamDecl = dynamic_cast(sndDeclRef.GetDecl())) + return TryUnifyTypeParam(constraints, typeParamDecl, fst); + + // can't be unified if they refer to differnt declarations. + if (fstDeclRef.GetDecl() != sndDeclRef.GetDecl()) return false; + + // next we need to unify the substitutions applied + // to each decalration reference. + if (!TryUnifySubstitutions( + constraints, + fstDeclRef.substitutions, + sndDeclRef.substitutions)) + { + return false; + } + + return true; + } + } + + return false; + } + + bool TryUnifyTypes( + ConstraintSystem& constraints, + RefPtr fst, + RefPtr snd) + { + if (fst->Equals(snd)) return true; + + // An error type can unify with anything, just so we avoid cascading errors. + + if (auto fstErrorType = fst->As()) + return true; + + if (auto sndErrorType = snd->As()) + return true; + + // A generic parameter type can unify with anything. + // TODO: there actually needs to be some kind of "occurs check" sort + // of thing here... + + if (auto fstDeclRefType = fst->As()) + { + auto fstDeclRef = fstDeclRefType->declRef; + + if (auto typeParamDecl = dynamic_cast(fstDeclRef.GetDecl())) + return TryUnifyTypeParam(constraints, typeParamDecl, snd); + } + + if (auto sndDeclRefType = snd->As()) + { + auto sndDeclRef = sndDeclRefType->declRef; + + if (auto typeParamDecl = dynamic_cast(sndDeclRef.GetDecl())) + return TryUnifyTypeParam(constraints, typeParamDecl, fst); + } + + // If we can unify the types structurally, then we are golden + if(TryUnifyTypesByStructuralMatch(constraints, fst, snd)) + return true; + + // Now we need to consider cases where coercion might + // need to be applied. For now we can try to do this + // in a completely ad hoc fashion, but eventually we'd + // want to do it more formally. + + if(auto fstVectorType = fst->As()) + { + if(auto sndScalarType = snd->As()) + { + return TryUnifyTypes( + constraints, + fstVectorType->elementType, + sndScalarType); + } + } + + if(auto fstScalarType = fst->As()) + { + if(auto sndVectorType = snd->As()) + { + return TryUnifyTypes( + constraints, + fstScalarType, + sndVectorType->elementType); + } + } + + // TODO: the same thing for vectors... + + return false; + } + + // Is the candidate extension declaration actually applicable to the given type + ExtensionDeclRef ApplyExtensionToType( + ExtensionDecl* extDecl, + RefPtr type) + { + if (auto extGenericDecl = GetOuterGeneric(extDecl)) + { + ConstraintSystem constraints; + + if (!TryUnifyTypes(constraints, extDecl->targetType, type)) + return DeclRef().As(); + + auto constraintSubst = TrySolveConstraintSystem(&constraints, DeclRef(extGenericDecl, nullptr).As()); + if (!constraintSubst) + { + return DeclRef().As(); + } + + // Consruct a reference to the extension with our constraint variables + // set as they were found by solving the constraint system. + ExtensionDeclRef extDeclRef = DeclRef(extDecl, constraintSubst).As(); + + // We expect/require that the result of unification is such that + // the target types are now equal + assert(extDeclRef.GetTargetType()->Equals(type)); + + return extDeclRef; + } + else + { + // The easy case is when the extension isn't generic: + // either it applies to the type or not. + if (!type->Equals(extDecl->targetType)) + return DeclRef().As(); + return DeclRef(extDecl, nullptr).As(); + } + } + + bool TryUnifyArgAndParamTypes( + ConstraintSystem& system, + RefPtr argExpr, + ParamDeclRef paramDeclRef) + { + // TODO(tfoley): potentially need a bit more + // nuance in case where argument might be + // an overload group... + return TryUnifyTypes(system, argExpr->Type, paramDeclRef.GetType()); + } + + // Take a generic declaration and try to specialize its parameters + // so that the resulting inner declaration can be applicable in + // a particular context... + DeclRef SpecializeGenericForOverload( + GenericDeclRef genericDeclRef, + OverloadResolveContext& context) + { + ConstraintSystem constraints; + + // Construct a reference to the inner declaration that has any generic + // parameter substitutions in place already, but *not* any substutions + // for the generic declaration we are currently trying to infer. + auto innerDecl = genericDeclRef.GetInner(); + DeclRef unspecializedInnerRef = DeclRef(innerDecl, genericDeclRef.substitutions); + + // Check what type of declaration we are dealing with, and then try + // to match it up with the arguments accordingly... + if (auto funcDeclRef = unspecializedInnerRef.As()) + { + auto& args = context.appExpr->Arguments; + auto params = funcDeclRef.GetParameters().ToArray(); + + int argCount = args.Count(); + int paramCount = params.Count(); + + // Bail out on mismatch. + // TODO(tfoley): need more nuance here + if (argCount != paramCount) + { + return DeclRef(nullptr, nullptr); + } + + for (int aa = 0; aa < argCount; ++aa) + { +#if 0 + if (!TryUnifyArgAndParamTypes(constraints, args[aa], params[aa])) + return DeclRef(nullptr, nullptr); +#else + // The question here is whether failure to "unify" an argument + // and parameter should lead to immediate failure. + // + // The case that is interesting is if we want to unify, say: + // `vector` and `vector` + // + // It is clear that we should solve with `N = 3`, and then + // a later step may find that the resulting types aren't + // actually a match. + // + // A more refined approach to "unification" could of course + // see that `int` can convert to `float` and use that fact. + // (and indeed we already use something like this to unify + // `float` and `vector`) + // + // So the question is then whether a mismatch during the + // unification step should be taken as an immediate failure... + + TryUnifyArgAndParamTypes(constraints, args[aa], params[aa]); +#endif + } + } + else + { + // TODO(tfoley): any other cases needed here? + return DeclRef(nullptr, nullptr); + } + + auto constraintSubst = TrySolveConstraintSystem(&constraints, genericDeclRef); + if (!constraintSubst) + { + // constraint solving failed + return DeclRef(nullptr, nullptr); + } + + // We can now construct a reference to the inner declaration using + // the solution to our constraints. + return DeclRef(innerDecl, constraintSubst); + } + + void AddAggTypeOverloadCandidates( + LookupResultItem typeItem, + RefPtr type, + AggTypeDeclRef aggTypeDeclRef, + OverloadResolveContext& context) + { + for (auto ctorDeclRef : aggTypeDeclRef.GetMembersOfType()) + { + // now work through this candidate... + AddCtorOverloadCandidate(typeItem, type, ctorDeclRef, context); + } + + // Now walk through any extensions we can find for this types + for (auto ext = aggTypeDeclRef.GetCandidateExtensions(); ext; ext = ext->nextCandidateExtension) + { + auto extDeclRef = ApplyExtensionToType(ext, type); + if (!extDeclRef) + continue; + + for (auto ctorDeclRef : extDeclRef.GetMembersOfType()) + { + // TODO(tfoley): `typeItem` here should really reference the extension... + + // now work through this candidate... + AddCtorOverloadCandidate(typeItem, type, ctorDeclRef, context); + } + + // Also check for generic constructors + for (auto genericDeclRef : extDeclRef.GetMembersOfType()) + { + if (auto ctorDecl = genericDeclRef.GetDecl()->inner.As()) + { + DeclRef innerRef = SpecializeGenericForOverload(genericDeclRef, context); + if (!innerRef) + continue; + + ConstructorDeclRef innerCtorRef = innerRef.As(); + + AddCtorOverloadCandidate(typeItem, type, innerCtorRef, context); + + // TODO(tfoley): need a way to do the solving step for the constraint system + } + } + } + } + + void AddTypeOverloadCandidates( + RefPtr type, + OverloadResolveContext& context) + { + if (auto declRefType = type->As()) + { + if (auto aggTypeDeclRef = declRefType->declRef.As()) + { + AddAggTypeOverloadCandidates(LookupResultItem(aggTypeDeclRef), type, aggTypeDeclRef, context); + } + } + } + + void AddDeclRefOverloadCandidates( + LookupResultItem item, + OverloadResolveContext& context) + { + auto declRef = item.declRef; + + if (auto funcDeclRef = item.declRef.As()) + { + AddFuncOverloadCandidate(item, funcDeclRef, context); + } + else if (auto aggTypeDeclRef = item.declRef.As()) + { + auto type = DeclRefType::Create(aggTypeDeclRef); + AddAggTypeOverloadCandidates(item, type, aggTypeDeclRef, context); + } + else if (auto genericDeclRef = item.declRef.As()) + { + // Try to infer generic arguments, based on the context + DeclRef innerRef = SpecializeGenericForOverload(genericDeclRef, context); + + if (innerRef) + { + // If inference works, then we've now got a + // specialized declaration reference we can apply. + + LookupResultItem innerItem; + innerItem.breadcrumbs = item.breadcrumbs; + innerItem.declRef = innerRef; + + AddDeclRefOverloadCandidates(innerItem, context); + } + else + { + // If inference failed, then we need to create + // a candidate that can be used to reflect that fact + // (so we can report a good error) + OverloadCandidate candidate; + candidate.item = item; + candidate.flavor = OverloadCandidate::Flavor::UnspecializedGeneric; + candidate.status = OverloadCandidate::Status::GenericArgumentInferenceFailed; + + AddOverloadCandidateInner(context, candidate); + } + } + else if( auto typeDefDeclRef = item.declRef.As() ) + { + AddTypeOverloadCandidates(typeDefDeclRef.GetType(), context); + } + else + { + // TODO(tfoley): any other cases needed here? + } + } + + void AddOverloadCandidates( + RefPtr funcExpr, + OverloadResolveContext& context) + { + auto funcExprType = funcExpr->Type; + + if (auto funcDeclRefExpr = funcExpr.As()) + { + // The expression referenced a function declaration + AddDeclRefOverloadCandidates(LookupResultItem(funcDeclRefExpr->declRef), context); + } + else if (auto funcType = funcExprType->As()) + { + // TODO(tfoley): deprecate this path... + AddFuncOverloadCandidate(funcType, context); + } + else if (auto overloadedExpr = funcExpr.As()) + { + auto lookupResult = overloadedExpr->lookupResult2; + assert(lookupResult.isOverloaded()); + for(auto item : lookupResult.items) + { + AddDeclRefOverloadCandidates(item, context); + } + } + else if (auto typeType = funcExprType->As()) + { + // If none of the above cases matched, but we are + // looking at a type, then I suppose we have + // a constructor call on our hands. + // + // TODO(tfoley): are there any meaningful types left + // that aren't declaration references? + AddTypeOverloadCandidates(typeType->type, context); + return; + } + } + + void formatType(StringBuilder& sb, RefPtr type) + { + sb << type->ToString(); + } + + void formatVal(StringBuilder& sb, RefPtr val) + { + sb << val->ToString(); + } + + void formatDeclPath(StringBuilder& sb, DeclRef declRef) + { + // Find the parent declaration + auto parentDeclRef = declRef.GetParent(); + + // If the immediate parent is a generic, then we probably + // want the declaration above that... + auto parentGenericDeclRef = parentDeclRef.As(); + if(parentGenericDeclRef) + { + parentDeclRef = parentGenericDeclRef.GetParent(); + } + + // Depending on what the parent is, we may want to format things specially + if(auto aggTypeDeclRef = parentDeclRef.As()) + { + formatDeclPath(sb, aggTypeDeclRef); + sb << "."; + } + + sb << declRef.GetName(); + + // If the parent declaration is a generic, then we need to print out its + // signature + if( parentGenericDeclRef ) + { + assert(declRef.substitutions); + assert(declRef.substitutions->genericDecl == parentGenericDeclRef.GetDecl()); + + sb << "<"; + bool first = true; + for(auto arg : declRef.substitutions->args) + { + if(!first) sb << ", "; + formatVal(sb, arg); + first = false; + } + sb << ">"; + } + } + + void formatDeclParams(StringBuilder& sb, DeclRef declRef) + { + if (auto funcDeclRef = declRef.As()) + { + + // This is something callable, so we need to also print parameter types for overloading + sb << "("; + + bool first = true; + for (auto paramDeclRef : funcDeclRef.GetParameters()) + { + if (!first) sb << ", "; + + formatType(sb, paramDeclRef.GetType()); + + first = false; + + } + + sb << ")"; + } + else if(auto genericDeclRef = declRef.As()) + { + sb << "<"; + bool first = true; + for (auto paramDeclRef : genericDeclRef.GetMembers()) + { + if(auto genericTypeParam = paramDeclRef.As()) + { + if (!first) sb << ", "; + first = false; + + sb << genericTypeParam.GetName(); + } + else if(auto genericValParam = paramDeclRef.As()) + { + if (!first) sb << ", "; + first = false; + + formatType(sb, genericValParam.GetType()); + sb << " "; + sb << genericValParam.GetName(); + } + else + {} + } + sb << ">"; + + formatDeclParams(sb, DeclRef(genericDeclRef.GetInner(), genericDeclRef.substitutions)); + } + else + { + } + } + + void formatDeclSignature(StringBuilder& sb, DeclRef declRef) + { + formatDeclPath(sb, declRef); + formatDeclParams(sb, declRef); + } + + String getDeclSignatureString(DeclRef declRef) + { + StringBuilder sb; + formatDeclSignature(sb, declRef); + return sb.ProduceString(); + } + + String getDeclSignatureString(LookupResultItem item) + { + return getDeclSignatureString(item.declRef); + } + + String GetCallSignatureString(RefPtr expr) + { + StringBuilder argsListBuilder; + argsListBuilder << "("; + bool first = true; + for (auto a : expr->Arguments) + { + if (!first) argsListBuilder << ", "; + argsListBuilder << a->Type->ToString(); + first = false; + } + argsListBuilder << ")"; + return argsListBuilder.ProduceString(); + } + + + RefPtr ResolveInvoke(InvokeExpressionSyntaxNode * expr) + { + // Look at the base expression for the call, and figure out how to invoke it. + auto funcExpr = expr->FunctionExpr; + auto funcExprType = funcExpr->Type; + + // If we are trying to apply an erroroneous expression, then just bail out now. + if(IsErrorExpr(funcExpr)) + { + return CreateErrorExpr(expr); + } + + OverloadResolveContext context; + context.appExpr = expr; + if (auto funcMemberExpr = funcExpr.As()) + { + context.baseExpr = funcMemberExpr->BaseExpression; + } + else if (auto funcOverloadExpr = funcExpr.As()) + { + context.baseExpr = funcOverloadExpr->base; + } + AddOverloadCandidates(funcExpr, context); + + if (context.bestCandidates.Count() > 0) + { + // Things were ambiguous. + + // It might be that things were only ambiguous because + // one of the argument expressions had an error, and + // so a bunch of candidates could match at that position. + // + // If any argument was an error, we skip out on printing + // another message, to avoid cascading errors. + for (auto arg : expr->Arguments) + { + if (IsErrorExpr(arg)) + { + return CreateErrorExpr(expr); + } + } + + String funcName; + if (auto baseVar = funcExpr.As()) + funcName = baseVar->Variable; + else if(auto baseMemberRef = funcExpr.As()) + funcName = baseMemberRef->MemberName; + + String argsList = GetCallSignatureString(expr); + + if (context.bestCandidates[0].status != OverloadCandidate::Status::Appicable) + { + // There were multple equally-good candidates, but none actually usable. + // We will construct a diagnostic message to help out. + if (funcName.Length() != 0) + { + getSink()->diagnose(expr, Diagnostics::noApplicableOverloadForNameWithArgs, funcName, argsList); + } + else + { + getSink()->diagnose(expr, Diagnostics::noApplicableWithArgs, argsList); + } + } + else + { + // There were multiple applicable candidates, so we need to report them. + + if (funcName.Length() != 0) + { + getSink()->diagnose(expr, Diagnostics::ambiguousOverloadForNameWithArgs, funcName, argsList); + } + else + { + getSink()->diagnose(expr, Diagnostics::ambiguousOverloadWithArgs, argsList); + } + } + + int candidateCount = context.bestCandidates.Count(); + int maxCandidatesToPrint = 10; // don't show too many candidates at once... + int candidateIndex = 0; + for (auto candidate : context.bestCandidates) + { + String declString = getDeclSignatureString(candidate.item); + + declString = declString + "[" + String(candidate.conversionCostSum) + "]"; + + getSink()->diagnose(candidate.item.declRef, Diagnostics::overloadCandidate, declString); + + candidateIndex++; + if (candidateIndex == maxCandidatesToPrint) + break; + } + if (candidateIndex != candidateCount) + { + getSink()->diagnose(expr, Diagnostics::moreOverloadCandidates, candidateCount - candidateIndex); + } + + return CreateErrorExpr(expr); + } + else if (context.bestCandidate) + { + // There was one best candidate, even if it might not have been + // applicable in the end. + // We will report errors for this one candidate, then, to give + // the user the most help we can. + return CompleteOverloadCandidate(context, *context.bestCandidate); + } + else + { + // Nothing at all was found that we could even consider invoking + getSink()->diagnose(expr->FunctionExpr, Diagnostics::expectedFunction); + expr->Type = ExpressionType::Error; + return expr; + } + } + + void AddGenericOverloadCandidate( + LookupResultItem baseItem, + OverloadResolveContext& context) + { + if (auto genericDeclRef = baseItem.declRef.As()) + { + EnsureDecl(genericDeclRef.GetDecl()); + + OverloadCandidate candidate; + candidate.flavor = OverloadCandidate::Flavor::Generic; + candidate.item = baseItem; + candidate.resultType = nullptr; + + AddOverloadCandidate(context, candidate); + } + } + + void AddGenericOverloadCandidates( + RefPtr baseExpr, + OverloadResolveContext& context) + { + if(auto baseDeclRefExpr = baseExpr.As()) + { + auto declRef = baseDeclRefExpr->declRef; + AddGenericOverloadCandidate(LookupResultItem(declRef), context); + } + else if (auto overloadedExpr = baseExpr.As()) + { + // We are referring to a bunch of declarations, each of which might be generic + LookupResult result; + for (auto item : overloadedExpr->lookupResult2.items) + { + AddGenericOverloadCandidate(item, context); + } + } + else + { + // any other cases? + } + } + + RefPtr VisitGenericApp(GenericAppExpr * genericAppExpr) override + { + // We are applying a generic to arguments, but there might be multiple generic + // declarations with the same name, so this becomes a specialized case of + // overload resolution. + + + // Start by checking the base expression and arguments. + auto& baseExpr = genericAppExpr->FunctionExpr; + baseExpr = CheckTerm(baseExpr); + auto& args = genericAppExpr->Arguments; + for (auto& arg : args) + { + arg = CheckTerm(arg); + } + + // If there was an error in the base expression, or in any of + // the arguments, then just bail. + if (IsErrorExpr(baseExpr)) + { + return CreateErrorExpr(genericAppExpr); + } + for (auto argExpr : args) + { + if (IsErrorExpr(argExpr)) + { + return CreateErrorExpr(genericAppExpr); + } + } + + // Otherwise, let's start looking at how to find an overload... + + OverloadResolveContext context; + context.appExpr = genericAppExpr; + context.baseExpr = GetBaseExpr(baseExpr); + + AddGenericOverloadCandidates(baseExpr, context); + + if (context.bestCandidates.Count() > 0) + { + // Things were ambiguous. + if (context.bestCandidates[0].status != OverloadCandidate::Status::Appicable) + { + // There were multple equally-good candidates, but none actually usable. + // We will construct a diagnostic message to help out. + + // TODO(tfoley): print a reasonable message here... + + getSink()->diagnose(genericAppExpr, Diagnostics::unimplemented, "no applicable generic"); + + return CreateErrorExpr(genericAppExpr); + } + else + { + // There were multiple viable candidates, but that isn't an error: we just need + // to complete all of them and create an overloaded expression as a result. + + LookupResult result; + for (auto candidate : context.bestCandidates) + { + auto candidateExpr = CompleteOverloadCandidate(context, candidate); + } + + throw "what now?"; +// auto overloadedExpr = new OverloadedExpr(); +// return overloadedExpr; + } + } + else if (context.bestCandidate) + { + // There was one best candidate, even if it might not have been + // applicable in the end. + // We will report errors for this one candidate, then, to give + // the user the most help we can. + return CompleteOverloadCandidate(context, *context.bestCandidate); + } + else + { + // Nothing at all was found that we could even consider invoking + getSink()->diagnose(genericAppExpr, Diagnostics::unimplemented, "expected a generic"); + return CreateErrorExpr(genericAppExpr); + } + + +#if TIMREMOVED + + if (IsErrorExpr(base)) + { + return CreateErrorExpr(typeNode); + } + else if(auto baseDeclRefExpr = base.As()) + { + auto declRef = baseDeclRefExpr->declRef; + + if (auto genericDeclRef = declRef.As()) + { + int argCount = typeNode->Args.Count(); + int argIndex = 0; + for (RefPtr member : genericDeclRef.GetDecl()->Members) + { + if (auto typeParam = member.As()) + { + if (argIndex == argCount) + { + // Too few arguments! + + } + + // TODO: checking! + } + else if (auto valParam = member.As()) + { + // TODO: checking + } + else + { + + } + } + if (argIndex != argCount) + { + // Too many arguments! + } + + // Now instantiate the declaration given those arguments + auto type = InstantiateGenericType(genericDeclRef, args); + typeResult = type; + typeNode->Type = new TypeExpressionType(type); + return typeNode; + } + } + else if (auto overloadedExpr = base.As()) + { + // We are referring to a bunch of declarations, each of which might be generic + LookupResult result; + for (auto item : overloadedExpr->lookupResult2.items) + { + auto applied = TryApplyGeneric(item, typeNode); + if (!applied) + continue; + + AddToLookupResult(result, appliedItem); + } + } + + // TODO: correct diagnostic here! + getSink()->diagnose(typeNode, Diagnostics::expectedAGeneric, base->Type); + return CreateErrorExpr(typeNode); +#endif + } + + RefPtr VisitSharedTypeExpr(SharedTypeExpr* expr) override + { + if (!expr->Type.Ptr()) + { + expr->base = CheckProperType(expr->base); + expr->Type = expr->base.exp->Type; + } + return expr; + } + + + + + RefPtr CheckExpr(RefPtr expr) + { + return expr->Accept(this).As(); + } + + RefPtr CheckInvokeExprWithCheckedOperands(InvokeExpressionSyntaxNode *expr) + { + + auto rs = ResolveInvoke(expr); + if (auto invoke = dynamic_cast(rs.Ptr())) + { + // if this is still an invoke expression, test arguments passed to inout/out parameter are LValues + if(auto funcType = invoke->FunctionExpr->Type->As()) + { + List> paramsStorage; + List> * params = nullptr; + if (auto func = funcType->declRef.GetDecl()) + { + paramsStorage = func->GetParameters().ToArray(); + params = ¶msStorage; + } + if (params) + { + for (int i = 0; i < (*params).Count(); i++) + { + if ((*params)[i]->HasModifier()) + { + if (i < expr->Arguments.Count() && expr->Arguments[i]->Type->AsBasicType() && + !expr->Arguments[i]->Type.IsLeftValue) + { + getSink()->diagnose(expr->Arguments[i], Diagnostics::argumentExpectedLValue, (*params)[i]->Name); + } + } + } + } + } + } + return rs; + } + + virtual RefPtr VisitInvokeExpression(InvokeExpressionSyntaxNode *expr) override + { + // check the base expression first + expr->FunctionExpr = CheckExpr(expr->FunctionExpr); + + // Next check the argument expressions + for (auto & arg : expr->Arguments) + { + arg = CheckExpr(arg); + } + + return CheckInvokeExprWithCheckedOperands(expr); + } + + + virtual RefPtr VisitVarExpression(VarExpressionSyntaxNode *expr) override + { + // If we've already resolved this expression, don't try again. + if (expr->declRef) + return expr; + + expr->Type = ExpressionType::Error; + + auto lookupResult = LookUp(expr->Variable, expr->scope); + if (lookupResult.isValid()) + { + return createLookupResultExpr( + lookupResult, + nullptr, + expr); + } + + getSink()->diagnose(expr, Diagnostics::undefinedIdentifier2, expr->Variable); + + return expr; + } + virtual RefPtr VisitTypeCastExpression(TypeCastExpressionSyntaxNode * expr) override + { + expr->Expression = expr->Expression->Accept(this).As(); + auto targetType = CheckProperType(expr->TargetType); + expr->TargetType = targetType; + + // The way to perform casting depends on the types involved + if (expr->Expression->Type->Equals(ExpressionType::Error.Ptr())) + { + // If the expression being casted has an error type, then just silently succeed + expr->Type = targetType; + return expr; + } + else if (auto targetArithType = targetType->AsArithmeticType()) + { + if (auto exprArithType = expr->Expression->Type->AsArithmeticType()) + { + // Both source and destination types are arithmetic, so we might + // have a valid cast + auto targetScalarType = targetArithType->GetScalarType(); + auto exprScalarType = exprArithType->GetScalarType(); + + if (!IsNumeric(exprScalarType->BaseType)) goto fail; + if (!IsNumeric(targetScalarType->BaseType)) goto fail; + + // TODO(tfoley): this checking is incomplete here, and could + // lead to downstream compilation failures + expr->Type = targetType; + return expr; + } + } + + fail: + // Default: in no other case succeds, then the cast failed and we emit a diagnostic. + getSink()->diagnose(expr, Diagnostics::invalidTypeCast, expr->Expression->Type, targetType->ToString()); + expr->Type = ExpressionType::Error; + return expr; + } +#if TIMREMOVED + virtual RefPtr VisitSelectExpression(SelectExpressionSyntaxNode * expr) override + { + auto selectorExpr = expr->SelectorExpr; + selectorExpr = CheckExpr(selectorExpr); + selectorExpr = Coerce(ExpressionType::GetBool(), selectorExpr); + expr->SelectorExpr = selectorExpr; + + // TODO(tfoley): We need a general purpose "join" on types for inferring + // generic argument types for builtins/intrinsics, so this should really + // be using the exact same logic... + // + expr->Expr0 = expr->Expr0->Accept(this).As(); + expr->Expr1 = expr->Expr1->Accept(this).As(); + if (!expr->Expr0->Type->Equals(expr->Expr1->Type.Ptr())) + { + getSink()->diagnose(expr, Diagnostics::selectValuesTypeMismatch); + } + expr->Type = expr->Expr0->Type; + return expr; + } +#endif + + // Get the type to use when referencing a declaration + QualType GetTypeForDeclRef(DeclRef declRef) + { + return getTypeForDeclRef( + this, + getSink(), + declRef, + &typeResult); + } + + RefPtr MaybeDereference(RefPtr inExpr) + { + RefPtr expr = inExpr; + for (;;) + { + auto& type = expr->Type; + if (auto pointerLikeType = type->As()) + { + type = pointerLikeType->elementType; + + auto derefExpr = new DerefExpr(); + derefExpr->base = expr; + derefExpr->Type = pointerLikeType->elementType; + + // TODO(tfoley): deal with l-value-ness here + + expr = derefExpr; + continue; + } + + // Default case: just use the expression as-is + return expr; + } + } + + RefPtr CheckSwizzleExpr( + MemberExpressionSyntaxNode* memberRefExpr, + RefPtr baseElementType, + int baseElementCount) + { + RefPtr swizExpr = new SwizzleExpr(); + swizExpr->Position = memberRefExpr->Position; + swizExpr->base = memberRefExpr->BaseExpression; + + int limitElement = baseElementCount; + + int elementIndices[4]; + int elementCount = 0; + + bool elementUsed[4] = { false, false, false, false }; + bool anyDuplicates = false; + bool anyError = false; + + for (int i = 0; i < memberRefExpr->MemberName.Length(); i++) + { + auto ch = memberRefExpr->MemberName[i]; + int elementIndex = -1; + switch (ch) + { + case 'x': case 'r': elementIndex = 0; break; + case 'y': case 'g': elementIndex = 1; break; + case 'z': case 'b': elementIndex = 2; break; + case 'w': case 'a': elementIndex = 3; break; + default: + // An invalid character in the swizzle is an error + getSink()->diagnose(swizExpr, Diagnostics::unimplemented, "invalid component name for swizzle"); + anyError = true; + continue; + } + + // TODO(tfoley): GLSL requires that all component names + // come from the same "family"... + + // Make sure the index is in range for the source type + if (elementIndex >= limitElement) + { + getSink()->diagnose(swizExpr, Diagnostics::unimplemented, "swizzle component out of range for type"); + anyError = true; + continue; + } + + // Check if we've seen this index before + for (int ee = 0; ee < elementCount; ee++) + { + if (elementIndices[ee] == elementIndex) + anyDuplicates = true; + } + + // add to our list... + elementIndices[elementCount++] = elementIndex; + } + + for (int ee = 0; ee < elementCount; ++ee) + { + swizExpr->elementIndices[ee] = elementIndices[ee]; + } + swizExpr->elementCount = elementCount; + + if (anyError) + { + swizExpr->Type = ExpressionType::Error; + } + else if (elementCount == 1) + { + // single-component swizzle produces a scalar + // + // Note(tfoley): the official HLSL rules seem to be that it produces + // a one-component vector, which is then implicitly convertible to + // a scalar, but that seems like it just adds complexity. + swizExpr->Type = baseElementType; + } + else + { + // TODO(tfoley): would be nice to "re-sugar" type + // here if the input type had a sugared name... + swizExpr->Type = createVectorType( + baseElementType, + new ConstantIntVal(elementCount)); + } + + // A swizzle can be used as an l-value as long as there + // were no duplicates in the list of components + swizExpr->Type.IsLeftValue = !anyDuplicates; + + return swizExpr; + } + + RefPtr CheckSwizzleExpr( + MemberExpressionSyntaxNode* memberRefExpr, + RefPtr baseElementType, + RefPtr baseElementCount) + { + if (auto constantElementCount = baseElementCount.As()) + { + return CheckSwizzleExpr(memberRefExpr, baseElementType, constantElementCount->value); + } + else + { + getSink()->diagnose(memberRefExpr, Diagnostics::unimplemented, "swizzle on vector of unknown size"); + return CreateErrorExpr(memberRefExpr); + } + } + + + virtual RefPtr VisitMemberExpression(MemberExpressionSyntaxNode * expr) override + { + expr->BaseExpression = CheckExpr(expr->BaseExpression); + + expr->BaseExpression = MaybeDereference(expr->BaseExpression); + + auto & baseType = expr->BaseExpression->Type; + + // Note: Checking for vector types before declaration-reference types, + // because vectors are also declaration reference types... + if (auto baseVecType = baseType->AsVectorType()) + { + return CheckSwizzleExpr( + expr, + baseVecType->elementType, + baseVecType->elementCount); + } + else if(auto baseScalarType = baseType->AsBasicType()) + { + // Treat scalar like a 1-element vector when swizzling + return CheckSwizzleExpr( + expr, + baseScalarType, + 1); + } + else if (auto declRefType = baseType->AsDeclRefType()) + { + if (auto aggTypeDeclRef = declRefType->declRef.As()) + { + // Checking of the type must be complete before we can reference its members safely + EnsureDecl(aggTypeDeclRef.GetDecl(), DeclCheckState::Checked); + + + LookupResult lookupResult = LookUpLocal(expr->MemberName, aggTypeDeclRef); + if (!lookupResult.isValid()) + { + goto fail; + } + + return createLookupResultExpr( + lookupResult, + expr->BaseExpression, + expr); +#if 0 + DeclRef memberDeclRef(lookupResult.decl, aggTypeDeclRef.substitutions); + return ConstructDeclRefExpr(memberDeclRef, expr->BaseExpression, expr); +#endif + +#if 0 + + + // TODO(tfoley): It is unfortunate that the lookup strategy + // here isn't unified with the ordinary `Scope` case. + // In particular, if we add support for "transparent" declarations, + // etc. here then we would need to add them in ordinary lookup + // as well. + + Decl* memberDecl = nullptr; // The first declaration we found, if any + Decl* secondDecl = nullptr; // Another declaration with the same name, if any + for (auto m : aggTypeDeclRef.GetMembers()) + { + if (m.GetName() != expr->MemberName) + continue; + + if (!memberDecl) + { + memberDecl = m.GetDecl(); + } + else + { + secondDecl = m.GetDecl(); + break; + } + } + + // If we didn't find any member, then we signal an error + if (!memberDecl) + { + expr->Type = ExpressionType::Error; + getSink()->diagnose(expr, Diagnostics::noMemberOfNameInType, expr->MemberName, baseType); + return expr; + } + + // If we found only a single member, then we are fine + if (!secondDecl) + { + // TODO: need to + DeclRef memberDeclRef(memberDecl, aggTypeDeclRef.substitutions); + + expr->declRef = memberDeclRef; + expr->Type = GetTypeForDeclRef(memberDeclRef); + + // When referencing a member variable, the result is an l-value + // if and only if the base expression was. + if (auto memberVarDecl = dynamic_cast(memberDecl)) + { + expr->Type.IsLeftValue = expr->BaseExpression->Type.IsLeftValue; + } + return expr; + } + + // We found multiple members with the same name, and need + // to resolve the embiguity at some point... + expr->Type = ExpressionType::Error; + getSink()->diagnose(expr, Diagnostics::unimplemented, "ambiguous member reference"); + return expr; + +#endif + +#if 0 + + StructField* field = structDecl->FindField(expr->MemberName); + if (!field) + { + expr->Type = ExpressionType::Error; + getSink()->diagnose(expr, Diagnostics::noMemberOfNameInType, expr->MemberName, baseType); + } + else + expr->Type = field->Type; + + // A reference to a struct member is an l-value if the reference to the struct + // value was also an l-value. + expr->Type.IsLeftValue = expr->BaseExpression->Type.IsLeftValue; + return expr; +#endif + } + + // catch-all + fail: + getSink()->diagnose(expr, Diagnostics::noMemberOfNameInType, expr->MemberName, baseType); + expr->Type = ExpressionType::Error; + return expr; + } + // All remaining cases assume we have a `BasicType` + else if (!baseType->AsBasicType()) + expr->Type = ExpressionType::Error; + else + expr->Type = ExpressionType::Error; + if (!baseType->Equals(ExpressionType::Error.Ptr()) && + expr->Type->Equals(ExpressionType::Error.Ptr())) + { + getSink()->diagnose(expr, Diagnostics::typeHasNoPublicMemberOfName, baseType, expr->MemberName); + } + return expr; + } + SemanticsVisitor & operator = (const SemanticsVisitor &) = delete; + + + // + + virtual RefPtr visitInitializerListExpr(InitializerListExpr* expr) override + { + // When faced with an initializer list, we first just check the sub-expressions blindly. + // Actually making them conform to a desired type will wait for when we know the desired + // type based on context. + + for( auto& arg : expr->args ) + { + arg = CheckTerm(arg); + } + + expr->Type = ExpressionType::getInitializerListType(); + + return expr; + } + }; + + SyntaxVisitor * CreateSemanticsVisitor( + DiagnosticSink * err, + CompileOptions const& options) + { + return new SemanticsVisitor(err, options); + } + + // + + // Get the type to use when referencing a declaration + QualType getTypeForDeclRef( + SemanticsVisitor* sema, + DiagnosticSink* sink, + DeclRef declRef, + RefPtr* outTypeResult) + { + if( sema ) + { + sema->EnsureDecl(declRef.GetDecl()); + } + + // We need to insert an appropriate type for the expression, based on + // what we found. + if (auto varDeclRef = declRef.As()) + { + QualType qualType; + qualType.type = varDeclRef.GetType(); + qualType.IsLeftValue = true; // TODO(tfoley): allow explicit `const` or `let` variables + return qualType; + } + else if (auto typeAliasDeclRef = declRef.As()) + { + auto type = new NamedExpressionType(typeAliasDeclRef); + *outTypeResult = type; + return new TypeType(type); + } + else if (auto aggTypeDeclRef = declRef.As()) + { + auto type = DeclRefType::Create(aggTypeDeclRef); + *outTypeResult = type; + return new TypeType(type); + } + else if (auto simpleTypeDeclRef = declRef.As()) + { + auto type = DeclRefType::Create(simpleTypeDeclRef); + *outTypeResult = type; + return new TypeType(type); + } + else if (auto genericDeclRef = declRef.As()) + { + auto type = new GenericDeclRefType(genericDeclRef); + *outTypeResult = type; + return new TypeType(type); + } + else if (auto funcDeclRef = declRef.As()) + { + auto type = new FuncType(); + type->declRef = funcDeclRef; + return type; + } + + if( sink ) + { + sink->diagnose(declRef, Diagnostics::unimplemented, "cannot form reference to this kind of declaration"); + } + return ExpressionType::Error; + } + + QualType getTypeForDeclRef( + DeclRef declRef) + { + RefPtr typeResult; + return getTypeForDeclRef(nullptr, nullptr, declRef, &typeResult); + } + + } +} \ No newline at end of file diff --git a/source/slang/compiled-program.h b/source/slang/compiled-program.h new file mode 100644 index 000000000..7a86dfe90 --- /dev/null +++ b/source/slang/compiled-program.h @@ -0,0 +1,96 @@ +#ifndef BAKER_SL_COMPILED_PROGRAM_H +#define BAKER_SL_COMPILED_PROGRAM_H + +#include "../core/basic.h" +#include "diagnostics.h" +#include "syntax.h" +#include "type-layout.h" + +namespace Slang +{ + namespace Compiler + { +#if 0 + class ShaderMetaData + { + public: + CoreLib::String ShaderName; + CoreLib::EnumerableDictionary> ParameterSets; // bindingName->DescSet + }; + + class StageSource + { + public: + String MainCode; + List BinaryCode; + }; + + class CompiledShaderSource + { + public: + EnumerableDictionary Stages; + ShaderMetaData MetaData; + }; +#endif + + void IndentString(StringBuilder & sb, String src); + + struct EntryPointResult + { + String outputSource; + }; + + struct TranslationUnitResult + { + String outputSource; + List entryPoints; + }; + + class CompileResult + { + public: + DiagnosticSink* mSink = nullptr; + +#if 0 + String ScheduleFile; + RefPtr Program; + EnumerableDictionary CompiledSource; // shader -> stage -> code +#endif + + // Per-translation-unit results + List translationUnits; + +#if 0 + void PrintDiagnostics() + { + for (int i = 0; i < sink.diagnostics.Count(); i++) + { + fprintf(stderr, "%S(%d): %s %d: %S\n", + sink.diagnostics[i].Position.FileName.ToWString(), + sink.diagnostics[i].Position.Line, + getSeverityName(sink.diagnostics[i].severity), + sink.diagnostics[i].ErrorID, + sink.diagnostics[i].Message.ToWString()); + } + } +#endif + + CompileResult() + {} + ~CompileResult() + { + } + DiagnosticSink * GetErrorWriter() + { + return mSink; + } + int GetErrorCount() + { + return mSink->GetErrorCount(); + } + }; + + } +} + +#endif \ No newline at end of file diff --git a/source/slang/compiler.cpp b/source/slang/compiler.cpp new file mode 100644 index 000000000..e78de9133 --- /dev/null +++ b/source/slang/compiler.cpp @@ -0,0 +1,659 @@ +// Compiler.cpp : Defines the entry point for the console application. +// +#include "../core/basic.h" +#include "../core/slang-io.h" +#include "compiler.h" +#include "lexer.h" +#include "parameter-binding.h" +#include "parser.h" +#include "preprocessor.h" +#include "syntax-visitors.h" +#include "slang-stdlib.h" + +#include "reflection.h" +#include "emit.h" + +// Utilities for pass-through modes +#include "../../tools/glslang/glslang.h" + + +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#undef WIN32_LEAN_AND_MEAN +#undef NOMINMAX +#include +#endif + +#ifdef CreateDirectory +#undef CreateDirectory +#endif + +using namespace CoreLib::Basic; +using namespace CoreLib::IO; +using namespace Slang::Compiler; + +namespace Slang +{ + namespace Compiler + { + // + + Profile Profile::LookUp(char const* name) + { + #define PROFILE(TAG, NAME, STAGE, VERSION) if(strcmp(name, #NAME) == 0) return Profile::TAG; + #define PROFILE_ALIAS(TAG, NAME) if(strcmp(name, #NAME) == 0) return Profile::TAG; + #include "profile-defs.h" + + return Profile::Unknown; + } + + + + // + + int compilerInstances = 0; + + class ShaderCompilerImpl : public ShaderCompiler + { + public: + + // Actual context for compilation... :( + struct ExtraContext + { + CompileOptions const* options = nullptr; + TranslationUnitOptions const* translationUnitOptions = nullptr; + + CompileResult* compileResult = nullptr; + + RefPtr programSyntax; + ProgramLayout* programLayout; + + String sourceText; + String sourcePath; + + CompileOptions const& getOptions() { return *options; } + TranslationUnitOptions const& getTranslationUnitOptions() { return *translationUnitOptions; } + }; + + + String EmitHLSL(ExtraContext& context) + { + if (context.getOptions().passThrough != PassThroughMode::None) + { + return context.sourceText; + } + else + { + // TODO(tfoley): probably need a way to customize the emit logic... + return emitProgram( + context.programSyntax.Ptr(), + context.programLayout, + CodeGenTarget::HLSL); + } + } + + String emitGLSLForEntryPoint(ExtraContext& context, EntryPointOption const& entryPoint) + { + if (context.getOptions().passThrough != PassThroughMode::None) + { + return context.sourceText; + } + else + { + // TODO(tfoley): probably need a way to customize the emit logic... + return emitProgram( + context.programSyntax.Ptr(), + context.programLayout, + CodeGenTarget::GLSL); + } + } + + char const* GetHLSLProfileName(Profile profile) + { + switch(profile.raw) + { + #define PROFILE(TAG, NAME, STAGE, VERSION) case Profile::TAG: return #NAME; + #include "profile-defs.h" + + default: + // TODO: emit an error here! + return "unknown"; + } + } + +#ifdef _WIN32 + void* GetD3DCompilerDLL() + { + // TODO(tfoley): let user specify version of d3dcompiler DLL to use. + static HMODULE d3dCompiler = LoadLibraryA("d3dcompiler_47"); + // TODO(tfoley): handle case where we can't find it gracefully + assert(d3dCompiler); + return d3dCompiler; + } + + List EmitDXBytecodeForEntryPoint( + ExtraContext& context, + EntryPointOption const& entryPoint) + { + static pD3DCompile D3DCompile_ = nullptr; + if (!D3DCompile_) + { + HMODULE d3dCompiler = (HMODULE)GetD3DCompilerDLL(); + assert(d3dCompiler); + + D3DCompile_ = (pD3DCompile)GetProcAddress(d3dCompiler, "D3DCompile"); + assert(D3DCompile_); + } + + // The HLSL compiler will try to "canonicalize" our input file path, + // and we don't want it to do that, because they it won't report + // the same locations on error messages that we would. + // + // To work around that, we prepend a custom `#line` directive. + + String rawHlslCode = EmitHLSL(context); + + StringBuilder hlslCodeBuilder; + hlslCodeBuilder << "#line 1 \""; + for(auto c : context.sourcePath) + { + char buffer[] = { c, 0 }; + switch(c) + { + default: + hlslCodeBuilder << buffer; + break; + + case '\\': + hlslCodeBuilder << "\\\\"; + } + } + hlslCodeBuilder << "\"\n"; + hlslCodeBuilder << rawHlslCode; + + auto hlslCode = hlslCodeBuilder.ProduceString(); + + ID3DBlob* codeBlob; + ID3DBlob* diagnosticsBlob; + HRESULT hr = D3DCompile_( + hlslCode.begin(), + hlslCode.Length(), + context.sourcePath.begin(), + nullptr, + nullptr, + entryPoint.name.begin(), + GetHLSLProfileName(entryPoint.profile), + 0, + 0, + &codeBlob, + &diagnosticsBlob); + List data; + if (codeBlob) + { + data.AddRange((uint8_t const*)codeBlob->GetBufferPointer(), (int)codeBlob->GetBufferSize()); + codeBlob->Release(); + } + if (diagnosticsBlob) + { + // TODO(tfoley): need a better policy for how we translate diagnostics + // back into the Slang world (although we should always try to generate + // HLSL that doesn't produce any diagnostics...) + String diagnostics = (char const*) diagnosticsBlob->GetBufferPointer(); + fprintf(stderr, "%s", diagnostics.begin()); + OutputDebugStringA(diagnostics.begin()); + diagnosticsBlob->Release(); + } + if (FAILED(hr)) + { + // TODO(tfoley): What to do on failure? + } + return data; + } + + List EmitDXBytecode( + ExtraContext& context) + { + if(context.getTranslationUnitOptions().entryPoints.Count() != 1) + { + if(context.getTranslationUnitOptions().entryPoints.Count() == 0) + { + // TODO(tfoley): need to write diagnostics into this whole thing... + fprintf(stderr, "no entry point specified\n"); + } + else + { + fprintf(stderr, "multiple entry points specified\n"); + } + return List(); + } + + return EmitDXBytecodeForEntryPoint(context, context.getTranslationUnitOptions().entryPoints[0]); + } + + String EmitDXBytecodeAssemblyForEntryPoint( + ExtraContext& context, + EntryPointOption const& entryPoint) + { + static pD3DDisassemble D3DDisassemble_ = nullptr; + if (!D3DDisassemble_) + { + HMODULE d3dCompiler = (HMODULE)GetD3DCompilerDLL(); + assert(d3dCompiler); + + D3DDisassemble_ = (pD3DDisassemble)GetProcAddress(d3dCompiler, "D3DDisassemble"); + assert(D3DDisassemble_); + } + + List dxbc = EmitDXBytecodeForEntryPoint(context, entryPoint); + if (!dxbc.Count()) + { + return ""; + } + + ID3DBlob* codeBlob; + HRESULT hr = D3DDisassemble_( + &dxbc[0], + dxbc.Count(), + 0, + nullptr, + &codeBlob); + + String result; + if (codeBlob) + { + result = String((char const*) codeBlob->GetBufferPointer()); + codeBlob->Release(); + } + if (FAILED(hr)) + { + // TODO(tfoley): need to figure out what to diagnose here... + } + return result; + } + + + String EmitDXBytecodeAssembly( + ExtraContext& context) + { + if(context.getTranslationUnitOptions().entryPoints.Count() == 0) + { + // TODO(tfoley): need to write diagnostics into this whole thing... + fprintf(stderr, "no entry point specified\n"); + return ""; + } + + StringBuilder sb; + for (auto entryPoint : context.getTranslationUnitOptions().entryPoints) + { + sb << EmitDXBytecodeAssemblyForEntryPoint(context, entryPoint); + } + return sb.ProduceString(); + } + + + HMODULE getGLSLCompilerDLL() + { + // TODO(tfoley): let user specify version of glslang DLL to use. + static HMODULE glslCompiler = LoadLibraryA("glslang"); + // TODO(tfoley): handle case where we can't find it gracefully + assert(glslCompiler); + return glslCompiler; + } + + + String emitSPIRVAssemblyForEntryPoint( + ExtraContext& context, + EntryPointOption const& entryPoint) + { + String rawGLSL = emitGLSLForEntryPoint(context, entryPoint); + + static glslang_CompileFunc glslang_compile = nullptr; + if (!glslang_compile) + { + HMODULE glslCompiler = getGLSLCompilerDLL(); + assert(glslCompiler); + + glslang_compile = (glslang_CompileFunc)GetProcAddress(glslCompiler, "glslang_compile"); + assert(glslang_compile); + } + + StringBuilder diagnosticBuilder; + StringBuilder outputBuilder; + + auto outputFunc = [](char const* text, void* userData) + { + *(StringBuilder*)userData << text; + }; + + glslang_CompileRequest request; + request.sourcePath = context.sourcePath.begin(); + request.sourceText = rawGLSL.begin(); + request.slangStage = (SlangStage) entryPoint.profile.GetStage(); + + request.diagnosticFunc = outputFunc; + request.diagnosticUserData = &diagnosticBuilder; + + request.outputFunc = outputFunc; + request.outputUserData = &outputBuilder; + + int err = glslang_compile(&request); + + String diagnostics = diagnosticBuilder.ProduceString(); + String output = outputBuilder.ProduceString(); + + if(err) + { + OutputDebugStringA(diagnostics.Buffer()); + fprintf(stderr, "%s", diagnostics.Buffer()); + exit(1); + } + + return output; + } +#endif + + String emitSPIRVAssembly( + ExtraContext& context) + { + if(context.getTranslationUnitOptions().entryPoints.Count() == 0) + { + // TODO(tfoley): need to write diagnostics into this whole thing... + fprintf(stderr, "no entry point specified\n"); + return ""; + } + + StringBuilder sb; + for (auto entryPoint : context.getTranslationUnitOptions().entryPoints) + { + sb << emitSPIRVAssemblyForEntryPoint(context, entryPoint); + } + return sb.ProduceString(); + } + + // Do emit logic for a single entry point + EntryPointResult emitEntryPoint(ExtraContext& context, EntryPointOption& entryPoint) + { + EntryPointResult result; + + switch (context.getOptions().Target) + { + case CodeGenTarget::GLSL: + { + String code = emitGLSLForEntryPoint(context, entryPoint); + result.outputSource = code; + } + break; + + case CodeGenTarget::DXBytecode: + { + auto code = EmitDXBytecodeForEntryPoint(context, entryPoint); + + // TODO(tfoley): Need to figure out an appropriate interface + // for returning binary code, in addition to source. +#if 0 + if (context.compileResult) + { + StringBuilder sb; + sb.Append((char*) code.begin(), code.Count()); + + String codeString = sb.ProduceString(); + result.outputSource = codeString; + } + else +#endif + { + int col = 0; + for(auto ii : code) + { + if(col != 0) fputs(" ", stdout); + fprintf(stdout, "%02X", ii); + col++; + if(col == 8) + { + fputs("\n", stdout); + col = 0; + } + } + if(col != 0) + { + fputs("\n", stdout); + } + } + return result; + } + break; + + case CodeGenTarget::DXBytecodeAssembly: + { + String code = EmitDXBytecodeAssemblyForEntryPoint(context, entryPoint); + result.outputSource = code; + } + break; + + case CodeGenTarget::SPIRVAssembly: + { + String code = emitSPIRVAssemblyForEntryPoint(context, entryPoint); + result.outputSource = code; + } + break; + + // Note(tfoley): We currently hit this case when compiling the stdlib + case CodeGenTarget::Unknown: + break; + + default: + throw "unimplemented"; + } + + return result; + + + } + + TranslationUnitResult emitTranslationUnitEntryPoints(ExtraContext& context) + { + TranslationUnitResult result; + + for (auto& entryPoint : context.getTranslationUnitOptions().entryPoints) + { + EntryPointResult entryPointResult = emitEntryPoint(context, entryPoint); + + result.entryPoints.Add(entryPointResult); + } + + // The result for the translation unit will just be the concatenation + // of the results for each entry point. This doesn't actually make + // much sense, but it is good enough for now. + StringBuilder sb; + for (auto& entryPointResult : result.entryPoints) + { + sb << entryPointResult.outputSource; + } + + result.outputSource = sb.ProduceString(); + + return result; + } + + // Do emit logic for an entire translation unit, which might + // have zero or more entry points + TranslationUnitResult emitTranslationUnit(ExtraContext& context) + { + // Most of our code generation targets will require us + // to proceed through one entry point at a time, but + // in some cases we can emit an entire translation unit + // in one go. + + switch (context.getOptions().Target) + { + default: + // The default behavior is going to loop over all the entry + // points, and then collect an aggregate result. + return emitTranslationUnitEntryPoints(context); + + case CodeGenTarget::HLSL: + // When targetting HLSL, we can emit the entire translation unit + // as a single HLSL program, and include all the entry points. + { + + String hlsl = EmitHLSL(context); + + TranslationUnitResult result; + result.outputSource = hlsl; + + // Because the user might ask for per-entry-point source, + // we will just attach the same string as the result for + // each entry point. + for( auto& entryPoint : context.getTranslationUnitOptions().entryPoints ) + { + (void)entryPoint; + + EntryPointResult entryPointResult; + entryPointResult.outputSource = hlsl; + result.entryPoints.Add(entryPointResult); + } + + return result; + } + break; + } + } + + TranslationUnitResult DoNewEmitLogic(ExtraContext& context) + { + TranslationUnitResult result = emitTranslationUnit(context); + + // As a bit of a hack, we include a mode where we just + // print things to standard output, so that we can see them + // + // TODO(tfoley): Is this path ever needed/used? + if( !context.compileResult ) + { + fprintf(stdout, "%s", result.outputSource.Buffer()); + } + + return result; + } + + void DoNewEmitLogic( + ExtraContext& context, + CollectionOfTranslationUnits* collectionOfTranslationUnits) + { + switch (context.getOptions().Target) + { + default: + // For most targets, we will do things per-translation-unit + for( auto translationUnit : collectionOfTranslationUnits->translationUnits ) + { + ExtraContext innerContext = context; + innerContext.translationUnitOptions = &translationUnit.options; + innerContext.programSyntax = translationUnit.SyntaxNode; + innerContext.sourcePath = "slang"; // don't have this any more! + innerContext.sourceText = ""; + + TranslationUnitResult translationUnitResult = DoNewEmitLogic(innerContext); + context.compileResult->translationUnits.Add(translationUnitResult); + } + break; + + case CodeGenTarget::ReflectionJSON: + { + String reflectionJSON = emitReflectionJSON(context.programLayout); + + // HACK(tfoley): just print it out since that is what people probably expect. + // TODO: need a way to control where output gets routed across all possible targets. + fprintf(stdout, "%s", reflectionJSON.begin()); + } + break; + } + } + + virtual void Compile( + CompileResult& result, + CollectionOfTranslationUnits* collectionOfTranslationUnits, + const CompileOptions& options) override + { + RefPtr visitor = CreateSemanticsVisitor(result.GetErrorWriter(), options); + try + { + for( auto& translationUnit : collectionOfTranslationUnits->translationUnits ) + { + visitor->setSourceLanguage(translationUnit.options.sourceLanguage); + + translationUnit.SyntaxNode->Accept(visitor.Ptr()); + } + if (result.GetErrorCount() > 0) + return; + + // Do binding generation, and then reflection (globally) + // before we move on to any code-generation activites. + GenerateParameterBindings(collectionOfTranslationUnits); + + + // HACK(tfoley): for right now I just want to pretty-print an AST + // into another language, so the whole compiler back-end is just + // getting in the way. + // + // I'm going to bypass it for now and see what I can do: + + ExtraContext extra; + extra.options = &options; + extra.programLayout = collectionOfTranslationUnits->layout.Ptr(); + extra.compileResult = &result; + DoNewEmitLogic(extra, collectionOfTranslationUnits); + } + catch (int) + { + } + catch (...) + { + throw; + } + return; + } + + ShaderCompilerImpl() + { + if (compilerInstances == 0) + { + BasicExpressionType::Init(); + } + compilerInstances++; + } + + ~ShaderCompilerImpl() + { + compilerInstances--; + if (compilerInstances == 0) + { + BasicExpressionType::Finalize(); + SlangStdLib::Finalize(); + } + } + + virtual TranslationUnitResult PassThrough( + String const& sourceText, + String const& sourcePath, + const CompileOptions & options, + TranslationUnitOptions const& translationUnitOptions) override + { + ExtraContext extra; + extra.options = &options; + extra.translationUnitOptions = &translationUnitOptions; + extra.sourcePath = sourcePath; + extra.sourceText = sourceText; + + return DoNewEmitLogic(extra); + } + + }; + + ShaderCompiler * CreateShaderCompiler() + { + return new ShaderCompilerImpl(); + } + + } +} diff --git a/source/slang/compiler.h b/source/slang/compiler.h new file mode 100644 index 000000000..f35d6603c --- /dev/null +++ b/source/slang/compiler.h @@ -0,0 +1,156 @@ +#ifndef RASTER_SHADER_COMPILER_H +#define RASTER_SHADER_COMPILER_H + +#include "../core/basic.h" + +#include "compiled-program.h" +#include "diagnostics.h" +#include "profile.h" +#include "syntax.h" +#include "type-layout.h" + +#include "../../slang.h" + +namespace Slang +{ + namespace Compiler + { + class ILConstOperand; + struct IncludeHandler; + + enum class CompilerMode + { + ProduceLibrary, + ProduceShader, + GenerateChoice + }; + + enum class StageTarget + { + Unknown, + VertexShader, + HullShader, + DomainShader, + GeometryShader, + FragmentShader, + ComputeShader, + }; + + enum class CodeGenTarget + { + Unknown = SLANG_TARGET_UNKNOWN, + GLSL = SLANG_GLSL, + GLSL_Vulkan = SLANG_GLSL_VULKAN, + GLSL_Vulkan_OneDesc = SLANG_GLSL_VULKAN_ONE_DESC, + HLSL = SLANG_HLSL, + SPIRV = SLANG_SPIRV, + SPIRVAssembly = SLANG_SPIRV_ASM, + DXBytecode = SLANG_DXBC, + DXBytecodeAssembly = SLANG_DXBC_ASM, + ReflectionJSON = SLANG_REFLECTION_JSON, + }; + + // Describes an entry point that we've been requested to compile + struct EntryPointOption + { + String name; + Profile profile; + }; + + enum class PassThroughMode : SlangPassThrough + { + None = SLANG_PASS_THROUGH_NONE, // don't pass through: use Slang compiler + HLSL = SLANG_PASS_THROUGH_FXC, // pass through HLSL to `D3DCompile` API +// GLSL, // pass through GLSL to `glslang` library + }; + + // Represents a single source file (either an on-disk file, or a + // "virtual" file passed in as a string) + class SourceFile : public RefObject + { + public: + // The file path for a real file, or the nominal path for a virtual file + String path; + + // The actual contents of the file + String content; + }; + + // Options for a single translation unit being requested by the user + class TranslationUnitOptions + { + public: + SourceLanguage sourceLanguage = SourceLanguage::Unknown; + + // All entry points we've been asked to compile for this translation unit + List entryPoints; + + // The source file(s) that will be compiled to form this translation unit + List > sourceFiles; + }; + + class CompileOptions + { + public: + CompilerMode Mode = CompilerMode::ProduceShader; + CodeGenTarget Target = CodeGenTarget::Unknown; + StageTarget stage = StageTarget::Unknown; + EnumerableDictionary BackendArguments; + + String SymbolToCompile; + String outputName; + List TemplateShaderArguments; + List SearchDirectories; + Dictionary PreprocessorDefinitions; + + List translationUnits; + + // the code generation profile we've been asked to use + Profile profile; + + // should we just pass the input to another compiler? + PassThroughMode passThrough = PassThroughMode::None; + + // Flags supplied through the API + SlangCompileFlags flags = 0; + }; + + // This is the representation of a given translation unit + class CompileUnit + { + public: + TranslationUnitOptions options; + RefPtr SyntaxNode; + }; + + // TODO: pick an appropriate name for this... + class CollectionOfTranslationUnits : public RefObject + { + public: + List translationUnits; + + // TODO: this is more output-oriented, but maybe okay to have here... + RefPtr layout; + }; + + class ShaderCompiler : public CoreLib::Basic::Object + { + public: + virtual void Compile( + CompileResult& result, + CollectionOfTranslationUnits* collectionOfTranslationUnits, + const CompileOptions& options) = 0; + + virtual TranslationUnitResult PassThrough( + String const& sourceText, + String const& sourcePath, + const CompileOptions & options, + TranslationUnitOptions const& translationUnitOptions) = 0; + + }; + + ShaderCompiler * CreateShaderCompiler(); + } +} + +#endif \ No newline at end of file diff --git a/source/slang/diagnostic-defs.h b/source/slang/diagnostic-defs.h new file mode 100644 index 000000000..3f690a5da --- /dev/null +++ b/source/slang/diagnostic-defs.h @@ -0,0 +1,338 @@ +// + +// The file is meant to be included multiple times, to produce different +// pieces of declaration/definition code related to diagnostic messages +// +// Each diagnostic is declared here with: +// +// DIAGNOSTIC(id, severity, name, messageFormat) +// +// Where `id` is the unique diagnostic ID, `severity` is the default +// severity (from the `Severity` enum), `name` is a name used to refer +// to this diagnostic from code, and `messageFormat` is the default +// (non-localized) message for the diagnostic, with placeholders +// for any arguments. + +#ifndef DIAGNOSTIC +#error Need to #define DIAGNOSTIC(...) before including "DiagnosticDefs.h" +#define DIAGNOSTIC(id, severity, name, messageFormat) /* */ +#endif + +// +// -1 - Notes that decorate another diagnostic. +// + +DIAGNOSTIC(-1, Note, alsoSeePipelineDefinition, "also see pipeline definition"); +DIAGNOSTIC(-1, Note, implicitParameterMatchingFailedBecauseNameNotAccessible, "implicit parameter matching failed because the component of the same name is not accessible from '$0'.\ncheck if you have declared necessary requirements and properly used the 'public' qualifier.") +DIAGNOSTIC(-1, Note, implicitParameterMatchingFailedBecauseShaderDoesNotDefineComponent, "implicit parameter matching failed because shader '$0' does not define component '$1'.") +DIAGNOSTIC(-1, Note, implicitParameterMatchingFailedBecauseTypeMismatch, "implicit parameter matching failed because the component of the same name does not match parameter type '$0'.") +DIAGNOSTIC(-1, Note, noteShaderIsTargetingPipeine, "shader '$0' is targeting pipeline '$1'") +DIAGNOSTIC(-1, Note, seeDefinitionOf, "see definition of '$0'") +DIAGNOSTIC(-1, Note, seeInterfaceDefinitionOf, "see interface definition of '$0'") +DIAGNOSTIC(-1, Note, seeUsingOf, "see using of '$0'") +DIAGNOSTIC(-1, Note, seeDefinitionOfShader, "see definition of shader '$0'") +DIAGNOSTIC(-1, Note, seeInclusionOf, "see inclusion of '$0'") +DIAGNOSTIC(-1, Note, seeModuleBeingUsedIn, "see module '$0' being used in '$1'") +DIAGNOSTIC(-1, Note, seePipelineRequirementDefinition, "see pipeline requirement definition") +DIAGNOSTIC(-1, Note, seePotentialDefinitionOfComponent, "see potential definition of component '$0'") +DIAGNOSTIC(-1, Note, seePreviousDefinition, "see previous definition") +DIAGNOSTIC(-1, Note, seePreviousDefinitionOf, "see previous definition of '$0'") +DIAGNOSTIC(-1, Note, seeRequirementDeclaration, "see requirement declaration") +DIAGNOSTIC(-1, Note, doYouForgetToMakeComponentAccessible, "do you forget to make component '$0' acessible from '$1' (missing public qualifier)?") +// +// 0xxxx - Command line and interaction with host platform APIs. +// + +DIAGNOSTIC( 1, Error, cannotOpenFile, "cannot open file '$0'.") +DIAGNOSTIC( 2, Error, cannotFindFile, "cannot find file '$0'.") +DIAGNOSTIC( 2, Error, unsupportedCompilerMode, "unsupported compiler mode.") +DIAGNOSTIC( 4, Error, cannotWriteOutputFile, "cannot write output file '$0'.") + +// +// 1xxxx - Lexical anaylsis +// + +DIAGNOSTIC(10000, Error, illegalCharacterPrint, "illegal character '$0'"); +DIAGNOSTIC(10000, Error, illegalCharacterHex, "illegal character (0x$0)"); +DIAGNOSTIC(10001, Error, illegalCharacterLiteral, "illegal character literal"); + +DIAGNOSTIC(10002, Warning, octalLiteral, "'0' prefix indicates octal literal") +DIAGNOSTIC(10003, Error, invalidDigitForBase, "invalid digit for base-$1 literal: '$0'") + +DIAGNOSTIC(10004, Error, endOfFileInLiteral, "end of file in literal"); +DIAGNOSTIC(10005, Error, newlineInLiteral, "newline in literal"); + +// +// 15xxx - Preprocessing +// + +// 150xx - conditionals +DIAGNOSTIC(15000, Error, endOfFileInPreprocessorConditional, "end of file encountered during preprocessor conditional") +DIAGNOSTIC(15001, Error, directiveWithoutIf, "'$0' directive without '#if'") +DIAGNOSTIC(15002, Error, directiveAfterElse , "'$0' directive without '#if'") + +DIAGNOSTIC(-1, Note, seeDirective, "see '$0' directive") + +// 151xx - directive parsing +DIAGNOSTIC(15100, Error, expectedPreprocessorDirectiveName, "expected preprocessor directive name") +DIAGNOSTIC(15101, Error, unknownPreprocessorDirective, "unknown preprocessor directive '$0'") +DIAGNOSTIC(15102, Error, expectedTokenInPreprocessorDirective, "expected '$0' in '$1' directive") +DIAGNOSTIC(15102, Error, expected2TokensInPreprocessorDirective, "expected '$0' or '$1' in '$2' directive") +DIAGNOSTIC(15103, Error, unexpectedTokensAfterDirective, "unexpected tokens following '$0' directive") + + +// 152xx - preprocessor expressions +DIAGNOSTIC(15200, Error, expectedTokenInPreprocessorExpression, "expected '$0' in preprocessor expression"); +DIAGNOSTIC(15201, Error, syntaxErrorInPreprocessorExpression, "syntax error in preprocessor expression"); +DIAGNOSTIC(15202, Error, divideByZeroInPreprocessorExpression, "division by zero in preprocessor expression"); +DIAGNOSTIC(15203, Error, expectedTokenInDefinedExpression, "expected '$0' in 'defined' expression"); +DIAGNOSTIC(15204, Warning, directiveExpectsExpression, "'$0' directive requires an expression"); + +DIAGNOSTIC(-1, Note, seeOpeningToken, "see opening '$0'") + +// 153xx - #include +DIAGNOSTIC(15300, Error, includeFailed, "failed to find include file '$0'") +DIAGNOSTIC(-1, Error, noIncludeHandlerSpecified, "no `#include` handler was specified") + +// 154xx - macro definition +DIAGNOSTIC(15400, Warning, macroRedefinition, "redefinition of macro '$0'") +DIAGNOSTIC(15401, Warning, macroNotDefined, "macro '$0' is not defined") +DIAGNOSTIC(15403, Error, expectedTokenInMacroParameters, "expected '$0' in macro parameters") + +// 155xx - macro expansion +DIAGNOSTIC(15500, Warning, expectedTokenInMacroArguments, "expected '$0' in macro invocation") + +// 159xx - user-defined error/warning +DIAGNOSTIC(15900, Error, userDefinedError, "#error: $0") +DIAGNOSTIC(15901, Warning, userDefinedWarning, "#warning: $0") + +// +// 2xxxx - Parsing +// + +DIAGNOSTIC(20003, Error, unexpectedToken, "unexpected $0"); +DIAGNOSTIC(20001, Error, unexpectedTokenExpectedTokenType, "unexpected $0, expected $1"); +DIAGNOSTIC(20001, Error, unexpectedTokenExpectedTokenName, "unexpected $0, expected '$1'"); + +DIAGNOSTIC(0, Error, tokenNameExpectedButEOF, "\"$0\" expected but end of file encountered."); +DIAGNOSTIC(0, Error, tokenTypeExpectedButEOF, "$0 expected but end of file encountered."); +DIAGNOSTIC(20001, Error, tokenNameExpected, "\"$0\" expected"); +DIAGNOSTIC(20001, Error, tokenNameExpectedButEOF2, "\"$0\" expected but end of file encountered."); +DIAGNOSTIC(20001, Error, tokenTypeExpected, "$0 expected"); +DIAGNOSTIC(20001, Error, tokenTypeExpectedButEOF2, "$0 expected but end of file encountered."); +DIAGNOSTIC(20001, Error, typeNameExpectedBut, "unexpected $0, expected type name"); +DIAGNOSTIC(20001, Error, typeNameExpectedButEOF, "type name expected but end of file encountered."); +DIAGNOSTIC(20001, Error, unexpectedEOF, " Unexpected end of file."); +DIAGNOSTIC(20002, Error, syntaxError, "syntax error."); +DIAGNOSTIC(20004, Error, unexpectedTokenExpectedComponentDefinition, "unexpected token '$0', only component definitions are allowed in a shader scope.") +DIAGNOSTIC(20008, Error, invalidOperator, "invalid operator '$0'."); +DIAGNOSTIC(20011, Error, unexpectedColon, "unexpected ':'.") + +// +// 3xxxx - Semantic analysis +// + +DIAGNOSTIC(30001, Error, functionRedefinitionWithArgList, "'$0$1': function redefinition.") +DIAGNOSTIC(30002, Error, parameterAlreadyDefined, "parameter '$0' already defined.") +DIAGNOSTIC(30003, Error, breakOutsideLoop, "'break' must appear inside loop constructs.") +DIAGNOSTIC(30004, Error, continueOutsideLoop, "'continue' must appear inside loop constructs.") +DIAGNOSTIC(30005, Error, whilePredicateTypeError, "'while': expression must evaluate to int.") +DIAGNOSTIC(30006, Error, ifPredicateTypeError, "'if': expression must evaluate to int.") +DIAGNOSTIC(30006, Error, returnNeedsExpression, "'return' should have an expression.") +DIAGNOSTIC(30007, Error, componentReturnTypeMismatch, "expression type '$0' does not match component's type '$1'") +DIAGNOSTIC(30007, Error, functionReturnTypeMismatch, "expression type '$0' does not match function's return type '$1'") +DIAGNOSTIC(30008, Error, variableNameAlreadyDefined, "variable $0 already defined.") +DIAGNOSTIC(30009, Error, invalidTypeVoid, "invalid type 'void'.") +DIAGNOSTIC(30010, Error, whilePredicateTypeError2, "'while': expression must evaluate to int.") +DIAGNOSTIC(30011, Error, assignNonLValue, "left of '=' is not an l-value.") +DIAGNOSTIC(30012, Error, noApplicationUnaryOperator, "no overload found for operator $0 ($1).") +DIAGNOSTIC(30012, Error, noOverloadFoundForBinOperatorOnTypes, "no overload found for operator $0 ($1, $2).") +DIAGNOSTIC(30013, Error, subscriptNonArray, "no subscript operation found for type '$0'") +DIAGNOSTIC(30014, Error, subscriptIndexNonInteger, "index expression must evaluate to int.") +DIAGNOSTIC(30015, Error, undefinedIdentifier, "'$0': undefined identifier.") +DIAGNOSTIC(30015, Error, undefinedIdentifier2, "undefined identifier '$0'.") +DIAGNOSTIC(30016, Error, parameterCannotBeVoid, "'void' can not be parameter type.") +DIAGNOSTIC(30017, Error, componentNotAccessibleFromShader, "component '$0' is not accessible from shader '$1'.") +DIAGNOSTIC(30019, Error, typeMismatch, "expected an expression of type '$0', got '$1'") +DIAGNOSTIC(30020, Error, importOperatorReturnTypeMismatch, "import operator should return '$1', but the expression has type '$0''. do you forget 'project'?") +DIAGNOSTIC(30021, Error, noApplicationFunction, "$0: no overload takes arguments ($1)") +DIAGNOSTIC(30022, Error, invalidTypeCast, "invalid type cast between \"$0\" and \"$1\".") +DIAGNOSTIC(30023, Error, typeHasNoPublicMemberOfName, "\"$0\" does not have public member \"$1\"."); +DIAGNOSTIC(30025, Error, invalidArraySize, "array size must be larger than zero.") +DIAGNOSTIC(30026, Error, returnInComponentMustComeLast, "'return' can only appear as the last statement in component definition.") +DIAGNOSTIC(30027, Error, noMemberOfNameInType, "'$0' is not a member of '$1'."); +DIAGNOSTIC(30028, Error, forPredicateTypeError, "'for': predicate expression must evaluate to bool.") +DIAGNOSTIC(30030, Error, projectionOutsideImportOperator, "'project': invalid use outside import operator.") +DIAGNOSTIC(30031, Error, projectTypeMismatch, "'project': expression must evaluate to record type '$0'.") +DIAGNOSTIC(30033, Error, invalidTypeForLocalVariable, "cannot declare a local variable of this type.") +DIAGNOSTIC(30035, Error, componentOverloadTypeMismatch, "'$0': type of overloaded component mismatches previous definition.") +DIAGNOSTIC(30041, Error, bitOperationNonIntegral, "bit operation: operand must be integral type.") +DIAGNOSTIC(30047, Error, argumentExpectedLValue, "argument passed to parameter '$0' must be l-value.") +DIAGNOSTIC(30051, Error, invalidValueForArgument, "invalid value for argument '$0'") +DIAGNOSTIC(30052, Error, ordinaryFunctionAsModuleArgument, "ordinary functions not allowed as argument to function-typed module parameter.") +DIAGNOSTIC(30079, Error, selectPrdicateTypeMismatch, "selector must evaluate to bool."); +DIAGNOSTIC(30080, Error, selectValuesTypeMismatch, "the two value expressions in a select clause must have same type."); +DIAGNOSTIC(31040, Error, undefinedTypeName, "undefined type name: '$0'.") +DIAGNOSTIC(32013, Error, circularReferenceNotAllowed, "'$0': circular reference is not allowed."); +DIAGNOSTIC(32014, Error, shaderDoesProvideRequirement, "shader '$0' does not provide '$1' as required by '$2'.") +DIAGNOSTIC(32015, Error, argumentNotAvilableInWorld, "argument '$0' is not available in world '$1' as required by '$2'.") +DIAGNOSTIC(32015, Error, componentNotAvilableInWorld, "component '$0' is not available in world '$1' as required by '$2'.") +DIAGNOSTIC(32047, Error, firstArgumentToImportNotComponent, "first argument of an import operator call does not resolve to a component."); +DIAGNOSTIC(32051, Error, componentTypeNotWhatPipelineRequires, "component '$0' has type '$1', but pipeline '$2' requires it to be '$3'.") +DIAGNOSTIC(32052, Error, shaderDoesNotDefineComponentAsRequiredByPipeline, "shader '$0' does not define '$1' as required by pipeline '$2''.") +DIAGNOSTIC(33001, Error, worldNameAlreadyDefined, "world '$0' is already defined.") +DIAGNOSTIC(33002, Error, explicitPipelineSpecificationRequiredForShader, "explicit pipeline specification required for shader '$0' because multiple pipelines are defined in current context.") +DIAGNOSTIC(33003, Error, cannotDefineComponentsInAPipeline, "cannot define components in a pipeline.") +DIAGNOSTIC(33004, Error, undefinedWorldName, "undefined world name '$0'.") +DIAGNOSTIC(33005, Error, abstractWorldAsTargetOfImport, "abstract world cannot appear as target as an import operator.") + +// Note(tfoley): This is a duplicate of 33004 above. +DIAGNOSTIC(33006, Error, undefinedWorldName2, "undefined world name '$0'.") + +DIAGNOSTIC(33007, Error, importOperatorCircularity, "import operator '$0' creates a circular dependency between world '$1' and '$2'") +DIAGNOSTIC(33009, Error, parametersOnlyAllowedInModules, "parameters can only be defined in modules.") +DIAGNOSTIC(33010, Error, undefinedPipelineName, "pipeline '$0' is undefined.") +DIAGNOSTIC(33011, Error, shaderCircularity, "shader '$0' involves circular reference.") +DIAGNOSTIC(33012, Error, worldIsNotDefinedInPipeline, "'$0' is not a defined world in '$1'.") +DIAGNOSTIC(33013, Error, abstractWorldCannotAppearWithOthers, "abstract world cannot appear with other worlds.") +DIAGNOSTIC(33014, Error, nonAbstractComponentMustHaveImplementation, "non-abstract component must have an implementation.") +DIAGNOSTIC(33016, Error, usingInComponentDefinition, "'using': importing not allowed in component definition.") +DIAGNOSTIC(33018, Error, nameAlreadyDefined, "'$0' is already defined.") +DIAGNOSTIC(33018, Error, shaderAlreadyDefined, "shader '$0' has already been defined.") +DIAGNOSTIC(33019, Error, componentMarkedExportMustHaveWorld, "component '$0': definition marked as 'export' must have an explicitly specified world.") +DIAGNOSTIC(33020, Error, componentIsAlreadyDefined, "'$0' is already defined.") +DIAGNOSTIC(33020, Error, componentIsAlreadyDefinedInThatWorld, "'$0' is already defined at '$1'.") +DIAGNOSTIC(33021, Error, inconsistentSignatureForComponent, "'$0': inconsistent signature.") +DIAGNOSTIC(33022, Error, nameAlreadyDefinedInCurrentScope, "'$0' is already defined in current scope.") +DIAGNOSTIC(33022, Error, parameterNameConflictsWithExistingDefinition, "'$0': parameter name conflicts with existing definition.") +DIAGNOSTIC(33023, Error, parameterOfModuleIsUnassigned, "parameter '$0' of module '$1' is unassigned.") +DIAGNOSTIC(33027, Error, argumentTypeDoesNotMatchParameterType, "argument type ($0) does not match parameter type ($1)") +DIAGNOSTIC(33028, Error, nameIsNotAParameterOfCallee, "'$0' is not a parameter of '$1'.") +DIAGNOSTIC(33029, Error, requirementsClashWithPreviousDef, "'$0': requirement clash with previous definition.") +DIAGNOSTIC(33030, Error, positionArgumentAfterNamed, "positional argument cannot appear after a named argument.") +DIAGNOSTIC(33032, Error, functionRedefinition, "'$0': function redefinition.") +DIAGNOSTIC(33034, Error, recordTypeVariableInImportOperator, "cannot declare a record-typed variable in an import operator.") +DIAGNOSTIC(33037, Error, componetMarkedExportCannotHaveParameters, "component '$0': definition marked as 'export' cannot have parameters.") +DIAGNOSTIC(33039, Error, componentInInputWorldCantHaveCode, "'$0': no code allowed for component defined in input world.") +DIAGNOSTIC(33040, Error, requireWithComputation, "'require': cannot define computation on component requirements.") +DIAGNOSTIC(33042, Error, paramWithComputation, "'param': cannot define computation on parameters.") +DIAGNOSTIC(33041, Error, pipelineOfModuleIncompatibleWithPipelineOfShader, "pipeline '$0' targeted by module '$1' is incompatible with pipeline '$2' targeted by shader '$3'.") +DIAGNOSTIC(33070, Error, expectedFunction, "expression preceding parenthesis of apparent call must have function type.") +DIAGNOSTIC(33071, Error, importOperatorCalledFromAutoPlacedComponent, "cannot call an import operator from an auto-placed component '$0'. try qualify the component with explicit worlds.") +DIAGNOSTIC(33072, Error, noApplicableImportOperator, "'$0' is an import operator defined in pipeline '$1', but none of the import operator overloads converting to world '$2' matches argument list ($3).") +DIAGNOSTIC(33073, Error, importOperatorCalledFromMultiWorldComponent, "cannot call an import operator from a multi-world component definition. consider qualify the component with only one explicit world.") +DIAGNOSTIC(33080, Error, componentTypeDoesNotMatchInterface, "'$0': component type does not match definition in interface '$1'.") +DIAGNOSTIC(33081, Error, shaderDidNotDefineComponentFunction, "shader '$0' did not define component function $1 as required by interface '$2'.") +DIAGNOSTIC(33082, Error, shaderDidNotDefineComponent, "shader '$0' did not define component '$1' as required by interface '$2'.") +DIAGNOSTIC(33083, Error, interfaceImplMustBePublic, "'$0': component fulfilling interface '$1' must be declared as 'public'.") +DIAGNOSTIC(33084, Error, defaultParamNotAllowedInInterface, "'$0': default parameter value not allowed in interface definition.") + +DIAGNOSTIC(33100, Error, componentCantBeComputedAtWorldBecauseDependentNotAvailable, "'$0' cannot be computed at '$1' because the dependent component '$2' is not accessible.") +DIAGNOSTIC(33101, Warning, worldIsNotAValidChoiceForKey, "'$0' is not a valid choice for '$1'.") +DIAGNOSTIC(33102, Error, componentDefinitionCircularity, "component definition '$0' involves circular reference.") +DIAGNOSTIC(34024, Error, componentAlreadyDefinedWhenCompiling, "component named '$0' is already defined when compiling '$1'.") +DIAGNOSTIC(34025, Error, globalComponentConflictWithPreviousDeclaration, "'$0': global component conflicts with previous declaration.") +DIAGNOSTIC(34026, Warning, componentIsAlreadyDefinedUseRequire, "'$0': component is already defined when compiling shader '$1'. use 'require' to declare it as a parameter.") +DIAGNOSTIC(34062, Error, cylicReference, "cyclic reference: $0"); +DIAGNOSTIC(34064, Error, noApplicableImplicitImportOperator, "cannot find import operator to import component '$0' to world '$1' when compiling '$2'.") +DIAGNOSTIC(34065, Error, resourceTypeMustBeParamOrRequire, "'$0': resource typed component must be declared as 'param' or 'require'."); +DIAGNOSTIC(34066, Error, cannotDefineComputationOnResourceType, "'$0': cannot define computation on resource typed component."); + +DIAGNOSTIC(35001, Error, fragDepthAttributeCanOnlyApplyToOutput, "FragDepth attribute can only apply to an output component."); +DIAGNOSTIC(35002, Error, fragDepthAttributeCanOnlyApplyToFloatComponent, "FragDepth attribute can only apply to a float component."); + + +DIAGNOSTIC(36001, Error, insufficientTemplateShaderArguments, "instantiating template shader '$0': insufficient arguments."); +DIAGNOSTIC(36002, Error, tooManyTemplateShaderArguments, "instantiating template shader '$0': too many arguments."); +DIAGNOSTIC(36003, Error, templateShaderArgumentIsNotDefined, "'$0' provided as template shader argument to '$1' is not a defined module."); +DIAGNOSTIC(36004, Error, templateShaderArgumentDidNotImplementRequiredInterface, "module '$0' provided as template shader argument to '$1' did not implement required interface '$2'."); + +// TODO: need to assign numbers to all these extra diagnostics... + +DIAGNOSTIC(39999, Error, expectedIntegerConstantWrongType, "expected integer constant (found: '$0')") +DIAGNOSTIC(39999, Error, expectedIntegerConstantNotConstant, "expression does not evaluate to a compile-time constant") +DIAGNOSTIC(39999, Error, expectedIntegerConstantNotLiteral, "could not extract value from integer constant") + +DIAGNOSTIC(39999, Error, noApplicableOverloadForNameWithArgs, "no overload for '$0' applicable to arguments of type $1") +DIAGNOSTIC(39999, Error, noApplicableWithArgs, "no overload applicable to arguments of type $0") + +DIAGNOSTIC(39999, Error, ambiguousOverloadForNameWithArgs, "ambiguous call to '$0' operation with arguments of type $1") +DIAGNOSTIC(39999, Error, ambiguousOverloadWithArgs, "ambiguous call to overloaded operation with arguments of type $0") + +DIAGNOSTIC(39999, Note, overloadCandidate, "candidate: $0") +DIAGNOSTIC(39999, Note, moreOverloadCandidates, "$0 more overload candidates") + +DIAGNOSTIC(39999, Error, caseOutsideSwitch, "'case' not allowed outside of a 'switch' statement") +DIAGNOSTIC(39999, Error, defaultOutsideSwitch, "'default' not allowed outside of a 'switch' statement") + +DIAGNOSTIC(39999, Error, expectedAGeneric, "expected a generic when using '<...>' (found: '$0')") + +DIAGNOSTIC(39999, Error, genericArgumentInferenceFailed, "could not specialize generic for arguments of type $0") +DIAGNOSTIC(39999, Note, genericSignatureTried, "see declaration of $0") + +DIAGNOSTIC(39999, Error, expectedATraitGot, "expected a trait, got '$0'") + +DIAGNOSTIC(39999, Error, ambiguousReference, "amiguous reference to '$0'"); + +DIAGNOSTIC(39999, Error, declarationDidntDeclareAnything, "declaration does not declare anything"); + + +DIAGNOSTIC(39999, Error, expectedPrefixOperator, "function called as prefix operator was not declared `__prefix`") +DIAGNOSTIC(39999, Error, expectedPostfixOperator, "function called as postfix operator was not declared `__postfix`") + +DIAGNOSTIC(39999, Error, notEnoughArguments, "not enough arguments to call (got $0, expected $1)") +DIAGNOSTIC(39999, Error, tooManyArguments, "too many arguments to call (got $0, expected $1)") + +// +// 4xxxx - IL code generation. +// +DIAGNOSTIC(40001, Error, bindingAlreadyOccupiedByComponent, "resource binding location '$0' is already occupied by component '$1'.") +DIAGNOSTIC(40002, Error, invalidBindingValue, "binding location '$0' is out of valid range.") +DIAGNOSTIC(40003, Error, bindingExceedsLimit, "binding location '$0' assigned to component '$1' exceeds maximum limit.") +DIAGNOSTIC(40004, Error, bindingAlreadyOccupiedByModule, "DescriptorSet ID '$0' is already occupied by module instance '$1'.") +DIAGNOSTIC(40005, Error, topLevelModuleUsedWithoutSpecifyingBinding, "top level module '$0' is being used without specifying binding location. Use [Binding: \"index\"] attribute to provide a binding location.") +// +// 5xxxx - Target code generation. +// + +DIAGNOSTIC(50020, Error, unknownStageType, "Unknown stage type '$0'.") +DIAGNOSTIC(50020, Error, invalidTessCoordType, "TessCoord must have vec2 or vec3 type.") +DIAGNOSTIC(50020, Error, invalidFragCoordType, "FragCoord must be a vec4.") +DIAGNOSTIC(50020, Error, invalidInvocationIdType, "InvocationId must have int type.") +DIAGNOSTIC(50020, Error, invalidThreadIdType, "ThreadId must have int type.") +DIAGNOSTIC(50020, Error, invalidPrimitiveIdType, "PrimitiveId must have int type.") +DIAGNOSTIC(50020, Error, invalidPatchVertexCountType, "PatchVertexCount must have int type.") +DIAGNOSTIC(50022, Error, worldIsNotDefined, "world '$0' is not defined."); +DIAGNOSTIC(50023, Error, stageShouldProvideWorldAttribute, "'$0' should provide 'World' attribute."); +DIAGNOSTIC(50040, Error, componentHasInvalidTypeForPositionOutput, "'$0': component used as 'Position' output must be of vec4 type.") +DIAGNOSTIC(50041, Error, componentNotDefined, "'$0': component not defined.") + +DIAGNOSTIC(50052, Error, domainShaderRequiresControlPointCount, "'DomainShader' requires attribute 'ControlPointCount'."); +DIAGNOSTIC(50052, Error, hullShaderRequiresControlPointCount, "'HullShader' requires attribute 'ControlPointCount'.") +DIAGNOSTIC(50052, Error, hullShaderRequiresControlPointWorld, "'HullShader' requires attribute 'ControlPointWorld'."); +DIAGNOSTIC(50052, Error, hullShaderRequiresCornerPointWorld, "'HullShader' requires attribute 'CornerPointWorld'."); +DIAGNOSTIC(50052, Error, hullShaderRequiresDomain, "'HullShader' requires attribute 'Domain'."); +DIAGNOSTIC(50052, Error, hullShaderRequiresInputControlPointCount, "'HullShader' requires attribute 'InputControlPointCount'.") +DIAGNOSTIC(50052, Error, hullShaderRequiresOutputTopology, "'HullShader' requires attribute 'OutputTopology'.") +DIAGNOSTIC(50052, Error, hullShaderRequiresPartitioning, "'HullShader' requires attribute 'Partitioning'.") +DIAGNOSTIC(50052, Error, hullShaderRequiresPatchWorld, "'HullShader' requires attribute 'PatchWorld'."); +DIAGNOSTIC(50052, Error, hullShaderRequiresTessLevelInner, "'HullShader' requires attribute 'TessLevelInner'.") +DIAGNOSTIC(50052, Error, hullShaderRequiresTessLevelOuter, "'HullShader' requires attribute 'TessLevelOuter'.") + +DIAGNOSTIC(50053, Error, invalidTessellationDomian, "'Domain' should be either 'triangles' or 'quads'."); +DIAGNOSTIC(50053, Error, invalidTessellationOutputTopology, "'OutputTopology' must be one of: 'point', 'line', 'triangle_cw', or 'triangle_ccw'."); +DIAGNOSTIC(50053, Error, invalidTessellationPartitioning, "'Partitioning' must be one of: 'integer', 'pow2', 'fractional_even', or 'fractional_odd'.") +DIAGNOSTIC(50053, Error, invalidTessellationDomain, "'Domain' should be either 'triangles' or 'quads'.") + +DIAGNOSTIC(50082, Error, importingFromPackedBufferUnsupported, "importing type '$0' from PackedBuffer is not supported by the GLSL backend.") +DIAGNOSTIC(51090, Error, cannotGenerateCodeForExternComponentType, "cannot generate code for extern component type '$0'.") +DIAGNOSTIC(51091, Error, typeCannotBePlacedInATexture, "type '$0' cannot be placed in a texture.") +DIAGNOSTIC(51092, Error, stageDoesntHaveInputWorld, "'$0' doesn't appear to have any input world"); + + +// 99999 - Internal compiler errors, and not-yet-classified diagnostics. + +DIAGNOSTIC(99999, Internal, internalCompilerError, "internal compiler error") +DIAGNOSTIC(99999, Internal, unimplemented, "unimplemented feature: $0") + +#undef DIAGNOSTIC diff --git a/source/slang/diagnostics.cpp b/source/slang/diagnostics.cpp new file mode 100644 index 000000000..d8527466b --- /dev/null +++ b/source/slang/diagnostics.cpp @@ -0,0 +1,204 @@ +// Diagnostics.cpp +#include "Diagnostics.h" + +#include "Syntax.h" + +#include + +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#undef WIN32_LEAN_AND_MEAN +#undef NOMINMAX +#include +#endif + +namespace Slang { +namespace Compiler { + +void printDiagnosticArg(StringBuilder& sb, char const* str) +{ + sb << str; +} + +void printDiagnosticArg(StringBuilder& sb, int str) +{ + sb << str; +} + +void printDiagnosticArg(StringBuilder& sb, CoreLib::Basic::String const& str) +{ + sb << str; +} + +void printDiagnosticArg(StringBuilder& sb, Decl* decl) +{ + sb << decl->Name.Content; +} + +void printDiagnosticArg(StringBuilder& sb, Type* type) +{ + sb << type->DataType->ToString(); +} + +void printDiagnosticArg(StringBuilder& sb, ExpressionType* type) +{ + sb << type->ToString(); +} + +void printDiagnosticArg(StringBuilder& sb, TypeExp const& type) +{ + sb << type.type->ToString(); +} + +void printDiagnosticArg(StringBuilder& sb, QualType const& type) +{ + sb << type.type->ToString(); +} + +void printDiagnosticArg(StringBuilder& sb, TokenType tokenType) +{ + sb << TokenTypeToString(tokenType); +} + +void printDiagnosticArg(StringBuilder& sb, Token const& token) +{ + sb << token.Content; +} + +CodePosition const& getDiagnosticPos(SyntaxNode const* syntax) +{ + return syntax->Position; +} + +CodePosition const& getDiagnosticPos(Token const& token) +{ + return token.Position; +} + +CodePosition const& getDiagnosticPos(TypeExp const& typeExp) +{ + return typeExp.exp->Position; +} + +// Take the format string for a diagnostic message, along with its arguments, and turn it into a +static void formatDiagnosticMessage(StringBuilder& sb, char const* format, int argCount, DiagnosticArg const* const* args) +{ + char const* spanBegin = format; + for(;;) + { + char const* spanEnd = spanBegin; + while (int c = *spanEnd) + { + if (c == '$') + break; + spanEnd++; + } + + sb.Append(spanBegin, int(spanEnd - spanBegin)); + if (!*spanEnd) + return; + + assert(*spanEnd == '$'); + spanEnd++; + int d = *spanEnd++; + switch (d) + { + // A double dollar sign `$$` is used to emit a single `$` + case '$': + sb.Append('$'); + break; + + // A single digit means to emit the corresponding argument. + // TODO: support more than 10 arguments, and add options + // to control formatting, etc. + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + { + int index = d - '0'; + if (index >= argCount) + { + // TODO(tfoley): figure out what a good policy will be for "panic" situations like this + throw InvalidOperationException("too few arguments for diagnostic message"); + } + else + { + DiagnosticArg const* arg = args[index]; + arg->printFunc(sb, arg->data); + } + } + break; + + default: + throw InvalidOperationException("invalid diagnostic message format"); + break; + } + + spanBegin = spanEnd; + } +} + +static void formatDiagnostic( + StringBuilder& sb, + Diagnostic const& diagnostic) +{ + sb << diagnostic.Position.FileName; + sb << "("; + sb << diagnostic.Position.Line; + sb << "): "; + sb << getSeverityName(diagnostic.severity); + sb << " "; + sb << diagnostic.ErrorID; + sb << ": "; + sb << diagnostic.Message; + sb << "\n"; +} + +void DiagnosticSink::diagnoseImpl(CodePosition const& pos, DiagnosticInfo const& info, int argCount, DiagnosticArg const* const* args) +{ + StringBuilder sb; + formatDiagnosticMessage(sb, info.messageFormat, argCount, args); + + Diagnostic diagnostic; + diagnostic.ErrorID = info.id; + diagnostic.Message = sb.ProduceString(); + diagnostic.Position = pos; + diagnostic.severity = info.severity; + + if (diagnostic.severity >= Severity::Error) + { + errorCount++; + } + + // Did the client supply a callback for us to use? + if( callback ) + { + // If so, pass the error string along to them + StringBuilder sb; + formatDiagnostic(sb, diagnostic); + + callback(sb.ProduceString().begin(), callbackUserData); + } + else + { + // If the user doesn't have a callback, then just + // collect our diagnostic messages into a buffer + formatDiagnostic(outputBuffer, diagnostic); + } + + if (diagnostic.severity >= Severity::Fatal) + { + // TODO: figure out a better policy for aborting compilation + throw InvalidOperationException(); + } +} + +namespace Diagnostics +{ +#define DIAGNOSTIC(id, severity, name, messageFormat) const DiagnosticInfo name = { id, Severity::severity, messageFormat }; +#include "diagnostic-defs.h" +} + + +}} // namespace Slang::Compiler diff --git a/source/slang/diagnostics.h b/source/slang/diagnostics.h new file mode 100644 index 000000000..c1559df5d --- /dev/null +++ b/source/slang/diagnostics.h @@ -0,0 +1,218 @@ +#ifndef RASTER_RENDERER_COMPILE_ERROR_H +#define RASTER_RENDERER_COMPILE_ERROR_H + +#include "../core/basic.h" + +#include "source-loc.h" +#include "token.h" + +#include "../../slang.h" + +namespace Slang +{ + namespace Compiler + { + using namespace CoreLib::Basic; + + enum class Severity + { + Note, + Warning, + Error, + Fatal, + Internal, + }; + + // TODO(tfoley): move this into a source file... + inline const char* getSeverityName(Severity severity) + { + switch (severity) + { + case Severity::Note: return "note"; + case Severity::Warning: return "warning"; + case Severity::Error: return "error"; + case Severity::Fatal: return "fatal error"; + case Severity::Internal: return "internal error"; + default: return "unknown error"; + } + } + + // A structure to be used in static data describing different + // diagnostic messages. + struct DiagnosticInfo + { + int id; + Severity severity; + char const* messageFormat; + }; + + class Diagnostic + { + public: + String Message; + CodePosition Position; + int ErrorID; + Severity severity; + + Diagnostic() + { + ErrorID = -1; + } + Diagnostic( + const String & msg, + int id, + const CodePosition & pos, + Severity severity) + : severity(severity) + { + Message = msg; + ErrorID = id; + Position = pos; + } + }; + + class Decl; + class Type; + class ExpressionType; + class ILType; + class StageAttribute; + struct TypeExp; + struct QualType; + + void printDiagnosticArg(StringBuilder& sb, char const* str); + void printDiagnosticArg(StringBuilder& sb, int val); + void printDiagnosticArg(StringBuilder& sb, CoreLib::Basic::String const& str); + void printDiagnosticArg(StringBuilder& sb, Decl* decl); + void printDiagnosticArg(StringBuilder& sb, Type* type); + void printDiagnosticArg(StringBuilder& sb, ExpressionType* type); + void printDiagnosticArg(StringBuilder& sb, TypeExp const& type); + void printDiagnosticArg(StringBuilder& sb, QualType const& type); + void printDiagnosticArg(StringBuilder& sb, TokenType tokenType); + void printDiagnosticArg(StringBuilder& sb, Token const& token); + + template + void printDiagnosticArg(StringBuilder& sb, RefPtr ptr) + { + printDiagnosticArg(sb, ptr.Ptr()); + } + + inline CodePosition const& getDiagnosticPos(CodePosition const& pos) { return pos; } + + class SyntaxNode; + class ShaderClosure; + CodePosition const& getDiagnosticPos(SyntaxNode const* syntax); + CodePosition const& getDiagnosticPos(Token const& token); + CodePosition const& getDiagnosticPos(TypeExp const& typeExp); + + template + CodePosition getDiagnosticPos(RefPtr const& ptr) + { + return getDiagnosticPos(ptr.Ptr()); + } + + struct DiagnosticArg + { + void* data; + void (*printFunc)(StringBuilder&, void*); + + template + struct Helper + { + static void printFunc(StringBuilder& sb, void* data) { printDiagnosticArg(sb, *(T*)data); } + }; + + template + DiagnosticArg(T const& arg) + : data((void*)&arg) + , printFunc(&Helper::printFunc) + {} + }; + + class DiagnosticSink + { + public: + StringBuilder outputBuffer; +// List diagnostics; + int errorCount = 0; + + SlangDiagnosticCallback callback = nullptr; + void* callbackUserData = nullptr; + +/* + void Error(int id, const String & msg, const CodePosition & pos) + { + diagnostics.Add(Diagnostic(msg, id, pos, Severity::Error)); + errorCount++; + } + + void Warning(int id, const String & msg, const CodePosition & pos) + { + diagnostics.Add(Diagnostic(msg, id, pos, Severity::Warning)); + } +*/ + int GetErrorCount() { return errorCount; } + + void diagnoseDispatch(CodePosition const& pos, DiagnosticInfo const& info) + { + diagnoseImpl(pos, info, 0, NULL); + } + + void diagnoseDispatch(CodePosition const& pos, DiagnosticInfo const& info, DiagnosticArg const& arg0) + { + DiagnosticArg const* args[] = { &arg0 }; + diagnoseImpl(pos, info, 1, args); + } + + void diagnoseDispatch(CodePosition const& pos, DiagnosticInfo const& info, DiagnosticArg const& arg0, DiagnosticArg const& arg1) + { + DiagnosticArg const* args[] = { &arg0, &arg1 }; + diagnoseImpl(pos, info, 2, args); + } + + void diagnoseDispatch(CodePosition const& pos, DiagnosticInfo const& info, DiagnosticArg const& arg0, DiagnosticArg const& arg1, DiagnosticArg const& arg2) + { + DiagnosticArg const* args[] = { &arg0, &arg1, &arg2 }; + diagnoseImpl(pos, info, 3, args); + } + + void diagnoseDispatch(CodePosition const& pos, DiagnosticInfo const& info, DiagnosticArg const& arg0, DiagnosticArg const& arg1, DiagnosticArg const& arg2, DiagnosticArg const& arg3) + { + DiagnosticArg const* args[] = { &arg0, &arg1, &arg2, &arg3 }; + diagnoseImpl(pos, info, 4, args); + } + + template + void diagnose(P const& pos, DiagnosticInfo const& info, Args const&... args ) + { + diagnoseDispatch(getDiagnosticPos(pos), info, args...); + } + + void diagnoseImpl(CodePosition const& pos, DiagnosticInfo const& info, int argCount, DiagnosticArg const* const* args); + }; + + namespace Diagnostics + { +#define DIAGNOSTIC(id, severity, name, messageFormat) extern const DiagnosticInfo name; +#include "diagnostic-defs.h" + } + } +} + +#ifdef _DEBUG +#define SLANG_INTERNAL_ERROR(sink, pos) \ + (sink)->diagnose(Slang::Compiler::CodePosition(__LINE__, 0, 0, __FILE__), Slang::Compiler::Diagnostics::internalCompilerError) +#define SLANG_UNIMPLEMENTED(sink, pos, what) \ + (sink)->diagnose(Slang::Compiler::CodePosition(__LINE__, 0, 0, __FILE__), Slang::Compiler::Diagnostics::unimplemented, what) + +#define SLANG_UNREACHABLE(msg) do { assert(!"ureachable code:" msg); exit(1); } while(0) +#else +#define SLANG_INTERNAL_ERROR(sink, pos) \ + (sink)->diagnose(pos, Slang::Compiler::Diagnostics::internalCompilerError) +#define SLANG_UNIMPLEMENTED(sink, pos, what) \ + (sink)->diagnose(pos, Slang::Compiler::Diagnostics::unimplemented, what) + +// TODO: find something that will perform better +#define SLANG_UNREACHABLE(msg) exit(1) +#endif + +#endif diff --git a/source/slang/emit.cpp b/source/slang/emit.cpp new file mode 100644 index 000000000..6b488a68f --- /dev/null +++ b/source/slang/emit.cpp @@ -0,0 +1,2537 @@ +// emit.cpp +#include "emit.h" + +#include "syntax.h" +#include "type-layout.h" + +#include + +#ifdef _WIN32 +#include +#pragma warning(disable:4996) +#endif + +namespace Slang { namespace Compiler { + +struct EmitContext +{ + StringBuilder sb; + + // Current source position for tracking purposes... + CodePosition loc; + + // The target language we want to generate code for + CodeGenTarget target; + + // A set of words reserved by the target + Dictionary reservedWords; +}; + +// + +static void EmitDecl(EmitContext* context, RefPtr decl); +static void EmitDecl(EmitContext* context, RefPtr declBase); +static void EmitDeclUsingLayout(EmitContext* context, RefPtr decl, RefPtr layout); +static void EmitType(EmitContext* context, RefPtr type, String const& name); +static void EmitType(EmitContext* context, RefPtr type); +static void EmitExpr(EmitContext* context, RefPtr expr); +static void EmitStmt(EmitContext* context, RefPtr stmt); +static void EmitDeclRef(EmitContext* context, DeclRef declRef); + +// Low-level emit logic + +static void emitRawTextSpan(EmitContext* context, char const* textBegin, char const* textEnd) +{ + // TODO(tfoley): Need to make "corelib" not use `int` for pointer-sized things... + auto len = int(textEnd - textBegin); + + context->sb.Append(textBegin, len); +} + +static void emitRawText(EmitContext* context, char const* text) +{ + emitRawTextSpan(context, text, text + strlen(text)); +} + +static void emitTextSpan(EmitContext* context, char const* textBegin, char const* textEnd) +{ + // Emit the raw text + emitRawTextSpan(context, textBegin, textEnd); + + // Update our logical position + // TODO(tfoley): Need to make "corelib" not use `int` for pointer-sized things... + auto len = int(textEnd - textBegin); + context->loc.Col += len; +} + +static void Emit(EmitContext* context, char const* textBegin, char const* textEnd) +{ + char const* spanBegin = textBegin; + + char const* spanEnd = spanBegin; + for(;;) + { + if(spanEnd == textEnd) + { + // We have a whole range of text waiting to be flushed + emitTextSpan(context, spanBegin, spanEnd); + return; + } + + auto c = *spanEnd++; + + if( c == '\n' ) + { + // At the end of a line, we need to update our tracking + // information on code positions + emitTextSpan(context, spanBegin, spanEnd); + context->loc.Line++; + context->loc.Col = 1; + + // Start a new span for emit purposes + spanBegin = spanEnd; + } + } +} + +static void Emit(EmitContext* context, char const* text) +{ + Emit(context, text, text + strlen(text)); +} + +static void emit(EmitContext* context, String const& text) +{ + Emit(context, text.begin(), text.end()); +} + +static bool isReservedWord(EmitContext* context, String const& name) +{ + return context->reservedWords.TryGetValue(name) != nullptr; +} + +static void emitName(EmitContext* context, String const& inName) +{ + String name = inName; + + // By default, we would like to emit a name in the generated + // code exactly as it appeared in the soriginal program. + // When that isn't possible, we'd like to emit a name as + // close to the original as possible (to ensure that existing + // debugging tools still work reasonably well). + // + // One reason why a name might not be allowed as-is is that + // it could collide with a reserved word in the target language. + // Another reason is that it might not follow a naming convention + // imposed by the target (e.g., in GLSL names starting with + // `gl_` or containing `__` are reserved). + // + // Given a name that should not be allowed, we want to + // change it to a name that *is* allowed. e.g., by adding + // `_` to the end of a reserved word. + // + // The next problem this creates is that the modified name + // could not collide with an existing use of the same + // (valid) name. + // + // For now we are going to solve this problem in a simple + // and ad hoc fashion, but longer term we'll want to do + // something sytematic. + + if (isReservedWord(context, name)) + { + name = name + "_"; + } + + emit(context, name); +} + +static void Emit(EmitContext* context, UInt value) +{ + char buffer[32]; + sprintf(buffer, "%llu", (unsigned long long)(value)); + Emit(context, buffer); +} + +static void Emit(EmitContext* context, int value) +{ + char buffer[16]; + sprintf(buffer, "%d", value); + Emit(context, buffer); +} + +static void Emit(EmitContext* context, double value) +{ + // TODO(tfoley): need to print things in a way that can round-trip + char buffer[128]; + sprintf(buffer, "%.20ff", value); + Emit(context, buffer); +} + +// Expressions + +// Determine if an expression should not be emitted when it is the base of +// a member reference expression. +static bool IsBaseExpressionImplicit(EmitContext* /*context*/, RefPtr expr) +{ + // HACK(tfoley): For now, anything with a constant-buffer type should be + // left implicit. + + // Look through any dereferencing that took place + RefPtr e = expr; + while (auto derefExpr = e.As()) + { + e = derefExpr->base; + } + // Is the expression referencing a constant buffer? + if (auto cbufferType = e->Type->As()) + { + return true; + } + + return false; +} + +enum +{ + kPrecedence_None, + kPrecedence_Comma, + + kPrecedence_Assign, + kPrecedence_AddAssign = kPrecedence_Assign, + kPrecedence_SubAssign = kPrecedence_Assign, + kPrecedence_MulAssign = kPrecedence_Assign, + kPrecedence_DivAssign = kPrecedence_Assign, + kPrecedence_ModAssign = kPrecedence_Assign, + kPrecedence_LshAssign = kPrecedence_Assign, + kPrecedence_RshAssign = kPrecedence_Assign, + kPrecedence_OrAssign = kPrecedence_Assign, + kPrecedence_AndAssign = kPrecedence_Assign, + kPrecedence_XorAssign = kPrecedence_Assign, + + kPrecedence_General = kPrecedence_Assign, + + kPrecedence_Conditional, // "ternary" + kPrecedence_Or, + kPrecedence_And, + kPrecedence_BitOr, + kPrecedence_BitXor, + kPrecedence_BitAnd, + + kPrecedence_Eql, + kPrecedence_Neq = kPrecedence_Eql, + + kPrecedence_Less, + kPrecedence_Greater = kPrecedence_Less, + kPrecedence_Leq = kPrecedence_Less, + kPrecedence_Geq = kPrecedence_Less, + + kPrecedence_Lsh, + kPrecedence_Rsh = kPrecedence_Lsh, + + kPrecedence_Add, + kPrecedence_Sub = kPrecedence_Add, + + kPrecedence_Mul, + kPrecedence_Div = kPrecedence_Mul, + kPrecedence_Mod = kPrecedence_Mul, + + kPrecedence_Prefix, + kPrecedence_Postfix, + kPrecedence_Atomic = kPrecedence_Postfix +}; + +static void EmitExprWithPrecedence(EmitContext* context, RefPtr expr, int outerPrec); + +static void EmitPostfixExpr(EmitContext* context, RefPtr expr) +{ + EmitExprWithPrecedence(context, expr, kPrecedence_Postfix); +} + +static void EmitExpr(EmitContext* context, RefPtr expr) +{ + EmitExprWithPrecedence(context, expr, kPrecedence_General); +} + +static bool MaybeEmitParens(EmitContext* context, int outerPrec, int prec) +{ + if (prec <= outerPrec) + { + Emit(context, "("); + return true; + } + return false; +} + +// When we are going to emit an expression in an l-value context, +// we may need to ignore certain constructs that the type-checker +// might have introduced, but which interfere with our ability +// to use it effectively in the target language +static RefPtr prepareLValueExpr( + EmitContext* context, + RefPtr expr) +{ + for(;;) + { + if(auto typeCastExpr = expr.As()) + { + expr = typeCastExpr->Expression; + } + // TODO: any other cases? + else + { + return expr; + } + } + +} + +static void emitInfixExprImpl( + EmitContext* context, + int outerPrec, + int prec, + char const* op, + RefPtr binExpr, + bool isAssign) +{ + bool needsClose = MaybeEmitParens(context, outerPrec, prec); + + auto left = binExpr->Arguments[0]; + if(isAssign) + { + left = prepareLValueExpr(context, left); + } + + EmitExprWithPrecedence(context, left, prec); + Emit(context, " "); + Emit(context, op); + Emit(context, " "); + EmitExprWithPrecedence(context, binExpr->Arguments[1], prec); + if (needsClose) + { + Emit(context, ")"); + } +} + +static void EmitBinExpr(EmitContext* context, int outerPrec, int prec, char const* op, RefPtr binExpr) +{ + emitInfixExprImpl(context, outerPrec, prec, op, binExpr, false); +} + +static void EmitBinAssignExpr(EmitContext* context, int outerPrec, int prec, char const* op, RefPtr binExpr) +{ + emitInfixExprImpl(context, outerPrec, prec, op, binExpr, true); +} + +static void emitUnaryExprImpl( + EmitContext* context, + int outerPrec, + int prec, + char const* preOp, + char const* postOp, + RefPtr expr, + bool isAssign) +{ + bool needsClose = MaybeEmitParens(context, outerPrec, prec); + Emit(context, preOp); + + auto arg = expr->Arguments[0]; + if(isAssign) + { + arg = prepareLValueExpr(context, arg); + } + + EmitExprWithPrecedence(context, arg, prec); + Emit(context, postOp); + if (needsClose) + { + Emit(context, ")"); + } +} + +static void EmitUnaryExpr( + EmitContext* context, + int outerPrec, + int prec, + char const* preOp, + char const* postOp, + RefPtr expr) +{ + emitUnaryExprImpl(context, outerPrec, prec, preOp, postOp, expr, false); +} + +static void EmitUnaryAssignExpr( + EmitContext* context, + int outerPrec, + int prec, + char const* preOp, + char const* postOp, + RefPtr expr) +{ + emitUnaryExprImpl(context, outerPrec, prec, preOp, postOp, expr, true); +} + +static void emitCallExpr( + EmitContext* context, + RefPtr callExpr, + int outerPrec) +{ + auto funcExpr = callExpr->FunctionExpr; + if (auto funcDeclRefExpr = funcExpr.As()) + { + auto funcDeclRef = funcDeclRefExpr->declRef; + auto funcDecl = funcDeclRef.GetDecl(); + if (auto intrinsicModifier = funcDecl->FindModifier()) + { + switch (intrinsicModifier->op) + { +#define CASE(NAME, OP) case IntrinsicOp::NAME: EmitBinExpr(context, outerPrec, kPrecedence_##NAME, #OP, callExpr); return + CASE(Mul, *); + CASE(Div, / ); + CASE(Mod, %); + CASE(Add, +); + CASE(Sub, -); + CASE(Lsh, << ); + CASE(Rsh, >> ); + CASE(Eql, == ); + CASE(Neq, != ); + CASE(Greater, >); + CASE(Less, <); + CASE(Geq, >= ); + CASE(Leq, <= ); + CASE(BitAnd, &); + CASE(BitXor, ^); + CASE(BitOr, | ); + CASE(And, &&); + CASE(Or, || ); +#undef CASE + +#define CASE(NAME, OP) case IntrinsicOp::NAME: EmitBinAssignExpr(context, outerPrec, kPrecedence_##NAME, #OP, callExpr); return + CASE(Assign, =); + CASE(AddAssign, +=); + CASE(SubAssign, -=); + CASE(MulAssign, *=); + CASE(DivAssign, /=); + CASE(ModAssign, %=); + CASE(LshAssign, <<=); + CASE(RshAssign, >>=); + CASE(OrAssign, |=); + CASE(AndAssign, &=); + CASE(XorAssign, ^=); +#undef CASE + + case IntrinsicOp::Sequence: EmitBinExpr(context, outerPrec, kPrecedence_Comma, ",", callExpr); return; + +#define CASE(NAME, OP) case IntrinsicOp::NAME: EmitUnaryExpr(context, outerPrec, kPrecedence_Prefix, #OP, "", callExpr); return + CASE(Neg, -); + CASE(Not, !); + CASE(BitNot, ~); +#undef CASE + +#define CASE(NAME, OP) case IntrinsicOp::NAME: EmitUnaryAssignExpr(context, outerPrec, kPrecedence_Prefix, #OP, "", callExpr); return + CASE(PreInc, ++); + CASE(PreDec, --); +#undef CASE + +#define CASE(NAME, OP) case IntrinsicOp::NAME: EmitUnaryAssignExpr(context, outerPrec, kPrecedence_Postfix, "", #OP, callExpr); return + CASE(PostInc, ++); + CASE(PostDec, --); +#undef CASE + + case IntrinsicOp::InnerProduct_Vector_Vector: + // HLSL allows `mul()` to be used as a synonym for `dot()`, + // so we need to translate to `dot` for GLSL + if (context->target == CodeGenTarget::GLSL) + { + Emit(context, "dot("); + EmitExpr(context, callExpr->Arguments[0]); + Emit(context, ", "); + EmitExpr(context, callExpr->Arguments[1]); + Emit(context, ")"); + return; + } + break; + + case IntrinsicOp::InnerProduct_Matrix_Matrix: + case IntrinsicOp::InnerProduct_Matrix_Vector: + case IntrinsicOp::InnerProduct_Vector_Matrix: + // HLSL exposes these with the `mul()` function, while GLSL uses ordinary + // `operator*`. + // + // The other critical detail here is that the way we handle matrix + // conventions requires that the operands to the product be swapped. + if (context->target == CodeGenTarget::GLSL) + { + Emit(context, "(("); + EmitExpr(context, callExpr->Arguments[1]); + Emit(context, ") * ("); + EmitExpr(context, callExpr->Arguments[0]); + Emit(context, "))"); + return; + } + break; + + default: + break; + } + + + // We might be calling an intrinsic subscript operation, + // and should desugar it accordingly + if(auto subscriptDeclRef = funcDeclRef.As()) + { + // We expect any subscript operation to be invoked as a member, + // so the function expression had better be in the correct form. + if(auto memberExpr = funcExpr.As()) + { + + Emit(context, "("); + EmitExpr(context, memberExpr->BaseExpression); + Emit(context, ")["); + int argCount = callExpr->Arguments.Count(); + for (int aa = 0; aa < argCount; ++aa) + { + if (aa != 0) Emit(context, ", "); + EmitExpr(context, callExpr->Arguments[aa]); + } + Emit(context, "]"); + return; + } + } + } + } + + // Fall through to default handling... + + bool needClose = MaybeEmitParens(context, outerPrec, kPrecedence_Postfix); + + if (auto funcDeclRefExpr = funcExpr.As()) + { + auto declRef = funcDeclRefExpr->declRef; + if (auto ctorDeclRef = declRef.As()) + { + // We really want to emit a reference to the type begin constructed + EmitType(context, callExpr->Type); + } + else + { + // default case: just emit the decl ref + EmitExpr(context, funcExpr); + } + } + else + { + // default case: just emit the expression + EmitPostfixExpr(context, funcExpr); + } + + Emit(context, "("); + int argCount = callExpr->Arguments.Count(); + for (int aa = 0; aa < argCount; ++aa) + { + if (aa != 0) Emit(context, ", "); + EmitExpr(context, callExpr->Arguments[aa]); + } + Emit(context, ")"); + + if (needClose) + { + Emit(context, ")"); + } +} + +static void EmitExprWithPrecedence(EmitContext* context, RefPtr expr, int outerPrec) +{ + bool needClose = false; + if (auto selectExpr = expr.As()) + { + needClose = MaybeEmitParens(context, outerPrec, kPrecedence_Conditional); + + EmitExprWithPrecedence(context, selectExpr->Arguments[0], kPrecedence_Conditional); + Emit(context, " ? "); + EmitExprWithPrecedence(context, selectExpr->Arguments[1], kPrecedence_Conditional); + Emit(context, " : "); + EmitExprWithPrecedence(context, selectExpr->Arguments[2], kPrecedence_Conditional); + } + else if (auto callExpr = expr.As()) + { + emitCallExpr(context, callExpr, outerPrec); + } + else if (auto memberExpr = expr.As()) + { + needClose = MaybeEmitParens(context, outerPrec, kPrecedence_Postfix); + + // TODO(tfoley): figure out a good way to reference + // declarations that might be generic and/or might + // not be generated as lexically nested declarations... + + // TODO(tfoley): also, probably need to special case + // this for places where we are using a built-in... + + auto base = memberExpr->BaseExpression; + if (IsBaseExpressionImplicit(context, base)) + { + // don't emit the base expression + } + else + { + EmitExprWithPrecedence(context, memberExpr->BaseExpression, kPrecedence_Postfix); + Emit(context, "."); + } + + emitName(context, memberExpr->declRef.GetName()); + } + else if (auto swizExpr = expr.As()) + { + needClose = MaybeEmitParens(context, outerPrec, kPrecedence_Postfix); + + EmitExprWithPrecedence(context, swizExpr->base, kPrecedence_Postfix); + Emit(context, "."); + static const char* kComponentNames[] = { "x", "y", "z", "w" }; + int elementCount = swizExpr->elementCount; + for (int ee = 0; ee < elementCount; ++ee) + { + Emit(context, kComponentNames[swizExpr->elementIndices[ee]]); + } + } + else if (auto indexExpr = expr.As()) + { + needClose = MaybeEmitParens(context, outerPrec, kPrecedence_Postfix); + + EmitExprWithPrecedence(context, indexExpr->BaseExpression, kPrecedence_Postfix); + Emit(context, "["); + EmitExpr(context, indexExpr->IndexExpression); + Emit(context, "]"); + } + else if (auto varExpr = expr.As()) + { + needClose = MaybeEmitParens(context, outerPrec, kPrecedence_Atomic); + + // Because of the "rewriter" use case, it is possible that we will + // be trying to emit an expression that hasn't been wired up to + // any associated declaration. In that case, we will just emit + // the variable name. + // + // TODO: A better long-term solution here is to have a distinct + // case for an "unchecked" `NameExpr` that doesn't include + // a declaration reference. + + if(varExpr->declRef) + { + EmitDeclRef(context, varExpr->declRef); + } + else + { + emitName(context, varExpr->Variable); + } + } + else if (auto derefExpr = expr.As()) + { + // TODO(tfoley): dereference shouldn't always be implicit + EmitExprWithPrecedence(context, derefExpr->base, outerPrec); + } + else if (auto litExpr = expr.As()) + { + needClose = MaybeEmitParens(context, outerPrec, kPrecedence_Atomic); + + switch (litExpr->ConstType) + { + case ConstantExpressionSyntaxNode::ConstantType::Int: + Emit(context, litExpr->IntValue); + break; + case ConstantExpressionSyntaxNode::ConstantType::Float: + Emit(context, litExpr->FloatValue); + break; + case ConstantExpressionSyntaxNode::ConstantType::Bool: + Emit(context, litExpr->IntValue ? "true" : "false"); + break; + default: + assert(!"unreachable"); + break; + } + } + else if (auto castExpr = expr.As()) + { + switch(context->target) + { + case CodeGenTarget::GLSL: + // GLSL requires constructor syntax for all conversions + EmitType(context, castExpr->Type); + Emit(context, "("); + EmitExpr(context, castExpr->Expression); + Emit(context, ")"); + break; + + default: + // HLSL (and C/C++) prefer cast syntax + // (In fact, HLSL doesn't allow constructor syntax for some conversions it allows as a cast) + needClose = MaybeEmitParens(context, outerPrec, kPrecedence_Prefix); + + Emit(context, "("); + EmitType(context, castExpr->Type); + Emit(context, ")("); + EmitExpr(context, castExpr->Expression); + Emit(context, ")"); + break; + } + + } + else if(auto initExpr = expr.As()) + { + Emit(context, "{ "); + for(auto& arg : initExpr->args) + { + EmitExpr(context, arg); + Emit(context, ", "); + } + Emit(context, "}"); + } + else + { + throw "unimplemented"; + } + if (needClose) + { + Emit(context, ")"); + } +} + +// Types + +void Emit(EmitContext* context, RefPtr val) +{ + if(auto constantIntVal = val.As()) + { + Emit(context, constantIntVal->value); + } + else if(auto varRefVal = val.As()) + { + EmitDeclRef(context, varRefVal->declRef); + } + else + { + assert(!"unimplemented"); + } +} + +// represents a declarator for use in emitting types +struct EDeclarator +{ + enum class Flavor + { + Name, + Array, + UnsizedArray, + }; + Flavor flavor; + EDeclarator* next = nullptr; + + // Used for `Flavor::Name` + String name; + + // Used for `Flavor::Array` + IntVal* elementCount; +}; + +static void EmitDeclarator(EmitContext* context, EDeclarator* declarator) +{ + if (!declarator) return; + + Emit(context, " "); + + switch (declarator->flavor) + { + case EDeclarator::Flavor::Name: + emitName(context, declarator->name); + break; + + case EDeclarator::Flavor::Array: + EmitDeclarator(context, declarator->next); + Emit(context, "["); + if(auto elementCount = declarator->elementCount) + { + Emit(context, elementCount); + } + Emit(context, "]"); + break; + + case EDeclarator::Flavor::UnsizedArray: + EmitDeclarator(context, declarator->next); + Emit(context, "[]"); + break; + + default: + assert(!"unreachable"); + break; + } +} + +static void emitGLSLTypePrefix( + EmitContext* context, + RefPtr type) +{ + if(auto basicElementType = type->As()) + { + switch (basicElementType->BaseType) + { + case BaseType::Float: + // no prefix + break; + + case BaseType::Int: Emit(context, "i"); break; + case BaseType::UInt: Emit(context, "u"); break; + case BaseType::Bool: Emit(context, "b"); break; + default: + assert(!"unreachable"); + break; + } + } + else if(auto vectorType = type->As()) + { + emitGLSLTypePrefix(context, vectorType->elementType); + } + else if(auto matrixType = type->As()) + { + emitGLSLTypePrefix(context, matrixType->getElementType()); + } + else + { + assert(!"unreachable"); + } +} + +static void emitHLSLTextureType( + EmitContext* context, + RefPtr texType) +{ + switch(texType->getAccess()) + { + case SLANG_RESOURCE_ACCESS_READ: + break; + + case SLANG_RESOURCE_ACCESS_READ_WRITE: + Emit(context, "RW"); + break; + + case SLANG_RESOURCE_ACCESS_RASTER_ORDERED: + Emit(context, "RasterizerOrdered"); + break; + + case SLANG_RESOURCE_ACCESS_APPEND: + Emit(context, "Append"); + break; + + case SLANG_RESOURCE_ACCESS_CONSUME: + Emit(context, "Consume"); + break; + + default: + assert(!"unreachable"); + break; + } + + switch (texType->GetBaseShape()) + { + case TextureType::Shape1D: Emit(context, "Texture1D"); break; + case TextureType::Shape2D: Emit(context, "Texture2D"); break; + case TextureType::Shape3D: Emit(context, "Texture3D"); break; + case TextureType::ShapeCube: Emit(context, "TextureCube"); break; + default: + assert(!"unreachable"); + break; + } + + if (texType->isMultisample()) + { + Emit(context, "MS"); + } + if (texType->isArray()) + { + Emit(context, "Array"); + } + Emit(context, "<"); + EmitType(context, texType->elementType); + Emit(context, ">"); +} + +static void emitGLSLTextureOrTextureSamplerType( + EmitContext* context, + RefPtr type, + char const* baseName) +{ + emitGLSLTypePrefix(context, type->elementType); + + Emit(context, baseName); + switch (type->GetBaseShape()) + { + case TextureType::Shape1D: Emit(context, "1D"); break; + case TextureType::Shape2D: Emit(context, "2D"); break; + case TextureType::Shape3D: Emit(context, "3D"); break; + case TextureType::ShapeCube: Emit(context, "Cube"); break; + default: + assert(!"unreachable"); + break; + } + + if (type->isMultisample()) + { + Emit(context, "MS"); + } + if (type->isArray()) + { + Emit(context, "Array"); + } +} + +static void emitGLSLTextureType( + EmitContext* context, + RefPtr texType) +{ + emitGLSLTextureOrTextureSamplerType(context, texType, "texture"); +} + +static void emitGLSLTextureSamplerType( + EmitContext* context, + RefPtr type) +{ + emitGLSLTextureOrTextureSamplerType(context, type, "sampler"); +} + +static void emitGLSLImageType( + EmitContext* context, + RefPtr type) +{ + emitGLSLTextureOrTextureSamplerType(context, type, "image"); +} + +static void emitTextureType( + EmitContext* context, + RefPtr texType) +{ + switch(context->target) + { + case CodeGenTarget::HLSL: + emitHLSLTextureType(context, texType); + break; + + case CodeGenTarget::GLSL: + emitGLSLTextureType(context, texType); + break; + + default: + assert(!"unreachable"); + break; + } +} + +static void emitTextureSamplerType( + EmitContext* context, + RefPtr type) +{ + switch(context->target) + { + case CodeGenTarget::GLSL: + emitGLSLTextureSamplerType(context, type); + break; + + default: + assert(!"unreachable"); + break; + } +} + +static void emitImageType( + EmitContext* context, + RefPtr type) +{ + switch(context->target) + { + case CodeGenTarget::HLSL: + emitHLSLTextureType(context, type); + break; + + case CodeGenTarget::GLSL: + emitGLSLImageType(context, type); + break; + + default: + assert(!"unreachable"); + break; + } +} + +static void EmitType(EmitContext* context, RefPtr type, EDeclarator* declarator) +{ + if (auto basicType = type->As()) + { + switch (basicType->BaseType) + { + case BaseType::Void: Emit(context, "void"); break; + case BaseType::Int: Emit(context, "int"); break; + case BaseType::Float: Emit(context, "float"); break; + case BaseType::UInt: Emit(context, "uint"); break; + case BaseType::Bool: Emit(context, "bool"); break; + default: + assert(!"unreachable"); + break; + } + + EmitDeclarator(context, declarator); + return; + } + else if (auto vecType = type->As()) + { + switch(context->target) + { + case CodeGenTarget::GLSL: + case CodeGenTarget::GLSL_Vulkan: + case CodeGenTarget::GLSL_Vulkan_OneDesc: + { + emitGLSLTypePrefix(context, vecType->elementType); + Emit(context, "vec"); + Emit(context, vecType->elementCount); + } + break; + + case CodeGenTarget::HLSL: + // TODO(tfoley): should really emit these with sugar + Emit(context, "vector<"); + EmitType(context, vecType->elementType); + Emit(context, ","); + Emit(context, vecType->elementCount); + Emit(context, ">"); + break; + + default: + assert(!"unreachable"); + break; + } + + Emit(context, " "); + EmitDeclarator(context, declarator); + return; + } + else if (auto matType = type->As()) + { + switch(context->target) + { + case CodeGenTarget::GLSL: + case CodeGenTarget::GLSL_Vulkan: + case CodeGenTarget::GLSL_Vulkan_OneDesc: + { + emitGLSLTypePrefix(context, matType->getElementType()); + Emit(context, "mat"); + Emit(context, matType->getRowCount()); + // TODO(tfoley): only emit the next bit + // for non-square matrix + Emit(context, "x"); + Emit(context, matType->getColumnCount()); + } + break; + + case CodeGenTarget::HLSL: + // TODO(tfoley): should really emit these with sugar + Emit(context, "matrix<"); + EmitType(context, matType->getElementType()); + Emit(context, ","); + Emit(context, matType->getRowCount()); + Emit(context, ","); + Emit(context, matType->getColumnCount()); + Emit(context, "> "); + break; + + default: + assert(!"unreachable"); + break; + } + + Emit(context, " "); + EmitDeclarator(context, declarator); + return; + } + else if (auto texType = type->As()) + { + emitTextureType(context, texType); + Emit(context, " "); + EmitDeclarator(context, declarator); + return; + } + else if (auto textureSamplerType = type->As()) + { + emitTextureSamplerType(context, textureSamplerType); + Emit(context, " "); + EmitDeclarator(context, declarator); + return; + } + else if (auto imageType = type->As()) + { + emitImageType(context, imageType); + Emit(context, " "); + EmitDeclarator(context, declarator); + return; + } + else if (auto samplerStateType = type->As()) + { + switch(context->target) + { + case CodeGenTarget::HLSL: + default: + switch (samplerStateType->flavor) + { + case SamplerStateType::Flavor::SamplerState: Emit(context, "SamplerState"); break; + case SamplerStateType::Flavor::SamplerComparisonState: Emit(context, "SamplerComparisonState"); break; + default: + assert(!"unreachable"); + break; + } + break; + + case CodeGenTarget::GLSL: + Emit(context, "sampler"); + break; + } + + + EmitDeclarator(context, declarator); + return; + } + else if (auto declRefType = type->As()) + { + EmitDeclRef(context, declRefType->declRef); + + EmitDeclarator(context, declarator); + return; + } + else if( auto arrayType = type->As() ) + { + EDeclarator arrayDeclarator; + arrayDeclarator.next = declarator; + + if(arrayType->ArrayLength) + { + arrayDeclarator.flavor = EDeclarator::Flavor::Array; + arrayDeclarator.elementCount = arrayType->ArrayLength.Ptr(); + } + else + { + arrayDeclarator.flavor = EDeclarator::Flavor::UnsizedArray; + } + + + EmitType(context, arrayType->BaseType, &arrayDeclarator); + return; + } + + throw "unimplemented"; +} + +static void EmitType(EmitContext* context, RefPtr type, String const& name) +{ + EDeclarator nameDeclarator; + nameDeclarator.flavor = EDeclarator::Flavor::Name; + nameDeclarator.name = name; + EmitType(context, type, &nameDeclarator); +} + +static void EmitType(EmitContext* context, RefPtr type) +{ + EmitType(context, type, nullptr); +} + +// Statements + +// Emit a statement as a `{}`-enclosed block statement, but avoid adding redundant +// curly braces if the statement is itself a block statement. +static void EmitBlockStmt(EmitContext* context, RefPtr stmt) +{ + // TODO(tfoley): support indenting + Emit(context, "{\n"); + if( auto blockStmt = stmt.As() ) + { + for (auto s : blockStmt->Statements) + { + EmitStmt(context, s); + } + } + else + { + EmitStmt(context, stmt); + } + Emit(context, "}\n"); +} + +static void EmitLoopAttributes(EmitContext* context, RefPtr decl) +{ + // TODO(tfoley): There really ought to be a semantic checking step for attributes, + // that turns abstract syntax into a concrete hierarchy of attribute types (e.g., + // a specific `LoopModifier` or `UnrollModifier`). + + for(auto attr : decl->GetModifiersOfType()) + { + if(attr->nameToken.Content == "loop") + { + Emit(context, "[loop]"); + } + else if(attr->nameToken.Content == "unroll") + { + Emit(context, "[unroll]"); + } + } +} + +static void advanceToSourceLocation( + EmitContext* context, + CodePosition const& sourceLocation) +{ + // If we are currently emitting code at a source location with + // a differnet file or line, *or* if the source location is + // somehow later on the line than what we want to emit, + // then we need to emit a new `#line` directive. + if(sourceLocation.FileName != context->loc.FileName + || sourceLocation.Line != context->loc.Line + || sourceLocation.Col < context->loc.Col) + { + emitRawText(context, "\n#line "); + + char buffer[16]; + sprintf(buffer, "%d", sourceLocation.Line); + emitRawText(context, buffer); + + emitRawText(context, "\""); + for(auto c : sourceLocation.FileName) + { + char charBuffer[] = { c, 0 }; + switch(c) + { + default: + emitRawText(context, charBuffer); + break; + + // TODO: should probably canonicalize paths to not use backslash somewhere else + // in the compilation pipeline... + case '\\': + emitRawText(context, "/"); + break; + } + } + emitRawText(context, "\"\n"); + + context->loc.FileName = sourceLocation.FileName; + context->loc.Line = sourceLocation.Line; + context->loc.Col = 1; + } + + // Now indent up to the appropriate column, so that error messages + // that reference columns will be correct. + // + // TODO: This logic does not take into account whether indentation + // came in as spaces or tabs, so there is necessarily going to be + // coupling between how the downstream compiler counts columns, + // and how we do. + if(sourceLocation.Col > context->loc.Col) + { + int delta = sourceLocation.Col - context->loc.Col; + for( int ii = 0; ii < delta; ++ii ) + { + emitRawText(context, " "); + } + context->loc.Col = sourceLocation.Col; + } +} + +static void emitTokenWithLocation(EmitContext* context, Token const& token) +{ + if( token.Position.FileName.Length() != 0 ) + { + advanceToSourceLocation(context, token.Position); + } + else + { + // If we don't have the original position info, we need to play + // it safe and emit whitespace to line things up nicely + + if(token.flags & TokenFlag::AtStartOfLine) + Emit(context, "\n"); + // TODO(tfoley): macro expansion can currently lead to whitespace getting dropped, + // so we will just insert it aggressively, to play it safe. + else // if(token.flags & TokenFlag::AfterWhitespace) + Emit(context, " "); + } + + // Emit the raw textual content of the token + emit(context, token.Content); +} + +static void EmitUnparsedStmt(EmitContext* context, RefPtr stmt) +{ + // TODO: actually emit the tokens that made up the statement... + Emit(context, "{\n"); + for( auto& token : stmt->tokens ) + { + emitTokenWithLocation(context, token); + } + Emit(context, "}\n"); +} + +static void EmitStmt(EmitContext* context, RefPtr stmt) +{ + if (auto blockStmt = stmt.As()) + { + EmitBlockStmt(context, blockStmt); + return; + } + else if( auto unparsedStmt = stmt.As() ) + { + EmitUnparsedStmt(context, unparsedStmt); + return; + } + else if (auto exprStmt = stmt.As()) + { + EmitExpr(context, exprStmt->Expression); + Emit(context, ";\n"); + return; + } + else if (auto returnStmt = stmt.As()) + { + Emit(context, "return"); + if (auto expr = returnStmt->Expression) + { + Emit(context, " "); + EmitExpr(context, expr); + } + Emit(context, ";\n"); + return; + } + else if (auto declStmt = stmt.As()) + { + EmitDecl(context, declStmt->decl); + return; + } + else if (auto ifStmt = stmt.As()) + { + Emit(context, "if("); + EmitExpr(context, ifStmt->Predicate); + Emit(context, ")\n"); + EmitBlockStmt(context, ifStmt->PositiveStatement); + if(auto elseStmt = ifStmt->NegativeStatement) + { + Emit(context, "\nelse\n"); + EmitBlockStmt(context, elseStmt); + } + return; + } + else if (auto forStmt = stmt.As()) + { + EmitLoopAttributes(context, forStmt); + + Emit(context, "for("); + if (auto initStmt = forStmt->InitialStatement) + { + EmitStmt(context, initStmt); + } + else + { + Emit(context, ";"); + } + if (auto testExp = forStmt->PredicateExpression) + { + EmitExpr(context, testExp); + } + Emit(context, ";"); + if (auto incrExpr = forStmt->SideEffectExpression) + { + EmitExpr(context, incrExpr); + } + Emit(context, ")\n"); + EmitBlockStmt(context, forStmt->Statement); + return; + } + else if (auto discardStmt = stmt.As()) + { + Emit(context, "discard;\n"); + return; + } + else if (auto emptyStmt = stmt.As()) + { + return; + } + else if (auto switchStmt = stmt.As()) + { + Emit(context, "switch("); + EmitExpr(context, switchStmt->condition); + Emit(context, ")\n"); + EmitBlockStmt(context, switchStmt->body); + return; + } + else if (auto caseStmt = stmt.As()) + { + Emit(context, "case "); + EmitExpr(context, caseStmt->expr); + Emit(context, ":\n"); + return; + } + else if (auto defaultStmt = stmt.As()) + { + Emit(context, "default:{}\n"); + return; + } + else if (auto breakStmt = stmt.As()) + { + Emit(context, "break;\n"); + return; + } + else if (auto continueStmt = stmt.As()) + { + Emit(context, "continue;\n"); + return; + } + + throw "unimplemented"; + +} + +// Declaration References + +static void EmitVal(EmitContext* context, RefPtr val) +{ + if (auto type = val.As()) + { + EmitType(context, type); + } + else if (auto intVal = val.As()) + { + Emit(context, intVal); + } + else + { + // Note(tfoley): ignore unhandled cases for semantics for now... +// assert(!"unimplemented"); + } +} + +static void EmitDeclRef(EmitContext* context, DeclRef declRef) +{ + // TODO: need to qualify a declaration name based on parent scopes/declarations + + // Emit the name for the declaration itself + emitName(context, declRef.GetName()); + + // If the declaration is nested directly in a generic, then + // we need to output the generic arguments here + auto parentDeclRef = declRef.GetParent(); + if (auto genericDeclRef = parentDeclRef.As()) + { + // Only do this for declarations of appropriate flavors + if(auto funcDeclRef = declRef.As()) + { + // Don't emit generic arguments for functions, because HLSL doesn't allow them + return; + } + + Substitutions* subst = declRef.substitutions.Ptr(); + Emit(context, "<"); + int argCount = subst->args.Count(); + for (int aa = 0; aa < argCount; ++aa) + { + if (aa != 0) Emit(context, ","); + EmitVal(context, subst->args[aa]); + } + Emit(context, ">"); + } + +} + +// Declarations + +// Emit any modifiers that should go in front of a declaration +static void EmitModifiers(EmitContext* context, RefPtr decl) +{ + // Emit any GLSL `layout` modifiers first + bool anyLayout = false; + for( auto mod : decl->GetModifiersOfType()) + { + if(!anyLayout) + { + Emit(context, "layout("); + anyLayout = true; + } + else + { + Emit(context, ", "); + } + + emit(context, mod->nameToken.Content); + if(mod->valToken.Type != TokenType::Unknown) + { + Emit(context, " = "); + emit(context, mod->valToken.Content); + } + } + if(anyLayout) + { + Emit(context, ")\n"); + } + + for (auto mod = decl->modifiers.first; mod; mod = mod->next) + { + if (0) {} + + #define CASE(TYPE, KEYWORD) \ + else if(auto mod_##TYPE = mod.As()) Emit(context, #KEYWORD " ") + + CASE(RowMajorLayoutModifier, row_major); + CASE(ColumnMajorLayoutModifier, column_major); + CASE(HLSLNoInterpolationModifier, nointerpolation); + CASE(HLSLPreciseModifier, precise); + CASE(HLSLEffectSharedModifier, shared); + CASE(HLSLGroupSharedModifier, groupshared); + CASE(HLSLStaticModifier, static); + CASE(HLSLUniformModifier, uniform); + CASE(HLSLVolatileModifier, volatile); + + CASE(InOutModifier, inout); + CASE(InModifier, in); + CASE(OutModifier, out); + + CASE(HLSLPointModifier, point); + CASE(HLSLLineModifier, line); + CASE(HLSLTriangleModifier, triangle); + CASE(HLSLLineAdjModifier, lineadj); + CASE(HLSLTriangleAdjModifier, triangleadj); + + CASE(HLSLLinearModifier, linear); + CASE(HLSLSampleModifier, sample); + CASE(HLSLCentroidModifier, centroid); + + CASE(ConstModifier, const); + + #undef CASE + + // TODO: eventually we should be checked these modifiers, but for + // now we can emit them unchecked, I guess + else if (auto uncheckedAttr = mod.As()) + { + Emit(context, "["); + emit(context, uncheckedAttr->nameToken.Content); + auto& args = uncheckedAttr->args; + auto argCount = args.Count(); + if (argCount != 0) + { + Emit(context, "("); + for (int aa = 0; aa < argCount; ++aa) + { + if (aa != 0) Emit(context, ", "); + EmitExpr(context, args[aa]); + } + Emit(context, ")"); + } + Emit(context, "]"); + } + + else if(auto simpleModifier = mod.As()) + { + emit(context, simpleModifier->nameToken.Content); + Emit(context, " "); + } + + else + { + // skip any extra modifiers + } + } +} + + +typedef unsigned int ESemanticMask; +enum +{ + kESemanticMask_None = 0, + + kESemanticMask_NoPackOffset = 1 << 0, + + kESemanticMask_Default = kESemanticMask_NoPackOffset, +}; + +static void EmitSemantic(EmitContext* context, RefPtr semantic, ESemanticMask /*mask*/) +{ + if (auto simple = semantic.As()) + { + Emit(context, ": "); + emit(context, simple->name.Content); + } + else if(auto registerSemantic = semantic.As()) + { + // Don't print out semantic from the user, since we are going to print the same thing our own way... +#if 0 + Emit(context, ": register("); + Emit(context, registerSemantic->registerName.Content); + if(registerSemantic->componentMask.Type != TokenType::Unknown) + { + Emit(context, "."); + Emit(context, registerSemantic->componentMask.Content); + } + Emit(context, ")"); +#endif + } + else if(auto packOffsetSemantic = semantic.As()) + { + // Don't print out semantic from the user, since we are going to print the same thing our own way... +#if 0 + if(mask & kESemanticMask_NoPackOffset) + return; + + Emit(context, ": packoffset("); + Emit(context, packOffsetSemantic->registerName.Content); + if(packOffsetSemantic->componentMask.Type != TokenType::Unknown) + { + Emit(context, "."); + Emit(context, packOffsetSemantic->componentMask.Content); + } + Emit(context, ")"); +#endif + } + else + { + assert(!"unimplemented"); + } +} + + +static void EmitSemantics(EmitContext* context, RefPtr decl, ESemanticMask mask = kESemanticMask_Default ) +{ + // Don't emit semantics if we aren't translating down to HLSL + switch (context->target) + { + case CodeGenTarget::HLSL: + break; + + default: + return; + } + + for (auto mod = decl->modifiers.first; mod; mod = mod->next) + { + auto semantic = mod.As(); + if (!semantic) + continue; + + EmitSemantic(context, semantic, mask); + } +} + +static void EmitDeclsInContainer(EmitContext* context, RefPtr container) +{ + for (auto member : container->Members) + { + EmitDecl(context, member); + } +} + +static void EmitDeclsInContainerUsingLayout( + EmitContext* context, + RefPtr container, + RefPtr containerLayout) +{ + for (auto member : container->Members) + { + RefPtr memberLayout; + if( containerLayout->mapVarToLayout.TryGetValue(member.Ptr(), memberLayout) ) + { + EmitDeclUsingLayout(context, member, memberLayout); + } + else + { + // No layout for this decl + EmitDecl(context, member); + } + } +} + +static void EmitTypeDefDecl(EmitContext* context, RefPtr decl) +{ + // TODO(tfoley): check if current compilation target even supports typedefs + + Emit(context, "typedef "); + EmitType(context, decl->Type, decl->Name.Content); + Emit(context, ";\n"); +} + +static void EmitStructDecl(EmitContext* context, RefPtr decl) +{ + // Don't emit a declaration that was only generated implicitly, for + // the purposes of semantic checking. + if(decl->HasModifier()) + return; + + Emit(context, "struct "); + emitName(context, decl->Name.Content); + Emit(context, "\n{\n"); + + // TODO(tfoley): Need to hoist members functions, etc. out to global scope + EmitDeclsInContainer(context, decl); + + Emit(context, "};\n"); +} + +// Shared emit logic for variable declarations (used for parameters, locals, globals, fields) +static void EmitVarDeclCommon(EmitContext* context, VarDeclBaseRef declRef) +{ + EmitModifiers(context, declRef.GetDecl()); + + EmitType(context, declRef.GetType(), declRef.GetName()); + + EmitSemantics(context, declRef.GetDecl()); + + // TODO(tfoley): technically have to apply substitution here too... + if (auto initExpr = declRef.GetDecl()->Expr) + { + Emit(context, " = "); + EmitExpr(context, initExpr); + } +} + +// Shared emit logic for variable declarations (used for parameters, locals, globals, fields) +static void EmitVarDeclCommon(EmitContext* context, RefPtr decl) +{ + EmitVarDeclCommon(context, DeclRef(decl.Ptr(), nullptr).As()); +} + +// Emit a single `regsiter` semantic, as appropriate for a given resource-type-specific layout info +static void emitHLSLRegisterSemantic( + EmitContext* context, + VarLayout::ResourceInfo const& info) +{ + if( info.kind == LayoutResourceKind::Uniform ) + { + size_t offset = info.index; + + // The HLSL `c` register space is logically grouped in 16-byte registers, + // while we try to traffic in byte offsets. That means we need to pick + // a register number, based on the starting offset in 16-byte register + // units, and then a "component" within that register, based on 4-byte + // offsets from there. We cannot support more fine-grained offsets than that. + + Emit(context, ": packoffset(c"); + + // Size of a logical `c` register in bytes + auto registerSize = 16; + + // Size of each component of a logical `c` register, in bytes + auto componentSize = 4; + + size_t startRegister = offset / registerSize; + Emit(context, int(startRegister)); + + size_t byteOffsetInRegister = offset % registerSize; + + // If this field doesn't start on an even register boundary, + // then we need to emit additional information to pick the + // right component to start from + if (byteOffsetInRegister != 0) + { + // The value had better occupy a whole number of components. + assert(byteOffsetInRegister % componentSize == 0); + + size_t startComponent = byteOffsetInRegister / componentSize; + + static const char* kComponentNames[] = {"x", "y", "z", "w"}; + Emit(context, "."); + Emit(context, kComponentNames[startComponent]); + } + Emit(context, ")"); + } + else + { + Emit(context, ": register("); + switch( info.kind ) + { + case LayoutResourceKind::ConstantBuffer: + Emit(context, "b"); + break; + case LayoutResourceKind::ShaderResource: + Emit(context, "t"); + break; + case LayoutResourceKind::UnorderedAccess: + Emit(context, "u"); + break; + case LayoutResourceKind::SamplerState: + Emit(context, "s"); + break; + default: + assert(!"unexpected"); + break; + } + Emit(context, info.index); + if(info.space) + { + Emit(context, ", space"); + Emit(context, info.space); + } + Emit(context, ")"); + } +} + +// Emit all the `register` semantics that are appropriate for a particular variable layout +static void emitHLSLRegisterSemantics( + EmitContext* context, + RefPtr layout) +{ + if (!layout) return; + + switch( context->target ) + { + default: + return; + + case CodeGenTarget::HLSL: + break; + } + + for( auto rr : layout->resourceInfos ) + { + emitHLSLRegisterSemantic(context, rr); + } +} + +static void emitHLSLParameterBlockDecl( + EmitContext* context, + RefPtr varDecl, + RefPtr parameterBlockType, + RefPtr layout) +{ + // The data type that describes where stuff in the constant buffer should go + RefPtr dataType = parameterBlockType->elementType; + + // We expect/require the data type to be a user-defined `struct` type + auto declRefType = dataType->As(); + assert(declRefType); + + // We expect to always have layout information + assert(layout); + + // We expect the layout to be for a structured type... + RefPtr bufferLayout = layout->typeLayout.As(); + assert(bufferLayout); + + RefPtr structTypeLayout = bufferLayout->elementTypeLayout.As(); + assert(structTypeLayout); + + if( auto constantBufferType = parameterBlockType->As() ) + { + Emit(context, "cbuffer "); + } + else if( auto textureBufferType = parameterBlockType->As() ) + { + Emit(context, "tbuffer "); + } + + if( auto reflectionNameModifier = varDecl->FindModifier() ) + { + Emit(context, " "); + emitName(context, reflectionNameModifier->nameToken.Content); + } + + EmitSemantics(context, varDecl, kESemanticMask_None); + + auto info = layout->FindResourceInfo(LayoutResourceKind::ConstantBuffer); + assert(info); + emitHLSLRegisterSemantic(context, *info); + + Emit(context, "\n{\n"); + if (auto structRef = declRefType->declRef.As()) + { + for (auto field : structRef.GetMembersOfType()) + { + EmitVarDeclCommon(context, field); + + RefPtr fieldLayout; + structTypeLayout->mapVarToLayout.TryGetValue(field.GetDecl(), fieldLayout); + assert(fieldLayout); + + // Emit explicit layout annotations for every field + for( auto rr : fieldLayout->resourceInfos ) + { + auto kind = rr.kind; + + auto offsetResource = rr; + + if(kind != LayoutResourceKind::Uniform) + { + // Add the base index from the cbuffer into the index of the field + // + // TODO(tfoley): consider maybe not doing this, since it actually + // complicates logic around constant buffers... + + // If the member of the cbuffer uses a resource, it had better + // appear as part of the cubffer layout as well. + auto cbufferResource = layout->FindResourceInfo(kind); + assert(cbufferResource); + + offsetResource.index += cbufferResource->index; + offsetResource.space += cbufferResource->space; + } + + emitHLSLRegisterSemantic(context, offsetResource); + } + + Emit(context, ";\n"); + } + } + Emit(context, "}\n"); +} + +static void +emitGLSLLayoutQualifier( + EmitContext* context, + VarLayout::ResourceInfo const& info) +{ + switch(info.kind) + { + case LayoutResourceKind::Uniform: + Emit(context, "layout(offset = "); + Emit(context, info.index); + Emit(context, ")\n"); + break; + + case LayoutResourceKind::VertexInput: + case LayoutResourceKind::FragmentOutput: + Emit(context, "layout(location = "); + Emit(context, info.index); + Emit(context, ")\n"); + break; + + case LayoutResourceKind::SpecializationConstant: + Emit(context, "layout(constant_id = "); + Emit(context, info.index); + Emit(context, ")\n"); + break; + + case LayoutResourceKind::ConstantBuffer: + case LayoutResourceKind::ShaderResource: + case LayoutResourceKind::UnorderedAccess: + case LayoutResourceKind::SamplerState: + case LayoutResourceKind::DescriptorTableSlot: + Emit(context, "layout(binding = "); + Emit(context, info.index); + if(info.space) + { + Emit(context, ", set = "); + Emit(context, info.space); + } + Emit(context, ")\n"); + break; + } +} + +static void +emitGLSLLayoutQualifiers( + EmitContext* context, + RefPtr layout) +{ + if(!layout) return; + + switch( context->target ) + { + default: + return; + + case CodeGenTarget::GLSL: + break; + } + + for( auto info : layout->resourceInfos ) + { + emitGLSLLayoutQualifier(context, info); + } +} + +static void emitGLSLParameterBlockDecl( + EmitContext* context, + RefPtr varDecl, + RefPtr parameterBlockType, + RefPtr layout) +{ + // The data type that describes where stuff in the constant buffer should go + RefPtr dataType = parameterBlockType->elementType; + + // We expect/require the data type to be a user-defined `struct` type + auto declRefType = dataType->As(); + assert(declRefType); + + // We expect to always have layout information + assert(layout); + + // We expect the layout to be for a structured type... + RefPtr bufferLayout = layout->typeLayout.As(); + assert(bufferLayout); + + RefPtr structTypeLayout = bufferLayout->elementTypeLayout.As(); + assert(structTypeLayout); + + emitGLSLLayoutQualifiers(context, layout); + + EmitModifiers(context, varDecl); + + // Emit an apprpriate declaration keyword based on the kind of block + if (parameterBlockType->As()) + { + Emit(context, "uniform"); + } + else if (parameterBlockType->As()) + { + Emit(context, "in"); + } + else if (parameterBlockType->As()) + { + Emit(context, "out"); + } + else if (parameterBlockType->As()) + { + Emit(context, "buffer"); + } + else + { + assert(!"unexpected"); + Emit(context, "uniform"); + } + + if( auto reflectionNameModifier = varDecl->FindModifier() ) + { + Emit(context, " "); + emitName(context, reflectionNameModifier->nameToken.Content); + } + + Emit(context, "\n{\n"); + if (auto structRef = declRefType->declRef.As()) + { + for (auto field : structRef.GetMembersOfType()) + { + RefPtr fieldLayout; + structTypeLayout->mapVarToLayout.TryGetValue(field.GetDecl(), fieldLayout); + assert(fieldLayout); + + // TODO(tfoley): We may want to emit *some* of these, + // some of the time... +// emitGLSLLayoutQualifiers(context, fieldLayout); + + EmitVarDeclCommon(context, field); + + Emit(context, ";\n"); + } + } + Emit(context, "}"); + + if( varDecl->Name.Type != TokenType::Unknown ) + { + Emit(context, " "); + emitName(context, varDecl->Name.Content); + } + + Emit(context, ";\n"); +} + +static void emitParameterBlockDecl( + EmitContext* context, + RefPtr varDecl, + RefPtr parameterBlockType, + RefPtr layout) +{ + switch(context->target) + { + case CodeGenTarget::HLSL: + emitHLSLParameterBlockDecl(context, varDecl, parameterBlockType, layout); + break; + + case CodeGenTarget::GLSL: + emitGLSLParameterBlockDecl(context, varDecl, parameterBlockType, layout); + break; + + default: + assert(!"unexpected"); + break; + } +} + +static void EmitVarDecl(EmitContext* context, RefPtr decl, RefPtr layout) +{ + // As a special case, a variable using a parameter block type + // will be translated into a declaration using the more primitive + // language syntax. + // + // TODO(tfoley): Be sure to unwrap arrays here, in the GLSL case. + // + // TODO(tfoley): Detect cases where we need to fall back to + // ordinary variable declaration syntax in HLSL. + // + // TODO(tfoley): there might be a better way to detect this, e.g., + // with an attribute that gets attached to the variable declaration. + if (auto parameterBlockType = decl->Type->As()) + { + emitParameterBlockDecl(context, decl, parameterBlockType, layout); + return; + } + + emitGLSLLayoutQualifiers(context, layout); + + EmitVarDeclCommon(context, decl); + + emitHLSLRegisterSemantics(context, layout); + + Emit(context, ";\n"); +} + +static void EmitParamDecl(EmitContext* context, RefPtr decl) +{ + EmitVarDeclCommon(context, decl); +} + +static void EmitFuncDecl(EmitContext* context, RefPtr decl) +{ + EmitModifiers(context, decl); + + // TODO: if a function returns an array type, or something similar that + // isn't allowed by declarator syntax and/or language rules, we could + // hypothetically wrap things in a `typedef` and work around it. + + EmitType(context, decl->ReturnType, decl->Name.Content); + + Emit(context, "("); + bool first = true; + for (auto paramDecl : decl->GetMembersOfType()) + { + if (!first) Emit(context, ", "); + EmitParamDecl(context, paramDecl); + first = false; + } + Emit(context, ")"); + + EmitSemantics(context, decl); + + if (auto bodyStmt = decl->Body) + { + EmitBlockStmt(context, bodyStmt); + } + else + { + Emit(context, ";\n"); + } +} + +static void emitGLSLPreprocessorDirectives( + EmitContext* context, + RefPtr program) +{ + switch(context->target) + { + // Don't emit this stuff unless we are targetting GLSL + default: + return; + + case CodeGenTarget::GLSL: + break; + } + + if( auto versionDirective = program->FindModifier() ) + { + // TODO(tfoley): Emit an appropriate `#line` directive... + + Emit(context, "#version "); + emit(context, versionDirective->versionNumberToken.Content); + if(versionDirective->glslProfileToken.Type != TokenType::Unknown) + { + Emit(context, " "); + emit(context, versionDirective->glslProfileToken.Content); + } + Emit(context, "\n"); + } + else + { + // No explicit version was given (probably because we are cross-compiling). + // + // We need to pick an appropriate version, ideally based on the features + // that the shader ends up using. + // + // For now we just fall back to a reasonably recent version. + + Emit(context, "#version 420\n"); + } + + // TODO: when cross-compiling we may need to output additional `#extension` directives + // based on the features that we have used. + + for( auto extensionDirective : program->GetModifiersOfType() ) + { + // TODO(tfoley): Emit an appropriate `#line` directive... + + Emit(context, "#extension "); + emit(context, extensionDirective->extensionNameToken.Content); + Emit(context, " : "); + emit(context, extensionDirective->dispositionToken.Content); + Emit(context, "\n"); + } + + // TODO: handle other cases... +} + +static void EmitProgram( + EmitContext* context, + RefPtr program, + RefPtr programLayout) +{ + // There may be global-scope modifiers that we should emit now + emitGLSLPreprocessorDirectives(context, program); + + switch(context->target) + { + case CodeGenTarget::GLSL: + { + // TODO(tfoley): Need a plan for how to enable/disable these as needed... +// Emit(context, "#extension GL_GOOGLE_cpp_style_line_directive : require\n"); + } + break; + + default: + break; + } + + + // Layout information for the global scope is either an ordinary + // `struct` in the common case, or a constant buffer in the case + // where there were global-scope uniforms. + auto globalScopeLayout = programLayout->globalScopeLayout; + if( auto globalStructLayout = globalScopeLayout.As() ) + { + // The `struct` case is easy enough to handle: we just + // emit all the declarations directly, using their layout + // information as a guideline. + EmitDeclsInContainerUsingLayout(context, program, globalStructLayout); + } + else if(auto globalConstantBufferLayout = globalScopeLayout.As()) + { + // TODO: the `cbuffer` case really needs to be emitted very + // carefully, but that is beyond the scope of what a simple rewriter + // can easily do (without semantic analysis, etc.). + // + // The crux of the problem is that we need to collect all the + // global-scope uniforms (but not declarations that don't involve + // uniform storage...) and put them in a single `cbuffer` declaration, + // so that we can give it an explicit location. The fields in that + // declaration might use various type declarations, so we'd really + // need to emit all the type declarations first, and that involves + // some large scale reorderings. + // + // For now we will punt and just emit the declarations normally, + // and hope that the global-scope block (`$Globals`) gets auto-assigned + // the same location that we manually asigned it. + + auto elementTypeLayout = globalConstantBufferLayout->elementTypeLayout; + auto elementTypeStructLayout = elementTypeLayout.As(); + + // We expect all constant buffers to contain `struct` types for now + assert(elementTypeStructLayout); + + EmitDeclsInContainerUsingLayout( + context, + program, + elementTypeStructLayout); + } + else + { + assert(!"unexpected"); + } +} + +static void EmitDeclImpl(EmitContext* context, RefPtr decl, RefPtr layout) +{ + // Don't emit code for declarations that came from the stdlib. + // + // TODO(tfoley): We probably need to relax this eventually, + // since different targets might have different sets of builtins. + if (decl->HasModifier()) + return; + + if (auto typeDefDecl = decl.As()) + { + EmitTypeDefDecl(context, typeDefDecl); + return; + } + else if (auto structDecl = decl.As()) + { + EmitStructDecl(context, structDecl); + return; + } + else if (auto varDecl = decl.As()) + { + EmitVarDecl(context, varDecl, layout); + return; + } + else if (auto funcDecl = decl.As()) + { + EmitFuncDecl(context, funcDecl); + return; + } + else if (auto genericDecl = decl.As()) + { + // Don't emit generic decls directly; we will only + // ever emit particular instantiations of them. + return; + } + else if (auto classDecl = decl.As()) + { + return; + } + else if( auto emptyDecl = decl.As() ) + { + EmitModifiers(context, emptyDecl); + Emit(context, ";\n"); + return; + } + throw "unimplemented"; +} + +static void EmitDecl(EmitContext* context, RefPtr decl) +{ + EmitDeclImpl(context, decl, nullptr); +} + +static void EmitDeclUsingLayout(EmitContext* context, RefPtr decl, RefPtr layout) +{ + EmitDeclImpl(context, decl, layout); +} + +static void EmitDecl(EmitContext* context, RefPtr declBase) +{ + if( auto decl = declBase.As() ) + { + EmitDecl(context, decl); + } + else if(auto declGroup = declBase.As()) + { + for(auto d : declGroup->decls) + EmitDecl(context, d); + } + else + { + throw "unimplemented"; + } +} + +static void registerReservedWord( + EmitContext* context, + String const& name) +{ + context->reservedWords.Add(name, name); +} + +static void registerReservedWords( + EmitContext* context) +{ +#define WORD(NAME) registerReservedWord(context, #NAME) + + switch (context->target) + { + case CodeGenTarget::GLSL: + WORD(attribute); + WORD(const); + WORD(uniform); + WORD(varying); + WORD(buffer); + + WORD(shared); + WORD(coherent); + WORD(volatile); + WORD(restrict); + WORD(readonly); + WORD(writeonly); + WORD(atomic_unit); + WORD(layout); + WORD(centroid); + WORD(flat); + WORD(smooth); + WORD(noperspective); + WORD(patch); + WORD(sample); + WORD(break); + WORD(continue); + WORD(do); + WORD(for); + WORD(while); + WORD(switch); + WORD(case); + WORD(default); + WORD(if); + WORD(else); + WORD(subroutine); + WORD(in); + WORD(out); + WORD(inout); + WORD(float); + WORD(double); + WORD(int); + WORD(void); + WORD(bool); + WORD(true); + WORD(false); + WORD(invariant); + WORD(precise); + WORD(discard); + WORD(return); + + WORD(lowp); + WORD(mediump); + WORD(highp); + WORD(precision); + WORD(struct); + WORD(uint); + + WORD(common); + WORD(partition); + WORD(active); + WORD(asm); + WORD(class); + WORD(union); + WORD(enum); + WORD(typedef); + WORD(template); + WORD(this); + WORD(resource); + + WORD(goto); + WORD(inline); + WORD(noinline); + WORD(public); + WORD(static); + WORD(extern); + WORD(external); + WORD(interface); + WORD(long); + WORD(short); + WORD(half); + WORD(fixed); + WORD(unsigned); + WORD(superp); + WORD(input); + WORD(output); + WORD(filter); + WORD(sizeof); + WORD(cast); + WORD(namespace); + WORD(using); + +#define CASE(NAME) \ + WORD(NAME ## 2); WORD(NAME ## 3); WORD(NAME ## 4) + + CASE(mat); + CASE(dmat); + CASE(mat2x); + CASE(mat3x); + CASE(mat4x); + CASE(dmat2x); + CASE(dmat3x); + CASE(dmat4x); + CASE(vec); + CASE(ivec); + CASE(bvec); + CASE(dvec); + CASE(uvec); + CASE(hvec); + CASE(fvec); + +#undef CASE + +#define CASE(NAME) \ + WORD(NAME ## 1D); \ + WORD(NAME ## 2D); \ + WORD(NAME ## 3D); \ + WORD(NAME ## Cube); \ + WORD(NAME ## 1DArray); \ + WORD(NAME ## 2DArray); \ + WORD(NAME ## 3DArray); \ + WORD(NAME ## CubeArray);\ + WORD(NAME ## 2DMS); \ + WORD(NAME ## 2DMSArray) \ + /* end */ + +#define CASE2(NAME) \ + CASE(NAME); \ + CASE(i ## NAME); \ + CASE(u ## NAME) \ + /* end */ + + CASE2(sampler); + CASE2(image); + CASE2(texture); + +#undef CASE2 +#undef CASE + break; + + default: + break; + } +} + +String emitProgram( + ProgramSyntaxNode* program, + ProgramLayout* programLayout, + CodeGenTarget target) +{ + // TODO(tfoley): only emit symbols on-demand, as needed by a particular entry point + + EmitContext context; + context.target = target; + + registerReservedWords(&context); + + EmitProgram(&context, program, programLayout); + + String code = context.sb.ProduceString(); + + return code; + +#if 0 + // HACK(tfoley): Invoke the D3D HLSL compiler on the result, to validate it + +#ifdef _WIN32 + { + HMODULE d3dCompiler = LoadLibraryA("d3dcompiler_47"); + assert(d3dCompiler); + + pD3DCompile D3DCompile_ = (pD3DCompile)GetProcAddress(d3dCompiler, "D3DCompile"); + assert(D3DCompile_); + + ID3DBlob* codeBlob; + ID3DBlob* diagnosticsBlob; + HRESULT hr = D3DCompile_( + code.begin(), + code.Length(), + "slang", + nullptr, + nullptr, + "main", + "ps_5_0", + 0, + 0, + &codeBlob, + &diagnosticsBlob); + if (codeBlob) codeBlob->Release(); + if (diagnosticsBlob) + { + String diagnostics = (char const*) diagnosticsBlob->GetBufferPointer(); + fprintf(stderr, "%s", diagnostics.begin()); + OutputDebugStringA(diagnostics.begin()); + diagnosticsBlob->Release(); + } + if (FAILED(hr)) + { + int f = 9; + } + } + + #include +#endif +#endif + +} + + +}} // Slang::Compiler diff --git a/source/slang/emit.h b/source/slang/emit.h new file mode 100644 index 000000000..05ea1550f --- /dev/null +++ b/source/slang/emit.h @@ -0,0 +1,24 @@ +// Emit.h +#ifndef SLANG_EMIT_H_INCLUDED +#define SLANG_EMIT_H_INCLUDED + +#include "../core/basic.h" + +#include "compiler.h" + +namespace Slang +{ + namespace Compiler + { + using namespace CoreLib::Basic; + + class ProgramSyntaxNode; + class ProgramLayout; + + String emitProgram( + ProgramSyntaxNode* program, + ProgramLayout* programLayout, + CodeGenTarget target); + } +} +#endif diff --git a/source/slang/intrinsic-defs.h b/source/slang/intrinsic-defs.h new file mode 100644 index 000000000..19a3899a3 --- /dev/null +++ b/source/slang/intrinsic-defs.h @@ -0,0 +1,94 @@ +// intrinsic-defs.h + +// The file is meant to be included multiple times, to produce different +// pieces of code related to intrinsic operations +// +// Each intrinsic op is declared here with: +// +// INTRINSIC(name) +// + +#ifndef INTRINSIC +#error Need to define INTRINSIC(NAME) before including "intrinsic-defs.h" +#endif + +INTRINSIC(Add) +INTRINSIC(Sub) +INTRINSIC(Mul) +INTRINSIC(Div) +INTRINSIC(Mod) + +INTRINSIC(Lsh) +INTRINSIC(Rsh) + +INTRINSIC(Eql) +INTRINSIC(Neq) +INTRINSIC(Greater) +INTRINSIC(Less) +INTRINSIC(Geq) +INTRINSIC(Leq) +INTRINSIC(BitAnd) +INTRINSIC(BitXor) +INTRINSIC(BitOr) + +// TODO(tfoley): need to distinguish short-circuiting and not... +INTRINSIC(And) +INTRINSIC(Or) + +INTRINSIC(Assign) +INTRINSIC(AddAssign) +INTRINSIC(SubAssign) +INTRINSIC(MulAssign) +INTRINSIC(DivAssign) +INTRINSIC(ModAssign) +INTRINSIC(LshAssign) +INTRINSIC(RshAssign) +INTRINSIC(OrAssign) +INTRINSIC(AndAssign) +INTRINSIC(XorAssign) +INTRINSIC(Neg) +INTRINSIC(Not) +INTRINSIC(BitNot) +INTRINSIC(PreInc) +INTRINSIC(PreDec) +INTRINSIC(PostInc) +INTRINSIC(PostDec) + +INTRINSIC(Sequence) +INTRINSIC(Select) + +INTRINSIC(Mul_Scalar_Scalar) +INTRINSIC(Mul_Vector_Scalar) +INTRINSIC(Mul_Scalar_Vector) +INTRINSIC(Mul_Matrix_Scalar) +INTRINSIC(Mul_Scalar_Matrix) +INTRINSIC(InnerProduct_Vector_Vector) +INTRINSIC(InnerProduct_Vector_Matrix) +INTRINSIC(InnerProduct_Matrix_Vector) +INTRINSIC(InnerProduct_Matrix_Matrix) + + + + + + + + + + + + + + + + + + + + + + + + +// Un-deefine the macor here, so that the client does not have to. +#undef INTRINSIC diff --git a/source/slang/lexer.cpp b/source/slang/lexer.cpp new file mode 100644 index 000000000..7234c4983 --- /dev/null +++ b/source/slang/lexer.cpp @@ -0,0 +1,1012 @@ +#include "Lexer.h" + +#include + +namespace Slang +{ + namespace Compiler + { + static Token GetEndOfFileToken() + { + return Token(TokenType::EndOfFile, "", 0, 0, 0, ""); + } + + Token* TokenList::begin() const + { + assert(mTokens.Count()); + return &mTokens[0]; + } + + Token* TokenList::end() const + { + assert(mTokens.Count()); + assert(mTokens[mTokens.Count()-1].Type == TokenType::EndOfFile); + return &mTokens[mTokens.Count() - 1]; + } + + TokenSpan::TokenSpan() + : mBegin(NULL) + , mEnd (NULL) + {} + + TokenReader::TokenReader() + : mCursor(NULL) + , mEnd (NULL) + {} + + + Token TokenReader::PeekToken() const + { + if (!mCursor) + return GetEndOfFileToken(); + + Token token = *mCursor; + if (mCursor == mEnd) + token.Type = TokenType::EndOfFile; + return token; + } + + TokenType TokenReader::PeekTokenType() const + { + if (mCursor == mEnd) + return TokenType::EndOfFile; + assert(mCursor); + return mCursor->Type; + } + + CodePosition TokenReader::PeekLoc() const + { + if (!mCursor) + return CodePosition(); + assert(mCursor); + return mCursor->Position; + } + + Token TokenReader::AdvanceToken() + { + if (!mCursor) + return GetEndOfFileToken(); + + Token token = *mCursor; + if (mCursor == mEnd) + token.Type = TokenType::EndOfFile; + else + mCursor++; + return token; + } + + // Lexer + + Lexer::Lexer( + String const& path, + String const& content, + DiagnosticSink* sink) + : path(path) + , content(content) + , sink(sink) + { + cursor = content.begin(); + end = content.end(); + + loc = CodePosition(1, 1, 0, path); + tokenFlags = TokenFlag::AtStartOfLine | TokenFlag::AfterWhitespace; + lexerFlags = 0; + } + + Lexer::~Lexer() + { + } + + enum { kEOF = -1 }; + + static int peek(Lexer* lexer) + { + if(lexer->cursor == lexer->end) + return kEOF; + + return *lexer->cursor; + } + + static int advance(Lexer* lexer) + { + if(lexer->cursor == lexer->end) + return kEOF; + + lexer->loc.Col++; + lexer->loc.Pos++; + + return *lexer->cursor++; + } + + static void handleNewLine(Lexer* lexer) + { + int c = advance(lexer); + assert(c == '\n' || c == '\r'); + + int d = peek(lexer); + if( (c ^ d) == ('\n' ^ '\r') ) + { + advance(lexer); + } + + lexer->loc.Line++; + lexer->loc.Col = 1; + } + + static void lexLineComment(Lexer* lexer) + { + for(;;) + { + switch(peek(lexer)) + { + case '\n': case '\r': case kEOF: + return; + + default: + advance(lexer); + continue; + } + } + } + + static void lexBlockComment(Lexer* lexer) + { + for(;;) + { + switch(peek(lexer)) + { + case kEOF: + // TODO(tfoley) diagnostic! + return; + + case '\n': case '\r': + handleNewLine(lexer); + continue; + + case '*': + advance(lexer); + switch( peek(lexer) ) + { + case '/': + advance(lexer); + return; + + default: + continue; + } + + default: + advance(lexer); + continue; + } + } + } + + static void lexHorizontalSpace(Lexer* lexer) + { + for(;;) + { + switch(peek(lexer)) + { + case ' ': case '\t': + advance(lexer); + continue; + + default: + return; + } + } + } + + static void lexIdentifier(Lexer* lexer) + { + for(;;) + { + int c = peek(lexer); + if(('a' <= c ) && (c <= 'z') + || ('A' <= c) && (c <= 'Z') + || ('0' <= c) && (c <= '9') + || (c == '_')) + { + advance(lexer); + continue; + } + + return; + } + } + + static void lexDigits(Lexer* lexer, int base) + { + for(;;) + { + int c = peek(lexer); + + int digitVal = 0; + switch(c) + { + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + digitVal = c - '0'; + break; + + case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': + if(base <= 10) return; + digitVal = 10 + c - 'a'; + break; + + case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': + if(base <= 10) return; + digitVal = 10 + c - 'A'; + break; + + default: + // Not more digits! + return; + } + + if(digitVal >= base) + { + char buffer[] = { (char) c, 0 }; + lexer->sink->diagnose(lexer->loc, Diagnostics::invalidDigitForBase, buffer, base); + } + + advance(lexer); + } + } + + static TokenType maybeLexNumberSuffix(Lexer* lexer, TokenType tokenType) + { + // First check for suffixes that + // indicate a floating-point number + switch(peek(lexer)) + { + case 'f': case 'F': + advance(lexer); + return TokenType::DoubleLiterial; + + default: + break; + } + + // Once we've ruled out floating-point + // suffixes, we can check for the inter cases + + // TODO: allow integer suffixes in any order... + + // Leading `u` or `U` for unsigned + switch(peek(lexer)) + { + default: + break; + + case 'u': case 'U': + advance(lexer); + break; + } + + // Optional `l`, `L`, `ll`, or `LL` + switch(peek(lexer)) + { + default: + break; + + case 'l': case 'L': + advance(lexer); + switch(peek(lexer)) + { + default: + break; + + case 'l': case 'L': + advance(lexer); + break; + } + break; + } + + return tokenType; + } + + static bool maybeLexNumberExponent(Lexer* lexer, int base) + { + switch( peek(lexer) ) + { + default: + return false; + + case 'e': case 'E': + if(base != 10) return false; + advance(lexer); + break; + + case 'p': case 'P': + if(base != 16) return false; + advance(lexer); + break; + } + + // we saw an exponent marker, so we must + switch( peek(lexer) ) + { + case '+': case '-': + advance(lexer); + break; + } + + // TODO(tfoley): it would be an error to not see digits here... + + lexDigits(lexer, 10); + + return true; + } + + static TokenType lexNumberAfterDecimalPoint(Lexer* lexer, int base) + { + lexDigits(lexer, base); + maybeLexNumberExponent(lexer, base); + + return maybeLexNumberSuffix(lexer, TokenType::DoubleLiterial); + } + + static TokenType lexNumber(Lexer* lexer, int base) + { + // TODO(tfoley): Need to consider whehter to allow any kind of digit separator character. + + TokenType tokenType = TokenType::IntLiterial; + + // At the start of things, we just concern ourselves with digits + lexDigits(lexer, base); + + if( peek(lexer) == '.' ) + { + tokenType = TokenType::DoubleLiterial; + + advance(lexer); + lexDigits(lexer, base); + } + + if( maybeLexNumberExponent(lexer, base)) + { + tokenType = TokenType::DoubleLiterial; + } + + maybeLexNumberSuffix(lexer, tokenType); + return tokenType; + } + + static void lexStringLiteralBody(Lexer* lexer, char quote) + { + for(;;) + { + int c = peek(lexer); + if(c == quote) + { + advance(lexer); + return; + } + + switch(c) + { + case kEOF: + lexer->sink->diagnose(lexer->loc, Diagnostics::endOfFileInLiteral); + return; + + case '\n': case '\r': + lexer->sink->diagnose(lexer->loc, Diagnostics::newlineInLiteral); + return; + + case '\\': + // Need to handle various escape sequence cases + advance(lexer); + switch(peek(lexer)) + { + case '\'': + case '\"': + case '\\': + case '?': + case 'a': + case 'b': + case 'f': + case 'n': + case 'r': + case 't': + case 'v': + advance(lexer); + break; + + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': + // octal escape: up to 3 characters + advance(lexer); + for(int ii = 0; ii < 3; ++ii) + { + int d = peek(lexer); + if(('0' <= d) && (d <= '7')) + { + advance(lexer); + continue; + } + else + { + break; + } + } + break; + + case 'x': + // hexadecimal escape: any number of characters + advance(lexer); + for(;;) + { + int d = peek(lexer); + if(('0' <= d) && (d <= '9') + || ('a' <= d) && (d <= 'f') + || ('A' <= d) && (d <= 'F')) + { + advance(lexer); + continue; + } + else + { + break; + } + } + break; + + // TODO: Unicode escape sequences + + } + break; + + default: + advance(lexer); + continue; + } + } + } + + String getStringLiteralTokenValue(Token const& token) + { + assert(token.Type == TokenType::StringLiterial + || token.Type == TokenType::CharLiterial); + + char const* cursor = token.Content.begin(); + char const* end = token.Content.end(); + + auto quote = *cursor++; + assert(quote == '\'' || quote == '"'); + + StringBuilder valueBuilder; + for(;;) + { + assert(cursor != end); + + auto c = *cursor++; + + // If we see a closing quote, then we are at the end of the string literal + if(c == quote) + { + assert(cursor == end); + return valueBuilder.ProduceString(); + } + + // Charcters that don't being escape sequences are easy; + // just append them to the buffer and move on. + if(c != '\\') + { + valueBuilder.Append(c); + continue; + } + + // Now we look at another character to figure out the kind of + // escape sequence we are dealing with: + + int d = *cursor++; + + switch(d) + { + // Simple characters that just needed to be escaped + case '\'': + case '\"': + case '\\': + case '?': + valueBuilder.Append(d); + continue; + + // Traditional escape sequences for special characters + case 'a': valueBuilder.Append('\a'); continue; + case 'b': valueBuilder.Append('\b'); continue; + case 'f': valueBuilder.Append('\f'); continue; + case 'n': valueBuilder.Append('\n'); continue; + case 'r': valueBuilder.Append('\r'); continue; + case 't': valueBuilder.Append('\t'); continue; + case 'v': valueBuilder.Append('\v'); continue; + + // Octal escape: up to 3 characterws + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': + { + cursor--; + int value = 0; + for(int ii = 0; ii < 3; ++ii) + { + d = *cursor; + if(('0' <= d) && (d <= '7')) + { + value = value*8 + (d - '0'); + + cursor++; + continue; + } + else + { + break; + } + } + + // TODO: add support for appending an arbitrary code point? + valueBuilder.Append((char) value); + } + continue; + + // Hexadecimal escape: any number of characters + case 'x': + { + cursor--; + int value = 0; + for(;;) + { + d = *cursor++; + int digitValue = 0; + if(('0' <= d) && (d <= '9')) + { + digitValue = d - '0'; + } + else if( ('a' <= d) && (d <= 'f') ) + { + digitValue = d - 'a'; + } + else if( ('A' <= d) && (d <= 'F') ) + { + digitValue = d - 'A'; + } + else + { + cursor--; + break; + } + + value = value*16 + digitValue; + } + + // TODO: add support for appending an arbitrary code point? + valueBuilder.Append((char) value); + } + continue; + + // TODO: Unicode escape sequences + + } + } + } + + String getFileNameTokenValue(Token const& token) + { + // A file name usually doesn't process escape sequences + // (this is import on Windows, where `\\` is a valid + // path separator cahracter). + + // Just trim off the first and last characters to remove the quotes + // (whether they were `""` or `<>`. + return token.Content.SubString(1, token.Content.Length()-2); + } + + + + static TokenType lexTokenImpl(Lexer* lexer) + { + switch(peek(lexer)) + { + default: + break; + + case kEOF: + if((lexer->lexerFlags & kLexerFlag_InDirective) != 0) + return TokenType::EndOfDirective; + return TokenType::EndOfFile; + + case '\r': case '\n': + if((lexer->lexerFlags & kLexerFlag_InDirective) != 0) + return TokenType::EndOfDirective; + handleNewLine(lexer); + return TokenType::NewLine; + + case ' ': case '\t': + lexHorizontalSpace(lexer); + return TokenType::WhiteSpace; + + case '.': + advance(lexer); + switch(peek(lexer)) + { + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + return lexNumberAfterDecimalPoint(lexer, 10); + + // TODO(tfoley): handle ellipsis (`...`) + + default: + return TokenType::Dot; + } + + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + return lexNumber(lexer, 10); + + case '0': + { + auto loc = lexer->loc; + advance(lexer); + switch(peek(lexer)) + { + default: + return TokenType::IntLiterial; + + case '.': + advance(lexer); + return lexNumberAfterDecimalPoint(lexer, 10); + + case 'x': case 'X': + advance(lexer); + return lexNumber(lexer, 16); + + case 'b': case 'B': + advance(lexer); + return lexNumber(lexer, 2); + + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + lexer->sink->diagnose(loc, Diagnostics::octalLiteral); + return lexNumber(lexer, 8); + } + } + + case 'a': case 'b': case 'c': case 'd': case 'e': + case 'f': case 'g': case 'h': case 'i': case 'j': + case 'k': case 'l': case 'm': case 'n': case 'o': + case 'p': case 'q': case 'r': case 's': case 't': + case 'u': case 'v': case 'w': case 'x': case 'y': + case 'z': + case 'A': case 'B': case 'C': case 'D': case 'E': + case 'F': case 'G': case 'H': case 'I': case 'J': + case 'K': case 'L': case 'M': case 'N': case 'O': + case 'P': case 'Q': case 'R': case 'S': case 'T': + case 'U': case 'V': case 'W': case 'X': case 'Y': + case 'Z': + case '_': + lexIdentifier(lexer); + return TokenType::Identifier; + + case '\"': + advance(lexer); + lexStringLiteralBody(lexer, '\"'); + return TokenType::StringLiterial; + + case '\'': + advance(lexer); + lexStringLiteralBody(lexer, '\''); + return TokenType::CharLiterial; + + case '+': + advance(lexer); + switch(peek(lexer)) + { + case '+': advance(lexer); return TokenType::OpInc; + case '=': advance(lexer); return TokenType::OpAddAssign; + default: + return TokenType::OpAdd; + } + + case '-': + advance(lexer); + switch(peek(lexer)) + { + case '-': advance(lexer); return TokenType::OpDec; + case '=': advance(lexer); return TokenType::OpSubAssign; + case '>': advance(lexer); return TokenType::RightArrow; + default: + return TokenType::OpSub; + } + + case '*': + advance(lexer); + switch(peek(lexer)) + { + case '=': advance(lexer); return TokenType::OpMulAssign; + default: + return TokenType::OpMul; + } + + case '/': + advance(lexer); + switch(peek(lexer)) + { + case '=': advance(lexer); return TokenType::OpDivAssign; + case '/': advance(lexer); lexLineComment(lexer); return TokenType::LineComment; + case '*': advance(lexer); lexBlockComment(lexer); return TokenType::BlockComment; + default: + return TokenType::OpDiv; + } + + case '%': + advance(lexer); + switch(peek(lexer)) + { + case '=': advance(lexer); return TokenType::OpModAssign; + default: + return TokenType::OpMod; + } + + case '|': + advance(lexer); + switch(peek(lexer)) + { + case '|': advance(lexer); return TokenType::OpOr; + case '=': advance(lexer); return TokenType::OpOrAssign; + default: + return TokenType::OpBitOr; + } + + case '&': + advance(lexer); + switch(peek(lexer)) + { + case '&': advance(lexer); return TokenType::OpAnd; + case '=': advance(lexer); return TokenType::OpAndAssign; + default: + return TokenType::OpBitAnd; + } + + case '^': + advance(lexer); + switch(peek(lexer)) + { + case '=': advance(lexer); return TokenType::OpXorAssign; + default: + return TokenType::OpBitXor; + } + + case '>': + advance(lexer); + switch(peek(lexer)) + { + case '>': + advance(lexer); + switch(peek(lexer)) + { + case '=': advance(lexer); return TokenType::OpShrAssign; + default: return TokenType::OpRsh; + } + case '=': advance(lexer); return TokenType::OpGeq; + default: + return TokenType::OpGreater; + } + + case '<': + advance(lexer); + switch(peek(lexer)) + { + case '<': + advance(lexer); + switch(peek(lexer)) + { + case '=': advance(lexer); return TokenType::OpShlAssign; + default: return TokenType::OpLsh; + } + case '=': advance(lexer); return TokenType::OpLeq; + default: + return TokenType::OpLess; + } + + case '=': + advance(lexer); + switch(peek(lexer)) + { + case '=': advance(lexer); return TokenType::OpEql; + default: + return TokenType::OpAssign; + } + + case '!': + advance(lexer); + switch(peek(lexer)) + { + case '=': advance(lexer); return TokenType::OpNeq; + default: + return TokenType::OpNot; + } + + case '#': + advance(lexer); + switch(peek(lexer)) + { + case '#': advance(lexer); return TokenType::PoundPound; + default: + return TokenType::Pound; + } + + case '~': advance(lexer); return TokenType::OpBitNot; + + case ':': advance(lexer); return TokenType::Colon; + case ';': advance(lexer); return TokenType::Semicolon; + case ',': advance(lexer); return TokenType::Comma; + + case '{': advance(lexer); return TokenType::LBrace; + case '}': advance(lexer); return TokenType::RBrace; + case '[': advance(lexer); return TokenType::LBracket; + case ']': advance(lexer); return TokenType::RBracket; + case '(': advance(lexer); return TokenType::LParent; + case ')': advance(lexer); return TokenType::RParent; + + case '?': advance(lexer); return TokenType::QuestionMark; + case '@': advance(lexer); return TokenType::At; + case '$': advance(lexer); return TokenType::Dollar; + + } + + // TODO(tfoley): If we ever wanted to support proper Unicode + // in identifiers, etc., then this would be the right place + // to perform a more expensive dispatch based on the actual + // code point (and not just the first byte). + + { + // If none of the above cases matched, then we have an + // unexpected/invalid character. + + auto loc = lexer->loc; + auto sink = lexer->sink; + int c = advance(lexer); + if(c >= 0x20 && c <= 0x7E) + { + char buffer[] = { (char) c, 0 }; + sink->diagnose(loc, Diagnostics::illegalCharacterPrint, buffer); + } + else + { + // Fallback: print as hexadecimal + sink->diagnose(loc, Diagnostics::illegalCharacterHex, String((unsigned char)c, 16)); + } + + return TokenType::Invalid; + } + } + + Token Lexer::lexToken() + { + auto flags = this->tokenFlags; + for(;;) + { + Token token; + token.Position = loc; + + char const* textBegin = cursor; + + auto tokenType = lexTokenImpl(this); + + // The low-level lexer produces tokens for things we want + // to ignore, such as white space, so we skip them here. + switch(tokenType) + { + case TokenType::Invalid: + flags = 0; + continue; + + case TokenType::NewLine: + flags = TokenFlag::AtStartOfLine | TokenFlag::AfterWhitespace; + continue; + + case TokenType::WhiteSpace: + case TokenType::LineComment: + case TokenType::BlockComment: + flags |= TokenFlag::AfterWhitespace; + continue; + + // We don't want to skip the end-of-file token, but we *do* + // want to make sure it has appropriate flags to make our life easier + case TokenType::EndOfFile: + flags = TokenFlag::AtStartOfLine | TokenFlag::AfterWhitespace; + break; + + // We will also do some book-keeping around preprocessor directives here: + // + // If we see a `#` at the start of a line, then we are entering a + // preprocessor directive. + case TokenType::Pound: + if((flags & TokenFlag::AtStartOfLine) != 0) + lexerFlags |= kLexerFlag_InDirective; + break; + // + // And if we saw an end-of-line during a directive, then we are + // now leaving that directive. + // + case TokenType::EndOfDirective: + lexerFlags &= ~kLexerFlag_InDirective; + break; + + default: + break; + } + + token.Type = tokenType; + + char const* textEnd = cursor; + + // Note(tfoley): `StringBuilder::Append()` seems to crash when appending zero bytes + if(textEnd != textBegin) + { + StringBuilder valueBuilder; + valueBuilder.Append(textBegin, int(textEnd - textBegin)); + token.Content = valueBuilder.ProduceString(); + } + + token.flags = flags; + + this->tokenFlags = 0; + + return token; + } + } + + TokenList Lexer::lexAllTokens() + { + TokenList tokenList; + for(;;) + { + Token token = lexToken(); + tokenList.mTokens.Add(token); + + if(token.Type == TokenType::EndOfFile) + return tokenList; + } + } + + + +#if 0 + TokenList Lexer::Parse(const String & fileName, const String & str, DiagnosticSink * sink) + { + TokenList tokenList; + tokenList.mTokens = TokenizeText(fileName, str, [&](TokenizeErrorType errType, CodePosition pos) + { + auto curChar = str[pos.Pos]; + switch (errType) + { + case TokenizeErrorType::InvalidCharacter: + // Check if inside the ASCII "printable" range + if(curChar >= 0x20 && curChar <= 0x7E) + { + char buffer[] = { curChar, 0 }; + sink->diagnose(pos, Diagnostics::illegalCharacterPrint, buffer); + } + else + { + // Fallback: print as hexadecimal + sink->diagnose(pos, Diagnostics::illegalCharacterHex, String((unsigned char)curChar, 16)); + } + break; + case TokenizeErrorType::InvalidEscapeSequence: + sink->diagnose(pos, Diagnostics::illegalCharacterLiteral); + break; + default: + break; + } + }); + + // Add an end-of-file token so that we can reference it in diagnostic messages + tokenList.mTokens.Add(Token(TokenType::EndOfFile, "", 0, 0, 0, fileName, TokenFlag::AtStartOfLine | TokenFlag::AfterWhitespace)); + return tokenList; + } +#endif + } +} \ No newline at end of file diff --git a/source/slang/lexer.h b/source/slang/lexer.h new file mode 100644 index 000000000..d11e92d84 --- /dev/null +++ b/source/slang/lexer.h @@ -0,0 +1,101 @@ +#ifndef RASTER_RENDERER_LEXER_H +#define RASTER_RENDERER_LEXER_H + +#include "../core/basic.h" +#include "diagnostics.h" + +namespace Slang +{ + namespace Compiler + { + using namespace CoreLib::Basic; + + struct TokenList + { + Token* begin() const; + Token* end() const; + + List mTokens; + }; + + struct TokenSpan + { + TokenSpan(); + TokenSpan( + TokenList const& tokenList) + : mBegin(tokenList.begin()) + , mEnd (tokenList.end ()) + {} + + Token* begin() const { return mBegin; } + Token* end () const { return mEnd ; } + + int GetCount() { return (int)(mEnd - mBegin); } + + Token* mBegin; + Token* mEnd; + }; + + struct TokenReader + { + TokenReader(); + explicit TokenReader(TokenSpan const& tokens) + : mCursor(tokens.begin()) + , mEnd (tokens.end ()) + {} + explicit TokenReader(TokenList const& tokens) + : mCursor(tokens.begin()) + , mEnd (tokens.end ()) + {} + + bool IsAtEnd() const { return mCursor == mEnd; } + Token PeekToken() const; + TokenType PeekTokenType() const; + CodePosition PeekLoc() const; + + Token AdvanceToken(); + + int GetCount() { return (int)(mEnd - mCursor); } + + Token* mCursor; + Token* mEnd; + }; + + typedef unsigned int LexerFlags; + enum + { + kLexerFlag_InDirective = 1 << 0, + kLexerFlag_ExpectFileName = 2 << 0, + }; + + struct Lexer + { + Lexer( + String const& path, + String const& content, + DiagnosticSink* sink); + + ~Lexer(); + + Token lexToken(); + + TokenList lexAllTokens(); + + String path; + String content; + DiagnosticSink* sink; + + char const* cursor; + char const* end; + CodePosition loc; + TokenFlags tokenFlags; + LexerFlags lexerFlags; + }; + + // Helper routines for extracting values from tokens + String getStringLiteralTokenValue(Token const& token); + String getFileNameTokenValue(Token const& token); + } +} + +#endif \ No newline at end of file diff --git a/source/slang/lookup.cpp b/source/slang/lookup.cpp new file mode 100644 index 000000000..9731b1c8a --- /dev/null +++ b/source/slang/lookup.cpp @@ -0,0 +1,311 @@ +// lookup.cpp +#include "lookup.h" + +namespace Slang { +namespace Compiler { + +// + +// Helper for constructing breadcrumb trails during lookup, without unnecessary heap allocaiton +struct BreadcrumbInfo +{ + LookupResultItem::Breadcrumb::Kind kind; + DeclRef declRef; + BreadcrumbInfo* prev = nullptr; +}; + +void DoLocalLookupImpl( + String const& name, + ContainerDeclRef containerDeclRef, + LookupRequest const& request, + LookupResult& result, + BreadcrumbInfo* inBreadcrumbs); + +// + +void buildMemberDictionary(ContainerDecl* decl) +{ + // Don't rebuild if already built + if (decl->memberDictionaryIsValid) + return; + + decl->memberDictionary.Clear(); + decl->transparentMembers.Clear(); + + for (auto m : decl->Members) + { + auto name = m->Name.Content; + + // Add any transparent members to a separate list for lookup + if (m->HasModifier()) + { + TransparentMemberInfo info; + info.decl = m.Ptr(); + decl->transparentMembers.Add(info); + } + + // Ignore members with an empty name + if (name.Length() == 0) + continue; + + m->nextInContainerWithSameName = nullptr; + + Decl* next = nullptr; + if (decl->memberDictionary.TryGetValue(name, next)) + m->nextInContainerWithSameName = next; + + decl->memberDictionary[name] = m.Ptr(); + + } + decl->memberDictionaryIsValid = true; +} + + +bool DeclPassesLookupMask(Decl* decl, LookupMask mask) +{ + // type declarations + if(auto aggTypeDecl = dynamic_cast(decl)) + { + return int(mask) & int(LookupMask::Type); + } + else if(auto simpleTypeDecl = dynamic_cast(decl)) + { + return int(mask) & int(LookupMask::Type); + } + // function declarations + else if(auto funcDecl = dynamic_cast(decl)) + { + return (int(mask) & int(LookupMask::Function)) != 0; + } + + // default behavior is to assume a value declaration + // (no overloading allowed) + + return (int(mask) & int(LookupMask::Value)) != 0; +} + +void AddToLookupResult( + LookupResult& result, + LookupResultItem item) +{ + if (!result.isValid()) + { + // If we hadn't found a hit before, we have one now + result.item = item; + } + else if (!result.isOverloaded()) + { + // We are about to make this overloaded + result.items.Add(result.item); + result.items.Add(item); + } + else + { + // The result was already overloaded, so we pile on + result.items.Add(item); + } +} + +LookupResult refineLookup(LookupResult const& inResult, LookupMask mask) +{ + if (!inResult.isValid()) return inResult; + if (!inResult.isOverloaded()) return inResult; + + LookupResult result; + for (auto item : inResult.items) + { + if (!DeclPassesLookupMask(item.declRef.GetDecl(), mask)) + continue; + + AddToLookupResult(result, item); + } + return result; +} + +LookupResultItem CreateLookupResultItem( + DeclRef declRef, + BreadcrumbInfo* breadcrumbInfos) +{ + LookupResultItem item; + item.declRef = declRef; + + // breadcrumbs were constructed "backwards" on the stack, so we + // reverse them here by building a linked list the other way + RefPtr breadcrumbs; + for (auto bb = breadcrumbInfos; bb; bb = bb->prev) + { + breadcrumbs = new LookupResultItem::Breadcrumb( + bb->kind, + bb->declRef, + breadcrumbs); + } + item.breadcrumbs = breadcrumbs; + return item; +} + +void DoMemberLookupImpl( + String const& name, + RefPtr baseType, + LookupRequest const& request, + LookupResult& ioResult, + BreadcrumbInfo* breadcrumbs) +{ + // If the type was pointer-like, then dereference it + // automatically here. + if (auto pointerLikeType = baseType->As()) + { + // Need to leave a breadcrumb to indicate that we + // did an implicit dereference here + BreadcrumbInfo derefBreacrumb; + derefBreacrumb.kind = LookupResultItem::Breadcrumb::Kind::Deref; + derefBreacrumb.prev = breadcrumbs; + + // Recursively perform lookup on the result of deref + return DoMemberLookupImpl(name, pointerLikeType->elementType, request, ioResult, &derefBreacrumb); + } + + // Default case: no dereference needed + + if (auto baseDeclRefType = baseType->As()) + { + if (auto baseAggTypeDeclRef = baseDeclRefType->declRef.As()) + { + DoLocalLookupImpl(name, baseAggTypeDeclRef, request, ioResult, breadcrumbs); + } + } + + // TODO(tfoley): any other cases to handle here? +} + +void DoMemberLookupImpl( + String const& name, + DeclRef baseDeclRef, + LookupRequest const& request, + LookupResult& ioResult, + BreadcrumbInfo* breadcrumbs) +{ + auto baseType = getTypeForDeclRef(baseDeclRef); + return DoMemberLookupImpl(name, baseType, request, ioResult, breadcrumbs); +} + +// Look for members of the given name in the given container for declarations +void DoLocalLookupImpl( + String const& name, + ContainerDeclRef containerDeclRef, + LookupRequest const& request, + LookupResult& result, + BreadcrumbInfo* inBreadcrumbs) +{ + ContainerDecl* containerDecl = containerDeclRef.GetDecl(); + + // Ensure that the lookup dictionary in the container is up to date + if (!containerDecl->memberDictionaryIsValid) + { + buildMemberDictionary(containerDecl); + } + + // Look up the declarations with the chosen name in the container. + Decl* firstDecl = nullptr; + containerDecl->memberDictionary.TryGetValue(name, firstDecl); + + // Now iterate over those declarations (if any) and see if + // we find any that meet our filtering criteria. + // For example, we might be filtering so that we only consider + // type declarations. + for (auto m = firstDecl; m; m = m->nextInContainerWithSameName) + { + if (!DeclPassesLookupMask(m, request.mask)) + continue; + + // The declaration passed the test, so add it! + AddToLookupResult(result, CreateLookupResultItem(DeclRef(m, containerDeclRef.substitutions), inBreadcrumbs)); + } + + + // TODO(tfoley): should we look up in the transparent decls + // if we already has a hit in the current container? + + for(auto transparentInfo : containerDecl->transparentMembers) + { + // The reference to the transparent member should use whatever + // substitutions we used in referring to its outer container + DeclRef transparentMemberDeclRef(transparentInfo.decl, containerDeclRef.substitutions); + + // We need to leave a breadcrumb so that we know that the result + // of lookup involves a member lookup step here + + BreadcrumbInfo memberRefBreadcrumb; + memberRefBreadcrumb.kind = LookupResultItem::Breadcrumb::Kind::Member; + memberRefBreadcrumb.declRef = transparentMemberDeclRef; + memberRefBreadcrumb.prev = inBreadcrumbs; + + DoMemberLookupImpl(name, transparentMemberDeclRef, request, result, &memberRefBreadcrumb); + } + + // TODO(tfoley): need to consider lookup via extension here? +} + +void DoLookupImpl( + String const& name, + LookupRequest const& request, + LookupResult& result) +{ + auto scope = request.scope; + auto endScope = request.endScope; + for (;scope != endScope; scope = scope->parent) + { + // Note that we consider all "peer" scopes together, + // so that a hit in one of them does not proclude + // also finding a hit in another + for(auto link = scope; link; link = link->nextSibling) + { + if(!link->containerDecl) + continue; + + ContainerDeclRef containerRef = DeclRef(link->containerDecl, nullptr).As(); + DoLocalLookupImpl(name, containerRef, request, result, nullptr); + } + + if (result.isValid()) + { + // If we've found a result in this scope, then there + // is no reason to look further up (for now). + return; + } + } + + // If we run out of scopes, then we are done. +} + +LookupResult DoLookup(String const& name, LookupRequest const& request) +{ + LookupResult result; + DoLookupImpl(name, request, result); + return result; +} + +LookupResult LookUp(String const& name, RefPtr scope) +{ + LookupRequest request; + request.scope = scope; + return DoLookup(name, request); +} + +// perform lookup within the context of a particular container declaration, +// and do *not* look further up the chain +LookupResult LookUpLocal(String const& name, ContainerDeclRef containerDeclRef) +{ + LookupRequest request; + LookupResult result; + DoLocalLookupImpl(name, containerDeclRef, request, result, nullptr); + return result; +} + +LookupResult LookUpLocal(String const& name, ContainerDecl* containerDecl) +{ + ContainerDeclRef containerRef = DeclRef(containerDecl, nullptr).As(); + return LookUpLocal(name, containerRef); +} + + +}} diff --git a/source/slang/lookup.h b/source/slang/lookup.h new file mode 100644 index 000000000..25b62738f --- /dev/null +++ b/source/slang/lookup.h @@ -0,0 +1,41 @@ +#ifndef SLANG_LOOKUP_H_INCLUDED +#define SLANG_LOOKUP_H_INCLUDED + +#include "Syntax.h" + +namespace Slang { +namespace Compiler { + +// Take an existing lookup result and refine it to only include +// results that pass the given `LookupMask`. +LookupResult refineLookup(LookupResult const& inResult, LookupMask mask); + +// Ensure that the dictionary for name-based member lookup has been +// built for the given container declaration. +void buildMemberDictionary(ContainerDecl* decl); + +// Look up a name in the given scope, proceeding up through +// parent scopes as needed. +LookupResult LookUp(String const& name, RefPtr scope); + +// perform lookup within the context of a particular container declaration, +// and do *not* look further up the chain +LookupResult LookUpLocal(String const& name, ContainerDeclRef containerDeclRef); +LookupResult LookUpLocal(String const& name, ContainerDecl* containerDecl); + +// TODO: this belongs somewhere else + +class SemanticsVisitor; +QualType getTypeForDeclRef( + SemanticsVisitor* sema, + DiagnosticSink* sink, + DeclRef declRef, + RefPtr* outTypeResult); + +QualType getTypeForDeclRef( + DeclRef declRef); + + +}} + +#endif \ No newline at end of file diff --git a/source/slang/parameter-binding.cpp b/source/slang/parameter-binding.cpp new file mode 100644 index 000000000..8bbb566af --- /dev/null +++ b/source/slang/parameter-binding.cpp @@ -0,0 +1,1252 @@ +// parameter-binding.cpp +#include "parameter-binding.h" + +#include "lookup.h" +#include "compiler.h" +#include "type-layout.h" + +#include "../../slang.h" + +#define SLANG_EXHAUSTIVE_SWITCH() default: assert(!"unexpected"); break; + +namespace Slang { +namespace Compiler { + +// Information on ranges of registers already claimed/used +struct UsedRange +{ + int begin; + int end; +}; +bool operator<(UsedRange left, UsedRange right) +{ + if (left.begin != right.begin) + return left.begin < right.begin; + if (left.end != right.end) + return left.end < right.end; + return false; +} + +struct UsedRanges +{ + List ranges; + + // Add a range to the set, either by extending + // an existing range, or by adding a new one... + void Add(UsedRange const& range) + { + for (auto& rr : ranges) + { + if (rr.begin == range.end) + { + rr.begin = range.begin; + return; + } + else if (rr.end == range.begin) + { + rr.end = range.end; + return; + } + } + ranges.Add(range); + ranges.Sort(); + } + + void Add(int begin, int end) + { + UsedRange range; + range.begin = begin; + range.end = end; + Add(range); + } + + + // Try to find space for `count` entries + int Allocate(int count) + { + int begin = 0; + + int rangeCount = ranges.Count(); + for (int rr = 0; rr < rangeCount; ++rr) + { + // try to fit in before this range... + + int end = ranges[rr].begin; + + // If there is enough space... + if (end >= begin + count) + { + // ... then claim it and be done + Add(begin, begin + count); + return begin; + } + + // ... otherwise, we need to look at the + // space between this range and the next + begin = ranges[rr].end; + } + + // We've run out of ranges to check, so we + // can safely go after the last one! + Add(begin, begin + count); + return begin; + } +}; + +struct ParameterBindingInfo +{ + size_t space; + size_t index; + size_t count; +}; + +enum +{ + kLayoutResourceKindCount = SLANG_PARAMETER_CATEGORY_MIXED, +}; + +// Information on a single parameter +struct ParameterInfo : RefObject +{ + // Layout info for the concrete variables that will make up this parameter + List> varLayouts; + + ParameterBindingInfo bindingInfo[kLayoutResourceKindCount]; + + // The next parameter that has the same name... + ParameterInfo* nextOfSameName; + + ParameterInfo() + { + // Make sure we aren't claiming any resources yet + for( int ii = 0; ii < kLayoutResourceKindCount; ++ii ) + { + bindingInfo[ii].count = 0; + } + } +}; + +// State that is shared during parameter binding, +// across all translation units +struct SharedParameterBindingContext +{ + LayoutRulesFamilyImpl* defaultLayoutRules; + + // All shader parameters we've discovered so far, and started to lay out... + List> parameters; + + // A dictionary to accellerate looking up parameters by name + Dictionary mapNameToParameterInfo; + + // The program layout we are trying to construct + RefPtr programLayout; + + // The source language we are trying to use + SourceLanguage sourceLanguage; + + // Information on what ranges of "registers" have already + // been claimed, for each resource type + UsedRanges usedResourceRanges[kLayoutResourceKindCount]; +}; + +// State that might be specific to a single translation unit +// or event to an entry point. +struct ParameterBindingContext +{ + // All the shared state needs to be available + SharedParameterBindingContext* shared; + + // The layout rules to use while computing usage... + LayoutRulesFamilyImpl* layoutRules; + + // What stage (if any) are we compiling for? + Stage stage; +}; + +struct LayoutSemanticInfo +{ + LayoutResourceKind kind; // the register kind + int space; + int index; + + // TODO: need to deal with component-granularity binding... +}; + +LayoutSemanticInfo ExtractLayoutSemanticInfo( + ParameterBindingContext* /*context*/, + HLSLLayoutSemantic* semantic) +{ + LayoutSemanticInfo info; + info.space = 0; + info.index = 0; + info.kind = LayoutResourceKind::None; + + auto registerName = semantic->registerName.Content; + if (registerName.Length() == 0) + return info; + + LayoutResourceKind kind = LayoutResourceKind::None; + switch (registerName[0]) + { + case 'b': + kind = LayoutResourceKind::ConstantBuffer; + break; + + case 't': + kind = LayoutResourceKind::ShaderResource; + break; + + case 'u': + kind = LayoutResourceKind::UnorderedAccess; + break; + + case 's': + kind = LayoutResourceKind::SamplerState; + break; + + default: + // TODO: issue an error here! + return info; + } + + // TODO: need to parse and handle `space` binding + int space = 0; + + int index = 0; + for (int ii = 1; ii < registerName.Length(); ++ii) + { + int c = registerName[ii]; + if (c >= '0' && c <= '9') + { + index = index * 10 + (c - '0'); + } + else + { + // TODO: issue an error here! + return info; + } + } + + // TODO: handle component mask part of things... + + info.kind = kind; + info.index = index; + info.space = space; + return info; +} + +static bool doesParameterMatch( + ParameterBindingContext* context, + RefPtr varLayout, + ParameterInfo* parameterInfo) +{ + // TODO: need to implement this eventually + return true; +} + +// + +// Given a GLSL `layout` modifier, we need to be able to check for +// a particular sub-argument and extract its value if present. +template +static bool findLayoutArg( + RefPtr syntax, + int* outVal) +{ + for( auto modifier : syntax->GetModifiersOfType() ) + { + *outVal = (int) strtol(modifier->valToken.Content.Buffer(), nullptr, 10); + return true; + } + return false; +} + +template +static bool findLayoutArg( + DeclRef declRef, + int* outVal) +{ + return findLayoutArg(declRef.GetDecl(), outVal); +} + +// + +RefPtr +getTypeLayoutForGlobalShaderParameter_GLSL( + ParameterBindingContext* context, + VarDeclBase* varDecl) +{ + auto rules = context->layoutRules; + auto type = varDecl->getType(); + + // A GLSL shader parameter will be marked with + // a qualifier to match the boundary it uses + // + // In the case of a parameter block, we will have + // consumed this qualifier as part of parsing, + // so that it won't be present on the declaration + // any more. As such we also inspect the type + // of the variable. + + // TODO(tfoley): We have multiple variations of + // the `uniform` modifier right now, and that + // needs to get fixed... + if(varDecl->HasModifier() || type->As()) + return CreateTypeLayout(type, rules->getConstantBufferRules()); + + if(varDecl->HasModifier() || type->As()) + return CreateTypeLayout(type, rules->getShaderStorageBufferRules()); + + if( varDecl->HasModifier() || type->As()) + { + // Special case to handle "arrayed" shader inputs, as used + // for Geometry and Hull input + switch( context->stage ) + { + case Stage::Geometry: + case Stage::Hull: + case Stage::Domain: + // Tessellation `patch` variables should stay as written + if( !varDecl->HasModifier() ) + { + // Unwrap array type, if prsent + if( auto arrayType = type->As() ) + { + type = arrayType->BaseType.Ptr(); + } + } + break; + + default: + break; + } + + return CreateTypeLayout(type, rules->getVaryingInputRules()); + } + + if( varDecl->HasModifier() || type->As()) + { + // Special case to handle "arrayed" shader outputs, as used + // for Hull Shader output + // + // Note(tfoley): there is unfortunate code duplication + // with the `in` case above. + switch( context->stage ) + { + case Stage::Hull: + // Tessellation `patch` variables should stay as written + if( !varDecl->HasModifier() ) + { + // Unwrap array type, if prsent + if( auto arrayType = type->As() ) + { + type = arrayType->BaseType.Ptr(); + } + } + break; + + default: + break; + } + + return CreateTypeLayout(type, rules->getVaryingOutputRules()); + } + + // A `const` global with a `layout(constant_id = ...)` modifier + // is a declaration of a specialization constant. + if(varDecl->HasModifier()) + return CreateTypeLayout(type, rules->getSpecializationConstantRules()); + + // GLSL says that an "ordinary" global variable + // is just a (thread local) global and not a + // parameter + return nullptr; +} + +RefPtr +getTypeLayoutForGlobalShaderParameter_HLSL( + ParameterBindingContext* context, + VarDeclBase* varDecl) +{ + auto rules = context->layoutRules; + auto type = varDecl->getType(); + + // HLSL `static` modifier indicates "thread local" + if(varDecl->HasModifier()) + return nullptr; + + // HLSL `groupshared` modifier indicates "thread-group local" + if(varDecl->HasModifier()) + return nullptr; + + // TODO(tfoley): there may be other cases that we need to handle here + + // An "ordinary" global variable is implicitly a uniform + // shader parameter. + return CreateTypeLayout(type, rules->getConstantBufferRules()); +} + +// Determine how to lay out a global variable that might be +// a shader parameter. +// Returns `nullptr` if the declaration does not represent +// a shader parameter. + +RefPtr +getTypeLayoutForGlobalShaderParameter( + ParameterBindingContext* context, + VarDeclBase* varDecl) +{ + auto rules = context->layoutRules; + switch( context->shared->sourceLanguage ) + { + case SourceLanguage::Slang: + case SourceLanguage::HLSL: + return getTypeLayoutForGlobalShaderParameter_HLSL(context, varDecl); + + case SourceLanguage::GLSL: + return getTypeLayoutForGlobalShaderParameter_GLSL(context, varDecl); + + default: + assert(false); + return nullptr; + } +} + + +// + + + +// Collect a single declaration into our set of parameters +static void collectGlobalScopeParameter( + ParameterBindingContext* context, + RefPtr varDecl) +{ + // We use a single operation to both check whether the + // variable represents a shader parameter, and to compute + // the layout for that parameter's type. + auto typeLayout = getTypeLayoutForGlobalShaderParameter( + context, + varDecl.Ptr()); + + // If we did not find appropriate layout rules, then it + // must mean that this global variable is *not* a shader + // parameter. + if(!typeLayout) + return; + + // Now create a variable layout that we can use + RefPtr varLayout = new VarLayout(); + varLayout->typeLayout = typeLayout; + varLayout->varDecl = DeclRef(varDecl.Ptr(), nullptr).As(); + + // This declaration may represent the same logical parameter + // as a declaration that came from a different translation unit. + // If that is the case, we want to re-use the same `VarLayout` + // across both parameters. + // + // First we look for an existing entry matching the name + // of this parameter: + auto parameterName = varDecl->Name.Content; + ParameterInfo* parameterInfo = nullptr; + if( context->shared->mapNameToParameterInfo.TryGetValue(parameterName, parameterInfo) ) + { + // If the parameters have the same name, but don't "match" according to some reasonable rules, + // then we need to bail out. + if( !doesParameterMatch(context, varLayout, parameterInfo) ) + { + parameterInfo = nullptr; + } + } + + // If we didn't find a matching parameter, then we need to create one here + if( !parameterInfo ) + { + parameterInfo = new ParameterInfo(); + context->shared->parameters.Add(parameterInfo); + context->shared->mapNameToParameterInfo.Add(parameterName, parameterInfo); + } + else + { + varLayout->flags |= VarLayoutFlag::IsRedeclaration; + } + + // Add this variable declaration to the list of declarations for the parameter + parameterInfo->varLayouts.Add(varLayout); +} + +static void addExplicitParameterBinding( + ParameterBindingContext* context, + RefPtr parameterInfo, + LayoutSemanticInfo const& semanticInfo, + int count) +{ + auto kind = semanticInfo.kind; + + auto& bindingInfo = parameterInfo->bindingInfo[(int)kind]; + if( bindingInfo.count != 0 ) + { + // We already have a binding here, so we want to + // confirm that it matches the new one that is + // incoming... + if( bindingInfo.count != count + || bindingInfo.index != semanticInfo.index + || bindingInfo.space != semanticInfo.space ) + { + // TODO: diagnose! + } + + // TODO(tfoley): `register` semantics can technically be + // profile-specific (not sure if anybody uses that)... + } + else + { + bindingInfo.count = count; + bindingInfo.index = semanticInfo.index; + bindingInfo.space = semanticInfo.space; + + // If things are bound in `space0` (the default), then we need + // to lay claim to the register range used, so that automatic + // assignment doesn't go and use the same registers. + if (semanticInfo.space == 0) + { + context->shared->usedResourceRanges[(int)semanticInfo.kind].Add( + semanticInfo.index, + semanticInfo.index + count); + } + } +} + +static void addExplicitParameterBindings_HLSL( + ParameterBindingContext* context, + RefPtr parameterInfo, + RefPtr varLayout) +{ + auto typeLayout = varLayout->typeLayout; + auto varDecl = varLayout->varDecl; + + // If the declaration has explicit binding modifiers, then + // here is where we want to extract and apply them... + + // Look for HLSL `register` or `packoffset` semantics. + for (auto semantic : varDecl.GetDecl()->GetModifiersOfType()) + { + // Need to extract the information encoded in the semantic + LayoutSemanticInfo semanticInfo = ExtractLayoutSemanticInfo(context, semantic); + auto kind = semanticInfo.kind; + if (kind == LayoutResourceKind::None) + continue; + + // TODO: need to special-case when this is a `c` register binding... + + // Find the appropriate resource-binding information + // inside the type, to see if we even use any resources + // of the given kind. + + auto typeRes = typeLayout->FindResourceInfo(kind); + int count = 0; + if (typeRes) + { + count = (int) typeRes->count; + } + else + { + // TODO: warning here! + } + + addExplicitParameterBinding(context, parameterInfo, semanticInfo, count); + } +} + +static void addExplicitParameterBindings_GLSL( + ParameterBindingContext* context, + RefPtr parameterInfo, + RefPtr varLayout) +{ + auto typeLayout = varLayout->typeLayout; + auto varDecl = varLayout->varDecl; + + // The catch in GLSL is that the expected resource type + // is implied by the parameter declaration itself, and + // the `layout` modifier is only allowed to adjust + // the index/offset/etc. + // + + TypeLayout::ResourceInfo* resInfo = nullptr; + LayoutSemanticInfo semanticInfo; + semanticInfo.index = 0; + semanticInfo.space = 0; + if( (resInfo = typeLayout->FindResourceInfo(LayoutResourceKind::DescriptorTableSlot)) ) + { + // Try to find `binding` and `set` + if(!findLayoutArg(varDecl, &semanticInfo.index)) + return; + + findLayoutArg(varDecl, &semanticInfo.space); + } + else if( (resInfo = typeLayout->FindResourceInfo(LayoutResourceKind::VertexInput)) ) + { + // Try to find `location` binding + if(!findLayoutArg(varDecl, &semanticInfo.index)) + return; + } + else if( (resInfo = typeLayout->FindResourceInfo(LayoutResourceKind::FragmentOutput)) ) + { + // Try to find `location` binding + if(!findLayoutArg(varDecl, &semanticInfo.index)) + return; + } + else if( (resInfo = typeLayout->FindResourceInfo(LayoutResourceKind::SpecializationConstant)) ) + { + // Try to find `constant_id` binding + if(!findLayoutArg(varDecl, &semanticInfo.index)) + return; + } + + // If we didn't find any matches, then bail + if(!resInfo) + return; + + auto kind = resInfo->kind; + auto count = resInfo->count; + semanticInfo.kind = kind; + + addExplicitParameterBinding(context, parameterInfo, semanticInfo, int(count)); +} + +// Given a single parameter, collect whatever information we have on +// how it has been explicitly bound, which may come from multiple declarations +void generateParameterBindings( + ParameterBindingContext* context, + RefPtr parameterInfo) +{ + // There must be at least one declaration for the parameter. + assert(parameterInfo->varLayouts.Count() != 0); + + // Iterate over all declarations looking for explicit binding information. + for( auto& varLayout : parameterInfo->varLayouts ) + { + // Handle HLSL `register` and `packoffset` modifiers + addExplicitParameterBindings_HLSL(context, parameterInfo, varLayout); + + + // Handle GLSL `layout` modifiers + addExplicitParameterBindings_GLSL(context, parameterInfo, varLayout); + } +} + +// Generate the binding information for a shader parameter. +static void completeBindingsForParameter( + ParameterBindingContext* context, + RefPtr parameterInfo) +{ + // For any resource kind used by the parameter + // we need to update its layout information + // to include a binding for that resource kind. + // + // We will use the first declaration of the parameter as + // a stand-in for all the declarations, so it is important + // that earlier code has validated that the declarations + // "match". + + assert(parameterInfo->varLayouts.Count() != 0); + auto firstVarLayout = parameterInfo->varLayouts.First(); + auto firstTypeLayout = firstVarLayout->typeLayout; + + for(auto typeRes : firstTypeLayout->resourceInfos) + { + // Did we already apply some explicit binding information + // for this resource kind? + auto kind = typeRes.kind; + auto& bindingInfo = parameterInfo->bindingInfo[(int)kind]; + if( bindingInfo.count != 0 ) + { + // If things have already been bound, our work is done. + continue; + } + + auto count = typeRes.count; + bindingInfo.count = count; + bindingInfo.index = context->shared->usedResourceRanges[(int)kind].Allocate((int) count); + + // For now we only auto-generate bindings in space zero + bindingInfo.space = 0; + } + + // At this point we should have explicit binding locations chosen for + // all the relevant resource kinds, so we can apply these to the + // declarations: + + for(auto& varLayout : parameterInfo->varLayouts) + { + for(auto k = 0; k < kLayoutResourceKindCount; ++k) + { + auto kind = LayoutResourceKind(k); + auto& bindingInfo = parameterInfo->bindingInfo[k]; + + // skip resources we aren't consuming + if(bindingInfo.count == 0) + continue; + + // Add a record to the variable layout + auto varRes = varLayout->AddResourceInfo(kind); + varRes->space = (int) bindingInfo.space; + varRes->index = (int) bindingInfo.index; + } + } +} + +static void collectGlobalScopeParameters( + ParameterBindingContext* context, + ProgramSyntaxNode* program) +{ + // First enumerate parameters at global scope + for( auto decl : program->Members ) + { + // A shader parameter is always a variable, + // so skip declarations that aren't variables. + auto varDecl = decl.As(); + if (!varDecl) + continue; + + collectGlobalScopeParameter(context, varDecl); + } + + // Next, we need to enumerate the parameters of + // each entry point (which requires knowing what the + // entry points *are*) + + // TODO(tfoley): Entry point functions should be identified + // by looking for a generated modifier that is attached + // to global-scope function declarations. +} + +struct SimpleSemanticInfo +{ + String name; + int index; +}; + +SimpleSemanticInfo decomposeSimpleSemantic( + HLSLSimpleSemantic* semantic) +{ + auto composedName = semantic->name.Content; + + // look for a trailing sequence of decimal digits + // at the end of the composed name + int length = composedName.Length(); + int indexLoc = length; + while( indexLoc > 0 ) + { + auto c = composedName[indexLoc-1]; + if( c >= '0' && c <= '9' ) + { + indexLoc--; + continue; + } + else + { + break; + } + } + + SimpleSemanticInfo info; + + // + if( indexLoc == length ) + { + // No index suffix + info.name = composedName; + info.index = 0; + } + else + { + // The name is everything before the digits + info.name = composedName.SubString(0, indexLoc); + info.index = strtol(composedName.SubString(indexLoc, length - indexLoc).begin(), nullptr, 10); + } + return info; +} + +enum class EntryPointParameterDirection +{ + Input, + Output, +}; + +struct EntryPointParameterState +{ + String* optSemanticName; + int* ioSemanticIndex; + EntryPointParameterDirection direction; + int semanticSlotCount; +}; + +static void processSimpleEntryPointInput( + ParameterBindingContext* context, + RefPtr type, + EntryPointParameterState const& state) +{ + auto optSemanticName = state.optSemanticName; + auto semanticIndex = *state.ioSemanticIndex; + auto semanticSlotCount = state.semanticSlotCount; +} + +static void processSimpleEntryPointOutput( + ParameterBindingContext* context, + RefPtr type, + EntryPointParameterState const& state) +{ + auto optSemanticName = state.optSemanticName; + auto semanticIndex = *state.ioSemanticIndex; + auto semanticSlotCount = state.semanticSlotCount; + + if(!optSemanticName) + return; + + auto semanticName = *optSemanticName; + + // Note: I'm just doing something expedient here and detecting `SV_Target` + // outputs and claiming the appropriate register range right away. + // + // TODO: we should really be building up some representation of all of this, + // once we've gone to the trouble of looking it all up... + if( semanticName.ToLower() == "sv_target" ) + { + context->shared->usedResourceRanges[int(LayoutResourceKind::UnorderedAccess)].Add(semanticIndex, semanticIndex + semanticSlotCount); + } +} + +static void processSimpleEntryPointParameter( + ParameterBindingContext* context, + RefPtr type, + EntryPointParameterState const& inState, + int semanticSlotCount = 1) +{ + EntryPointParameterState state = inState; + state.semanticSlotCount = semanticSlotCount; + + switch( state.direction ) + { + case EntryPointParameterDirection::Input: + processSimpleEntryPointInput(context, type, state); + break; + + case EntryPointParameterDirection::Output: + processSimpleEntryPointOutput(context, type, state); + break; + + SLANG_EXHAUSTIVE_SWITCH() + } + + *state.ioSemanticIndex += state.semanticSlotCount; +} + +static void processEntryPointParameter( + ParameterBindingContext* context, + RefPtr type, + EntryPointParameterState const& state); + +static void processEntryPointParameterWithPossibleSemantic( + ParameterBindingContext* context, + Decl* declForSemantic, + RefPtr type, + EntryPointParameterState const& state) +{ + // If there is no explicit semantic already in effect, *and* we find an explicit + // semantic on the associated declaration, then we'll use it. + if( !state.optSemanticName ) + { + if( auto semantic = declForSemantic->FindModifier() ) + { + auto semanticInfo = decomposeSimpleSemantic(semantic); + int semanticIndex = semanticInfo.index; + + EntryPointParameterState subState = state; + subState.optSemanticName = &semanticInfo.name; + subState.ioSemanticIndex = &semanticIndex; + + processEntryPointParameter(context, type, subState); + } + } + + // Default case: either there was an explicit semantic in effect already, + // *or* we couldn't find an explicit semantic to apply on the given + // declaration, so we will just recursive with whatever we have at + // the moment. + processEntryPointParameter(context, type, state); +} + + +static void processEntryPointParameter( + ParameterBindingContext* context, + RefPtr type, + EntryPointParameterState const& state) +{ + // Scalar and vector types are treated as outputs directly + if(auto basicType = type->As()) + { + processSimpleEntryPointParameter(context, basicType, state); + } + else if(auto basicType = type->As()) + { + processSimpleEntryPointParameter(context, basicType, state); + } + // A matrix is processed as if it was an array of rows + else if( auto matrixType = type->As() ) + { + auto rowCount = GetIntVal(matrixType->getRowCount()); + processSimpleEntryPointParameter(context, basicType, state, rowCount); + } + else if( auto arrayType = type->As() ) + { + auto elementCount = GetIntVal(arrayType->ArrayLength); + + for( int ii = 0; ii < elementCount; ++ii ) + { + processEntryPointParameter(context, arrayType->BaseType, state); + } + } + // Ignore a bunch of types that don't make sense here... + else if(auto textureType = type->As()) {} + else if(auto samplerStateType = type->As()) {} + else if(auto constantBufferType = type->As()) {} + // Catch declaration-reference types late in the sequence, since + // otherwise they will include all of the above cases... + else if( auto declRefType = type->As() ) + { + auto declRef = declRefType->declRef; + + if (auto structDeclRef = declRef.As()) + { + // Need to recursively walk the fields of the structure now... + for( auto field : structDeclRef.GetFields() ) + { + processEntryPointParameterWithPossibleSemantic( + context, + field.GetDecl(), + field.GetType(), + state); + } + } + else + { + assert(!"unimplemented"); + } + } + else + { + assert(!"unimplemented"); + } +} + +static void collectEntryPointParameters( + ParameterBindingContext* context, + EntryPointOption const& entryPoint, + ProgramSyntaxNode* translationUnitSyntax) +{ + // First, look for the entry point with the specified name + + // Make sure we've got a query-able member dictionary + buildMemberDictionary(translationUnitSyntax); + + Decl* entryPointDecl; + if( !translationUnitSyntax->memberDictionary.TryGetValue(entryPoint.name, entryPointDecl) ) + { + // No such entry point! + return; + } + if( entryPointDecl->nextInContainerWithSameName ) + { + // Not the only decl of that name! + return; + } + + FunctionSyntaxNode* entryPointFuncDecl = dynamic_cast(entryPointDecl); + if( !entryPointFuncDecl ) + { + // Not a function! + return; + } + + // Create the layout object here + auto entryPointLayout = new EntryPointLayout(); + entryPointLayout->profile = entryPoint.profile; + entryPointLayout->entryPoint = entryPointFuncDecl; + + + context->shared->programLayout->entryPoints.Add(entryPointLayout); + + // Okay, we seemingly have an entry-point function, and now we need to collect info on its parameters too + // + // TODO: Long-term we probably want complete information on all inputs/outputs of an entry point, + // but for now we are really just trying to scrape information on fragment outputs, so lets do that: + // + // TODO: check whether we should enumerate the parameters before the return type, or vice versa + + int defaultSemanticIndex = 0; + + EntryPointParameterState state; + state.ioSemanticIndex = &defaultSemanticIndex; + state.optSemanticName = nullptr; + state.semanticSlotCount = 0; + + for( auto m : entryPointFuncDecl->Members ) + { + auto paramDecl = m.As(); + if(!paramDecl) + continue; + + // We have an entry-point parameter, and need to figure out what to do with it. + + // If it appears to be an input, process it as such. + if( paramDecl->HasModifier() || paramDecl->HasModifier() || !paramDecl->HasModifier() ) + { + state.direction = EntryPointParameterDirection::Input; + + processEntryPointParameterWithPossibleSemantic( + context, + paramDecl.Ptr(), + paramDecl->Type.type, + state); + } + + // If it appears to be an output, process it as such. + if(paramDecl->HasModifier() || paramDecl->HasModifier()) + { + state.direction = EntryPointParameterDirection::Output; + + processEntryPointParameterWithPossibleSemantic( + context, + paramDecl.Ptr(), + paramDecl->Type.type, + state); + } + } + + // If we can find an output type for the entry point, then process it as + // an output parameter. + if( auto resultType = entryPointFuncDecl->ReturnType.type ) + { + state.direction = EntryPointParameterDirection::Output; + + processEntryPointParameterWithPossibleSemantic( + context, + entryPointFuncDecl, + resultType, + state); + } +} + +// When doing parameter binding for global-scope stuff in GLSL, +// we may need to know what stage we are compiling for, so that +// we can handle special cases appropriately (e.g., "arrayed" +// inputs and outputs). +static Stage +inferStageForTranslationUnit( + CompileUnit const& translationUnit) +{ + // In the specific case where we are compiling GLSL input, + // and have only a single entry point, use the stage + // of the entry point. + // + // TODO: can we generalize this at all? + if( translationUnit.options.sourceLanguage == SourceLanguage::GLSL ) + { + if( translationUnit.options.entryPoints.Count() == 1 ) + { + return translationUnit.options.entryPoints[0].profile.GetStage(); + } + } + + return Stage::Unknown; +} + +static void collectParameters( + ParameterBindingContext* inContext, + CollectionOfTranslationUnits* program) +{ + ParameterBindingContext contextData = *inContext; + auto context = &contextData; + + for( auto& translationUnit : program->translationUnits ) + { + context->stage = inferStageForTranslationUnit(translationUnit); + + // First look at global-scope parameters + collectGlobalScopeParameters(context, translationUnit.SyntaxNode.Ptr()); + + // Next consider parameters for entry points + for( auto& entryPoint : translationUnit.options.entryPoints ) + { + context->stage = entryPoint.profile.GetStage(); + collectEntryPointParameters(context, entryPoint, translationUnit.SyntaxNode.Ptr()); + } + } +} + +void GenerateParameterBindings( + CollectionOfTranslationUnits* program) +{ + // TODO: infer a language or set of language rules to use based on the + // source files and entry points given + auto language = SourceLanguage::Unknown; + for( auto& translationUnit : program->translationUnits ) + { + auto translationUnitLanguage = translationUnit.options.sourceLanguage; + if( language == SourceLanguage::Unknown ) + { + language = translationUnitLanguage; + } + else if( language == translationUnitLanguage ) + { + // same language: nothing to do... + } + else + { + // mismatch! + // TODO(tfoley): emit a diagnostic + } + } + + // TODO(tfoley): We should really be picking layout rules + // based on the *target* language, and not the source... + auto rules = GetLayoutRulesFamilyImpl(language); + assert(rules); + + RefPtr programLayout = new ProgramLayout; + + // Create a context to hold shared state during the process + // of generating parameter bindings + SharedParameterBindingContext sharedContext; + sharedContext.defaultLayoutRules = rules; + sharedContext.programLayout = programLayout; + sharedContext.sourceLanguage = language; + + // Create a sub-context to collect parameters that get + // declared into the global scope + ParameterBindingContext context; + context.shared = &sharedContext; + context.layoutRules = sharedContext.defaultLayoutRules; + + // Walk through AST to discover all the parameters + collectParameters(&context, program); + + // Now walk through the parameters to generate initial binding information + for( auto& parameter : sharedContext.parameters ) + { + generateParameterBindings(&context, parameter); + } + + bool anyGlobalUniforms = false; + for( auto& parameterInfo : sharedContext.parameters ) + { + assert(parameterInfo->varLayouts.Count() != 0); + auto firstVarLayout = parameterInfo->varLayouts.First(); + + // Does the field have any uniform data? + if( firstVarLayout->typeLayout->FindResourceInfo(LayoutResourceKind::Uniform) ) + { + anyGlobalUniforms = true; + break; + } + } + + // If there are any global-scope uniforms, then we need to + // allocate a constant-buffer binding for them here. + ParameterBindingInfo globalConstantBufferBinding; + if( anyGlobalUniforms ) + { + globalConstantBufferBinding.index = + context.shared->usedResourceRanges[ + (int)LayoutResourceKind::ConstantBuffer].Allocate(1); + + // For now we only auto-generate bindings in space zero + globalConstantBufferBinding.space = 0; + } + + + // Now walk through again to actually give everything + // ranges of registers... + for( auto& parameter : sharedContext.parameters ) + { + completeBindingsForParameter(&context, parameter); + } + + // TODO: need to deal with parameters declared inside entry-point + // parameter lists at some point... + + + // Next we need to create a type layout to reflect the information + // we have collected. + + // We will lay out any bare uniforms at the global scope into + // a single constant buffer. This is appropriate for HLSL global-scope + // uniforms, and Vulkan GLSL doesn't allow uniforms at global scope, + // so it should work out. + // + // For legacy GLSL targets, we'd probably need a distinct resource + // kind and set of rules here, since legacy uniforms are not the + // same as the contents of a constant buffer. + auto globalScopeRules = context.layoutRules->getConstantBufferRules(); + + RefPtr globalScopeStructLayout = new StructTypeLayout(); + globalScopeStructLayout->rules = globalScopeRules; + + UniformLayoutInfo structLayoutInfo = globalScopeRules->BeginStructLayout(); + for( auto& parameterInfo : sharedContext.parameters ) + { + assert(parameterInfo->varLayouts.Count() != 0); + auto firstVarLayout = parameterInfo->varLayouts.First(); + + // Does the field have any uniform data? + auto layoutInfo = firstVarLayout->typeLayout->FindResourceInfo(LayoutResourceKind::Uniform); + size_t uniformSize = layoutInfo ? layoutInfo->count : 0; + if( uniformSize != 0 ) + { + // Make sure uniform fields get laid out properly... + + UniformLayoutInfo fieldInfo( + uniformSize, + firstVarLayout->typeLayout->uniformAlignment); + + size_t uniformOffset = globalScopeRules->AddStructField( + &structLayoutInfo, + fieldInfo); + + for( auto& varLayout : parameterInfo->varLayouts ) + { + varLayout->findOrAddResourceInfo(LayoutResourceKind::Uniform)->index = uniformOffset; + } + } + + globalScopeStructLayout->fields.Add(firstVarLayout); + + for( auto& varLayout : parameterInfo->varLayouts ) + { + globalScopeStructLayout->mapVarToLayout.Add(varLayout->varDecl.GetDecl(), varLayout); + } + } + globalScopeRules->EndStructLayout(&structLayoutInfo); + + RefPtr globalScopeLayout = globalScopeStructLayout; + + // If there are global-scope uniforms, then we need to wrap + // up a global constant buffer type layout to hold them + if( anyGlobalUniforms ) + { + auto globalConstantBufferLayout = createParameterBlockTypeLayout( + nullptr, + globalScopeStructLayout, + globalScopeRules); + + globalScopeLayout = globalConstantBufferLayout; + } + + // We now have a bunch of layout information, which we should + // record into a suitable object that represents the program + programLayout->globalScopeLayout = globalScopeLayout; + program->layout = programLayout; +} + +}} diff --git a/source/slang/parameter-binding.h b/source/slang/parameter-binding.h new file mode 100644 index 000000000..8165f1b2e --- /dev/null +++ b/source/slang/parameter-binding.h @@ -0,0 +1,32 @@ +#ifndef SLANG_PARAMETER_BINDING_H +#define SLANG_PARAMETER_BINDING_H + +#include "../core/basic.h" +#include "syntax.h" + +#include "../../Slang.h" + +namespace Slang { +namespace Compiler { + +class CollectionOfTranslationUnits; + +// The parameter-binding interface is responsible for assigning +// binding locations/registers to every parameter of a shader +// program. This can include both parameters declared on a +// particular entry point, as well as parameters declared at +// global scope. +// + + +// Generate binding information for the given program, +// represented as a collection of different translation units, +// and attach that information to the syntax nodes +// of the program. + +void GenerateParameterBindings( + CollectionOfTranslationUnits* program); + +}} + +#endif // SLANG_REFLECTION_H diff --git a/source/slang/parser.cpp b/source/slang/parser.cpp new file mode 100644 index 000000000..773e3b74b --- /dev/null +++ b/source/slang/parser.cpp @@ -0,0 +1,3106 @@ +#include "Parser.h" + +#include + +#include "lookup.h" + +namespace Slang +{ + namespace Compiler + { + enum Precedence : int + { + Invalid = -1, + Comma, + Assignment, + TernaryConditional, + LogicalOr, + LogicalAnd, + BitOr, + BitXor, + BitAnd, + EqualityComparison, + RelationalComparison, + BitShift, + Additive, + Multiplicative, + Prefix, + Postfix, + }; + + // TODO: implement two pass parsing for file reference and struct type recognition + + class Parser + { + public: + CompileOptions& options; + int anonymousCounter = 0; + + RefPtr outerScope; + RefPtr currentScope; + + TokenReader tokenReader; + DiagnosticSink * sink; + String fileName; + int genericDepth = 0; + + // Is the parser in a "recovering" state? + // During recovery we don't emit additional errors, until we find + // a token that we expected, when we exit recovery. + bool isRecovering = false; + + void FillPosition(SyntaxNode * node) + { + node->Position = tokenReader.PeekLoc(); + } + void PushScope(ContainerDecl* containerDecl) + { + RefPtr newScope = new Scope(); + newScope->containerDecl = containerDecl; + newScope->parent = currentScope; + + currentScope = newScope; + } + void PopScope() + { + currentScope = currentScope->parent; + } + Parser( + CompileOptions& options, + TokenSpan const& _tokens, + DiagnosticSink * sink, + String _fileName, + RefPtr const& outerScope) + : options(options) + , tokenReader(_tokens) + , sink(sink) + , fileName(_fileName) + , outerScope(outerScope) + {} + RefPtr Parse(); + + Token ReadToken(); + Token ReadToken(TokenType type); + Token ReadToken(const char * string); + bool LookAheadToken(TokenType type, int offset = 0); + bool LookAheadToken(const char * string, int offset = 0); + void parseSourceFile(ProgramSyntaxNode* program); + RefPtr ParseProgram(); + RefPtr ParseStruct(); + RefPtr ParseClass(); + RefPtr ParseStatement(); + RefPtr ParseBlockStatement(); + RefPtr ParseVarDeclrStatement(Modifiers modifiers); + RefPtr ParseIfStatement(); + RefPtr ParseForStatement(); + RefPtr ParseWhileStatement(); + RefPtr ParseDoWhileStatement(); + RefPtr ParseBreakStatement(); + RefPtr ParseContinueStatement(); + RefPtr ParseReturnStatement(); + RefPtr ParseExpressionStatement(); + RefPtr ParseExpression(Precedence level = Precedence::Comma); + + // Parse an expression that might be used in an initializer or argument context, so we should avoid operator-comma + inline RefPtr ParseInitExpr() { return ParseExpression(Precedence::Assignment); } + inline RefPtr ParseArgExpr() { return ParseExpression(Precedence::Assignment); } + + RefPtr ParseLeafExpression(); + RefPtr ParseParameter(); + RefPtr ParseType(); + TypeExp ParseTypeExp(); + + Parser & operator = (const Parser &) = delete; + }; + + // Forward Declarations + + static void ParseDeclBody( + Parser* parser, + ContainerDecl* containerDecl, + TokenType closingToken); + + static RefPtr ParseOptSemantics( + Parser* parser); + + static void ParseOptSemantics( + Parser* parser, + Decl* decl); + + static RefPtr ParseDecl( + Parser* parser, + ContainerDecl* containerDecl); + + static RefPtr ParseSingleDecl( + Parser* parser, + ContainerDecl* containerDecl); + + // + + static void Unexpected( + Parser* parser) + { + // Don't emit "unexpected token" errors if we are in recovering mode + if (!parser->isRecovering) + { + parser->sink->diagnose(parser->tokenReader.PeekLoc(), Diagnostics::unexpectedToken, + parser->tokenReader.PeekTokenType()); + + // Switch into recovery mode, to suppress additional errors + parser->isRecovering = true; + } + } + + static void Unexpected( + Parser* parser, + char const* expected) + { + // Don't emit "unexpected token" errors if we are in recovering mode + if (!parser->isRecovering) + { + parser->sink->diagnose(parser->tokenReader.PeekLoc(), Diagnostics::unexpectedTokenExpectedTokenName, + parser->tokenReader.PeekTokenType(), + expected); + + // Switch into recovery mode, to suppress additional errors + parser->isRecovering = true; + } + } + + static void Unexpected( + Parser* parser, + TokenType expected) + { + // Don't emit "unexpected token" errors if we are in recovering mode + if (!parser->isRecovering) + { + parser->sink->diagnose(parser->tokenReader.PeekLoc(), Diagnostics::unexpectedTokenExpectedTokenType, + parser->tokenReader.PeekTokenType(), + expected); + + // Switch into recovery mode, to suppress additional errors + parser->isRecovering = true; + } + } + + static TokenType SkipToMatchingToken(TokenReader* reader, TokenType tokenType); + + // Skip a singel balanced token, which is either a single token in + // the common case, or a matched pair of tokens for `()`, `[]`, and `{}` + static TokenType SkipBalancedToken( + TokenReader* reader) + { + TokenType tokenType = reader->AdvanceToken().Type; + switch (tokenType) + { + default: + break; + + case TokenType::LParent: tokenType = SkipToMatchingToken(reader, TokenType::RParent); break; + case TokenType::LBrace: tokenType = SkipToMatchingToken(reader, TokenType::RBrace); break; + case TokenType::LBracket: tokenType = SkipToMatchingToken(reader, TokenType::RBracket); break; + } + return tokenType; + } + + // Skip balanced + static TokenType SkipToMatchingToken( + TokenReader* reader, + TokenType tokenType) + { + for (;;) + { + if (reader->IsAtEnd()) return TokenType::EndOfFile; + if (reader->PeekTokenType() == tokenType) + { + reader->AdvanceToken(); + return tokenType; + } + SkipBalancedToken(reader); + } + } + + // Is the given token type one that is used to "close" a + // balanced construct. + static bool IsClosingToken(TokenType tokenType) + { + switch (tokenType) + { + case TokenType::EndOfFile: + case TokenType::RBracket: + case TokenType::RParent: + case TokenType::RBrace: + return true; + + default: + return false; + } + } + + + // Expect an identifier token with the given content, and consume it. + Token Parser::ReadToken(const char* expected) + { + if (tokenReader.PeekTokenType() == TokenType::Identifier + && tokenReader.PeekToken().Content == expected) + { + isRecovering = false; + return tokenReader.AdvanceToken(); + } + + if (!isRecovering) + { + Unexpected(this, expected); + return tokenReader.PeekToken(); + } + else + { + // Try to find a place to recover + for (;;) + { + // The token we expected? + // Then exit recovery mode and pretend like all is well. + if (tokenReader.PeekTokenType() == TokenType::Identifier + && tokenReader.PeekToken().Content == expected) + { + isRecovering = false; + return tokenReader.AdvanceToken(); + } + + + // Don't skip past any "closing" tokens. + if (IsClosingToken(tokenReader.PeekTokenType())) + { + return tokenReader.PeekToken(); + } + + // Skip balanced tokens and try again. + SkipBalancedToken(&tokenReader); + } + } + } + + Token Parser::ReadToken() + { + return tokenReader.AdvanceToken(); + } + + static bool TryRecover( + Parser* parser, + TokenType const* recoverBefore, + int recoverBeforeCount, + TokenType const* recoverAfter, + int recoverAfterCount) + { + if (!parser->isRecovering) + return true; + + // Determine if we are looking for a closing token at all... + bool lookingForClose = false; + for (int ii = 0; ii < recoverBeforeCount; ++ii) + { + if (IsClosingToken(recoverBefore[ii])) + lookingForClose = true; + } + for (int ii = 0; ii < recoverAfterCount; ++ii) + { + if (IsClosingToken(recoverAfter[ii])) + lookingForClose = true; + } + + TokenReader* tokenReader = &parser->tokenReader; + for (;;) + { + TokenType peek = tokenReader->PeekTokenType(); + + // Is the next token in our recover-before set? + // If so, then we have recovered successfully! + for (int ii = 0; ii < recoverBeforeCount; ++ii) + { + if (peek == recoverBefore[ii]) + { + parser->isRecovering = false; + return true; + } + } + + // If we are looking at a token in our recover-after set, + // then consume it and recover + for (int ii = 0; ii < recoverAfterCount; ++ii) + { + if (peek == recoverAfter[ii]) + { + tokenReader->AdvanceToken(); + parser->isRecovering = false; + return true; + } + } + + // Don't try to skip past end of file + if (peek == TokenType::EndOfFile) + return false; + + switch (peek) + { + // Don't skip past simple "closing" tokens, *unless* + // we are looking for a closing token + case TokenType::RParent: + case TokenType::RBracket: + if (!lookingForClose) + return false; + break; + + // never skip a `}`, to avoid spurious errors + case TokenType::RBrace: + return false; + } + + // Skip balanced tokens and try again. + TokenType skipped = SkipBalancedToken(tokenReader); + + // If we happened to find a matched pair of tokens, and + // the end of it was a token we were looking for, + // then recover here + for (int ii = 0; ii < recoverAfterCount; ++ii) + { + if (skipped == recoverAfter[ii]) + { + parser->isRecovering = false; + return true; + } + } + } + } + + static bool TryRecoverBefore( + Parser* parser, + TokenType before0) + { + TokenType recoverBefore[] = { before0 }; + return TryRecover(parser, recoverBefore, 1, nullptr, 0); + } + + // Default recovery strategy, to use inside `{}`-delimeted blocks. + static bool TryRecover( + Parser* parser) + { + TokenType recoverBefore[] = { TokenType::RBrace }; + TokenType recoverAfter[] = { TokenType::Semicolon }; + return TryRecover(parser, recoverBefore, 1, recoverAfter, 1); + } + + Token Parser::ReadToken(TokenType expected) + { + if (tokenReader.PeekTokenType() == expected) + { + isRecovering = false; + return tokenReader.AdvanceToken(); + } + + if (!isRecovering) + { + Unexpected(this, expected); + return tokenReader.PeekToken(); + } + else + { + // Try to find a place to recover + if (TryRecoverBefore(this, expected)) + { + isRecovering = false; + return tokenReader.AdvanceToken(); + } + + return tokenReader.PeekToken(); + } + } + + bool Parser::LookAheadToken(const char * string, int offset) + { + TokenReader r = tokenReader; + for (int ii = 0; ii < offset; ++ii) + r.AdvanceToken(); + + return r.PeekTokenType() == TokenType::Identifier + && r.PeekToken().Content == string; + } + + bool Parser::LookAheadToken(TokenType type, int offset) + { + TokenReader r = tokenReader; + for (int ii = 0; ii < offset; ++ii) + r.AdvanceToken(); + + return r.PeekTokenType() == type; + } + + // Consume a token and return true it if matches, otherwise false + bool AdvanceIf(Parser* parser, TokenType tokenType) + { + if (parser->LookAheadToken(tokenType)) + { + parser->ReadToken(); + return true; + } + return false; + } + + // Consume a token and return true it if matches, otherwise false + bool AdvanceIf(Parser* parser, char const* text) + { + if (parser->LookAheadToken(text)) + { + parser->ReadToken(); + return true; + } + return false; + } + + // Consume a token and return true if it matches, otherwise check + // for end-of-file and expect that token (potentially producing + // an error) and return true to maintain forward progress. + // Otherwise return false. + bool AdvanceIfMatch(Parser* parser, TokenType tokenType) + { + // If we've run into a syntax error, but haven't recovered inside + // the block, then try to recover here. + if (parser->isRecovering) + { + TryRecoverBefore(parser, tokenType); + } + if (AdvanceIf(parser, tokenType)) + return true; + if (parser->tokenReader.PeekTokenType() == TokenType::EndOfFile) + { + parser->ReadToken(tokenType); + return true; + } + return false; + } + + RefPtr Parser::Parse() + { + return ParseProgram(); + } + + RefPtr ParseTypeDef(Parser* parser) + { + // Consume the `typedef` keyword + parser->ReadToken("typedef"); + + // TODO(tfoley): parse an actual declarator + auto type = parser->ParseTypeExp(); + + auto nameToken = parser->ReadToken(TokenType::Identifier); + + RefPtr typeDefDecl = new TypeDefDecl(); + typeDefDecl->Name = nameToken; + typeDefDecl->Type = type; + + return typeDefDecl; + } + + // Add a modifier to a list of modifiers being built + static void AddModifier(RefPtr** ioModifierLink, RefPtr modifier) + { + RefPtr*& modifierLink = *ioModifierLink; + + while(*modifierLink) + modifierLink = &(*modifierLink)->next; + + *modifierLink = modifier; + modifierLink = &modifier->next; + } + + void addModifier( + RefPtr syntax, + RefPtr modifier) + { + auto modifierLink = &syntax->modifiers.first; + AddModifier(&modifierLink, modifier); + } + + // Parse HLSL-style `[name(arg, ...)]` style "attribute" modifiers + static void ParseSquareBracketAttributes(Parser* parser, RefPtr** ioModifierLink) + { + parser->ReadToken(TokenType::LBracket); + for(;;) + { + auto nameToken = parser->ReadToken(TokenType::Identifier); + RefPtr modifier = new HLSLUncheckedAttribute(); + modifier->nameToken = nameToken; + + if (AdvanceIf(parser, TokenType::LParent)) + { + // HLSL-style `[name(arg0, ...)]` attribute + + while (!AdvanceIfMatch(parser, TokenType::RParent)) + { + auto arg = parser->ParseArgExpr(); + if (arg) + { + modifier->args.Add(arg); + } + + if (AdvanceIfMatch(parser, TokenType::RParent)) + break; + + parser->ReadToken(TokenType::Comma); + } + } + AddModifier(ioModifierLink, modifier); + + + if (AdvanceIfMatch(parser, TokenType::RBracket)) + break; + + parser->ReadToken(TokenType::Comma); + } + } + + static Modifiers ParseModifiers(Parser* parser) + { + Modifiers modifiers; + RefPtr* modifierLink = &modifiers.first; + for (;;) + { + CodePosition loc = parser->tokenReader.PeekLoc(); + + if (0) {} + + #define CASE(KEYWORD, TYPE) \ + else if(AdvanceIf(parser, #KEYWORD)) do { \ + RefPtr modifier = new TYPE(); \ + modifier->Position = loc; \ + AddModifier(&modifierLink, modifier); \ + } while(0) + + CASE(in, InModifier); + CASE(input, InputModifier); + CASE(out, OutModifier); + CASE(inout, InOutModifier); + CASE(const, ConstModifier); + CASE(instance, InstanceModifier); + CASE(__builtin, BuiltinModifier); + + CASE(inline, InlineModifier); + CASE(public, PublicModifier); + CASE(require, RequireModifier); + CASE(param, ParamModifier); + CASE(extern, ExternModifier); + + CASE(row_major, HLSLRowMajorLayoutModifier); + CASE(column_major, HLSLColumnMajorLayoutModifier); + + CASE(nointerpolation, HLSLNoInterpolationModifier); + CASE(linear, HLSLLinearModifier); + CASE(sample, HLSLSampleModifier); + CASE(centroid, HLSLCentroidModifier); + CASE(precise, HLSLPreciseModifier); + CASE(shared, HLSLEffectSharedModifier); + CASE(groupshared, HLSLGroupSharedModifier); + CASE(static, HLSLStaticModifier); + CASE(uniform, HLSLUniformModifier); + CASE(volatile, HLSLVolatileModifier); + + // Modifiers for geometry shader input + CASE(point, HLSLPointModifier); + CASE(line, HLSLLineModifier); + CASE(triangle, HLSLTriangleModifier); + CASE(lineadj, HLSLLineAdjModifier); + CASE(triangleadj, HLSLTriangleAdjModifier); + + // Modifiers for unary operator declarations + CASE(__prefix, PrefixModifier); + CASE(__postfix, PostfixModifier); + + #undef CASE + + else if (AdvanceIf(parser, "__intrinsic")) + { + auto modifier = new IntrinsicModifier(); + modifier->Position = loc; + + if (AdvanceIf(parser, TokenType::LParent)) + { + if (parser->LookAheadToken(TokenType::IntLiterial)) + { + modifier->op = (IntrinsicOp)StringToInt(parser->ReadToken().Content); + } + else + { + modifier->opToken = parser->ReadToken(TokenType::Identifier); + + modifier->op = findIntrinsicOp(modifier->opToken.Content.Buffer()); + + if (modifier->op == IntrinsicOp::Unknown) + { + parser->sink->diagnose(loc, Diagnostics::unimplemented, "unknown intrinsic op"); + } + } + + parser->ReadToken(TokenType::RParent); + } + + AddModifier(&modifierLink, modifier); + } + + + else if (AdvanceIf(parser, "layout")) + { + parser->ReadToken(TokenType::LParent); + while (!AdvanceIfMatch(parser, TokenType::RParent)) + { + auto nameToken = parser->ReadToken(TokenType::Identifier); + + RefPtr modifier; + + // TODO: better handling of this choise (e.g., lookup in scope) + if(0) {} + #define CASE(KEYWORD, CLASS) \ + else if(nameToken.Content == #KEYWORD) modifier = new CLASS() + + CASE(constant_id, GLSLConstantIDLayoutModifier); + CASE(binding, GLSLBindingLayoutModifier); + CASE(set, GLSLSetLayoutModifier); + CASE(location, GLSLLocationLayoutModifier); + + #undef CASE + else + { + modifier = new GLSLUnparsedLayoutModifier(); + } + + modifier->nameToken = nameToken; + + if(AdvanceIf(parser, TokenType::OpAssign)) + { + modifier->valToken = parser->ReadToken(TokenType::IntLiterial); + } + + AddModifier(&modifierLink, modifier); + + if (AdvanceIf(parser, TokenType::RParent)) + break; + parser->ReadToken(TokenType::Comma); + } + } + else if (parser->tokenReader.PeekTokenType() == TokenType::LBracket) + { + ParseSquareBracketAttributes(parser, &modifierLink); + } + else if (AdvanceIf(parser,"__builtin_type")) + { + RefPtr modifier = new BuiltinTypeModifier(); + parser->ReadToken(TokenType::LParent); + modifier->tag = BaseType(StringToInt(parser->ReadToken(TokenType::IntLiterial).Content)); + parser->ReadToken(TokenType::RParent); + + AddModifier(&modifierLink, modifier); + } + else if (AdvanceIf(parser,"__magic_type")) + { + RefPtr modifier = new MagicTypeModifier(); + parser->ReadToken(TokenType::LParent); + modifier->name = parser->ReadToken(TokenType::Identifier).Content; + if (AdvanceIf(parser, TokenType::Comma)) + { + modifier->tag = uint32_t(StringToInt(parser->ReadToken(TokenType::IntLiterial).Content)); + } + parser->ReadToken(TokenType::RParent); + + AddModifier(&modifierLink, modifier); + } + else + { + // Fallback case if none of the above explicit cases matched. + + // If we are looking at an identifier, then it may map to a + // modifier declaration visible in the current scope + if( parser->LookAheadToken(TokenType::Identifier) ) + { + LookupResult lookupResult = LookUp( + parser->tokenReader.PeekToken().Content, + parser->currentScope); + + if( lookupResult.isValid() && !lookupResult.isOverloaded() ) + { + auto& item = lookupResult.item; + auto decl = item.declRef.GetDecl(); + + if( auto modifierDecl = dynamic_cast(decl) ) + { + // We found a declaration for some modifier syntax, + // so lets create an instance of the type it names + // here. + + auto syntax = createInstanceOfSyntaxClassByName(modifierDecl->classNameToken.Content); + auto modifier = dynamic_cast(syntax); + + if( modifier ) + { + modifier->Position = parser->tokenReader.PeekLoc(); + modifier->nameToken = parser->ReadToken(TokenType::Identifier); + + AddModifier(&modifierLink, modifier); + continue; + } + else + { + parser->ReadToken(TokenType::Identifier); + assert(!"unexpected"); + } + } + } + } + + // Done with modifier list + return modifiers; + } + } + } + + static RefPtr ParseUsing( + Parser* parser) + { + parser->ReadToken("using"); + if (parser->tokenReader.PeekTokenType() == TokenType::StringLiterial) + { + auto usingDecl = new UsingFileDecl(); + usingDecl->fileName = parser->ReadToken(TokenType::StringLiterial); + parser->ReadToken(TokenType::Semicolon); + return usingDecl; + } + else + { + unexpected(); + } + } + + static Token ParseDeclName( + Parser* parser) + { + Token name; + if (AdvanceIf(parser, "operator")) + { + name = parser->ReadToken(); + switch (name.Type) + { + case TokenType::OpAdd: case TokenType::OpSub: case TokenType::OpMul: case TokenType::OpDiv: + case TokenType::OpMod: case TokenType::OpNot: case TokenType::OpBitNot: case TokenType::OpLsh: case TokenType::OpRsh: + case TokenType::OpEql: case TokenType::OpNeq: case TokenType::OpGreater: case TokenType::OpLess: case TokenType::OpGeq: + case TokenType::OpLeq: case TokenType::OpAnd: case TokenType::OpOr: case TokenType::OpBitXor: case TokenType::OpBitAnd: + case TokenType::OpBitOr: case TokenType::OpInc: case TokenType::OpDec: + case TokenType::OpAddAssign: + case TokenType::OpSubAssign: + case TokenType::OpMulAssign: + case TokenType::OpDivAssign: + case TokenType::OpModAssign: + case TokenType::OpShlAssign: + case TokenType::OpShrAssign: + case TokenType::OpOrAssign: + case TokenType::OpAndAssign: + case TokenType::OpXorAssign: + + // Note(tfoley): A bit of a hack: + case TokenType::Comma: + case TokenType::OpAssign: + break; + + // Note(tfoley): Even more of a hack! + case TokenType::QuestionMark: + if (AdvanceIf(parser, TokenType::Colon)) + { + name.Content = name.Content + ":"; + break; + } + + default: + parser->sink->diagnose(name.Position, Diagnostics::invalidOperator, name.Content); + break; + } + } + else + { + name = parser->ReadToken(TokenType::Identifier); + } + return name; + } + + // A "declarator" as used in C-style languages + struct Declarator : RefObject + { + // Different cases of declarator appear as "flavors" here + enum class Flavor + { + Name, + Pointer, + Array, + }; + Flavor flavor; + }; + + // The most common case of declarator uses a simple name + struct NameDeclarator : Declarator + { + Token nameToken; + }; + + // A declarator that declares a pointer type + struct PointerDeclarator : Declarator + { + // location of the `*` token + CodePosition starLoc; + + RefPtr inner; + }; + + // A declarator that declares an array type + struct ArrayDeclarator : Declarator + { + RefPtr inner; + + // location of the `[` token + CodePosition openBracketLoc; + + // The expression that yields the element count, or NULL + RefPtr elementCountExpr; + }; + + // "Unwrapped" information about a declarator + struct DeclaratorInfo + { + RefPtr typeSpec; + Token nameToken; + RefPtr semantics; + RefPtr initializer; + }; + + // Add a member declaration to its container, and ensure that its + // parent link is set up correctly. + static void AddMember(RefPtr container, RefPtr member) + { + if (container) + { + member->ParentDecl = container.Ptr(); + container->Members.Add(member); + + container->memberDictionaryIsValid = false; + } + } + + static void AddMember(RefPtr scope, RefPtr member) + { + if (scope) + { + AddMember(scope->containerDecl, member); + } + } + + static void parseParameterList( + Parser* parser, + RefPtr decl) + { + parser->ReadToken(TokenType::LParent); + + // Allow a declaration to use the keyword `void` for a parameter list, + // since that was required in ancient C, and continues to be supported + // in a bunc hof its derivatives even if it is a Bad Design Choice + // + // TODO: conditionalize this so we don't keep this around for "pure" + // Slang code + if( parser->LookAheadToken("void") && parser->LookAheadToken(TokenType::RParent, 1) ) + { + parser->ReadToken("void"); + parser->ReadToken(TokenType::RParent); + return; + } + + while (!AdvanceIfMatch(parser, TokenType::RParent)) + { + AddMember(decl, parser->ParseParameter()); + if (AdvanceIf(parser, TokenType::RParent)) + break; + parser->ReadToken(TokenType::Comma); + } + } + + static void ParseFuncDeclHeader( + Parser* parser, + DeclaratorInfo const& declaratorInfo, + RefPtr decl) + { + parser->PushScope(decl.Ptr()); + + parser->FillPosition(decl.Ptr()); + decl->Position = declaratorInfo.nameToken.Position; + + decl->Name = declaratorInfo.nameToken; + decl->ReturnType = TypeExp(declaratorInfo.typeSpec); + parseParameterList(parser, decl); + ParseOptSemantics(parser, decl.Ptr()); + } + + static RefPtr ParseFuncDecl( + Parser* parser, + ContainerDecl* /*containerDecl*/, + DeclaratorInfo const& declaratorInfo) + { + RefPtr decl = new FunctionSyntaxNode(); + ParseFuncDeclHeader(parser, declaratorInfo, decl); + + if (AdvanceIf(parser, TokenType::Semicolon)) + { + // empty body + } + else + { + decl->Body = parser->ParseBlockStatement(); + } + + parser->PopScope(); + return decl; + } + + static RefPtr CreateVarDeclForContext( + ContainerDecl* containerDecl ) + { + if (dynamic_cast(containerDecl) || dynamic_cast(containerDecl)) + { + return new StructField(); + } + else if (dynamic_cast(containerDecl)) + { + return new ParameterSyntaxNode(); + } + else + { + return new Variable(); + } + } + + // Add modifiers to the end of the modifier list for a declaration + void AddModifiers(Decl* decl, RefPtr modifiers) + { + if (!modifiers) + return; + + RefPtr* link = &decl->modifiers.first; + while (*link) + { + link = &(*link)->next; + } + *link = modifiers; + } + + + static String GenerateName(Parser* parser, String const& base) + { + // TODO: somehow mangle the name to avoid clashes + return base; + } + + static String GenerateName(Parser* parser) + { + return GenerateName(parser, "_anonymous_" + String(parser->anonymousCounter++)); + } + + + // Set up a variable declaration based on what we saw in its declarator... + static void CompleteVarDecl( + Parser* parser, + RefPtr decl, + DeclaratorInfo const& declaratorInfo) + { + parser->FillPosition(decl.Ptr()); + + if( declaratorInfo.nameToken.Type == TokenType::Unknown ) + { + // HACK(tfoley): we always give a name, even if the declarator didn't include one... :( + decl->Name.Content = GenerateName(parser); + } + else + { + decl->Position = declaratorInfo.nameToken.Position; + decl->Name = declaratorInfo.nameToken; + } + decl->Type = TypeExp(declaratorInfo.typeSpec); + + AddModifiers(decl.Ptr(), declaratorInfo.semantics); + + decl->Expr = declaratorInfo.initializer; + } + + static RefPtr ParseDeclarator(Parser* parser); + + static RefPtr ParseDirectAbstractDeclarator( + Parser* parser) + { + RefPtr declarator; + switch( parser->tokenReader.PeekTokenType() ) + { + case TokenType::Identifier: + { + auto nameDeclarator = new NameDeclarator(); + nameDeclarator->flavor = Declarator::Flavor::Name; + nameDeclarator->nameToken = ParseDeclName(parser); + declarator = nameDeclarator; + } + break; + + case TokenType::LParent: + { + // Note(tfoley): This is a point where disambiguation is required. + // We could be looking at an abstract declarator for a function-type + // parameter: + // + // void F( int(int) ); + // + // Or we could be looking at the use of parenthesese in an ordinary + // declarator: + // + // void (*f)(int); + // + // The difference really doesn't matter right now, but we err in + // the direction of assuming the second case. + parser->ReadToken(TokenType::LParent); + declarator = ParseDeclarator(parser); + parser->ReadToken(TokenType::RParent); + } + break; + + default: + // an empty declarator is allowed + return nullptr; + } + + // postifx additions + for( ;;) + { + switch( parser->tokenReader.PeekTokenType() ) + { + case TokenType::LBracket: + { + auto arrayDeclarator = new ArrayDeclarator(); + arrayDeclarator->openBracketLoc = parser->tokenReader.PeekLoc(); + arrayDeclarator->flavor = Declarator::Flavor::Array; + arrayDeclarator->inner = declarator; + + parser->ReadToken(TokenType::LBracket); + if( parser->tokenReader.PeekTokenType() != TokenType::RBracket ) + { + arrayDeclarator->elementCountExpr = parser->ParseExpression(); + } + parser->ReadToken(TokenType::RBracket); + + declarator = arrayDeclarator; + continue; + } + + case TokenType::LParent: + break; + + default: + break; + } + + break; + } + + return declarator; + } + + // Parse a declarator (or at least as much of one as we support) + static RefPtr ParseDeclarator( + Parser* parser) + { + if( parser->tokenReader.PeekTokenType() == TokenType::OpMul ) + { + auto ptrDeclarator = new PointerDeclarator(); + ptrDeclarator->starLoc = parser->tokenReader.PeekLoc(); + ptrDeclarator->flavor = Declarator::Flavor::Pointer; + + parser->ReadToken(TokenType::OpMul); + + // TODO(tfoley): allow qualifiers like `const` here? + + ptrDeclarator->inner = ParseDeclarator(parser); + return ptrDeclarator; + } + else + { + return ParseDirectAbstractDeclarator(parser); + } + } + + // A declarator plus optional semantics and initializer + struct InitDeclarator + { + RefPtr declarator; + RefPtr semantics; + RefPtr initializer; + }; + + // Parse a declarator plus optional semantics + static InitDeclarator ParseSemanticDeclarator( + Parser* parser) + { + InitDeclarator result; + result.declarator = ParseDeclarator(parser); + result.semantics = ParseOptSemantics(parser); + return result; + } + + // Parse a declarator plus optional semantics and initializer + static InitDeclarator ParseInitDeclarator( + Parser* parser) + { + InitDeclarator result = ParseSemanticDeclarator(parser); + if (AdvanceIf(parser, TokenType::OpAssign)) + { + result.initializer = parser->ParseInitExpr(); + } + return result; + } + + static void UnwrapDeclarator( + RefPtr declarator, + DeclaratorInfo* ioInfo) + { + while( declarator ) + { + switch(declarator->flavor) + { + case Declarator::Flavor::Name: + { + auto nameDeclarator = (NameDeclarator*) declarator.Ptr(); + ioInfo->nameToken = nameDeclarator->nameToken; + return; + } + break; + + case Declarator::Flavor::Pointer: + { + auto ptrDeclarator = (PointerDeclarator*) declarator.Ptr(); + + // TODO(tfoley): we don't support pointers for now + // ioInfo->typeSpec = new PointerTypeExpr(ioInfo->typeSpec); + + declarator = ptrDeclarator->inner; + } + break; + + case Declarator::Flavor::Array: + { + // TODO(tfoley): we don't support pointers for now + auto arrayDeclarator = (ArrayDeclarator*) declarator.Ptr(); + + auto arrayTypeExpr = new IndexExpressionSyntaxNode(); + arrayTypeExpr->Position = arrayDeclarator->openBracketLoc; + arrayTypeExpr->BaseExpression = ioInfo->typeSpec; + arrayTypeExpr->IndexExpression = arrayDeclarator->elementCountExpr; + ioInfo->typeSpec = arrayTypeExpr; + + declarator = arrayDeclarator->inner; + } + break; + + default: + SLANG_UNREACHABLE("all cases handled"); + break; + } + } + } + + static void UnwrapDeclarator( + InitDeclarator const& initDeclarator, + DeclaratorInfo* ioInfo) + { + UnwrapDeclarator(initDeclarator.declarator, ioInfo); + ioInfo->semantics = initDeclarator.semantics; + ioInfo->initializer = initDeclarator.initializer; + } + + // Either a single declaration, or a group of them + struct DeclGroupBuilder + { + CodePosition startPosition; + RefPtr decl; + RefPtr group; + + // Add a new declaration to the potential group + void addDecl( + RefPtr newDecl) + { + assert(newDecl); + + if( decl ) + { + group = new DeclGroup(); + group->Position = startPosition; + group->decls.Add(decl); + decl = nullptr; + } + + if( group ) + { + group->decls.Add(newDecl); + } + else + { + decl = newDecl; + } + } + + RefPtr getResult() + { + if(group) return group; + return decl; + } + }; + + // Pares an argument to an application of a generic + RefPtr ParseGenericArg(Parser* parser) + { + return parser->ParseArgExpr(); + } + + // Create a type expression that will refer to the given declaration + static RefPtr + createDeclRefType(Parser* parser, RefPtr decl) + { + // For now we just construct an expression that + // will look up the given declaration by name. + // + // TODO: do this better, e.g. by filling in the `declRef` field directly + + auto expr = new VarExpressionSyntaxNode(); + expr->scope = parser->currentScope.Ptr(); + expr->Position = decl->getNameToken().Position; + expr->Variable = decl->getName(); + return expr; + } + + // Representation for a parsed type specifier, which might + // include a declaration (e.g., of a `struct` type) + struct TypeSpec + { + // If the type-spec declared something, then put it here + RefPtr decl; + + // Put the resulting expression (which should evaluate to a type) here + RefPtr expr; + }; + + static TypeSpec + parseTypeSpec(Parser* parser) + { + TypeSpec typeSpec; + + // We may see a `struct` type specified here, and need to act accordingly + // + // TODO(tfoley): Handle the case where the user is just using `struct` + // as a way to name an existing struct "tag" (e.g., `struct Foo foo;`) + // + if( parser->LookAheadToken("struct") ) + { + auto decl = parser->ParseStruct(); + typeSpec.decl = decl; + typeSpec.expr = createDeclRefType(parser, decl); + return typeSpec; + } + else if( parser->LookAheadToken("class") ) + { + auto decl = parser->ParseClass(); + typeSpec.decl = decl; + typeSpec.expr = createDeclRefType(parser, decl); + return typeSpec; + } + + Token typeName = parser->ReadToken(TokenType::Identifier); + + auto basicType = new VarExpressionSyntaxNode(); + basicType->scope = parser->currentScope.Ptr(); + basicType->Position = typeName.Position; + basicType->Variable = typeName.Content; + + RefPtr typeExpr = basicType; + + if (parser->LookAheadToken(TokenType::OpLess)) + { + RefPtr gtype = new GenericAppExpr(); + parser->FillPosition(gtype.Ptr()); // set up scope for lookup + gtype->Position = typeName.Position; + gtype->FunctionExpr = typeExpr; + parser->ReadToken(TokenType::OpLess); + parser->genericDepth++; + // For now assume all generics have at least one argument + gtype->Arguments.Add(ParseGenericArg(parser)); + while (AdvanceIf(parser, TokenType::Comma)) + { + gtype->Arguments.Add(ParseGenericArg(parser)); + } + parser->genericDepth--; + parser->ReadToken(TokenType::OpGreater); + typeExpr = gtype; + } + + typeSpec.expr = typeExpr; + return typeSpec; + } + + + static RefPtr ParseDeclaratorDecl( + Parser* parser, + ContainerDecl* containerDecl) + { + CodePosition startPosition = parser->tokenReader.PeekLoc(); + + auto typeSpec = parseTypeSpec(parser); + + // We may need to build up multiple declarations in a group, + // but the common case will be when we have just a single + // declaration + DeclGroupBuilder declGroupBuilder; + declGroupBuilder.startPosition = startPosition; + + // The type specifier may include a declaration. E.g., + // it might declare a `struct` type. + if(typeSpec.decl) + declGroupBuilder.addDecl(typeSpec.decl); + + if( AdvanceIf(parser, TokenType::Semicolon) ) + { + // No actual variable is being declared here, but + // that might not be an error. + + auto result = declGroupBuilder.getResult(); + if( !result ) + { + parser->sink->diagnose(startPosition, Diagnostics::declarationDidntDeclareAnything); + } + return result; + } + + + InitDeclarator initDeclarator = ParseInitDeclarator(parser); + + DeclaratorInfo declaratorInfo; + declaratorInfo.typeSpec = typeSpec.expr; + + + // Rather than parse function declarators properly for now, + // we'll just do a quick disambiguation here. This won't + // matter unless we actually decide to support function-type parameters, + // using C syntax. + // + if( parser->tokenReader.PeekTokenType() == TokenType::LParent + + // Only parse as a function if we didn't already see mutually-exclusive + // constructs when parsing the declarator. + && !initDeclarator.initializer + && !initDeclarator.semantics) + { + // Looks like a function, so parse it like one. + UnwrapDeclarator(initDeclarator, &declaratorInfo); + return ParseFuncDecl(parser, containerDecl, declaratorInfo); + } + + // Otherwise we are looking at a variable declaration, which could be one in a sequence... + + if( AdvanceIf(parser, TokenType::Semicolon) ) + { + // easy case: we only had a single declaration! + UnwrapDeclarator(initDeclarator, &declaratorInfo); + RefPtr firstDecl = CreateVarDeclForContext(containerDecl); + CompleteVarDecl(parser, firstDecl, declaratorInfo); + + declGroupBuilder.addDecl(firstDecl); + return declGroupBuilder.getResult(); + + return firstDecl; + } + + // Otherwise we have multiple declarations in a sequence, and these + // declarations need to somehow share both the type spec and modifiers. + // + // If there are any errors in the type specifier, we only want to hear + // about it once, so we need to share structure rather than just + // clone syntax. + + auto sharedTypeSpec = new SharedTypeExpr(); + sharedTypeSpec->Position = typeSpec.expr->Position; + sharedTypeSpec->base = TypeExp(typeSpec.expr); + + for(;;) + { + declaratorInfo.typeSpec = sharedTypeSpec; + UnwrapDeclarator(initDeclarator, &declaratorInfo); + + RefPtr varDecl = CreateVarDeclForContext(containerDecl); + CompleteVarDecl(parser, varDecl, declaratorInfo); + + declGroupBuilder.addDecl(varDecl); + + // end of the sequence? + if(AdvanceIf(parser, TokenType::Semicolon)) + return declGroupBuilder.getResult(); + + // ad-hoc recovery, to avoid infinite loops + if( parser->isRecovering ) + { + parser->ReadToken(TokenType::Semicolon); + return declGroupBuilder.getResult(); + } + + // Let's default to assuming that a missing `,` + // indicates the end of a declaration, + // where a `;` would be expected, and not + // a continuation of this declaration, where + // a `,` would be expected (this is tailoring + // the diagnostic message a bit). + // + // TODO: a more advanced heuristic here might + // look at whether the next token is on the + // same line, to predict whether `,` or `;` + // would be more likely... + + if (!AdvanceIf(parser, TokenType::Comma)) + { + parser->ReadToken(TokenType::Semicolon); + return declGroupBuilder.getResult(); + } + + // expect another variable declaration... + initDeclarator = ParseInitDeclarator(parser); + } + } + + // + // layout-semantic ::= (register | packoffset) '(' register-name component-mask? ')' + // register-name ::= identifier + // component-mask ::= '.' identifier + // + static void ParseHLSLLayoutSemantic( + Parser* parser, + HLSLLayoutSemantic* semantic) + { + semantic->name = parser->ReadToken(TokenType::Identifier); + + parser->ReadToken(TokenType::LParent); + semantic->registerName = parser->ReadToken(TokenType::Identifier); + if (AdvanceIf(parser, TokenType::Dot)) + { + semantic->componentMask = parser->ReadToken(TokenType::Identifier); + } + parser->ReadToken(TokenType::RParent); + } + + // + // semantic ::= identifier ( '(' args ')' )? + // + static RefPtr ParseSemantic( + Parser* parser) + { + if (parser->LookAheadToken("register")) + { + RefPtr semantic = new HLSLRegisterSemantic(); + ParseHLSLLayoutSemantic(parser, semantic.Ptr()); + return semantic; + } + else if (parser->LookAheadToken("packoffset")) + { + RefPtr semantic = new HLSLPackOffsetSemantic(); + ParseHLSLLayoutSemantic(parser, semantic.Ptr()); + return semantic; + } + else + { + RefPtr semantic = new HLSLSimpleSemantic(); + semantic->name = parser->ReadToken(TokenType::Identifier); + return semantic; + } + } + + // + // opt-semantics ::= (':' semantic)* + // + static RefPtr ParseOptSemantics( + Parser* parser) + { + if (!AdvanceIf(parser, TokenType::Colon)) + return nullptr; + + RefPtr result; + RefPtr* link = &result; + assert(!*link); + + for (;;) + { + RefPtr semantic = ParseSemantic(parser); + if (semantic) + { + *link = semantic; + link = &semantic->next; + } + + switch (parser->tokenReader.PeekTokenType()) + { + case TokenType::LBrace: + case TokenType::Semicolon: + case TokenType::Comma: + case TokenType::RParent: + case TokenType::EndOfFile: + return result; + + default: + break; + } + + parser->ReadToken(TokenType::Colon); + } + + } + + + static void ParseOptSemantics( + Parser* parser, + Decl* decl) + { + AddModifiers(decl, ParseOptSemantics(parser)); + } + + static RefPtr ParseHLSLBufferDecl( + Parser* parser) + { + // An HLSL declaration of a constant buffer like this: + // + // cbuffer Foo : register(b0) { int a; float b; }; + // + // is treated as syntax sugar for a type declaration + // and then a global variable declaration using that type: + // + // struct $anonymous { int a; float b; }; + // ConstantBuffer<$anonymous> Foo; + // + // where `$anonymous` is a fresh name, and the variable + // declaration is made to be "transparent" so that lookup + // will see through it to the members inside. + + // We first look at the declaration keywrod to determine + // the type of buffer to declare: + String bufferWrapperTypeName; + CodePosition bufferWrapperTypeNamePos = parser->tokenReader.PeekLoc(); + if (AdvanceIf(parser, "cbuffer")) + { + bufferWrapperTypeName = "ConstantBuffer"; + } + else if (AdvanceIf(parser, "tbuffer")) + { + bufferWrapperTypeName = "TextureBuffer"; + } + else + { + Unexpected(parser); + } + + // We are going to represent each buffer as a pair of declarations. + // The first is a type declaration that holds all the members, while + // the second is a variable declaration that uses the buffer type. + RefPtr bufferDataTypeDecl = new StructSyntaxNode(); + RefPtr bufferVarDecl = new Variable(); + + // Both declarations will have a location that points to the name + parser->FillPosition(bufferDataTypeDecl.Ptr()); + parser->FillPosition(bufferVarDecl.Ptr()); + + auto reflectionNameToken = parser->ReadToken(TokenType::Identifier); + + // Attach the reflection name to the block so we can use it + auto reflectionNameModifier = new ParameterBlockReflectionName(); + reflectionNameModifier->nameToken = reflectionNameToken; + addModifier(bufferVarDecl, reflectionNameModifier); + + // Both the buffer variable and its type need to have names generated + bufferVarDecl->Name.Content = GenerateName(parser, "SLANG_constantBuffer_" + reflectionNameToken.Content); + bufferDataTypeDecl->Name.Content = GenerateName(parser, "SLANG_ConstantBuffer_" + reflectionNameToken.Content); + + addModifier(bufferDataTypeDecl, new ImplicitParameterBlockElementTypeModifier()); + addModifier(bufferVarDecl, new ImplicitParameterBlockVariableModifier()); + + // TODO(tfoley): We end up constructing unchecked syntax here that + // is expected to type check into the right form, but it might be + // cleaner to have a more explicit desugaring pass where we parse + // these constructs directly into the AST and *then* desugar them. + + // Construct a type expression to reference the buffer data type + auto bufferDataTypeExpr = new VarExpressionSyntaxNode(); + bufferDataTypeExpr->Position = bufferDataTypeDecl->Position; + bufferDataTypeExpr->Variable = bufferDataTypeDecl->Name.Content; + bufferDataTypeExpr->scope = parser->currentScope.Ptr(); + + // Construct a type exrpession to reference the type constructor + auto bufferWrapperTypeExpr = new VarExpressionSyntaxNode(); + bufferWrapperTypeExpr->Position = bufferWrapperTypeNamePos; + bufferWrapperTypeExpr->Variable = bufferWrapperTypeName; + + // Always need to look this up in the outer scope, + // so that it won't collide with, e.g., a local variable called `ConstantBuffer` + bufferWrapperTypeExpr->scope = parser->outerScope; + + // Construct a type expression that represents the type for the variable, + // which is the wrapper type applied to the data type + auto bufferVarTypeExpr = new GenericAppExpr(); + bufferVarTypeExpr->Position = bufferVarDecl->Position; + bufferVarTypeExpr->FunctionExpr = bufferWrapperTypeExpr; + bufferVarTypeExpr->Arguments.Add(bufferDataTypeExpr); + + bufferVarDecl->Type.exp = bufferVarTypeExpr; + + // Any semantics applied to the bufer declaration are taken as applying + // to the variable instead. + ParseOptSemantics(parser, bufferVarDecl.Ptr()); + + // The declarations in the body belong to the data type. + parser->ReadToken(TokenType::LBrace); + ParseDeclBody(parser, bufferDataTypeDecl.Ptr(), TokenType::RBrace); + + // All HLSL buffer declarations are "transparent" in that their + // members are implicitly made visible in the parent scope. + // We achieve this by applying the transparent modifier to the variable. + auto transparentModifier = new TransparentModifier(); + transparentModifier->next = bufferVarDecl->modifiers.first; + bufferVarDecl->modifiers.first = transparentModifier; + + // Because we are constructing two declarations, we have a thorny + // issue that were are only supposed to return one. + // For now we handle this by adding the type declaration to + // the current scope manually, and then returning the variable + // declaration. + // + // Note: this means that any modifiers that have already been parsed + // will get attached to the variable declaration, not the type. + // There might be cases where we need to shuffle things around. + + AddMember(parser->currentScope, bufferDataTypeDecl); + + return bufferVarDecl; + } + + static void removeModifier( + Modifiers& modifiers, + RefPtr modifier) + { + RefPtr* link = &modifiers.first; + while (*link) + { + if (*link == modifier) + { + *link = (*link)->next; + return; + } + + link = &(*link)->next; + } + } + + static RefPtr parseGLSLBlockDecl( + Parser* parser, + Modifiers& modifiers) + { + // An GLSL block like this: + // + // uniform Foo { int a; float b; } foo; + // + // is treated as syntax sugar for a type declaration + // and then a global variable declaration using that type: + // + // struct $anonymous { int a; float b; }; + // Block<$anonymous> foo; + // + // where `$anonymous` is a fresh name. + // + // If a "local name" like `foo` is not given, then + // we make the declaration "transparent" so that lookup + // will see through it to the members inside. + + + CodePosition pos = parser->tokenReader.PeekLoc(); + + // The initial name before the `{` is only supposed + // to be made visible to reflection + auto reflectionNameToken = parser->ReadToken(TokenType::Identifier); + + // Look at the qualifiers present on the block to decide what kind + // of block we are looking at. Also *remove* those qualifiers so + // that they don't interfere with downstream work. + String blockWrapperTypeName; + if( auto uniformMod = modifiers.findModifier() ) + { + removeModifier(modifiers, uniformMod); + blockWrapperTypeName = "ConstantBuffer"; + } + else if( auto inMod = modifiers.findModifier() ) + { + removeModifier(modifiers, inMod); + blockWrapperTypeName = "__GLSLInputParameterBlock"; + } + else if( auto outMod = modifiers.findModifier() ) + { + removeModifier(modifiers, outMod); + blockWrapperTypeName = "__GLSLOutputParameterBlock"; + } + else if( auto bufferMod = modifiers.findModifier() ) + { + removeModifier(modifiers, bufferMod); + blockWrapperTypeName = "__GLSLShaderStorageBuffer"; + } + else + { + // Unknown case: just map to a constant buffer and hope for the best + blockWrapperTypeName = "ConstantBuffer"; + } + + // We are going to represent each buffer as a pair of declarations. + // The first is a type declaration that holds all the members, while + // the second is a variable declaration that uses the buffer type. + RefPtr blockDataTypeDecl = new StructSyntaxNode(); + RefPtr blockVarDecl = new Variable(); + + addModifier(blockDataTypeDecl, new ImplicitParameterBlockElementTypeModifier()); + addModifier(blockVarDecl, new ImplicitParameterBlockVariableModifier()); + + // Attach the reflection name to the block so we can use it + auto reflectionNameModifier = new ParameterBlockReflectionName(); + reflectionNameModifier->nameToken = reflectionNameToken; + addModifier(blockVarDecl, reflectionNameModifier); + + // Both declarations will have a location that points to the name + parser->FillPosition(blockDataTypeDecl.Ptr()); + parser->FillPosition(blockVarDecl.Ptr()); + + // Generate a unique name for the data type + blockDataTypeDecl->Name.Content = GenerateName(parser, "SLANG_ParameterBlock_" + reflectionNameToken.Content); + + // TODO(tfoley): We end up constructing unchecked syntax here that + // is expected to type check into the right form, but it might be + // cleaner to have a more explicit desugaring pass where we parse + // these constructs directly into the AST and *then* desugar them. + + // Construct a type expression to reference the buffer data type + auto blockDataTypeExpr = new VarExpressionSyntaxNode(); + blockDataTypeExpr->Position = blockDataTypeDecl->Position; + blockDataTypeExpr->Variable = blockDataTypeDecl->Name.Content; + blockDataTypeExpr->scope = parser->currentScope.Ptr(); + + // Construct a type exrpession to reference the type constructor + auto blockWrapperTypeExpr = new VarExpressionSyntaxNode(); + blockWrapperTypeExpr->Position = pos; + blockWrapperTypeExpr->Variable = blockWrapperTypeName; + // Always need to look this up in the outer scope, + // so that it won't collide with, e.g., a local variable called `ConstantBuffer` + blockWrapperTypeExpr->scope = parser->outerScope; + + // Construct a type expression that represents the type for the variable, + // which is the wrapper type applied to the data type + auto blockVarTypeExpr = new GenericAppExpr(); + blockVarTypeExpr->Position = blockVarDecl->Position; + blockVarTypeExpr->FunctionExpr = blockWrapperTypeExpr; + blockVarTypeExpr->Arguments.Add(blockDataTypeExpr); + + blockVarDecl->Type.exp = blockVarTypeExpr; + + // The declarations in the body belong to the data type. + parser->ReadToken(TokenType::LBrace); + ParseDeclBody(parser, blockDataTypeDecl.Ptr(), TokenType::RBrace); + + if( parser->LookAheadToken(TokenType::Identifier) ) + { + // The user gave an explicit name to the block, + // so we need to use that as our variable name + blockVarDecl->Name = parser->ReadToken(TokenType::Identifier); + + // TODO: in this case we make actually have a more complex + // declarator, including `[]` brackets. + } + else + { + // synthesize a dummy name + blockVarDecl->Name.Content = GenerateName(parser, "SLANG_parameterBlock_" + reflectionNameToken.Content); + + // Otherwise we have a transparent declaration, similar + // to an HLSL `cbuffer` + auto transparentModifier = new TransparentModifier(); + transparentModifier->Position = pos; + addModifier(blockVarDecl, transparentModifier); + } + + // Expect a trailing `;` + parser->ReadToken(TokenType::Semicolon); + + // Because we are constructing two declarations, we have a thorny + // issue that were are only supposed to return one. + // For now we handle this by adding the type declaration to + // the current scope manually, and then returning the variable + // declaration. + // + // Note: this means that any modifiers that have already been parsed + // will get attached to the variable declaration, not the type. + // There might be cases where we need to shuffle things around. + + AddMember(parser->currentScope, blockDataTypeDecl); + + return blockVarDecl; + } + + + + + static RefPtr ParseGenericParamDecl( + Parser* parser, + RefPtr genericDecl) + { + // simple syntax to introduce a value parameter + if (AdvanceIf(parser, "let")) + { + // default case is a type parameter + auto paramDecl = new GenericValueParamDecl(); + paramDecl->Name = parser->ReadToken(TokenType::Identifier); + if (AdvanceIf(parser, TokenType::Colon)) + { + paramDecl->Type = parser->ParseTypeExp(); + } + if (AdvanceIf(parser, TokenType::OpAssign)) + { + paramDecl->Expr = parser->ParseInitExpr(); + } + return paramDecl; + } + else + { + // default case is a type parameter + auto paramDecl = new GenericTypeParamDecl(); + parser->FillPosition(paramDecl); + paramDecl->Name = parser->ReadToken(TokenType::Identifier); + if (AdvanceIf(parser, TokenType::Colon)) + { + // The user is apply a constraint to this type parameter... + + auto paramConstraint = new GenericTypeConstraintDecl(); + parser->FillPosition(paramConstraint); + + auto paramType = DeclRefType::Create(DeclRef(paramDecl, nullptr)); + + auto paramTypeExpr = new SharedTypeExpr(); + paramTypeExpr->Position = paramDecl->Position; + paramTypeExpr->base.type = paramType; + paramTypeExpr->Type = new TypeType(paramType); + + paramConstraint->sub = TypeExp(paramTypeExpr); + paramConstraint->sup = parser->ParseTypeExp(); + + AddMember(genericDecl, paramConstraint); + + + } + if (AdvanceIf(parser, TokenType::OpAssign)) + { + paramDecl->initType = parser->ParseTypeExp(); + } + return paramDecl; + } + } + + static RefPtr ParseGenericDecl( + Parser* parser) + { + RefPtr decl = new GenericDecl(); + parser->FillPosition(decl.Ptr()); + parser->PushScope(decl.Ptr()); + parser->ReadToken("__generic"); + parser->ReadToken(TokenType::OpLess); + parser->genericDepth++; + while (!parser->LookAheadToken(TokenType::OpGreater)) + { + AddMember(decl, ParseGenericParamDecl(parser, decl)); + +if( parser->LookAheadToken(TokenType::OpGreater) ) +break; + +parser->ReadToken(TokenType::Comma); + } + parser->genericDepth--; + parser->ReadToken(TokenType::OpGreater); + + decl->inner = ParseSingleDecl(parser, decl.Ptr()); + + // A generic decl hijacks the name of the declaration + // it wraps, so that lookup can find it. + decl->Name = decl->inner->Name; + + parser->PopScope(); + return decl; + } + + static RefPtr ParseTraitConformanceDecl( + Parser* parser) + { + RefPtr decl = new TraitConformanceDecl(); + parser->FillPosition(decl.Ptr()); + parser->ReadToken("__conforms"); + + decl->base = parser->ParseTypeExp(); + + return decl; + } + + + static RefPtr ParseExtensionDecl(Parser* parser) + { + RefPtr decl = new ExtensionDecl(); + parser->FillPosition(decl.Ptr()); + parser->ReadToken("__extension"); + decl->targetType = parser->ParseTypeExp(); + parser->ReadToken(TokenType::LBrace); + ParseDeclBody(parser, decl.Ptr(), TokenType::RBrace); + return decl; + } + + static RefPtr ParseTraitDecl(Parser* parser) + { + RefPtr decl = new TraitDecl(); + parser->FillPosition(decl.Ptr()); + parser->ReadToken("__trait"); + decl->Name = parser->ReadToken(TokenType::Identifier); + + if( AdvanceIf(parser, TokenType::Colon) ) + { + do + { + auto base = parser->ParseTypeExp(); + decl->bases.Add(base); + } while( AdvanceIf(parser, TokenType::Comma) ); + } + + parser->ReadToken(TokenType::LBrace); + ParseDeclBody(parser, decl.Ptr(), TokenType::RBrace); + return decl; + } + + static RefPtr ParseConstructorDecl(Parser* parser) + { + RefPtr decl = new ConstructorDecl(); + parser->FillPosition(decl.Ptr()); + parser->ReadToken("__init"); + + parseParameterList(parser, decl); + + if( AdvanceIf(parser, TokenType::Semicolon) ) + { + // empty body + } + else + { + decl->Body = parser->ParseBlockStatement(); + } + return decl; + } + + static RefPtr parseAccessorDecl(Parser* parser) + { + RefPtr decl; + if( AdvanceIf(parser, "get") ) + { + decl = new GetterDecl(); + } + else if( AdvanceIf(parser, "set") ) + { + decl = new SetterDecl(); + } + else + { + Unexpected(parser); + return nullptr; + } + + if( parser->tokenReader.PeekTokenType() == TokenType::LBrace ) + { + decl->Body = parser->ParseBlockStatement(); + } + else + { + parser->ReadToken(TokenType::Semicolon); + } + + return decl; + } + + static RefPtr ParseSubscriptDecl(Parser* parser) + { + RefPtr decl = new SubscriptDecl(); + parser->FillPosition(decl.Ptr()); + parser->ReadToken("__subscript"); + + // TODO: the use of this name here is a bit magical... + decl->Name.Content = "operator[]"; + + parseParameterList(parser, decl); + + if( AdvanceIf(parser, TokenType::RightArrow) ) + { + decl->ReturnType = parser->ParseTypeExp(); + } + + if( AdvanceIf(parser, TokenType::LBrace) ) + { + // We want to parse nested "accessor" declarations + while( !AdvanceIfMatch(parser, TokenType::RBrace) ) + { + auto accessor = parseAccessorDecl(parser); + AddMember(decl, accessor); + } + } + else + { + parser->ReadToken(TokenType::Semicolon); + + // empty body should be treated like `{ get; }` + } + + return decl; + } + + // Parse a declaration of a new modifier keyword + static RefPtr parseModifierDecl(Parser* parser) + { + RefPtr decl = new ModifierDecl(); + + // read the `__modifier` keyword + parser->ReadToken(TokenType::Identifier); + + parser->ReadToken(TokenType::LParent); + decl->classNameToken = parser->ReadToken(TokenType::Identifier); + parser->ReadToken(TokenType::RParent); + + parser->FillPosition(decl.Ptr()); + decl->Name = parser->ReadToken(TokenType::Identifier); + + parser->ReadToken(TokenType::Semicolon); + return decl; + } + + // Finish up work on a declaration that was parsed + static void CompleteDecl( + Parser* /*parser*/, + RefPtr decl, + ContainerDecl* containerDecl, + Modifiers modifiers) + { + // Add any modifiers we parsed before the declaration to the list + // of modifiers on the declaration itself. + AddModifiers(decl.Ptr(), modifiers.first); + + // Make sure the decl is properly nested inside its lexical parent + if (containerDecl) + { + AddMember(containerDecl, decl); + } + } + + static RefPtr ParseDeclWithModifiers( + Parser* parser, + ContainerDecl* containerDecl, + Modifiers modifiers ) + { + RefPtr decl; + + auto loc = parser->tokenReader.PeekLoc(); + + // TODO: actual dispatch! + if (parser->LookAheadToken("struct")) + decl = ParseDeclaratorDecl(parser, containerDecl); + else if (parser->LookAheadToken("class")) + decl = ParseDeclaratorDecl(parser, containerDecl); + else if (parser->LookAheadToken("typedef")) + decl = ParseTypeDef(parser); + else if (parser->LookAheadToken("using")) + decl = ParseUsing(parser); + else if (parser->LookAheadToken("cbuffer") || parser->LookAheadToken("tbuffer")) + decl = ParseHLSLBufferDecl(parser); + else if (parser->LookAheadToken("__generic")) + decl = ParseGenericDecl(parser); + else if (parser->LookAheadToken("__conforms")) + decl = ParseTraitConformanceDecl(parser); + else if (parser->LookAheadToken("__extension")) + decl = ParseExtensionDecl(parser); + else if (parser->LookAheadToken("__init")) + decl = ParseConstructorDecl(parser); + else if (parser->LookAheadToken("__subscript")) + decl = ParseSubscriptDecl(parser); + else if (parser->LookAheadToken("__trait")) + decl = ParseTraitDecl(parser); + else if(parser->LookAheadToken("__modifier")) + decl = parseModifierDecl(parser); + else if (AdvanceIf(parser, TokenType::Semicolon)) + { + decl = new EmptyDecl(); + decl->Position = loc; + } + // GLSL requires that we be able to parse "block" declarations, + // which look superficially similar to declarator declarations + else if( parser->LookAheadToken(TokenType::Identifier) + && parser->LookAheadToken(TokenType::LBrace, 1) ) + { + decl = parseGLSLBlockDecl(parser, modifiers); + } + else + { + // Default case: just parse a declarator-based declaration + decl = ParseDeclaratorDecl(parser, containerDecl); + } + + if (decl) + { + if( auto dd = decl.As() ) + { + CompleteDecl(parser, dd, containerDecl, modifiers); + } + else if(auto declGroup = decl.As()) + { + // We are going to add the same modifiers to *all* of these declarations, + // so we want to give later passes a way to detect which modifiers + // were shared, vs. which ones are specific to a single declaration. + + auto sharedModifiers = new SharedModifiers(); + sharedModifiers->next = modifiers.first; + modifiers.first = sharedModifiers; + + for( auto subDecl : declGroup->decls ) + { + CompleteDecl(parser, subDecl, containerDecl, modifiers); + } + } + } + return decl; + } + + static RefPtr ParseDecl( + Parser* parser, + ContainerDecl* containerDecl) + { + Modifiers modifiers = ParseModifiers(parser); + return ParseDeclWithModifiers(parser, containerDecl, modifiers); + } + + static RefPtr ParseSingleDecl( + Parser* parser, + ContainerDecl* containerDecl) + { + auto declBase = ParseDecl(parser, containerDecl); + if(!declBase) + return nullptr; + if( auto decl = declBase.As() ) + { + return decl; + } + else if( auto declGroup = declBase.As() ) + { + if( declGroup->decls.Count() == 1 ) + { + return declGroup->decls[0]; + } + } + + parser->sink->diagnose(declBase->Position, Diagnostics::unimplemented, "didn't expect multiple declarations here"); + return nullptr; + } + + + // Parse a body consisting of declarations + static void ParseDeclBody( + Parser* parser, + ContainerDecl* containerDecl, + TokenType closingToken) + { + while(!AdvanceIfMatch(parser, closingToken)) + { + ParseDecl(parser, containerDecl); + TryRecover(parser); + } + } + + void Parser::parseSourceFile(ProgramSyntaxNode* program) + { + if (outerScope) + { + currentScope = outerScope; + } + + PushScope(program); + program->Position = CodePosition(0, 0, 0, fileName); + ParseDeclBody(this, program, TokenType::EndOfFile); + PopScope(); + + assert(currentScope == outerScope); + currentScope = nullptr; + } + + RefPtr Parser::ParseProgram() + { + RefPtr program = new ProgramSyntaxNode(); + + parseSourceFile(program.Ptr()); + + return program; + } + + RefPtr Parser::ParseStruct() + { + RefPtr rs = new StructSyntaxNode(); + FillPosition(rs.Ptr()); + ReadToken("struct"); + rs->Name = ReadToken(TokenType::Identifier); + ReadToken(TokenType::LBrace); + ParseDeclBody(this, rs.Ptr(), TokenType::RBrace); + + return rs; + } + + RefPtr Parser::ParseClass() + { + RefPtr rs = new ClassSyntaxNode(); + FillPosition(rs.Ptr()); + ReadToken("class"); + rs->Name = ReadToken(TokenType::Identifier); + ReadToken(TokenType::LBrace); + ParseDeclBody(this, rs.Ptr(), TokenType::RBrace); + return rs; + } + + static RefPtr ParseSwitchStmt(Parser* parser) + { + RefPtr stmt = new SwitchStmt(); + parser->FillPosition(stmt.Ptr()); + parser->ReadToken("switch"); + parser->ReadToken(TokenType::LParent); + stmt->condition = parser->ParseExpression(); + parser->ReadToken(TokenType::RParent); + stmt->body = parser->ParseBlockStatement(); + return stmt; + } + + static RefPtr ParseCaseStmt(Parser* parser) + { + RefPtr stmt = new CaseStmt(); + parser->FillPosition(stmt.Ptr()); + parser->ReadToken("case"); + stmt->expr = parser->ParseExpression(); + parser->ReadToken(TokenType::Colon); + return stmt; + } + + static RefPtr ParseDefaultStmt(Parser* parser) + { + RefPtr stmt = new DefaultStmt(); + parser->FillPosition(stmt.Ptr()); + parser->ReadToken("default"); + parser->ReadToken(TokenType::Colon); + return stmt; + } + + static bool peekTypeName(Parser* parser) + { + if(!parser->LookAheadToken(TokenType::Identifier)) + return false; + + auto name = parser->tokenReader.PeekToken().Content; + + auto lookupResult = LookUp(name, parser->currentScope); + if(!lookupResult.isValid() || lookupResult.isOverloaded()) + return false; + + auto decl = lookupResult.item.declRef.GetDecl(); + if( auto typeDecl = dynamic_cast(decl) ) + { + return true; + } + else if( auto typeVarDecl = dynamic_cast(decl) ) + { + return true; + } + else + { + return false; + } + } + + RefPtr Parser::ParseStatement() + { + auto modifiers = ParseModifiers(this); + + RefPtr statement; + if (LookAheadToken(TokenType::LBrace)) + statement = ParseBlockStatement(); + else if (peekTypeName(this)) + statement = ParseVarDeclrStatement(modifiers); + else if (LookAheadToken("if")) + statement = ParseIfStatement(); + else if (LookAheadToken("for")) + statement = ParseForStatement(); + else if (LookAheadToken("while")) + statement = ParseWhileStatement(); + else if (LookAheadToken("do")) + statement = ParseDoWhileStatement(); + else if (LookAheadToken("break")) + statement = ParseBreakStatement(); + else if (LookAheadToken("continue")) + statement = ParseContinueStatement(); + else if (LookAheadToken("return")) + statement = ParseReturnStatement(); + else if (LookAheadToken("discard")) + { + statement = new DiscardStatementSyntaxNode(); + FillPosition(statement.Ptr()); + ReadToken("discard"); + ReadToken(TokenType::Semicolon); + } + else if (LookAheadToken("switch")) + statement = ParseSwitchStmt(this); + else if (LookAheadToken("case")) + statement = ParseCaseStmt(this); + else if (LookAheadToken("default")) + statement = ParseDefaultStmt(this); + else if (LookAheadToken(TokenType::Identifier)) + { + // We might be looking at a local declaration, or an + // expression statement, and we need to figure out which. + // + // We'll solve this with backtracking for now. + + Token* startPos = tokenReader.mCursor; + + // Try to parse a type (knowing that the type grammar is + // a subset of the expression grammar, and so this should + // always succeed). + RefPtr type = ParseType(); + // We don't actually care about the type, though, so + // don't retain it + type = nullptr; + + // If the next token after we parsed a type looks like + // we are going to declare a variable, then lets guess + // that this is a declaration. + // + // TODO(tfoley): this wouldn't be robust for more + // general kinds of declarators (notably pointer declarators), + // so we'll need to be careful about this. + if (LookAheadToken(TokenType::Identifier)) + { + // Reset the cursor and try to parse a declaration now. + // Note: the declaration will consume any modifiers + // that had been in place on the statement. + tokenReader.mCursor = startPos; + statement = ParseVarDeclrStatement(modifiers); + return statement; + } + + // Fallback: reset and parse an expression + tokenReader.mCursor = startPos; + statement = ParseExpressionStatement(); + } + else if (LookAheadToken(TokenType::Semicolon)) + { + statement = new EmptyStatementSyntaxNode(); + FillPosition(statement.Ptr()); + ReadToken(TokenType::Semicolon); + } + else + { + // Default case should always fall back to parsing an expression, + // and then let that detect any errors + statement = ParseExpressionStatement(); + } + + if (statement) + { + // Install any modifiers onto the statement. + // Note: this path is bypassed in the case of a + // declaration statement, so we don't end up + // doubling up the modifiers. + statement->modifiers = modifiers; + } + + return statement; + } + + RefPtr Parser::ParseBlockStatement() + { + if( options.flags & SLANG_COMPILE_FLAG_NO_CHECKING ) + { + // We have been asked to parse the input, but not attempt to understand it. + + // TODO: record start/end locations... + + List tokens; + + ReadToken(TokenType::LBrace); + + int depth = 1; + for( ;;) + { + switch( tokenReader.PeekTokenType() ) + { + case TokenType::EndOfFile: + goto done; + + case TokenType::RBrace: + depth--; + if(depth == 0) + goto done; + break; + + case TokenType::LBrace: + depth++; + break; + + default: + break; + } + + auto token = tokenReader.AdvanceToken(); + tokens.Add(token); + } + done: + ReadToken(TokenType::RBrace); + + RefPtr unparsedStmt = new UnparsedStmt(); + unparsedStmt->tokens = tokens; + return unparsedStmt; + } + + + RefPtr scopeDecl = new ScopeDecl(); + RefPtr blockStatement = new BlockStatementSyntaxNode(); + blockStatement->scopeDecl = scopeDecl; + PushScope(scopeDecl.Ptr()); + ReadToken(TokenType::LBrace); + if(!tokenReader.IsAtEnd()) + { + FillPosition(blockStatement.Ptr()); + } + while (!AdvanceIfMatch(this, TokenType::RBrace)) + { + auto stmt = ParseStatement(); + if(stmt) + { + blockStatement->Statements.Add(stmt); + } + TryRecover(this); + } + PopScope(); + return blockStatement; + } + + RefPtr Parser::ParseVarDeclrStatement( + Modifiers modifiers) + { + RefPtrvarDeclrStatement = new VarDeclrStatementSyntaxNode(); + + FillPosition(varDeclrStatement.Ptr()); + auto decl = ParseDeclWithModifiers(this, currentScope->containerDecl, modifiers); + varDeclrStatement->decl = decl; + return varDeclrStatement; + } + + RefPtr Parser::ParseIfStatement() + { + RefPtr ifStatement = new IfStatementSyntaxNode(); + FillPosition(ifStatement.Ptr()); + ReadToken("if"); + ReadToken(TokenType::LParent); + ifStatement->Predicate = ParseExpression(); + ReadToken(TokenType::RParent); + ifStatement->PositiveStatement = ParseStatement(); + if (LookAheadToken("else")) + { + ReadToken("else"); + ifStatement->NegativeStatement = ParseStatement(); + } + return ifStatement; + } + + RefPtr Parser::ParseForStatement() + { + RefPtr scopeDecl = new ScopeDecl(); + RefPtr stmt = new ForStatementSyntaxNode(); + stmt->scopeDecl = scopeDecl; + + // Note(tfoley): HLSL implements `for` with incorrect scoping. + // We need an option to turn on this behavior in a kind of "legacy" mode +// PushScope(scopeDecl.Ptr()); + FillPosition(stmt.Ptr()); + ReadToken("for"); + ReadToken(TokenType::LParent); + if (peekTypeName(this)) + { + stmt->InitialStatement = ParseVarDeclrStatement(Modifiers()); + } + else + { + if (!LookAheadToken(TokenType::Semicolon)) + { + stmt->InitialStatement = ParseExpressionStatement(); + } + else + { + ReadToken(TokenType::Semicolon); + } + } + if (!LookAheadToken(TokenType::Semicolon)) + stmt->PredicateExpression = ParseExpression(); + ReadToken(TokenType::Semicolon); + if (!LookAheadToken(TokenType::RParent)) + stmt->SideEffectExpression = ParseExpression(); + ReadToken(TokenType::RParent); + stmt->Statement = ParseStatement(); +// PopScope(); + return stmt; + } + + RefPtr Parser::ParseWhileStatement() + { + RefPtr whileStatement = new WhileStatementSyntaxNode(); + FillPosition(whileStatement.Ptr()); + ReadToken("while"); + ReadToken(TokenType::LParent); + whileStatement->Predicate = ParseExpression(); + ReadToken(TokenType::RParent); + whileStatement->Statement = ParseStatement(); + return whileStatement; + } + + RefPtr Parser::ParseDoWhileStatement() + { + RefPtr doWhileStatement = new DoWhileStatementSyntaxNode(); + FillPosition(doWhileStatement.Ptr()); + ReadToken("do"); + doWhileStatement->Statement = ParseStatement(); + ReadToken("while"); + ReadToken(TokenType::LParent); + doWhileStatement->Predicate = ParseExpression(); + ReadToken(TokenType::RParent); + ReadToken(TokenType::Semicolon); + return doWhileStatement; + } + + RefPtr Parser::ParseBreakStatement() + { + RefPtr breakStatement = new BreakStatementSyntaxNode(); + FillPosition(breakStatement.Ptr()); + ReadToken("break"); + ReadToken(TokenType::Semicolon); + return breakStatement; + } + + RefPtr Parser::ParseContinueStatement() + { + RefPtr continueStatement = new ContinueStatementSyntaxNode(); + FillPosition(continueStatement.Ptr()); + ReadToken("continue"); + ReadToken(TokenType::Semicolon); + return continueStatement; + } + + RefPtr Parser::ParseReturnStatement() + { + RefPtr returnStatement = new ReturnStatementSyntaxNode(); + FillPosition(returnStatement.Ptr()); + ReadToken("return"); + if (!LookAheadToken(TokenType::Semicolon)) + returnStatement->Expression = ParseExpression(); + ReadToken(TokenType::Semicolon); + return returnStatement; + } + + RefPtr Parser::ParseExpressionStatement() + { + RefPtr statement = new ExpressionStatementSyntaxNode(); + + FillPosition(statement.Ptr()); + statement->Expression = ParseExpression(); + + ReadToken(TokenType::Semicolon); + return statement; + } + + RefPtr Parser::ParseParameter() + { + RefPtr parameter = new ParameterSyntaxNode(); + parameter->modifiers = ParseModifiers(this); + + DeclaratorInfo declaratorInfo; + declaratorInfo.typeSpec = ParseType(); + + InitDeclarator initDeclarator = ParseInitDeclarator(this); + UnwrapDeclarator(initDeclarator, &declaratorInfo); + + // Assume it is a variable-like declarator + CompleteVarDecl(this, parameter, declaratorInfo); + return parameter; + } + + RefPtr Parser::ParseType() + { + auto typeSpec = parseTypeSpec(this); + if( typeSpec.decl ) + { + AddMember(currentScope, typeSpec.decl); + } + auto typeExpr = typeSpec.expr; + + while (LookAheadToken(TokenType::LBracket)) + { + RefPtr arrType = new IndexExpressionSyntaxNode(); + arrType->Position = typeExpr->Position; + arrType->BaseExpression = typeExpr; + ReadToken(TokenType::LBracket); + if (!LookAheadToken(TokenType::RBracket)) + { + arrType->IndexExpression = ParseExpression(); + } + ReadToken(TokenType::RBracket); + typeExpr = arrType; + } + + return typeExpr; + } + + + + TypeExp Parser::ParseTypeExp() + { + return TypeExp(ParseType()); + } + + enum class Associativity + { + Left, Right + }; + + + + Associativity GetAssociativityFromLevel(Precedence level) + { + if (level == Precedence::Assignment) + return Associativity::Right; + else + return Associativity::Left; + } + + + + + Precedence GetOpLevel(Parser* parser, TokenType type) + { + switch(type) + { + case TokenType::Comma: + return Precedence::Comma; + case TokenType::OpAssign: + case TokenType::OpMulAssign: + case TokenType::OpDivAssign: + case TokenType::OpAddAssign: + case TokenType::OpSubAssign: + case TokenType::OpModAssign: + case TokenType::OpShlAssign: + case TokenType::OpShrAssign: + case TokenType::OpOrAssign: + case TokenType::OpAndAssign: + case TokenType::OpXorAssign: + return Precedence::Assignment; + case TokenType::OpOr: + return Precedence::LogicalOr; + case TokenType::OpAnd: + return Precedence::LogicalAnd; + case TokenType::OpBitOr: + return Precedence::BitOr; + case TokenType::OpBitXor: + return Precedence::BitXor; + case TokenType::OpBitAnd: + return Precedence::BitAnd; + case TokenType::OpEql: + case TokenType::OpNeq: + return Precedence::EqualityComparison; + case TokenType::OpGreater: + case TokenType::OpGeq: + // Don't allow these ops inside a generic argument + if (parser->genericDepth > 0) return Precedence::Invalid; + case TokenType::OpLeq: + case TokenType::OpLess: + return Precedence::RelationalComparison; + case TokenType::OpRsh: + // Don't allow this op inside a generic argument + if (parser->genericDepth > 0) return Precedence::Invalid; + case TokenType::OpLsh: + return Precedence::BitShift; + case TokenType::OpAdd: + case TokenType::OpSub: + return Precedence::Additive; + case TokenType::OpMul: + case TokenType::OpDiv: + case TokenType::OpMod: + return Precedence::Multiplicative; + default: + return Precedence::Invalid; + } + } + + Operator GetOpFromToken(Token & token) + { + switch(token.Type) + { + case TokenType::Comma: + return Operator::Sequence; + case TokenType::OpAssign: + return Operator::Assign; + case TokenType::OpAddAssign: + return Operator::AddAssign; + case TokenType::OpSubAssign: + return Operator::SubAssign; + case TokenType::OpMulAssign: + return Operator::MulAssign; + case TokenType::OpDivAssign: + return Operator::DivAssign; + case TokenType::OpModAssign: + return Operator::ModAssign; + case TokenType::OpShlAssign: + return Operator::LshAssign; + case TokenType::OpShrAssign: + return Operator::RshAssign; + case TokenType::OpOrAssign: + return Operator::OrAssign; + case TokenType::OpAndAssign: + return Operator::AddAssign; + case TokenType::OpXorAssign: + return Operator::XorAssign; + case TokenType::OpOr: + return Operator::Or; + case TokenType::OpAnd: + return Operator::And; + case TokenType::OpBitOr: + return Operator::BitOr; + case TokenType::OpBitXor: + return Operator::BitXor; + case TokenType::OpBitAnd: + return Operator::BitAnd; + case TokenType::OpEql: + return Operator::Eql; + case TokenType::OpNeq: + return Operator::Neq; + case TokenType::OpGeq: + return Operator::Geq; + case TokenType::OpLeq: + return Operator::Leq; + case TokenType::OpGreater: + return Operator::Greater; + case TokenType::OpLess: + return Operator::Less; + case TokenType::OpLsh: + return Operator::Lsh; + case TokenType::OpRsh: + return Operator::Rsh; + case TokenType::OpAdd: + return Operator::Add; + case TokenType::OpSub: + return Operator::Sub; + case TokenType::OpMul: + return Operator::Mul; + case TokenType::OpDiv: + return Operator::Div; + case TokenType::OpMod: + return Operator::Mod; + case TokenType::OpInc: + return Operator::PostInc; + case TokenType::OpDec: + return Operator::PostDec; + case TokenType::OpNot: + return Operator::Not; + case TokenType::OpBitNot: + return Operator::BitNot; + default: + throw "Illegal TokenType."; + } + } + + static RefPtr parseOperator(Parser* parser) + { + Token opToken; + switch(parser->tokenReader.PeekTokenType()) + { + case TokenType::QuestionMark: + opToken = parser->ReadToken(); + opToken.Content = "?:"; + break; + + default: + opToken = parser->ReadToken(); + break; + } + + auto opExpr = new VarExpressionSyntaxNode(); + opExpr->Variable = opToken.Content; + opExpr->scope = parser->currentScope; + opExpr->Position = opToken.Position; + + return opExpr; + + } + + RefPtr Parser::ParseExpression(Precedence level) + { + if (level == Precedence::Prefix) + return ParseLeafExpression(); + if (level == Precedence::TernaryConditional) + { + // parse select clause + auto condition = ParseExpression(Precedence(level + 1)); + if (LookAheadToken(TokenType::QuestionMark)) + { + RefPtr select = new SelectExpressionSyntaxNode(); + FillPosition(select.Ptr()); + + select->Arguments.Add(condition); + + select->FunctionExpr = parseOperator(this); + + select->Arguments.Add(ParseExpression(level)); + ReadToken(TokenType::Colon); + select->Arguments.Add(ParseExpression(level)); + return select; + } + else + return condition; + } + else + { + if (GetAssociativityFromLevel(level) == Associativity::Left) + { + auto left = ParseExpression(Precedence(level + 1)); + while (GetOpLevel(this, tokenReader.PeekTokenType()) == level) + { + RefPtr tmp = new InfixExpr(); + tmp->FunctionExpr = parseOperator(this); + + tmp->Arguments.Add(left); + FillPosition(tmp.Ptr()); + tmp->Arguments.Add(ParseExpression(Precedence(level + 1))); + left = tmp; + } + return left; + } + else + { + auto left = ParseExpression(Precedence(level + 1)); + if (GetOpLevel(this, tokenReader.PeekTokenType()) == level) + { + RefPtr tmp = new InfixExpr(); + tmp->Arguments.Add(left); + FillPosition(tmp.Ptr()); + tmp->FunctionExpr = parseOperator(this); + tmp->Arguments.Add(ParseExpression(level)); + left = tmp; + } + return left; + } + } + } + + RefPtr Parser::ParseLeafExpression() + { + RefPtr rs; + if (LookAheadToken(TokenType::OpInc) || + LookAheadToken(TokenType::OpDec) || + LookAheadToken(TokenType::OpNot) || + LookAheadToken(TokenType::OpBitNot) || + LookAheadToken(TokenType::OpSub)) + { + RefPtr unaryExpr = new PrefixExpr(); + FillPosition(unaryExpr.Ptr()); + unaryExpr->FunctionExpr = parseOperator(this); + unaryExpr->Arguments.Add(ParseLeafExpression()); + rs = unaryExpr; + return rs; + } + + if (LookAheadToken(TokenType::LParent)) + { + ReadToken(TokenType::LParent); + RefPtr expr; + if (peekTypeName(this) && LookAheadToken(TokenType::RParent, 1)) + { + RefPtr tcexpr = new TypeCastExpressionSyntaxNode(); + FillPosition(tcexpr.Ptr()); + tcexpr->TargetType = ParseTypeExp(); + ReadToken(TokenType::RParent); + tcexpr->Expression = ParseExpression(Precedence::Multiplicative); // Note(tfoley): need to double-check this + expr = tcexpr; + } + else + { + expr = ParseExpression(); + ReadToken(TokenType::RParent); + } + rs = expr; + } + else if( LookAheadToken(TokenType::LBrace) ) + { + RefPtr initExpr = new InitializerListExpr(); + FillPosition(initExpr.Ptr()); + + // Initializer list + ReadToken(TokenType::LBrace); + + List> exprs; + + for(;;) + { + if(AdvanceIfMatch(this, TokenType::RBrace)) + break; + + auto expr = ParseArgExpr(); + if( expr ) + { + initExpr->args.Add(expr); + } + + if(AdvanceIfMatch(this, TokenType::RBrace)) + break; + + ReadToken(TokenType::Comma); + } + rs = initExpr; + } + + else if (LookAheadToken(TokenType::IntLiterial) || + LookAheadToken(TokenType::DoubleLiterial)) + { + RefPtr constExpr = new ConstantExpressionSyntaxNode(); + auto token = tokenReader.AdvanceToken(); + FillPosition(constExpr.Ptr()); + if (token.Type == TokenType::IntLiterial) + { + constExpr->ConstType = ConstantExpressionSyntaxNode::ConstantType::Int; + constExpr->IntValue = StringToInt(token.Content); + } + else if (token.Type == TokenType::DoubleLiterial) + { + constExpr->ConstType = ConstantExpressionSyntaxNode::ConstantType::Float; + constExpr->FloatValue = (FloatingPointLiteralValue) StringToDouble(token.Content); + } + rs = constExpr; + } + else if (LookAheadToken("true") || LookAheadToken("false")) + { + RefPtr constExpr = new ConstantExpressionSyntaxNode(); + auto token = tokenReader.AdvanceToken(); + FillPosition(constExpr.Ptr()); + constExpr->ConstType = ConstantExpressionSyntaxNode::ConstantType::Bool; + constExpr->IntValue = token.Content == "true" ? 1 : 0; + rs = constExpr; + } + else if (LookAheadToken(TokenType::Identifier)) + { + RefPtr varExpr = new VarExpressionSyntaxNode(); + varExpr->scope = currentScope.Ptr(); + FillPosition(varExpr.Ptr()); + auto token = ReadToken(TokenType::Identifier); + varExpr->Variable = token.Content; + rs = varExpr; + } + + while (!tokenReader.IsAtEnd() && + (LookAheadToken(TokenType::OpInc) || + LookAheadToken(TokenType::OpDec) || + LookAheadToken(TokenType::Dot) || + LookAheadToken(TokenType::LBracket) || + LookAheadToken(TokenType::LParent))) + { + if (LookAheadToken(TokenType::OpInc)) + { + RefPtr unaryExpr = new PostfixExpr(); + FillPosition(unaryExpr.Ptr()); + unaryExpr->FunctionExpr = parseOperator(this); + unaryExpr->Arguments.Add(rs); + rs = unaryExpr; + } + else if (LookAheadToken(TokenType::OpDec)) + { + RefPtr unaryExpr = new PostfixExpr(); + FillPosition(unaryExpr.Ptr()); + unaryExpr->FunctionExpr = parseOperator(this); + unaryExpr->Arguments.Add(rs); + rs = unaryExpr; + } + else if (LookAheadToken(TokenType::LBracket)) + { + RefPtr indexExpr = new IndexExpressionSyntaxNode(); + indexExpr->BaseExpression = rs; + FillPosition(indexExpr.Ptr()); + ReadToken(TokenType::LBracket); + indexExpr->IndexExpression = ParseExpression(); + ReadToken(TokenType::RBracket); + rs = indexExpr; + } + else if (LookAheadToken(TokenType::LParent)) + { + RefPtr invokeExpr = new InvokeExpressionSyntaxNode(); + invokeExpr->FunctionExpr = rs; + FillPosition(invokeExpr.Ptr()); + ReadToken(TokenType::LParent); + while (!tokenReader.IsAtEnd()) + { + if (!LookAheadToken(TokenType::RParent)) + invokeExpr->Arguments.Add(ParseArgExpr()); + else + { + break; + } + if (!LookAheadToken(TokenType::Comma)) + break; + ReadToken(TokenType::Comma); + } + ReadToken(TokenType::RParent); + rs = invokeExpr; + } + else if (LookAheadToken(TokenType::Dot)) + { + RefPtr memberExpr = new MemberExpressionSyntaxNode(); + memberExpr->scope = currentScope.Ptr(); + FillPosition(memberExpr.Ptr()); + memberExpr->BaseExpression = rs; + ReadToken(TokenType::Dot); + memberExpr->MemberName = ReadToken(TokenType::Identifier).Content; + rs = memberExpr; + } + } + if (!rs) + { + sink->diagnose(tokenReader.PeekLoc(), Diagnostics::syntaxError); + } + return rs; + } + + // Parse a source file into an existing translation unit + void parseSourceFile( + ProgramSyntaxNode* translationUnitSyntax, + CompileOptions& options, + TokenSpan const& tokens, + DiagnosticSink* sink, + String const& fileName, + RefPtr const&outerScope) + { + Parser parser(options, tokens, sink, fileName, outerScope); + return parser.parseSourceFile(translationUnitSyntax); + } + } +} \ No newline at end of file diff --git a/source/slang/parser.h b/source/slang/parser.h new file mode 100644 index 000000000..90af69158 --- /dev/null +++ b/source/slang/parser.h @@ -0,0 +1,23 @@ +#ifndef RASTER_RENDERER_PARSER_H +#define RASTER_RENDERER_PARSER_H + +#include "lexer.h" +#include "compiler.h" +#include "syntax.h" + +namespace Slang +{ + namespace Compiler + { + // Parse a source file into an existing translation unit + void parseSourceFile( + ProgramSyntaxNode* translationUnitSyntax, + CompileOptions& options, + TokenSpan const& tokens, + DiagnosticSink* sink, + String const& fileName, + RefPtr const&outerScope); + } +} + +#endif \ No newline at end of file diff --git a/source/slang/preprocessor.cpp b/source/slang/preprocessor.cpp new file mode 100644 index 000000000..cdde2591d --- /dev/null +++ b/source/slang/preprocessor.cpp @@ -0,0 +1,2032 @@ +// Preprocessor.cpp +#include "Preprocessor.h" + +#include "Diagnostics.h" +#include "Lexer.h" + +// Needed so that we can construct modifier syntax +// to represent GLSL directives +#include "Syntax.h" + +#include + +using namespace CoreLib; + +// This file provides an implementation of a simple C-style preprocessor. +// It does not aim for 100% compatibility with any particular preprocessor +// specification, but the goal is to have it accept the most common +// idioms for using the preprocessor, found in shader code in the wild. + + +namespace Slang{ namespace Compiler { + +// State of a preprocessor conditional, which can change when +// we encounter directives like `#elif` or `#endif` +enum class PreprocessorConditionalState +{ + Before, // We have not yet seen a branch with a `true` condition. + During, // We are inside the branch with a `true` condition. + After, // We have already seen the branch with a `true` condition. +}; + +// Represents a preprocessor conditional that we are currently +// nested inside. +struct PreprocessorConditional +{ + // The next outer conditional in the current file/stream, or NULL. + PreprocessorConditional* parent; + + // The directive token that started the conditional (an `#if` or `#ifdef`) + Token ifToken; + + // The `#else` directive token, if one has been seen (otherwise `TokenType::Unknown`) + Token elseToken; + + // The state of the conditional + PreprocessorConditionalState state; +}; + +struct PreprocessorMacro; + +struct PreprocessorEnvironment +{ + // The "outer" environment, to be used if lookup in this env fails + PreprocessorEnvironment* parent = NULL; + + // Macros defined in this environment + Dictionary macros; + + ~PreprocessorEnvironment(); +}; + +// Input tokens can either come from source text, or from macro expansion. +// In general, input streams can be nested, so we have to keep a conceptual +// stack of input. + +// A stream of input tokens to be consumed +struct PreprocessorInputStream +{ + // The next input stream up the stack, if any. + PreprocessorInputStream* parent; + + // The deepest preprocessor conditional active for this stream. + PreprocessorConditional* conditional; + + // Environment to use when looking up macros + PreprocessorEnvironment* environment; + + // Reader for pre-tokenized input + TokenReader tokenReader; + + // If we are clobbering source locations with `#line`, then + // the state is tracked here: + + // Are we overriding source locations? + bool isOverridingSourceLoc; + + // What is the file name we are overriding to? + String overrideFileName; + + // What is the relative offset to apply to any line numbers? + int overrideLineOffset; + + // Destructor is virtual so that we can clean up + // after concrete subtypes. + virtual ~PreprocessorInputStream() = default; +}; + +struct SourceTextInputStream : PreprocessorInputStream +{ + // The pre-tokenized input + TokenList lexedTokens; +}; + +struct MacroExpansion : PreprocessorInputStream +{ + // The macro we will expand + PreprocessorMacro* macro; +}; + +struct ObjectLikeMacroExpansion : MacroExpansion +{ +}; + +struct FunctionLikeMacroExpansion : MacroExpansion +{ + // Environment for macro arguments + PreprocessorEnvironment argumentEnvironment; +}; + +// An enumeration for the diferent types of macros +enum class PreprocessorMacroFlavor +{ + ObjectLike, + FunctionArg, + FunctionLike, +}; + +// In the current design (which we may want to re-consider), +// a macro is a specialized flavor of input stream, that +// captures the token list in its expansion, and then +// can be "played back." +struct PreprocessorMacro +{ + // The name under which the macro was `#define`d + Token nameToken; + + // Parameters of the macro, in case of a function-like macro + List params; + + // The tokens that make up the macro body + TokenList tokens; + + // The flavor of macro + PreprocessorMacroFlavor flavor; + + // The environment in which this macro needs to be expanded. + // For ordinary macros this will be the global environment, + // while for function-like macro arguments, it will be + // the environment of the macro invocation. + PreprocessorEnvironment* environment; +}; + +// State of the preprocessor +struct Preprocessor +{ + // diagnostics sink to use when writing messages + DiagnosticSink* sink; + + // An external callback interface to use when looking + // for files in a `#include` directive + IncludeHandler* includeHandler; + + // Current input stream (top of the stack of input) + PreprocessorInputStream* inputStream; + + // Currently-defined macros + PreprocessorEnvironment globalEnv; + + // A pre-allocated token that can be returned to + // represent end-of-input situations. + Token endOfFileToken; + + // Syntax for the program we are trying to parse + ProgramSyntaxNode* syntax; +}; + +// Convenience routine to access the diagnostic sink +static DiagnosticSink* GetSink(Preprocessor* preprocessor) +{ + return preprocessor->sink; +} + +// +// Forward declarations +// + +static void DestroyConditional(PreprocessorConditional* conditional); +static void DestroyMacro(Preprocessor* preprocessor, PreprocessorMacro* macro); + +// +// Basic Input Handling +// + +// Create a fresh input stream +static void InitializeInputStream(Preprocessor* preprocessor, PreprocessorInputStream* inputStream) +{ + inputStream->parent = NULL; + inputStream->conditional = NULL; + inputStream->environment = &preprocessor->globalEnv; +} + +// Destroy an input stream +static void DestroyInputStream(Preprocessor* /*preprocessor*/, PreprocessorInputStream* inputStream) +{ + delete inputStream; +} + +// Create an input stream to represent a pre-tokenized input file. +// TODO(tfoley): pre-tokenizing files isn't going to work in the long run. +static PreprocessorInputStream* CreateInputStreamForSource(Preprocessor* preprocessor, CoreLib::String const& source, CoreLib::String const& fileName) +{ + SourceTextInputStream* inputStream = new SourceTextInputStream(); + InitializeInputStream(preprocessor, inputStream); + + // Use existing `Lexer` to generate a token stream. + Lexer lexer(fileName, source, GetSink(preprocessor)); + inputStream->lexedTokens = lexer.lexAllTokens(); + inputStream->tokenReader = TokenReader(inputStream->lexedTokens); + + return inputStream; +} + + + +static void PushInputStream(Preprocessor* preprocessor, PreprocessorInputStream* inputStream) +{ + inputStream->parent = preprocessor->inputStream; + preprocessor->inputStream = inputStream; +} + +// Called when we reach the end of an input stream. +// Performs some validation and then destroys the input stream if required. +static void EndInputStream(Preprocessor* preprocessor, PreprocessorInputStream* inputStream) +{ + // If there are any conditionals that weren't completed, then it is an error + if (inputStream->conditional) + { + PreprocessorConditional* conditional = inputStream->conditional; + + GetSink(preprocessor)->diagnose(conditional->ifToken.Position, Diagnostics::endOfFileInPreprocessorConditional); + + while (conditional) + { + PreprocessorConditional* parent = conditional->parent; + DestroyConditional(conditional); + conditional = parent; + } + } + + DestroyInputStream(preprocessor, inputStream); +} + +// Potentially clobber source location information based on `#line` +static Token PossiblyOverrideSourceLoc(PreprocessorInputStream* inputStream, Token const& token) +{ + Token result = token; + if( inputStream->isOverridingSourceLoc ) + { + result.Position.FileName = inputStream->overrideFileName; + result.Position.Line += inputStream->overrideLineOffset; + } + return result; +} + +// Consume one token from an input stream +static Token AdvanceRawToken(PreprocessorInputStream* inputStream) +{ + return PossiblyOverrideSourceLoc(inputStream, inputStream->tokenReader.AdvanceToken()); +} + +// Peek one token from an input stream +static Token PeekRawToken(PreprocessorInputStream* inputStream) +{ + return PossiblyOverrideSourceLoc(inputStream, inputStream->tokenReader.PeekToken()); +} + +// Peek one token type from an input stream +static TokenType PeekRawTokenType(PreprocessorInputStream* inputStream) +{ + return inputStream->tokenReader.PeekTokenType(); +} + + +// Read one token in "raw" mode (meaning don't expand macros) +static Token AdvanceRawToken(Preprocessor* preprocessor) +{ + for (;;) + { + // Look at the input stream on top of the stack + PreprocessorInputStream* inputStream = preprocessor->inputStream; + + // If there isn't one, then there is no more input left to read. + if (!inputStream) + { + return preprocessor->endOfFileToken; + } + + // The top-most input stream may be at its end + if (PeekRawTokenType(inputStream) == TokenType::EndOfFile) + { + // If there is another stream remaining, switch to it + if (inputStream->parent) + { + preprocessor->inputStream = inputStream->parent; + EndInputStream(preprocessor, inputStream); + continue; + } + else + { + // HACK(tfoley): A place to fall into debugger... + int f = 0; + } + } + + // Everything worked, so read a token from the top-most stream + return AdvanceRawToken(inputStream); + } +} + +// Return the next token in "raw" mode, but don't advance the +// current token state. +static Token PeekRawToken(Preprocessor* preprocessor) +{ + // We need to find the strema that `advanceRawToken` would read from. + PreprocessorInputStream* inputStream = preprocessor->inputStream; + for (;;) + { + if (!inputStream) + { + // No more input streams left to read + return preprocessor->endOfFileToken; + } + + // The top-most input stream may be at its end, so + // look one entry up the stack (don't actually pop + // here, since we are just peeking) + if (PeekRawTokenType(inputStream) == TokenType::EndOfFile) + { + if (inputStream->parent) + { + inputStream = inputStream->parent; + continue; + } + else + { + // HACK(tfoley): A place to fall into debugger... + int f = 0; + } + } + + // Everything worked, so the token we just peeked is fine. + return PeekRawToken(inputStream); + } +} + +// Without advancing preprocessor state, look *two* raw tokens ahead +// (This is only needed in order to determine when we are possibly +// expanding a function-style macro) +TokenType PeekSecondRawTokenType(Preprocessor* preprocessor) +{ + // We need to find the strema that `advanceRawToken` would read from. + PreprocessorInputStream* inputStream = preprocessor->inputStream; + int count = 1; + for (;;) + { + if (!inputStream) + { + // No more input streams left to read + return TokenType::EndOfFile; + } + + // The top-most input stream may be at its end, so + // look one entry up the stack (don't actually pop + // here, since we are just peeking) + + TokenReader reader = inputStream->tokenReader; + if (reader.PeekTokenType() == TokenType::EndOfFile) + { + inputStream = inputStream->parent; + continue; + } + + if (count) + { + count--; + + // Note: we are advancing our temporary + // copy of the token reader + reader.AdvanceToken(); + if (reader.PeekTokenType() == TokenType::EndOfFile) + { + inputStream = inputStream->parent; + continue; + } + } + + // Everything worked, so peek a token from the top-most stream + return reader.PeekTokenType(); + } +} + + +// Get the location of the current (raw) token +static CodePosition PeekLoc(Preprocessor* preprocessor) +{ + return PeekRawToken(preprocessor).Position; +} + +// Get the `TokenType` of the current (raw) token +static TokenType PeekRawTokenType(Preprocessor* preprocessor) +{ + return PeekRawToken(preprocessor).Type; +} + +// +// Macros +// + +// Create a macro +static PreprocessorMacro* CreateMacro(Preprocessor* preprocessor) +{ + // TODO(tfoley): Allocate these more intelligently. + // For example, consider pooling them on the preprocessor. + + PreprocessorMacro* macro = new PreprocessorMacro(); + macro->flavor = PreprocessorMacroFlavor::ObjectLike; + macro->environment = &preprocessor->globalEnv; + return macro; +} + +// Destroy a macro +static void DestroyMacro(Preprocessor* /*preprocessor*/, PreprocessorMacro* macro) +{ + delete macro; +} + + +// Find the currently-defined macro of the given name, or return NULL +static PreprocessorMacro* LookupMacro(PreprocessorEnvironment* environment, String const& name) +{ + for(PreprocessorEnvironment* e = environment; e; e = e->parent) + { + PreprocessorMacro* macro = NULL; + if (e->macros.TryGetValue(name, macro)) + return macro; + } + + return NULL; +} + +static PreprocessorEnvironment* GetCurrentEnvironment(Preprocessor* preprocessor) +{ + PreprocessorInputStream* inputStream = preprocessor->inputStream; + return inputStream ? inputStream->environment : &preprocessor->globalEnv; +} + +static PreprocessorMacro* LookupMacro(Preprocessor* preprocessor, String const& name) +{ + return LookupMacro(GetCurrentEnvironment(preprocessor), name); +} + +// A macro is "busy" if it is currently being used for expansion. +// A macro cannot be expanded again while busy, to avoid infinite recursion. +static bool IsMacroBusy(PreprocessorMacro* /*macro*/) +{ + // TODO: need to implement this correctly + // + // The challenge here is that we are implementing expansion + // for argumenst to function-like macros in a "lazy" fashion. + // + // The letter of the spec is that we should macro expand + // each argument *before* substitution, and then go and + // macro-expand the substituted body. This means that we + // can invoke a macro as part of an argument to an + // invocation of the same macro: + // + // FOO( 1, FOO(22), 333 ); + // + // In our implementation, the "inner" invocation of `FOO` + // gets expanded at the point where it gets referenced + // in the body of the "outer" invocation of `FOO`. + // Doing things this way leads to greatly simplified + // code for handling expansion. + // + // A proper implementation of `IsMacroBusy` needs to + // take context into account, so that it bans recursive + // use of a macro when it occurs (indirectly) through + // the *body* of the expansion, but not when it occcurs + // only through an *argument*. + return false; +} + +// +// Reading Tokens With Expansion +// + +static void InitializeMacroExpansion( + Preprocessor* preprocessor, + MacroExpansion* expansion, + PreprocessorMacro* macro) +{ + InitializeInputStream(preprocessor, expansion); + expansion->environment = macro->environment; + expansion->macro = macro; + expansion->tokenReader = TokenReader(macro->tokens); +} + +static void PushMacroExpansion( + Preprocessor* preprocessor, + MacroExpansion* expansion) +{ + PushInputStream(preprocessor, expansion); +} + +static void AddEndOfStreamToken( + Preprocessor* preprocessor, + PreprocessorMacro* macro) +{ + Token token = PeekRawToken(preprocessor); + token.Type = TokenType::EndOfFile; + macro->tokens.mTokens.Add(token); +} + +// Check whether the current token on the given input stream should be +// treated as a macro invocation, and if so set up state for expanding +// that macro. +static void MaybeBeginMacroExpansion( + Preprocessor* preprocessor ) +{ + // We iterate because the first token in the expansion of one + // macro may be another macro invocation. + for (;;) + { + // Look at the next token ahead of us + Token const& token = PeekRawToken(preprocessor); + + // Not an identifier? Can't be a macro. + if (token.Type != TokenType::Identifier) + return; + + // Look for a macro with the given name. + String name = token.Content; + PreprocessorMacro* macro = LookupMacro(preprocessor, name); + + // Not a macro? Can't be an invocation. + if (!macro) + return; + + // If the macro is busy (already being expanded), + // don't try to trigger recursive expansion + if (IsMacroBusy(macro)) + return; + + // A function-style macro invocation should only match + // if the token *after* the identifier is `(`. This + // requires more lookahead than we usually have/need + if (macro->flavor == PreprocessorMacroFlavor::FunctionLike) + { + if(PeekSecondRawTokenType(preprocessor) != TokenType::LParent) + return; + + // Consume the token that triggered macro expansion + AdvanceRawToken(preprocessor); + + // Consume the opening `(` + Token leftParen = AdvanceRawToken(preprocessor); + + FunctionLikeMacroExpansion* expansion = new FunctionLikeMacroExpansion(); + InitializeMacroExpansion(preprocessor, expansion, macro); + expansion->argumentEnvironment.parent = &preprocessor->globalEnv; + expansion->environment = &expansion->argumentEnvironment; + + // Try to read any arguments present. + int paramCount = macro->params.Count(); + int argIndex = 0; + + switch (PeekRawTokenType(preprocessor)) + { + case TokenType::EndOfFile: + case TokenType::RParent: + // No arguments. + break; + + default: + // At least one argument + while(argIndex < paramCount) + { + // Read an argument + + // Create the argument, represented as a special flavor of macro + PreprocessorMacro* arg = CreateMacro(preprocessor); + arg->flavor = PreprocessorMacroFlavor::FunctionArg; + arg->environment = GetCurrentEnvironment(preprocessor); + + // Associate the new macro with its parameter name + Token paramToken = macro->params[argIndex]; + String const& paramName = paramToken.Content; + arg->nameToken = paramToken; + expansion->argumentEnvironment.macros[paramName] = arg; + argIndex++; + + // Read tokens for the argument + + // We track the nesting depth, since we don't break + // arguments on a `,` nested in balanced parentheses + // + int nesting = 0; + for (;;) + { + switch (PeekRawTokenType(preprocessor)) + { + case TokenType::EndOfFile: + // if we reach the end of the file, + // then we have an error, and need to + // bail out + AddEndOfStreamToken(preprocessor, arg); + goto doneWithAllArguments; + + case TokenType::RParent: + // If we see a right paren when we aren't nested + // then we are at the end of an argument + if (nesting == 0) + { + AddEndOfStreamToken(preprocessor, arg); + goto doneWithAllArguments; + } + // Otherwise we decrease our nesting depth, add + // the token, and keep going + nesting--; + break; + + case TokenType::Comma: + // If we see a comma when we aren't nested + // then we are at the end of an argument + if (nesting == 0) + { + AddEndOfStreamToken(preprocessor, arg); + AdvanceRawToken(preprocessor); + goto doneWithArgument; + } + // Otherwise we add it as a normal token + break; + + case TokenType::LParent: + // If we see a left paren then we need to + // increase our tracking of nesting + nesting++; + break; + + default: + break; + } + + // Add the token and continue parsing. + arg->tokens.mTokens.Add(AdvanceRawToken(preprocessor)); + } + doneWithArgument: {} + // We've parsed an argument and should move onto + // the next one. + } + break; + } + doneWithAllArguments: + // TODO: handle possible varargs + + // Expect closing right paren + if (PeekRawTokenType(preprocessor) == TokenType::RParent) + { + AdvanceRawToken(preprocessor); + } + else + { + GetSink(preprocessor)->diagnose(PeekLoc(preprocessor), Diagnostics::expectedTokenInMacroArguments, TokenType::RParent, PeekRawTokenType(preprocessor)); + } + + int argCount = argIndex; + if (argCount != paramCount) + { + // TODO: diagnose + throw 99; + } + + // We are ready to expand. + PushMacroExpansion(preprocessor, expansion); + } + else + { + // Consume the token that triggered macro expansion + AdvanceRawToken(preprocessor); + + // Object-like macros are the easy case. + ObjectLikeMacroExpansion* expansion = new ObjectLikeMacroExpansion(); + InitializeMacroExpansion(preprocessor, expansion, macro); + PushMacroExpansion(preprocessor, expansion); + } + } +} + +// Read one token with macro-expansion enabled. +static Token AdvanceToken(Preprocessor* preprocessor) +{ +top: + // Check whether we need to macro expand at the cursor. + MaybeBeginMacroExpansion(preprocessor); + + // Read a raw token (now that expansion has been triggered) + Token token = AdvanceRawToken(preprocessor); + + // Check if we need to perform token pasting + if (PeekRawTokenType(preprocessor) != TokenType::PoundPound) + { + // If we aren't token pasting, then we are done + return token; + } + else + { + // We are pasting tokens, which could get messy + + StringBuilder sb; + sb << token.Content; + + while (PeekRawTokenType(preprocessor) == TokenType::PoundPound) + { + // Consume the `##` + AdvanceRawToken(preprocessor); + + // Possibly macro-expand the next token + MaybeBeginMacroExpansion(preprocessor); + + // Read the next raw token (now that expansion has been triggered) + Token nextToken = AdvanceRawToken(preprocessor); + + sb << nextToken.Content; + } + + // Now re-lex the input + PreprocessorInputStream* inputStream = CreateInputStreamForSource(preprocessor, sb.ProduceString(), "token paste"); + if (inputStream->tokenReader.GetCount() != 1) + { + // We expect a token paste to produce a single token + // TODO(tfoley): emit a diagnostic here + } + + PushInputStream(preprocessor, inputStream); + goto top; + } +} + +// Read one token with macro-expansion enabled. +// +// Note that because triggering macro expansion may +// involve changing the input-stream state, this +// operation *can* have side effects. +static Token PeekToken(Preprocessor* preprocessor) +{ + // Check whether we need to macro expand at the cursor. + MaybeBeginMacroExpansion(preprocessor); + + // Peek a raw token (now that expansion has been triggered) + return PeekRawToken(preprocessor); + + // TODO: need a plan for how to handle token pasting + // here without it being onerous. Would be nice if we + // didn't have to re-do pasting on a "peek"... +} + +// Peek the type of the next token, including macro expansion. +static TokenType PeekTokenType(Preprocessor* preprocessor) +{ + return PeekToken(preprocessor).Type; +} + +// +// Preprocessor Directives +// + +// When reading a preprocessor directive, we use a context +// to wrap the direct preprocessor routines defines so far. +// +// One of the most important things the directive context +// does is give us a convenient way to read tokens with +// a guarantee that we won't read past the end of a line. +struct PreprocessorDirectiveContext +{ + // The preprocessor that is parsing the directive. + Preprocessor* preprocessor; + + // The directive token (e.g., the `if` in `#if`). + // Useful for reference in diagnostic messages. + Token directiveToken; + + // Has any kind of parse error been encountered in + // the directive so far? + bool parseError; + + // Have we done the necessary checks at the end + // of the directive already? + bool haveDoneEndOfDirectiveChecks; +}; + +// Get the token for the preprocessor directive being parsed. +inline Token const& GetDirective(PreprocessorDirectiveContext* context) +{ + return context->directiveToken; +} + +// Get the name of the directive being parsed. +inline String const& GetDirectiveName(PreprocessorDirectiveContext* context) +{ + return context->directiveToken.Content; +} + +// Get the location of the directive being parsed. +inline CodePosition const& GetDirectiveLoc(PreprocessorDirectiveContext* context) +{ + return context->directiveToken.Position; +} + +// Wrapper to get the diagnostic sink in the context of a directive. +static inline DiagnosticSink* GetSink(PreprocessorDirectiveContext* context) +{ + return GetSink(context->preprocessor); +} + +// Wrapper to get a "current" location when parsing a directive +static CodePosition PeekLoc(PreprocessorDirectiveContext* context) +{ + return PeekLoc(context->preprocessor); +} + +// Wrapper to look up a macro in the context of a directive. +static PreprocessorMacro* LookupMacro(PreprocessorDirectiveContext* context, String const& name) +{ + return LookupMacro(context->preprocessor, name); +} + +// Determine if we have read everthing on the directive's line. +static bool IsEndOfLine(PreprocessorDirectiveContext* context) +{ + return PeekRawToken(context->preprocessor).Type == TokenType::EndOfDirective; +} + +// Peek one raw token in a directive, without going past the end of the line. +static Token PeekRawToken(PreprocessorDirectiveContext* context) +{ + return PeekRawToken(context->preprocessor); +} + +// Read one raw token in a directive, without going past the end of the line. +static Token AdvanceRawToken(PreprocessorDirectiveContext* context) +{ + if (IsEndOfLine(context)) + return PeekRawToken(context); + return AdvanceRawToken(context->preprocessor); +} + +// Peek next raw token type, without going past the end of the line. +static TokenType PeekRawTokenType(PreprocessorDirectiveContext* context) +{ + return PeekRawTokenType(context->preprocessor); +} + +// Read one token, with macro-expansion, without going past the end of the line. +static Token AdvanceToken(PreprocessorDirectiveContext* context) +{ + if (IsEndOfLine(context)) + return PeekRawToken(context); + return AdvanceToken(context->preprocessor); +} + +// Peek one token, with macro-expansion, without going past the end of the line. +static Token PeekToken(PreprocessorDirectiveContext* context) +{ + if (IsEndOfLine(context)) + context->preprocessor->endOfFileToken; + return PeekToken(context->preprocessor); +} + +// Peek next token type, with macro-expansion, without going past the end of the line. +static TokenType PeekTokenType(PreprocessorDirectiveContext* context) +{ + if (IsEndOfLine(context)) + return TokenType::EndOfDirective; + return PeekTokenType(context->preprocessor); +} + +// Skip to the end of the line (useful for recovering from errors in a directive) +static void SkipToEndOfLine(PreprocessorDirectiveContext* context) +{ + while(!IsEndOfLine(context)) + { + AdvanceRawToken(context); + } +} + +static bool ExpectRaw(PreprocessorDirectiveContext* context, TokenType tokenType, DiagnosticInfo const& diagnostic, Token* outToken = NULL) +{ + if (PeekRawTokenType(context) != tokenType) + { + // Only report the first parse error within a directive + if (!context->parseError) + { + GetSink(context)->diagnose(PeekLoc(context), diagnostic, tokenType, GetDirectiveName(context)); + } + context->parseError = true; + return false; + } + Token const& token = AdvanceRawToken(context); + if (outToken) + *outToken = token; + return true; +} + +static bool Expect(PreprocessorDirectiveContext* context, TokenType tokenType, DiagnosticInfo const& diagnostic, Token* outToken = NULL) +{ + if (PeekTokenType(context) != tokenType) + { + // Only report the first parse error within a directive + if (!context->parseError) + { + GetSink(context)->diagnose(PeekLoc(context), diagnostic, tokenType, GetDirectiveName(context)); + context->parseError = true; + } + return false; + } + Token const& token = AdvanceToken(context); + if (outToken) + *outToken = token; + return true; +} + + + +// +// Preprocessor Conditionals +// + +// Determine whether the current preprocessor state means we +// should be skipping tokens. +static bool IsSkipping(Preprocessor* preprocessor) +{ + PreprocessorInputStream* inputStream = preprocessor->inputStream; + if (!inputStream) return false; + + // If we are not inside a preprocessor conditional, then don't skip + PreprocessorConditional* conditional = inputStream->conditional; + if (!conditional) return false; + + // skip tokens unless the conditional is inside its `true` case + return conditional->state != PreprocessorConditionalState::During; +} + +// Wrapper for use inside directives +static inline bool IsSkipping(PreprocessorDirectiveContext* context) +{ + return IsSkipping(context->preprocessor); +} + +// Create a preprocessor conditional +static PreprocessorConditional* CreateConditional(Preprocessor* /*preprocessor*/) +{ + // TODO(tfoley): allocate these more intelligently (for example, + // pool them on the `Preprocessor`. + return new PreprocessorConditional(); +} + +// Destroy a preprocessor conditional. +static void DestroyConditional(PreprocessorConditional* conditional) +{ + delete conditional; +} + +// Start a preprocessor conditional, with an initial enable/disable state. +static void BeginConditional(PreprocessorDirectiveContext* context, bool enable) +{ + Preprocessor* preprocessor = context->preprocessor; + PreprocessorInputStream* inputStream = preprocessor->inputStream; + assert(inputStream); + + PreprocessorConditional* conditional = CreateConditional(preprocessor); + + conditional->ifToken = context->directiveToken; + + // Set state of this condition appropriately. + // + // Default to the "haven't yet seen a `true` branch" state. + PreprocessorConditionalState state = PreprocessorConditionalState::Before; + // + // If we are nested inside a `false` branch of another condition, then + // we never want to enable, so we act as if we already *saw* the `true` branch. + // + if (IsSkipping(preprocessor)) state = PreprocessorConditionalState::After; + // + // Similarly, if we ran into any parse errors when dealing with the + // opening directive, then things are probably screwy and we should just + // skip all the branches. + if (IsSkipping(preprocessor)) state = PreprocessorConditionalState::After; + // + // Otherwise, if our condition was true, then set us to be inside the `true` branch + else if (enable) state = PreprocessorConditionalState::During; + + conditional->state = state; + + // Push conditional onto the stack + conditional->parent = inputStream->conditional; + inputStream->conditional = conditional; +} + +// +// Preprocessor Conditional Expressions +// + +// Conditional expressions are always of type `int` +typedef int PreprocessorExpressionValue; + +// Forward-declaretion +static PreprocessorExpressionValue ParseAndEvaluateExpression(PreprocessorDirectiveContext* context); + +// Parse a unary (prefix) expression inside of a preprocessor directive. +static PreprocessorExpressionValue ParseAndEvaluateUnaryExpression(PreprocessorDirectiveContext* context) +{ + switch (PeekTokenType(context)) + { + // handle prefix unary ops + case TokenType::OpSub: + AdvanceToken(context); + return -ParseAndEvaluateUnaryExpression(context); + case TokenType::OpNot: + AdvanceToken(context); + return !ParseAndEvaluateUnaryExpression(context); + case TokenType::OpBitNot: + AdvanceToken(context); + return ~ParseAndEvaluateUnaryExpression(context); + + // handle parenthized sub-expression + case TokenType::LParent: + { + Token leftParen = AdvanceToken(context); + PreprocessorExpressionValue value = ParseAndEvaluateExpression(context); + if (!Expect(context, TokenType::RParent, Diagnostics::expectedTokenInPreprocessorExpression)) + { + GetSink(context)->diagnose(leftParen.Position, Diagnostics::seeOpeningToken, leftParen); + } + return value; + } + + case TokenType::IntLiterial: + return StringToInt(AdvanceToken(context).Content); + + case TokenType::Identifier: + { + Token token = AdvanceToken(context); + if (token.Content == "defined") + { + // handle `defined(someName)` + + // Possibly parse a `(` + Token leftParen; + if (PeekRawTokenType(context) == TokenType::LParent) + { + leftParen = AdvanceRawToken(context); + } + + // Expect an identifier + Token nameToken; + if (!ExpectRaw(context, TokenType::Identifier, Diagnostics::expectedTokenInDefinedExpression, &nameToken)) + { + return 0; + } + String name = nameToken.Content; + + // If we saw an opening `(`, then expect one to close + if (leftParen.Type != TokenType::Unknown) + { + if(!ExpectRaw(context, TokenType::RParent, Diagnostics::expectedTokenInDefinedExpression)) + { + GetSink(context)->diagnose(leftParen.Position, Diagnostics::seeOpeningToken, leftParen); + return 0; + } + } + + return LookupMacro(context, name) != NULL; + } + + // An identifier here means it was not defined as a macro (or + // it is defined, but as a function-like macro. These should + // just evaluate to zero (possibly with a warning) + return 0; + } + + default: + GetSink(context)->diagnose(PeekLoc(context), Diagnostics::syntaxErrorInPreprocessorExpression); + return 0; + } +} + +// Determine the precedence level of an infix operator +// for use in parsing preprocessor conditionals. +static int GetInfixOpPrecedence(Token const& opToken) +{ + // If token is on another line, it is not part of the + // expression + if (opToken.flags & TokenFlag::AtStartOfLine) + return -1; + + // otherwise we look at the token type to figure + // out what precednece it should be parse with + switch (opToken.Type) + { + default: + // tokens that aren't infix operators should + // cause us to stop parsing an expression + return -1; + + case TokenType::OpMul: return 10; + case TokenType::OpDiv: return 10; + case TokenType::OpMod: return 10; + + case TokenType::OpAdd: return 9; + case TokenType::OpSub: return 9; + + case TokenType::OpLsh: return 8; + case TokenType::OpRsh: return 8; + + case TokenType::OpLess: return 7; + case TokenType::OpGreater: return 7; + case TokenType::OpLeq: return 7; + case TokenType::OpGeq: return 7; + + case TokenType::OpEql: return 6; + case TokenType::OpNeq: return 6; + + case TokenType::OpBitAnd: return 5; + case TokenType::OpBitOr: return 4; + case TokenType::OpBitXor: return 3; + case TokenType::OpAnd: return 2; + case TokenType::OpOr: return 1; + } +}; + +// Evaluate one infix operation in a preprocessor +// conditional expression +static PreprocessorExpressionValue EvaluateInfixOp( + PreprocessorDirectiveContext* context, + Token const& opToken, + PreprocessorExpressionValue left, + PreprocessorExpressionValue right) +{ + switch (opToken.Type) + { + default: +// SLANG_INTERNAL_ERROR(getSink(preprocessor), opToken); + return 0; + break; + + case TokenType::OpMul: return left * right; + case TokenType::OpDiv: + { + if (right == 0) + { + if (!context->parseError) + { + GetSink(context)->diagnose(opToken.Position, Diagnostics::divideByZeroInPreprocessorExpression); + } + return 0; + } + return left / right; + } + case TokenType::OpMod: + { + if (right == 0) + { + if (!context->parseError) + { + GetSink(context)->diagnose(opToken.Position, Diagnostics::divideByZeroInPreprocessorExpression); + } + return 0; + } + return left % right; + } + case TokenType::OpAdd: return left + right; + case TokenType::OpSub: return left - right; + case TokenType::OpLsh: return left << right; + case TokenType::OpRsh: return left >> right; + case TokenType::OpLess: return left < right ? 1 : 0; + case TokenType::OpGreater: return left > right ? 1 : 0; + case TokenType::OpLeq: return left <= right ? 1 : 0; + case TokenType::OpGeq: return left <= right ? 1 : 0; + case TokenType::OpEql: return left == right ? 1 : 0; + case TokenType::OpNeq: return left != right ? 1 : 0; + case TokenType::OpBitAnd: return left & right; + case TokenType::OpBitOr: return left | right; + case TokenType::OpBitXor: return left ^ right; + case TokenType::OpAnd: return left && right; + case TokenType::OpOr: return left || right; + } +} + +// Parse the rest of an infix preprocessor expression with +// precedence greater than or equal to the given `precedence` argument. +// The value of the left-hand-side expression is provided as +// an argument. +// This is used to form a simple recursive-descent expression parser. +static PreprocessorExpressionValue ParseAndEvaluateInfixExpressionWithPrecedence( + PreprocessorDirectiveContext* context, + PreprocessorExpressionValue left, + int precedence) +{ + for (;;) + { + // Look at the next token, and see if it is an operator of + // high enough precedence to be included in our expression + Token opToken = PeekToken(context); + int opPrecedence = GetInfixOpPrecedence(opToken); + + // If it isn't an operator of high enough precendece, we are done. + if(opPrecedence < precedence) + break; + + // Otherwise we need to consume the operator token. + AdvanceToken(context); + + // Next we parse a right-hand-side expression by starting with + // a unary expression and absorbing and many infix operators + // as possible with strictly higher precedence than the operator + // we found above. + PreprocessorExpressionValue right = ParseAndEvaluateUnaryExpression(context); + for (;;) + { + // Look for an operator token + Token rightOpToken = PeekToken(context); + int rightOpPrecedence = GetInfixOpPrecedence(rightOpToken); + + // If no operator was found, or the operator wasn't high + // enough precedence to fold into the right-hand-side, + // exit this loop. + if (rightOpPrecedence <= opPrecedence) + break; + + // Now invoke the parser recursively, passing in our + // existing right-hand side to form an even larger one. + right = ParseAndEvaluateInfixExpressionWithPrecedence( + context, + right, + rightOpPrecedence); + } + + // Now combine the left- and right-hand sides using + // the operator we found above. + left = EvaluateInfixOp(context, opToken, left, right); + } + return left; +} + +// Parse a complete (infix) preprocessor expression, and return its value +static PreprocessorExpressionValue ParseAndEvaluateExpression(PreprocessorDirectiveContext* context) +{ + // First read in the left-hand side (or the whole expression in the unary case) + PreprocessorExpressionValue value = ParseAndEvaluateUnaryExpression(context); + + // Try to read in trailing infix operators with correct precedence + return ParseAndEvaluateInfixExpressionWithPrecedence(context, value, 0); +} + +// Handle a `#if` directive +static void HandleIfDirective(PreprocessorDirectiveContext* context) +{ + // Parse a preprocessor expression. + PreprocessorExpressionValue value = ParseAndEvaluateExpression(context); + + // Begin a preprocessor block, enabled based on the expression. + BeginConditional(context, value != 0); +} + +// Handle a `#ifdef` directive +static void HandleIfDefDirective(PreprocessorDirectiveContext* context) +{ + // Expect a raw identifier, so we can check if it is defined + Token nameToken; + if(!ExpectRaw(context, TokenType::Identifier, Diagnostics::expectedTokenInPreprocessorDirective, &nameToken)) + return; + String name = nameToken.Content; + + // Check if the name is defined. + BeginConditional(context, LookupMacro(context, name) != NULL); +} + +// Handle a `#ifndef` directive +static void HandleIfNDefDirective(PreprocessorDirectiveContext* context) +{ + // Expect a raw identifier, so we can check if it is defined + Token nameToken; + if(!ExpectRaw(context, TokenType::Identifier, Diagnostics::expectedTokenInPreprocessorDirective, &nameToken)) + return; + String name = nameToken.Content; + + // Check if the name is defined. + BeginConditional(context, LookupMacro(context, name) == NULL); +} + +// Handle a `#else` directive +static void HandleElseDirective(PreprocessorDirectiveContext* context) +{ + PreprocessorInputStream* inputStream = context->preprocessor->inputStream; + assert(inputStream); + + // if we aren't inside a conditional, then error + PreprocessorConditional* conditional = inputStream->conditional; + if (!conditional) + { + GetSink(context)->diagnose(GetDirectiveLoc(context), Diagnostics::directiveWithoutIf, GetDirectiveName(context)); + return; + } + + // if we've already seen a `#else`, then it is an error + if (conditional->elseToken.Type != TokenType::Unknown) + { + GetSink(context)->diagnose(GetDirectiveLoc(context), Diagnostics::directiveAfterElse, GetDirectiveName(context)); + GetSink(context)->diagnose(conditional->elseToken.Position, Diagnostics::seeDirective); + return; + } + conditional->elseToken = context->directiveToken; + + switch (conditional->state) + { + case PreprocessorConditionalState::Before: + conditional->state = PreprocessorConditionalState::During; + break; + + case PreprocessorConditionalState::During: + conditional->state = PreprocessorConditionalState::After; + break; + + default: + break; + } +} + +// Handle a `#elif` directive +static void HandleElifDirective(PreprocessorDirectiveContext* context) +{ + // HACK(tfoley): handle an empty `elif` like an `else` directive + // + // This is the behavior expected by at least one input program. + // We will eventually want to be pedantic about this. + // even if t + if (PeekRawTokenType(context) == TokenType::EndOfDirective) + { + GetSink(context)->diagnose(GetDirectiveLoc(context), Diagnostics::directiveExpectsExpression, GetDirectiveName(context)); + HandleElseDirective(context); + return; + } + + PreprocessorExpressionValue value = ParseAndEvaluateExpression(context); + + PreprocessorInputStream* inputStream = context->preprocessor->inputStream; + assert(inputStream); + + // if we aren't inside a conditional, then error + PreprocessorConditional* conditional = inputStream->conditional; + if (!conditional) + { + GetSink(context)->diagnose(GetDirectiveLoc(context), Diagnostics::directiveWithoutIf, GetDirectiveName(context)); + return; + } + + // if we've already seen a `#else`, then it is an error + if (conditional->elseToken.Type != TokenType::Unknown) + { + GetSink(context)->diagnose(GetDirectiveLoc(context), Diagnostics::directiveAfterElse, GetDirectiveName(context)); + GetSink(context)->diagnose(conditional->elseToken.Position, Diagnostics::seeDirective); + return; + } + + switch (conditional->state) + { + case PreprocessorConditionalState::Before: + if(value) + conditional->state = PreprocessorConditionalState::During; + break; + + case PreprocessorConditionalState::During: + conditional->state = PreprocessorConditionalState::After; + break; + + default: + break; + } +} + +// Handle a `#endif` directive +static void HandleEndIfDirective(PreprocessorDirectiveContext* context) +{ + PreprocessorInputStream* inputStream = context->preprocessor->inputStream; + assert(inputStream); + + // if we aren't inside a conditional, then error + PreprocessorConditional* conditional = inputStream->conditional; + if (!conditional) + { + GetSink(context)->diagnose(GetDirectiveLoc(context), Diagnostics::directiveWithoutIf, GetDirectiveName(context)); + return; + } + + inputStream->conditional = conditional->parent; + DestroyConditional(conditional); +} + +// Helper routine to check that we find the end of a directive where +// we expect it. +// +// Most directives do not need to call this directly, since we have +// a catch-all case in the main `HandleDirective()` funciton. +// The `#include` case will call it directly to avoid complications +// when it switches the input stream. +static void expectEndOfDirective(PreprocessorDirectiveContext* context) +{ + if(context->haveDoneEndOfDirectiveChecks) + return; + + context->haveDoneEndOfDirectiveChecks = true; + + if (!IsEndOfLine(context)) + { + // If we already saw a previous parse error, then don't + // emit another one for the same directive. + if (!context->parseError) + { + GetSink(context)->diagnose(PeekLoc(context), Diagnostics::unexpectedTokensAfterDirective, GetDirectiveName(context)); + } + SkipToEndOfLine(context); + } + + // Clear out the end-of-directive token + AdvanceRawToken(context->preprocessor); +} + + +// Handle a `#include` directive +static void HandleIncludeDirective(PreprocessorDirectiveContext* context) +{ + Token pathToken; + if(!Expect(context, TokenType::StringLiterial, Diagnostics::expectedTokenInPreprocessorDirective, &pathToken)) + return; + + String path = getFileNameTokenValue(pathToken); + + // TODO(tfoley): make this robust in presence of `#line` + String pathIncludedFrom = GetDirectiveLoc(context).FileName; + String foundPath; + String foundSource; + + + IncludeHandler* includeHandler = context->preprocessor->includeHandler; + if (!includeHandler) + { + GetSink(context)->diagnose(pathToken.Position, Diagnostics::includeFailed, path); + GetSink(context)->diagnose(pathToken.Position, Diagnostics::noIncludeHandlerSpecified); + return; + } + if (!includeHandler->TryToFindIncludeFile(path, pathIncludedFrom, &foundPath, &foundSource)) + { + GetSink(context)->diagnose(pathToken.Position, Diagnostics::includeFailed, path); + return; + } + + // Do all checking related to the end of this directive before we push a new stream, + // just to avoid complications where that check would need to deal with + // a switch of input stream + expectEndOfDirective(context); + + // Push the new file onto our stack of input streams + // TODO(tfoley): check if we have made our include stack too deep + PreprocessorInputStream* inputStream = CreateInputStreamForSource(context->preprocessor, foundSource, foundPath); + inputStream->parent = context->preprocessor->inputStream; + context->preprocessor->inputStream = inputStream; +} + +// Handle a `#define` directive +static void HandleDefineDirective(PreprocessorDirectiveContext* context) +{ + Token nameToken; + if (!Expect(context, TokenType::Identifier, Diagnostics::expectedTokenInPreprocessorDirective, &nameToken)) + return; + String name = nameToken.Content; + + PreprocessorMacro* macro = CreateMacro(context->preprocessor); + macro->nameToken = nameToken; + + PreprocessorMacro* oldMacro = LookupMacro(&context->preprocessor->globalEnv, name); + if (oldMacro) + { + GetSink(context)->diagnose(nameToken.Position, Diagnostics::macroRedefinition, name); + GetSink(context)->diagnose(oldMacro->nameToken.Position, Diagnostics::seePreviousDefinitionOf, name); + + DestroyMacro(context->preprocessor, oldMacro); + } + context->preprocessor->globalEnv.macros[name] = macro; + + // If macro name is immediately followed (with no space) by `(`, + // then we have a function-like macro + if (PeekRawTokenType(context) == TokenType::LParent) + { + if (!(PeekRawToken(context).flags & TokenFlag::AfterWhitespace)) + { + // This is a function-like macro, so we need to remember that + // and start capturing parameters + macro->flavor = PreprocessorMacroFlavor::FunctionLike; + + AdvanceRawToken(context); + + // If there are any parameters, parse them + if (PeekRawTokenType(context) != TokenType::RParent) + { + for (;;) + { + // TODO: handle elipsis (`...`) for varags + + // A macro parameter name should be a raw identifier + Token paramToken; + if (!ExpectRaw(context, TokenType::Identifier, Diagnostics::expectedTokenInMacroParameters, ¶mToken)) + break; + + // TODO(tfoley): some validation on parameter name. + // Certain names (e.g., `defined` and `__VA_ARGS__` + // are not allowed to be used as macros or parameters). + + // Add the parameter to the macro being deifned + macro->params.Add(paramToken); + + // If we see `)` then we are done with arguments + if (PeekRawTokenType(context) == TokenType::RParent) + break; + + ExpectRaw(context, TokenType::Comma, Diagnostics::expectedTokenInMacroParameters); + } + } + + ExpectRaw(context, TokenType::RParent, Diagnostics::expectedTokenInMacroParameters); + } + } + + // consume tokens until end-of-line + for(;;) + { + Token token = AdvanceRawToken(context); + if( token.Type == TokenType::EndOfDirective ) + { + // Last token on line will be turned into a conceptual end-of-file + // token for the sub-stream that the macro expands into. + token.Type = TokenType::EndOfFile; + macro->tokens.mTokens.Add(token); + break; + } + + // In the ordinary case, we just add the token to the definition + macro->tokens.mTokens.Add(token); + } +} + +// Handle a `#undef` directive +static void HandleUndefDirective(PreprocessorDirectiveContext* context) +{ + Token nameToken; + if (!Expect(context, TokenType::Identifier, Diagnostics::expectedTokenInPreprocessorDirective, &nameToken)) + return; + String name = nameToken.Content; + + PreprocessorEnvironment* env = &context->preprocessor->globalEnv; + PreprocessorMacro* macro = LookupMacro(env, name); + if (macro != NULL) + { + // name was defined, so remove it + env->macros.Remove(name); + + DestroyMacro(context->preprocessor, macro); + } + else + { + // name wasn't defined + GetSink(context)->diagnose(nameToken.Position, Diagnostics::macroNotDefined, name); + } +} + +// Handle a `#warning` directive +static void HandleWarningDirective(PreprocessorDirectiveContext* context) +{ + // TODO: read rest of line without actual tokenization + GetSink(context)->diagnose(GetDirectiveLoc(context), Diagnostics::userDefinedWarning, "user-defined warning"); + SkipToEndOfLine(context); +} + +// Handle a `#error` directive +static void HandleErrorDirective(PreprocessorDirectiveContext* context) +{ + // TODO: read rest of line without actual tokenization + GetSink(context)->diagnose(GetDirectiveLoc(context), Diagnostics::userDefinedError, "user-defined warning"); + SkipToEndOfLine(context); +} + +// Handle a `#line` directive +static void HandleLineDirective(PreprocessorDirectiveContext* context) +{ + int line = 0; + if (PeekTokenType(context) == TokenType::IntLiterial) + { + line = StringToInt(AdvanceToken(context).Content); + } + else if (PeekTokenType(context) == TokenType::Identifier + && PeekToken(context).Content == "default") + { + AdvanceToken(context); + + // Stop overiding soure locations. + context->preprocessor->inputStream->isOverridingSourceLoc = false; + return; + } + else + { + GetSink(context)->diagnose(PeekLoc(context), Diagnostics::expected2TokensInPreprocessorDirective, + TokenType::IntLiterial, + "default", + GetDirectiveName(context)); + context->parseError = true; + return; + } + + CodePosition directiveLoc = GetDirectiveLoc(context); + + String file; + if (PeekTokenType(context) == TokenType::EndOfDirective) + { + file = directiveLoc.FileName; + } + else if (PeekTokenType(context) == TokenType::StringLiterial) + { + file = AdvanceToken(context).Content; + } + else if (PeekTokenType(context) == TokenType::IntLiterial) + { + // Note(tfoley): GLSL allows the "source string" to be indicated by an integer + // TODO(tfoley): Figure out a better way to handle this, if it matters + file = AdvanceToken(context).Content; + } + else + { + Expect(context, TokenType::StringLiterial, Diagnostics::expectedTokenInPreprocessorDirective); + return; + } + + PreprocessorInputStream* inputStream = context->preprocessor->inputStream; + + inputStream->isOverridingSourceLoc = true; + inputStream->overrideFileName = file; + inputStream->overrideLineOffset = line - (directiveLoc.Line + 1); +} + +// Handle a `#pragma` directive +static void HandlePragmaDirective(PreprocessorDirectiveContext* context) +{ + // TODO(tfoley): figure out which pragmas to parse, + // and which to pass along + SkipToEndOfLine(context); +} + +// Handle a `#version` directive +static void handleGLSLVersionDirective(PreprocessorDirectiveContext* context) +{ + Token versionNumberToken; + if(!ExpectRaw( + context, + TokenType::IntLiterial, + Diagnostics::expectedTokenInPreprocessorDirective, + &versionNumberToken)) + { + return; + } + + Token glslProfileToken; + if(PeekTokenType(context) == TokenType::Identifier) + { + glslProfileToken = AdvanceToken(context); + } + + // Need to construct a representation taht we can hook into our compilation result + + auto modifier = new GLSLVersionDirective(); + modifier->versionNumberToken = versionNumberToken; + modifier->glslProfileToken = glslProfileToken; + + // Attach the modifier to the program we are parsing! + + addModifier( + context->preprocessor->syntax, + modifier); +} + +// Handle a `#extension` directive, e.g., +// +// #extension some_extension_name : enable +// +static void handleGLSLExtensionDirective(PreprocessorDirectiveContext* context) +{ + Token extensionNameToken; + if(!ExpectRaw( + context, + TokenType::Identifier, + Diagnostics::expectedTokenInPreprocessorDirective, + &extensionNameToken)) + { + return; + } + + if( !ExpectRaw(context, TokenType::Colon, Diagnostics::expectedTokenInPreprocessorDirective) ) + { + return; + } + + Token dispositionToken; + if(!ExpectRaw( + context, + TokenType::Identifier, + Diagnostics::expectedTokenInPreprocessorDirective, + &dispositionToken)) + { + return; + } + + // Need to construct a representation taht we can hook into our compilation result + + auto modifier = new GLSLExtensionDirective(); + modifier->extensionNameToken = extensionNameToken; + modifier->dispositionToken = dispositionToken; + + // Attach the modifier to the program we are parsing! + + addModifier( + context->preprocessor->syntax, + modifier); +} + +// Handle an invalid directive +static void HandleInvalidDirective(PreprocessorDirectiveContext* context) +{ + GetSink(context)->diagnose(GetDirectiveLoc(context), Diagnostics::unknownPreprocessorDirective, GetDirectiveName(context)); + SkipToEndOfLine(context); +} + +// Callback interface used by preprocessor directives +typedef void (*PreprocessorDirectiveCallback)(PreprocessorDirectiveContext* context); + +enum PreprocessorDirectiveFlag : unsigned int +{ + // Should this directive be handled even when skipping disbaled code? + ProcessWhenSkipping = 1 << 0, +}; + +// Information about a specific directive +struct PreprocessorDirective +{ + // Name of the directive + char const* name; + + // Callback to handle the directive + PreprocessorDirectiveCallback callback; + + unsigned int flags; +}; + +// A simple array of all the directives we know how to handle. +// TODO(tfoley): considering making this into a real hash map, +// and then make it easy-ish for users of the codebase to add +// their own directives as desired. +static const PreprocessorDirective kDirectives[] = +{ + { "if", &HandleIfDirective, ProcessWhenSkipping }, + { "ifdef", &HandleIfDefDirective, ProcessWhenSkipping }, + { "ifndef", &HandleIfNDefDirective, ProcessWhenSkipping }, + { "else", &HandleElseDirective, ProcessWhenSkipping }, + { "elif", &HandleElifDirective, ProcessWhenSkipping }, + { "endif", &HandleEndIfDirective, ProcessWhenSkipping }, + + { "include", &HandleIncludeDirective, 0 }, + { "define", &HandleDefineDirective, 0 }, + { "undef", &HandleUndefDirective, 0 }, + { "warning", &HandleWarningDirective, 0 }, + { "error", &HandleErrorDirective, 0 }, + { "line", &HandleLineDirective, 0 }, + { "pragma", &HandlePragmaDirective, 0 }, + + // TODO(tfoley): These are specific to GLSL, and probably + // shouldn't be enabled for HLSL or Slang + { "version", &handleGLSLVersionDirective, 0 }, + { "extension", &handleGLSLExtensionDirective, 0 }, + + { NULL, NULL }, +}; + +static const PreprocessorDirective kInvalidDirective = { + NULL, &HandleInvalidDirective, 0, +}; + +// Look up the directive with the given name. +static PreprocessorDirective const* FindDirective(String const& name) +{ + char const* nameStr = name.Buffer(); + for (int ii = 0; kDirectives[ii].name; ++ii) + { + if (strcmp(kDirectives[ii].name, nameStr) != 0) + continue; + + return &kDirectives[ii]; + } + + return &kInvalidDirective; +} + +// Process a directive, where the preprocessor has already consumed the +// `#` token that started the directive line. +static void HandleDirective(PreprocessorDirectiveContext* context) +{ + // Try to read the directive name. + context->directiveToken = PeekRawToken(context); + + TokenType directiveTokenType = GetDirective(context).Type; + + // An empty directive is allowed, and ignored. + if (directiveTokenType == TokenType::EndOfDirective) + { + return; + } + // Otherwise the directive name had better be an identifier + else if (directiveTokenType != TokenType::Identifier) + { + GetSink(context)->diagnose(GetDirectiveLoc(context), Diagnostics::expectedPreprocessorDirectiveName); + SkipToEndOfLine(context); + return; + } + + // Consume the directive name token. + AdvanceRawToken(context); + + // Look up the handler for the directive. + PreprocessorDirective const* directive = FindDirective(GetDirectiveName(context)); + + // If we are skipping disabled code, and the directive is not one + // of the small number that need to run even in that case, skip it. + if (IsSkipping(context) && !(directive->flags & PreprocessorDirectiveFlag::ProcessWhenSkipping)) + { + SkipToEndOfLine(context); + return; + } + + // Apply the directive-specific callback + (directive->callback)(context); + + // We expect the directive callback to consume the entire line, so if + // it hasn't that is a parse error. + expectEndOfDirective(context); +} + +// Read one token using the full preprocessor, with all its behaviors. +static Token ReadToken(Preprocessor* preprocessor) +{ + for (;;) + { + // Look at the next raw token in the input. + Token const& token = PeekRawToken(preprocessor); + + // If we have a directive (`#` at start of line) then handle it + if ((token.Type == TokenType::Pound) && (token.flags & TokenFlag::AtStartOfLine)) + { + // Skip the `#` + AdvanceRawToken(preprocessor); + + // Create a context for parsing the directive + PreprocessorDirectiveContext directiveContext; + directiveContext.preprocessor = preprocessor; + directiveContext.parseError = false; + directiveContext.haveDoneEndOfDirectiveChecks = false; + + // Parse and handle the directive + HandleDirective(&directiveContext); + continue; + } + + // otherwise, if we are currently in a skipping mode, then skip tokens + if (IsSkipping(preprocessor)) + { + AdvanceRawToken(preprocessor); + continue; + } + + // otherwise read a token, which may involve macro expansion + return AdvanceToken(preprocessor); + } +} + +// intialize a preprocessor context, using the given sink for errros +static void InitializePreprocessor( + Preprocessor* preprocessor, + DiagnosticSink* sink) +{ + preprocessor->sink = sink; + preprocessor->includeHandler = NULL; + preprocessor->endOfFileToken.Type = TokenType::EndOfFile; + preprocessor->endOfFileToken.flags = TokenFlag::AtStartOfLine; +} + +// clean up after an environment +PreprocessorEnvironment::~PreprocessorEnvironment() +{ + for (auto pair : this->macros) + { + DestroyMacro(NULL, pair.Value); + } +} + +// finalize a preprocessor and free any memory still in use +static void FinalizePreprocessor( + Preprocessor* preprocessor) +{ + // Clear out any waiting input streams + PreprocessorInputStream* input = preprocessor->inputStream; + while (input) + { + PreprocessorInputStream* parent = input->parent; + DestroyInputStream(preprocessor, input); + input = parent; + } + +#if 0 + // clean up any macros that were allocated + for (auto pair : preprocessor->globalEnv.macros) + { + DestroyMacro(preprocessor, pair.Value); + } +#endif +} + +// Add a simple macro definition from a string (e.g., for a +// `-D` option passed on the command line +static void DefineMacro( + Preprocessor* preprocessor, + String const& key, + String const& value) +{ + String fileName = "command line"; + PreprocessorMacro* macro = CreateMacro(preprocessor); + + // Use existing `Lexer` to generate a token stream. + Lexer lexer(fileName, value, GetSink(preprocessor)); + macro->tokens = lexer.lexAllTokens(); + macro->nameToken = Token(TokenType::Identifier, key, 0, 0, 0, fileName); + + PreprocessorMacro* oldMacro = NULL; + if (preprocessor->globalEnv.macros.TryGetValue(key, oldMacro)) + { + DestroyMacro(preprocessor, oldMacro); + } + + preprocessor->globalEnv.macros[key] = macro; +} + +// read the entire input into tokens +static TokenList ReadAllTokens( + Preprocessor* preprocessor) +{ + TokenList tokens; + for (;;) + { + Token token = ReadToken(preprocessor); + + tokens.mTokens.Add(token); + + // Note: we include the EOF token in the list, + // since that is expected by the `TokenList` type. + if (token.Type == TokenType::EndOfFile) + break; + } + return tokens; +} + +TokenList preprocessSource( + CoreLib::String const& source, + CoreLib::String const& fileName, + DiagnosticSink* sink, + IncludeHandler* includeHandler, + CoreLib::Dictionary defines, + ProgramSyntaxNode* syntax) +{ + Preprocessor preprocessor; + InitializePreprocessor(&preprocessor, sink); + preprocessor.syntax = syntax; + + preprocessor.includeHandler = includeHandler; + for (auto p : defines) + { + DefineMacro(&preprocessor, p.Key, p.Value); + } + + // create an initial input stream based on the provided buffer + preprocessor.inputStream = CreateInputStreamForSource(&preprocessor, source, fileName); + + TokenList tokens = ReadAllTokens(&preprocessor); + + FinalizePreprocessor(&preprocessor); + + // debugging: build the pre-processed source back together +#if 0 + StringBuilder sb; + for (auto t : tokens) + { + if (t.flags & TokenFlag::AtStartOfLine) + { + sb << "\n"; + } + else if (t.flags & TokenFlag::AfterWhitespace) + { + sb << " "; + } + + sb << t.Content; + } + + String s = sb.ProduceString(); +#endif + + return tokens; +} + +}} diff --git a/source/slang/preprocessor.h b/source/slang/preprocessor.h new file mode 100644 index 000000000..ab72f3f87 --- /dev/null +++ b/source/slang/preprocessor.h @@ -0,0 +1,35 @@ +// Preprocessor.h +#ifndef SLANG_PREPROCESSOR_H_INCLUDED +#define SLANG_PREPROCESSOR_H_INCLUDED + +#include "../core/basic.h" +#include "../slang/lexer.h" + +namespace Slang{ namespace Compiler { + +class DiagnosticSink; +class ProgramSyntaxNode; + +// Callback interface for the preprocessor to use when looking +// for files in `#include` directives. +struct IncludeHandler +{ + virtual bool TryToFindIncludeFile( + CoreLib::String const& pathToInclude, + CoreLib::String const& pathIncludedFrom, + CoreLib::String* outFoundPath, + CoreLib::String* outFoundSource) = 0; +}; + +// Take a string of source code and preprocess it into a list of tokens. +TokenList preprocessSource( + CoreLib::String const& source, + CoreLib::String const& fileName, + DiagnosticSink* sink, + IncludeHandler* includeHandler, + CoreLib::Dictionary defines, + ProgramSyntaxNode* syntax); + +}} + +#endif diff --git a/source/slang/profile-defs.h b/source/slang/profile-defs.h new file mode 100644 index 000000000..76ba476bb --- /dev/null +++ b/source/slang/profile-defs.h @@ -0,0 +1,123 @@ +// + +// Define all the various language "profiles" we want to support. + +#ifndef LANGUAGE +#define LANGUAGE(TAG, NAME) /* emptry */ +#endif + +#ifndef LANGUAGE_ALIAS +#define LANGUAGE_ALIAS(TAG, NAME) /* empty */ +#endif + +#ifndef PROFILE_FAMILY +#define PROFILE_FAMILY(TAG) /* empty */ +#endif + +#ifndef PROFILE_VERSION +#define PROFILE_VERSION(TAG, FAMILY) /* empty */ +#endif + +#ifndef PROFILE_STAGE +#define PROFILE_STAGE(TAG, NAME, VAL) /* empty */ +#endif + +#ifndef PROFILE_STAGE_ALIAS +#define PROFILE_STAGE_ALIAS(TAG, NAME) /* empty */ +#endif + + +#ifndef PROFILE +#define PROFILE(TAG, NAME, STAGE, VERSION) /* empty */ +#endif + +#ifndef PROFILE_ALIAS +#define PROFILE_ALIAS(TAG, NAME) /* empty */ +#endif + +// Source and destination languages + +LANGUAGE(HLSL, hlsl) +LANGUAGE(DXBytecode, dxbc) +LANGUAGE(DXBytecodeAssembly,dxbc_asm) +LANGUAGE(DXIL, dxil) +LANGUAGE(DXILAssembly, dxil_asm) +LANGUAGE(GLSL, glsl) +LANGUAGE(GLSL_ES, glsl_es) +LANGUAGE(GLSL_VK, glsl_vk) +LANGUAGE(SPIRV, spirv) +LANGUAGE(SPIRV_GL, spirv_gl) + +LANGUAGE_ALIAS(GLSL, glsl_gl) +LANGUAGE_ALIAS(SPIRV, spirv_vk) + + +// Pipeline stages to target +PROFILE_STAGE(Vertex, vertex, SLANG_STAGE_VERTEX) +PROFILE_STAGE(Hull, hull, SLANG_STAGE_HULL) +PROFILE_STAGE(Domain, domain, SLANG_STAGE_DOMAIN) +PROFILE_STAGE(Geometry, geometry, SLANG_STAGE_GEOMETRY) +PROFILE_STAGE(Fragment, fragment, SLANG_STAGE_FRAGMENT) +PROFILE_STAGE(Compute, compute, SLANG_STAGE_COMPUTE) + +PROFILE_STAGE_ALIAS(Fragment, pixel) + +// Profile families + +PROFILE_FAMILY(DX) +PROFILE_FAMILY(GLSL) +PROFILE_FAMILY(SPRIV) + +// Profile versions + + +PROFILE_VERSION(DX_4_0, DX) +PROFILE_VERSION(DX_4_0_Level_9_0, DX) +PROFILE_VERSION(DX_4_0_Level_9_1, DX) +PROFILE_VERSION(DX_4_0_Level_9_3, DX) +PROFILE_VERSION(DX_4_1, DX) +PROFILE_VERSION(DX_5_0, DX) + +PROFILE_VERSION(GLSL, GLSL) + + +// Specific profiles + +PROFILE(DX_Compute_4_0, cs_4_0, Compute, DX_4_0) +PROFILE(DX_Compute_4_1, cs_4_1, Compute, DX_4_1) +PROFILE(DX_Compute_5_0, cs_5_0, Compute, DX_5_0) +PROFILE(DX_Domain_5_0, ds_5_0, Domain, DX_5_0) +PROFILE(DX_Geometry_4_0, gs_4_0, Geometry, DX_4_0) +PROFILE(DX_Geometry_4_1, gs_4_1, Geometry, DX_4_1) +PROFILE(DX_Geometry_5_0, gs_5_0, Geometry, DX_5_0) +PROFILE(DX_Hull_5_0, hs_5_0, Hull, DX_5_0) +PROFILE(DX_Fragment_4_0, ps_4_0, Fragment, DX_4_0) +PROFILE(DX_Fragment_4_0_Level_9_0, ps_4_0_level_9_0, Fragment, DX_4_0_Level_9_0) +PROFILE(DX_Fragment_4_0_Level_9_1, ps_4_0_level_9_1, Fragment, DX_4_0_Level_9_1) +PROFILE(DX_Fragment_4_0_Level_9_3, ps_4_0_level_9_3, Fragment, DX_4_0_Level_9_3) +PROFILE(DX_Fragment_4_1, ps_4_1, Fragment, DX_4_1) +PROFILE(DX_Fragment_5_0, ps_5_0, Fragment, DX_5_0) +PROFILE(DX_Vertex_4_0, vs_4_0, Vertex, DX_4_0) +PROFILE(DX_Vertex_4_0_Level_9_0, vs_4_0_level_9_0, Vertex, DX_4_0_Level_9_0) +PROFILE(DX_Vertex_4_0_Level_9_1, vs_4_0_level_9_1, Vertex, DX_4_0_Level_9_1) +PROFILE(DX_Vertex_4_0_Level_9_3, vs_4_0_level_9_3, Vertex, DX_4_0_Level_9_3) +PROFILE(DX_Vertex_4_1, vs_4_1, Vertex, DX_4_1) +PROFILE(DX_Vertex_5_0, vs_5_0, Vertex, DX_5_0) + +// + +PROFILE(GLSL_Compute, glsl_compute, Compute, GLSL) +PROFILE(GLSL_Vertex, glsl_vertex, Vertex, GLSL) +PROFILE(GLSL_Fragment, glsl_fragment, Fragment, GLSL) +PROFILE(GLSL_Geometry, glsl_geometry, Geometry, GLSL) +PROFILE(GLSL_TessControl, glsl_tess_control, Hull, GLSL) +PROFILE(GLSL_TessEval, glsl_tess_eval, Domain, GLSL) + +#undef LANGUAGE +#undef LANGUAGE_ALIAS +#undef PROFILE_FAMILY +#undef PROFILE_VERSION +#undef PROFILE_STAGE +#undef PROFILE_STAGE_ALIAS +#undef PROFILE +#undef PROFILE_ALIAS diff --git a/source/slang/profile.cpp b/source/slang/profile.cpp new file mode 100644 index 000000000..923dc2841 --- /dev/null +++ b/source/slang/profile.cpp @@ -0,0 +1,20 @@ +// profile.cpp +#include "Profile.h" + + +namespace Slang { +namespace Compiler { + + +ProfileFamily getProfileFamily(ProfileVersion version) +{ + switch( version ) + { + default: return ProfileFamily::Unknown; + +#define PROFILE_VERSION(TAG, FAMILY) case ProfileVersion::TAG: return ProfileFamily::FAMILY; +#include "profile-defs.h" + } +} + +}} diff --git a/source/slang/profile.h b/source/slang/profile.h new file mode 100644 index 000000000..31465c38c --- /dev/null +++ b/source/slang/profile.h @@ -0,0 +1,84 @@ +#ifndef SLANG_PROFILE_H_INCLUDED +#define SLANG_PROFILE_H_INCLUDED + +#include "../core/basic.h" +#include "../../slang.h" + +namespace Slang +{ + namespace Compiler + { + // Flavors of translation unit + enum class SourceLanguage : SlangSourceLanguage + { + Unknown = SLANG_SOURCE_LANGUAGE_UNKNOWN, // should not occur + Slang = SLANG_SOURCE_LANGUAGE_SLANG, + HLSL = SLANG_SOURCE_LANGUAGE_HLSL, + GLSL = SLANG_SOURCE_LANGUAGE_GLSL, + + // A separate PACKAGE of Slang code that has been imported + ImportedSlangCode, + }; + + // TODO(tfoley): This should merge with the above... + enum class Language + { + Unknown, +#define LANGUAGE(TAG, NAME) TAG, +#include "profile-defs.h" + }; + + enum class ProfileFamily + { + Unknown, +#define PROFILE_FAMILY(TAG) TAG, +#include "profile-defs.h" + }; + + enum class ProfileVersion + { + Unknown, +#define PROFILE_VERSION(TAG, FAMILY) TAG, +#include "profile-defs.h" + }; + + enum class Stage : SlangStage + { + Unknown = SLANG_STAGE_NONE, +#define PROFILE_STAGE(TAG, NAME, VAL) TAG = VAL, +#include "profile-defs.h" + }; + + ProfileFamily getProfileFamily(ProfileVersion version); + + struct Profile + { + typedef uint32_t RawVal; + enum : RawVal + { + Unknown, + +#define PROFILE(TAG, NAME, STAGE, VERSION) TAG = (uint32_t(Stage::STAGE) << 16) | uint32_t(ProfileVersion::VERSION), +#include "profile-defs.h" + }; + + Profile() {} + Profile(RawVal raw) + : raw(raw) + {} + + bool operator==(Profile const& other) const { return raw == other.raw; } + bool operator!=(Profile const& other) const { return raw != other.raw; } + + Stage GetStage() const { return Stage((uint32_t(raw) >> 16) & 0xFFFF); } + ProfileVersion GetVersion() const { return ProfileVersion(uint32_t(raw) & 0xFFFF); } + ProfileFamily getFamily() const { return getProfileFamily(GetVersion()); } + + static Profile LookUp(char const* name); + + RawVal raw = Unknown; + }; + } +} + +#endif diff --git a/source/slang/reflection.cpp b/source/slang/reflection.cpp new file mode 100644 index 000000000..1a56a8c1f --- /dev/null +++ b/source/slang/reflection.cpp @@ -0,0 +1,1404 @@ +// reflection.cpp +#include "reflection.h" + +#include "compiler.h" +#include "type-layout.h" + +#include + +// Implementation to back public-facing reflection API + +using namespace Slang; +using namespace Slang::Compiler; + + +// Conversion routines to help with strongly-typed reflection API + +static inline ExpressionType* convert(SlangReflectionType* type) +{ + return (ExpressionType*) type; +} + +static inline SlangReflectionType* convert(ExpressionType* type) +{ + return (SlangReflectionType*) type; +} + +static inline TypeLayout* convert(SlangReflectionTypeLayout* type) +{ + return (TypeLayout*) type; +} + +static inline SlangReflectionTypeLayout* convert(TypeLayout* type) +{ + return (SlangReflectionTypeLayout*) type; +} + +static inline VarDeclBase* convert(SlangReflectionVariable* var) +{ + return (VarDeclBase*) var; +} + +static inline SlangReflectionVariable* convert(VarDeclBase* var) +{ + return (SlangReflectionVariable*) var; +} + +static inline VarLayout* convert(SlangReflectionVariableLayout* var) +{ + return (VarLayout*) var; +} + +static inline SlangReflectionVariableLayout* convert(VarLayout* var) +{ + return (SlangReflectionVariableLayout*) var; +} + +static inline EntryPointLayout* convert(SlangReflectionEntryPoint* entryPoint) +{ + return (EntryPointLayout*) entryPoint; +} + +static inline SlangReflectionEntryPoint* convert(EntryPointLayout* entryPoint) +{ + return (SlangReflectionEntryPoint*) entryPoint; +} + + +static inline ProgramLayout* convert(SlangReflection* program) +{ + return (ProgramLayout*) program; +} + +static inline SlangReflection* convert(ProgramLayout* program) +{ + return (SlangReflection*) program; +} + +// Type Reflection + + +SLANG_API SlangTypeKind spReflectionType_GetKind(SlangReflectionType* inType) +{ + auto type = convert(inType); + if(!type) return SLANG_TYPE_KIND_NONE; + + // TODO(tfoley: Don't emit the same type more than once... + + if (auto basicType = type->As()) + { + return SLANG_TYPE_KIND_SCALAR; + } + else if (auto vectorType = type->As()) + { + return SLANG_TYPE_KIND_VECTOR; + } + else if (auto matrixType = type->As()) + { + return SLANG_TYPE_KIND_MATRIX; + } + else if (auto constantBufferType = type->As()) + { + return SLANG_TYPE_KIND_CONSTANT_BUFFER; + } + else if (auto samplerStateType = type->As()) + { + return SLANG_TYPE_KIND_SAMPLER_STATE; + } + else if (auto textureType = type->As()) + { + return SLANG_TYPE_KIND_RESOURCE; + } + + // TODO: need a better way to handle this stuff... +#define CASE(TYPE) \ + else if(type->As()) do { \ + return SLANG_TYPE_KIND_RESOURCE; \ + } while(0) + + CASE(HLSLBufferType); + CASE(HLSLRWBufferType); + CASE(HLSLBufferType); + CASE(HLSLRWBufferType); + CASE(HLSLStructuredBufferType); + CASE(HLSLRWStructuredBufferType); + CASE(HLSLAppendStructuredBufferType); + CASE(HLSLConsumeStructuredBufferType); + CASE(HLSLByteAddressBufferType); + CASE(HLSLRWByteAddressBufferType); + CASE(UntypedBufferResourceType); +#undef CASE + + else if (auto arrayType = type->As()) + { + return SLANG_TYPE_KIND_ARRAY; + } + else if( auto declRefType = type->As() ) + { + auto declRef = declRefType->declRef; + if( auto structDeclRef = declRef.As() ) + { + return SLANG_TYPE_KIND_STRUCT; + } + } + + assert(!"unexpected"); + return SLANG_TYPE_KIND_NONE; +} + +SLANG_API unsigned int spReflectionType_GetFieldCount(SlangReflectionType* inType) +{ + auto type = convert(inType); + if(!type) return 0; + + // TODO: maybe filter based on kind + + if(auto declRefType = dynamic_cast(type)) + { + auto declRef = declRefType->declRef; + if( auto structDeclRef = declRef.As()) + { + return structDeclRef.GetFields().Count(); + } + } + + return 0; +} + +SLANG_API SlangReflectionVariable* spReflectionType_GetFieldByIndex(SlangReflectionType* inType, unsigned index) +{ + auto type = convert(inType); + if(!type) return nullptr; + + // TODO: maybe filter based on kind + + if(auto declRefType = dynamic_cast(type)) + { + auto declRef = declRefType->declRef; + if( auto structDeclRef = declRef.As()) + { + auto fieldDeclRef = structDeclRef.GetFields().ToArray()[index]; + return (SlangReflectionVariable*) fieldDeclRef.GetDecl(); + } + } + + return nullptr; +} + +SLANG_API size_t spReflectionType_GetElementCount(SlangReflectionType* inType) +{ + auto type = convert(inType); + if(!type) return 0; + + if(auto arrayType = dynamic_cast(type)) + { + return GetIntVal(arrayType->ArrayLength); + } + else if( auto vectorType = dynamic_cast(type)) + { + return GetIntVal(vectorType->elementCount); + } + + return 0; +} + +SLANG_API SlangReflectionType* spReflectionType_GetElementType(SlangReflectionType* inType) +{ + auto type = convert(inType); + if(!type) return nullptr; + + if(auto arrayType = dynamic_cast(type)) + { + return (SlangReflectionType*) arrayType->BaseType.Ptr(); + } + else if( auto constantBufferType = dynamic_cast(type)) + { + return convert(constantBufferType->elementType.Ptr()); + } + else if( auto vectorType = dynamic_cast(type)) + { + return convert(vectorType->elementType.Ptr()); + } + else if( auto matrixType = dynamic_cast(type)) + { + return convert(matrixType->getElementType()); + } + + return nullptr; +} + +SLANG_API unsigned int spReflectionType_GetRowCount(SlangReflectionType* inType) +{ + auto type = convert(inType); + if(!type) return 0; + + if(auto matrixType = dynamic_cast(type)) + { + return GetIntVal(matrixType->getRowCount()); + } + else if(auto vectorType = dynamic_cast(type)) + { + return 1; + } + else if( auto basicType = dynamic_cast(type) ) + { + return 1; + } + + return 0; +} + +SLANG_API unsigned int spReflectionType_GetColumnCount(SlangReflectionType* inType) +{ + auto type = convert(inType); + if(!type) return 0; + + if(auto matrixType = dynamic_cast(type)) + { + return GetIntVal(matrixType->getColumnCount()); + } + else if(auto vectorType = dynamic_cast(type)) + { + return GetIntVal(vectorType->elementCount); + } + else if( auto basicType = dynamic_cast(type) ) + { + return 1; + } + + return 0; +} + +SLANG_API SlangScalarType spReflectionType_GetScalarType(SlangReflectionType* inType) +{ + auto type = convert(inType); + if(!type) return 0; + + if(auto matrixType = dynamic_cast(type)) + { + type = matrixType->getElementType(); + } + else if(auto vectorType = dynamic_cast(type)) + { + type = vectorType->elementType.Ptr(); + } + + if(auto basicType = dynamic_cast(type)) + { + switch (basicType->BaseType) + { +#define CASE(BASE, TAG) \ + case BaseType::BASE: return SLANG_SCALAR_TYPE_##TAG + + CASE(Void, VOID); + CASE(Int, INT32); + CASE(Float, FLOAT32); + CASE(UInt, UINT32); + CASE(Bool, BOOL); + CASE(UInt64, UINT64); + +#undef CASE + + default: + assert(!"unexpected"); + return SLANG_SCALAR_TYPE_NONE; + break; + } + } + + return SLANG_SCALAR_TYPE_NONE; +} + +SLANG_API SlangResourceShape spReflectionType_GetResourceShape(SlangReflectionType* inType) +{ + auto type = convert(inType); + if(!type) return 0; + + while(auto arrayType = type->As()) + { + type = arrayType->BaseType.Ptr(); + } + + if(auto textureType = type->As()) + { + return textureType->getShape(); + } + + // TODO: need a better way to handle this stuff... +#define CASE(TYPE, SHAPE, ACCESS) \ + else if(type->As()) do { \ + return SHAPE; \ + } while(0) + + CASE(HLSLBufferType, SLANG_TEXTURE_BUFFER, SLANG_RESOURCE_ACCESS_READ); + CASE(HLSLRWBufferType, SLANG_TEXTURE_BUFFER, SLANG_RESOURCE_ACCESS_READ_WRITE); + CASE(HLSLBufferType, SLANG_TEXTURE_BUFFER, SLANG_RESOURCE_ACCESS_READ); + CASE(HLSLRWBufferType, SLANG_TEXTURE_BUFFER, SLANG_RESOURCE_ACCESS_READ_WRITE); + CASE(HLSLStructuredBufferType, SLANG_STRUCTURED_BUFFER, SLANG_RESOURCE_ACCESS_READ); + CASE(HLSLRWStructuredBufferType, SLANG_STRUCTURED_BUFFER, SLANG_RESOURCE_ACCESS_READ_WRITE); + CASE(HLSLAppendStructuredBufferType, SLANG_STRUCTURED_BUFFER, SLANG_RESOURCE_ACCESS_APPEND); + CASE(HLSLConsumeStructuredBufferType, SLANG_STRUCTURED_BUFFER, SLANG_RESOURCE_ACCESS_CONSUME); + CASE(HLSLByteAddressBufferType, SLANG_BYTE_ADDRESS_BUFFER, SLANG_RESOURCE_ACCESS_READ); + CASE(HLSLRWByteAddressBufferType, SLANG_BYTE_ADDRESS_BUFFER, SLANG_RESOURCE_ACCESS_READ_WRITE); + CASE(UntypedBufferResourceType, SLANG_BYTE_ADDRESS_BUFFER, SLANG_RESOURCE_ACCESS_READ); +#undef CASE + + return SLANG_RESOURCE_NONE; +} + +SLANG_API SlangResourceAccess spReflectionType_GetResourceAccess(SlangReflectionType* inType) +{ + auto type = convert(inType); + if(!type) return 0; + + while(auto arrayType = type->As()) + { + type = arrayType->BaseType.Ptr(); + } + + if(auto textureType = type->As()) + { + return textureType->getAccess(); + } + + // TODO: need a better way to handle this stuff... +#define CASE(TYPE, SHAPE, ACCESS) \ + else if(type->As()) do { \ + return ACCESS; \ + } while(0) + + CASE(HLSLBufferType, SLANG_TEXTURE_BUFFER, SLANG_RESOURCE_ACCESS_READ); + CASE(HLSLRWBufferType, SLANG_TEXTURE_BUFFER, SLANG_RESOURCE_ACCESS_READ_WRITE); + CASE(HLSLBufferType, SLANG_TEXTURE_BUFFER, SLANG_RESOURCE_ACCESS_READ); + CASE(HLSLRWBufferType, SLANG_TEXTURE_BUFFER, SLANG_RESOURCE_ACCESS_READ_WRITE); + CASE(HLSLStructuredBufferType, SLANG_STRUCTURED_BUFFER, SLANG_RESOURCE_ACCESS_READ); + CASE(HLSLRWStructuredBufferType, SLANG_STRUCTURED_BUFFER, SLANG_RESOURCE_ACCESS_READ_WRITE); + CASE(HLSLAppendStructuredBufferType, SLANG_STRUCTURED_BUFFER, SLANG_RESOURCE_ACCESS_APPEND); + CASE(HLSLConsumeStructuredBufferType, SLANG_STRUCTURED_BUFFER, SLANG_RESOURCE_ACCESS_CONSUME); + CASE(HLSLByteAddressBufferType, SLANG_BYTE_ADDRESS_BUFFER, SLANG_RESOURCE_ACCESS_READ); + CASE(HLSLRWByteAddressBufferType, SLANG_BYTE_ADDRESS_BUFFER, SLANG_RESOURCE_ACCESS_READ_WRITE); + CASE(UntypedBufferResourceType, SLANG_BYTE_ADDRESS_BUFFER, SLANG_RESOURCE_ACCESS_READ); +#undef CASE + + return SLANG_RESOURCE_ACCESS_NONE; +} + +SLANG_API SlangReflectionType* spReflectionType_GetResourceResultType(SlangReflectionType* inType) +{ + auto type = convert(inType); + if(!type) return nullptr; + + while(auto arrayType = type->As()) + { + type = arrayType->BaseType.Ptr(); + } + + if (auto textureType = type->As()) + { + return convert(textureType->elementType.Ptr()); + } + + // TODO: need a better way to handle this stuff... +#define CASE(TYPE, SHAPE, ACCESS) \ + else if(type->As()) do { \ + return convert(type->As()->elementType.Ptr()); \ + } while(0) + + CASE(HLSLBufferType, SLANG_TEXTURE_BUFFER, SLANG_RESOURCE_ACCESS_READ); + CASE(HLSLRWBufferType, SLANG_TEXTURE_BUFFER, SLANG_RESOURCE_ACCESS_READ_WRITE); + CASE(HLSLBufferType, SLANG_TEXTURE_BUFFER, SLANG_RESOURCE_ACCESS_READ); + CASE(HLSLRWBufferType, SLANG_TEXTURE_BUFFER, SLANG_RESOURCE_ACCESS_READ_WRITE); + + // TODO: structured buffer needs to expose type layout! + + CASE(HLSLStructuredBufferType, SLANG_STRUCTURED_BUFFER, SLANG_RESOURCE_ACCESS_READ); + CASE(HLSLRWStructuredBufferType, SLANG_STRUCTURED_BUFFER, SLANG_RESOURCE_ACCESS_READ_WRITE); + CASE(HLSLAppendStructuredBufferType, SLANG_STRUCTURED_BUFFER, SLANG_RESOURCE_ACCESS_APPEND); + CASE(HLSLConsumeStructuredBufferType, SLANG_STRUCTURED_BUFFER, SLANG_RESOURCE_ACCESS_CONSUME); +#undef CASE + + return nullptr; +} + +// Type Layout Reflection + +SLANG_API SlangReflectionType* spReflectionTypeLayout_GetType(SlangReflectionTypeLayout* inTypeLayout) +{ + auto typeLayout = convert(inTypeLayout); + if(!typeLayout) return nullptr; + + return (SlangReflectionType*) typeLayout->type.Ptr(); +} + +SLANG_API size_t spReflectionTypeLayout_GetSize(SlangReflectionTypeLayout* inTypeLayout, SlangParameterCategory category) +{ + auto typeLayout = convert(inTypeLayout); + if(!typeLayout) return 0; + + auto info = typeLayout->FindResourceInfo(LayoutResourceKind(category)); + if(!info) return 0; + + return info->count; +} + +SLANG_API SlangReflectionVariableLayout* spReflectionTypeLayout_GetFieldByIndex(SlangReflectionTypeLayout* inTypeLayout, unsigned index) +{ + auto typeLayout = convert(inTypeLayout); + if(!typeLayout) return nullptr; + + if(auto structTypeLayout = dynamic_cast(typeLayout)) + { + return (SlangReflectionVariableLayout*) structTypeLayout->fields[index].Ptr(); + } + + return nullptr; +} + +SLANG_API size_t spReflectionTypeLayout_GetElementStride(SlangReflectionTypeLayout* inTypeLayout, SlangParameterCategory category) +{ + auto typeLayout = convert(inTypeLayout); + if(!typeLayout) return 0; + + if( auto arrayTypeLayout = dynamic_cast(typeLayout)) + { + if(category == SLANG_PARAMETER_CATEGORY_UNIFORM) + { + return arrayTypeLayout->uniformStride; + } + else + { + auto elementTypeLayout = arrayTypeLayout->elementTypeLayout; + auto info = elementTypeLayout->FindResourceInfo(LayoutResourceKind(category)); + if(!info) return 0; + return info->count; + } + } + + return 0; +} + +SLANG_API SlangReflectionTypeLayout* spReflectionTypeLayout_GetElementTypeLayout(SlangReflectionTypeLayout* inTypeLayout) +{ + auto typeLayout = convert(inTypeLayout); + if(!typeLayout) return nullptr; + + if( auto arrayTypeLayout = dynamic_cast(typeLayout)) + { + return (SlangReflectionTypeLayout*) arrayTypeLayout->elementTypeLayout.Ptr(); + } + else if( auto constantBufferTypeLayout = dynamic_cast(typeLayout)) + { + return convert(constantBufferTypeLayout->elementTypeLayout.Ptr()); + } + else if( auto structuredBufferTypeLayout = dynamic_cast(typeLayout)) + { + return convert(structuredBufferTypeLayout->elementTypeLayout.Ptr()); + } + + return nullptr; +} + +static SlangParameterCategory getParameterCategory( + LayoutResourceKind kind) +{ + return SlangParameterCategory(kind); +} + +static SlangParameterCategory getParameterCategory( + TypeLayout* typeLayout) +{ + auto resourceInfoCount = typeLayout->resourceInfos.Count(); + if(resourceInfoCount == 1) + { + return getParameterCategory(typeLayout->resourceInfos[0].kind); + } + else if(resourceInfoCount == 0) + { + // TODO: can this ever happen? + return SLANG_PARAMETER_CATEGORY_NONE; + } + return SLANG_PARAMETER_CATEGORY_MIXED; +} + +SLANG_API SlangParameterCategory spReflectionTypeLayout_GetParameterCategory(SlangReflectionTypeLayout* inTypeLayout) +{ + auto typeLayout = convert(inTypeLayout); + if(!typeLayout) return SLANG_PARAMETER_CATEGORY_NONE; + + return getParameterCategory(typeLayout); +} + +SLANG_API unsigned spReflectionTypeLayout_GetCategoryCount(SlangReflectionTypeLayout* inTypeLayout) +{ + auto typeLayout = convert(inTypeLayout); + if(!typeLayout) return 0; + + return (unsigned) typeLayout->resourceInfos.Count(); +} + +SLANG_API SlangParameterCategory spReflectionTypeLayout_GetCategoryByIndex(SlangReflectionTypeLayout* inTypeLayout, unsigned index) +{ + auto typeLayout = convert(inTypeLayout); + if(!typeLayout) return SLANG_PARAMETER_CATEGORY_NONE; + + return typeLayout->resourceInfos[index].kind; +} + +// Variable Reflection + +SLANG_API char const* spReflectionVariable_GetName(SlangReflectionVariable* inVar) +{ + auto var = convert(inVar); + if(!var) return nullptr; + + // If the variable is one that has an "external" name that is supposed + // to be exposed for reflection, then report it here + if(auto reflectionNameMod = var->FindModifier()) + return reflectionNameMod->nameToken.Content.Buffer(); + + return var->getName().Buffer(); +} + +SLANG_API SlangReflectionType* spReflectionVariable_GetType(SlangReflectionVariable* inVar) +{ + auto var = convert(inVar); + if(!var) return nullptr; + + return convert(var->getType()); +} + +// Variable Layout Reflection + +SLANG_API SlangReflectionVariable* spReflectionVariableLayout_GetVariable(SlangReflectionVariableLayout* inVarLayout) +{ + auto varLayout = convert(inVarLayout); + if(!varLayout) return nullptr; + + return convert(varLayout->varDecl.GetDecl()); +} + +SLANG_API SlangReflectionTypeLayout* spReflectionVariableLayout_GetTypeLayout(SlangReflectionVariableLayout* inVarLayout) +{ + auto varLayout = convert(inVarLayout); + if(!varLayout) return nullptr; + + return convert(varLayout->getTypeLayout()); +} + +SLANG_API size_t spReflectionVariableLayout_GetOffset(SlangReflectionVariableLayout* inVarLayout, SlangParameterCategory category) +{ + auto varLayout = convert(inVarLayout); + if(!varLayout) return 0; + + auto info = varLayout->FindResourceInfo(LayoutResourceKind(category)); + if(!info) return 0; + + return info->index; +} + +SLANG_API size_t spReflectionVariableLayout_GetSpace(SlangReflectionVariableLayout* inVarLayout, SlangParameterCategory category) +{ + auto varLayout = convert(inVarLayout); + if(!varLayout) return 0; + + auto info = varLayout->FindResourceInfo(LayoutResourceKind(category)); + if(!info) return 0; + + return info->space; +} + + +// Shader Parameter Reflection + +SLANG_API unsigned spReflectionParameter_GetBindingIndex(SlangReflectionParameter* inVarLayout) +{ + auto varLayout = convert(inVarLayout); + if(!varLayout) return 0; + + if(varLayout->resourceInfos.Count() > 0) + { + return (unsigned) varLayout->resourceInfos[0].index; + } + + return 0; +} + +SLANG_API unsigned spReflectionParameter_GetBindingSpace(SlangReflectionParameter* inVarLayout) +{ + auto varLayout = convert(inVarLayout); + if(!varLayout) return 0; + + if(varLayout->resourceInfos.Count() > 0) + { + return (unsigned) varLayout->resourceInfos[0].space; + } + + return 0; +} + +// Entry Point Reflection + +SLANG_API SlangStage spReflectionEntryPoint_getStage(SlangReflectionEntryPoint* inEntryPoint) +{ + auto entryPointLayout = convert(inEntryPoint); + + if(!entryPointLayout) return SLANG_STAGE_NONE; + + return SlangStage(entryPointLayout->profile.GetStage()); +} + +SLANG_API void spReflectionEntryPoint_getComputeThreadGroupSize( + SlangReflectionEntryPoint* inEntryPoint, + SlangUInt axisCount, + SlangUInt* outSizeAlongAxis) +{ + auto entryPointLayout = convert(inEntryPoint); + + if(!entryPointLayout) return; + if(!axisCount) return; + if(!outSizeAlongAxis) return; + + auto entryPointFunc = entryPointLayout->entryPoint; + if(!entryPointFunc) return; + + auto numThreadsAttribute = entryPointFunc->FindModifier(); + if(!numThreadsAttribute) return; + + if(axisCount > 0) outSizeAlongAxis[0] = numThreadsAttribute->x; + if(axisCount > 1) outSizeAlongAxis[1] = numThreadsAttribute->y; + if(axisCount > 2) outSizeAlongAxis[2] = numThreadsAttribute->z; + for( SlangUInt aa = 3; aa < axisCount; ++aa ) + { + outSizeAlongAxis[aa] = 1; + } +} + + +// Shader Reflection + +SLANG_API unsigned spReflection_GetParameterCount(SlangReflection* inProgram) +{ + auto program = convert(inProgram); + if(!program) return 0; + + auto globalLayout = program->globalScopeLayout; + if(auto globalConstantBufferLayout = globalLayout.As()) + { + globalLayout = globalConstantBufferLayout->elementTypeLayout; + } + + if(auto globalStructLayout = globalLayout.As()) + { + return globalStructLayout->fields.Count(); + } + + return 0; +} + +SLANG_API SlangReflectionParameter* spReflection_GetParameterByIndex(SlangReflection* inProgram, unsigned index) +{ + auto program = convert(inProgram); + if(!program) return nullptr; + + auto globalLayout = program->globalScopeLayout; + if(auto globalConstantBufferLayout = globalLayout.As()) + { + globalLayout = globalConstantBufferLayout->elementTypeLayout; + } + + if(auto globalStructLayout = globalLayout.As()) + { + return convert(globalStructLayout->fields[index].Ptr()); + } + + return nullptr; +} + +SLANG_API SlangUInt spReflection_getEntryPointCount(SlangReflection* inProgram) +{ + auto program = convert(inProgram); + if(!program) return 0; + + return SlangUInt(program->entryPoints.Count()); +} + +SLANG_API SlangReflectionEntryPoint* spReflection_getEntryPointByIndex(SlangReflection* inProgram, SlangUInt index) +{ + auto program = convert(inProgram); + if(!program) return 0; + + return convert(program->entryPoints[(int) index].Ptr()); +} + + + + + + + + + + + + + + + + + + + + +namespace Slang { +namespace Compiler { + + + + + + + +// Debug helper code: dump reflection data after generation + +struct PrettyWriter +{ + StringBuilder sb; + bool startOfLine = true; + int indent = 0; +}; + +static void adjust(PrettyWriter& writer) +{ + if (!writer.startOfLine) + return; + + int indent = writer.indent; + for (int ii = 0; ii < indent; ++ii) + writer.sb << " "; + + writer.startOfLine = false; +} + +static void indent(PrettyWriter& writer) +{ + writer.indent++; +} + +static void dedent(PrettyWriter& writer) +{ + writer.indent--; +} + +static void write(PrettyWriter& writer, char const* text) +{ + // TODO: can do this more efficiently... + char const* cursor = text; + for(;;) + { + char c = *cursor++; + if (!c) break; + + if (c == '\n') + { + writer.startOfLine = true; + } + else + { + adjust(writer); + } + + writer.sb << c; + } +} + +static void write(PrettyWriter& writer, UInt val) +{ + adjust(writer); + writer.sb << ((unsigned int) val); +} + +static void emitReflectionVarInfoJSON(PrettyWriter& writer, slang::VariableReflection* var); +static void emitReflectionTypeLayoutJSON(PrettyWriter& writer, slang::TypeLayoutReflection* type); +static void emitReflectionTypeJSON(PrettyWriter& writer, slang::TypeReflection* type); + +static void emitReflectionVarBindingInfoJSON( + PrettyWriter& writer, + SlangParameterCategory category, + UInt index, + UInt count, + UInt space = 0) +{ + if( category == SLANG_PARAMETER_CATEGORY_UNIFORM ) + { + write(writer,"\"kind\": \"uniform\""); + write(writer, ", "); + write(writer,"\"offset\": "); + write(writer, index); + write(writer, ", "); + write(writer, "\"size\": "); + write(writer, count); + } + else + { + write(writer, "\"kind\": \""); + switch( category ) + { + #define CASE(NAME, KIND) case SLANG_PARAMETER_CATEGORY_##NAME: write(writer, #KIND); break + CASE(CONSTANT_BUFFER, constantBuffer); + CASE(SHADER_RESOURCE, shaderResource); + CASE(UNORDERED_ACCESS, unorderedAccess); + CASE(VERTEX_INPUT, vertexInput); + CASE(FRAGMENT_OUTPUT, fragmentOutput); + CASE(SAMPLER_STATE, samplerState); + #undef CASE + + default: + write(writer, "unknown"); + assert(!"unexpected"); + break; + } + write(writer, "\""); + if( space ) + { + write(writer, ", "); + write(writer, "\"space\": "); + write(writer, space); + } + write(writer, ", "); + write(writer, "\"index\": "); + write(writer, index); + if( count != 1) + { + write(writer, ", "); + write(writer, "\"count\": "); + write(writer, count); + } + } +} + +static void emitReflectionVarBindingInfoJSON( + PrettyWriter& writer, + slang::VariableLayoutReflection* var) +{ + auto typeLayout = var->getTypeLayout(); + auto categoryCount = var->getCategoryCount(); + + if( categoryCount != 1 ) + { + write(writer,"\"bindings\": [\n"); + } + else + { + write(writer,"\"binding\": "); + } + indent(writer); + + for(uint32_t cc = 0; cc < categoryCount; ++cc ) + { + auto category = var->getCategoryByIndex(cc); + auto index = var->getOffset(category); + auto space = var->getBindingSpace(category); + auto count = typeLayout->getSize(category); + + if (cc != 0) write(writer, ",\n"); + + write(writer,"{"); + emitReflectionVarBindingInfoJSON( + writer, + category, + index, + count, + space); + write(writer,"}"); + } + + dedent(writer); + if( categoryCount != 1 ) + { + write(writer,"\n]"); + } +} + +static void emitReflectionNameInfoJSON( + PrettyWriter& writer, + char const* name) +{ + // TODO: deal with escaping special characters if/when needed + write(writer, "\"name\": \""); + write(writer, name); + write(writer, "\""); +} + +static void emitReflectionVarLayoutJSON( + PrettyWriter& writer, + slang::VariableLayoutReflection* var) +{ + write(writer, "{\n"); + indent(writer); + + emitReflectionNameInfoJSON(writer, var->getName()); + write(writer, ",\n"); + + write(writer, "\"type\": "); + emitReflectionTypeLayoutJSON(writer, var->getTypeLayout()); + write(writer, ",\n"); + + emitReflectionVarBindingInfoJSON(writer, var); + + dedent(writer); + write(writer, "\n}"); +} + +static void emitReflectionScalarTypeInfoJSON( + PrettyWriter& writer, + SlangScalarType scalarType) +{ + write(writer, "\"scalarType\": \""); + switch (scalarType) + { + default: + write(writer, "unknown"); + assert(!"unexpected"); + break; +#define CASE(TAG, ID) case slang::TypeReflection::ScalarType::TAG: write(writer, #ID); break + CASE(Void, void); + CASE(Bool, bool); + CASE(Int32, int32); + CASE(UInt32, uint32); + CASE(Int64, int64); + CASE(UInt64, uint64); + CASE(Float16, float16); + CASE(Float32, float32); + CASE(Float64, float64); +#undef CASE + } + write(writer, "\""); +} + +static void emitReflectionTypeInfoJSON( + PrettyWriter& writer, + slang::TypeReflection* type) +{ + switch( type->getKind() ) + { + case SLANG_TYPE_KIND_SAMPLER_STATE: + write(writer, "\"kind\": \"samplerState\""); + break; + + case SLANG_TYPE_KIND_RESOURCE: + { + auto shape = type->getResourceShape(); + auto access = type->getResourceAccess(); + write(writer, "\"kind\": \"resource\""); + write(writer, ",\n"); + write(writer, "\"baseShape\": \""); + switch (shape & SLANG_RESOURCE_BASE_SHAPE_MASK) + { + default: + write(writer, "unknown"); + assert(!"unexpected"); + break; + +#define CASE(SHAPE, NAME) case SLANG_##SHAPE: write(writer, #NAME); break + CASE(TEXTURE_1D, texture1D); + CASE(TEXTURE_2D, texture2D); + CASE(TEXTURE_3D, texture3D); + CASE(TEXTURE_CUBE, textureCube); + CASE(TEXTURE_BUFFER, textureBuffer); + CASE(STRUCTURED_BUFFER, structuredBuffer); + CASE(BYTE_ADDRESS_BUFFER, byteAddressBuffer); +#undef CASE + } + write(writer, "\""); + if (shape & SLANG_TEXTURE_ARRAY_FLAG) + { + write(writer, ",\n"); + write(writer, "\"array\": true"); + } + if (shape & SLANG_TEXTURE_MULTISAMPLE_FLAG) + { + write(writer, ",\n"); + write(writer, "\"multisample\": true"); + } + + if( access != SLANG_RESOURCE_ACCESS_READ ) + { + write(writer, ",\n\"access\": \""); + switch(access) + { + default: + write(writer, "unknown"); + assert(!"unexpected"); + break; + + case SLANG_RESOURCE_ACCESS_READ: + break; + + case SLANG_RESOURCE_ACCESS_READ_WRITE: write(writer, "readWrite"); break; + case SLANG_RESOURCE_ACCESS_RASTER_ORDERED: write(writer, "rasterOrdered"); break; + case SLANG_RESOURCE_ACCESS_APPEND: write(writer, "append"); break; + case SLANG_RESOURCE_ACCESS_CONSUME: write(writer, "consume"); break; + } + write(writer, "\""); + } + } + break; + + case SLANG_TYPE_KIND_CONSTANT_BUFFER: + write(writer, "\"kind\": \"constantBuffer\""); + write(writer, ",\n"); + write(writer, "\"elementType\": "); + emitReflectionTypeJSON( + writer, + type->getElementType()); + break; + + case SLANG_TYPE_KIND_SCALAR: + write(writer, "\"kind\": \"scalar\""); + write(writer, ",\n"); + emitReflectionScalarTypeInfoJSON( + writer, + type->getScalarType()); + break; + + case SLANG_TYPE_KIND_VECTOR: + write(writer, "\"kind\": \"vector\""); + write(writer, ",\n"); + write(writer, "\"elementCount\": "); + write(writer, type->getElementCount()); + write(writer, ",\n"); + write(writer, "\"elementType\": "); + emitReflectionTypeJSON( + writer, + type->getElementType()); + break; + + case SLANG_TYPE_KIND_MATRIX: + write(writer, "\"kind\": \"matrix\""); + write(writer, ",\n"); + write(writer, "\"rowCount\": "); + write(writer, type->getRowCount()); + write(writer, ",\n"); + write(writer, "\"columnCount\": "); + write(writer, type->getColumnCount()); + write(writer, ",\n"); + write(writer, "\"elementType\": "); + emitReflectionTypeJSON( + writer, + type->getElementType()); + break; + + case SLANG_TYPE_KIND_ARRAY: + { + auto arrayType = type; + write(writer, "\"kind\": \"array\""); + write(writer, ",\n"); + write(writer, "\"elementCount\": "); + write(writer, arrayType->getElementCount()); + write(writer, ",\n"); + write(writer, "\"elementType\": "); + emitReflectionTypeJSON(writer, arrayType->getElementType()); + } + break; + + case SLANG_TYPE_KIND_STRUCT: + { + write(writer, "\"kind\": \"struct\",\n"); + write(writer, "\"fields\": [\n"); + indent(writer); + + auto structType = type; + auto fieldCount = structType->getFieldCount(); + for( uint32_t ff = 0; ff < fieldCount; ++ff ) + { + if (ff != 0) write(writer, ",\n"); + emitReflectionVarInfoJSON( + writer, + structType->getFieldByIndex(ff)); + } + dedent(writer); + write(writer, "\n]"); + } + break; + + default: + assert(!"unimplemented"); + break; + } +} + +static void emitReflectionTypeLayoutInfoJSON( + PrettyWriter& writer, + slang::TypeLayoutReflection* typeLayout) +{ + switch( typeLayout->getKind() ) + { + default: + emitReflectionTypeInfoJSON(writer, typeLayout->getType()); + break; + + case SLANG_TYPE_KIND_ARRAY: + { + auto arrayTypeLayout = typeLayout; + auto elementTypeLayout = arrayTypeLayout->getElementTypeLayout(); + write(writer, "\"kind\": \"array\""); + write(writer, ",\n"); + write(writer, "\"elementCount\": "); + write(writer, arrayTypeLayout->getElementCount()); + write(writer, ",\n"); + write(writer, "\"elementType\": "); + emitReflectionTypeLayoutJSON( + writer, + elementTypeLayout); + if (arrayTypeLayout->getSize(SLANG_PARAMETER_CATEGORY_UNIFORM) != 0) + { + write(writer, ",\n"); + write(writer, "\"uniformStride\": "); + write(writer, arrayTypeLayout->getElementStride(SLANG_PARAMETER_CATEGORY_UNIFORM)); + } + } + break; + + case SLANG_TYPE_KIND_STRUCT: + { + write(writer, "\"kind\": \"struct\",\n"); + write(writer, "\"fields\": [\n"); + indent(writer); + + auto structTypeLayout = typeLayout; + auto fieldCount = structTypeLayout->getFieldCount(); + for( uint32_t ff = 0; ff < fieldCount; ++ff ) + { + if (ff != 0) write(writer, ",\n"); + emitReflectionVarLayoutJSON( + writer, + structTypeLayout->getFieldByIndex(ff)); + } + dedent(writer); + write(writer, "\n]"); + } + break; + + case SLANG_TYPE_KIND_CONSTANT_BUFFER: + write(writer, "\"kind\": \"constantBuffer\""); + write(writer, ",\n"); + write(writer, "\"elementType\": "); + emitReflectionTypeLayoutJSON( + writer, + typeLayout->getElementTypeLayout()); + break; + + } + + // TODO: emit size info for types +} + +static void emitReflectionTypeLayoutJSON( + PrettyWriter& writer, + slang::TypeLayoutReflection* typeLayout) +{ + write(writer, "{\n"); + indent(writer); + emitReflectionTypeLayoutInfoJSON(writer, typeLayout); + dedent(writer); + write(writer, "\n}"); +} + +static void emitReflectionTypeJSON( + PrettyWriter& writer, + slang::TypeReflection* type) +{ + write(writer, "{\n"); + indent(writer); + emitReflectionTypeInfoJSON(writer, type); + dedent(writer); + write(writer, "\n}"); +} + +static void emitReflectionVarInfoJSON( + PrettyWriter& writer, + slang::VariableReflection* var) +{ + emitReflectionNameInfoJSON(writer, var->getName()); + write(writer, ",\n"); + + write(writer, "\"type\": "); + emitReflectionTypeJSON(writer, var->getType()); +} + +#if 0 +static void emitReflectionBindingInfoJSON( + PrettyWriter& writer, + + ReflectionParameterNode* param) +{ + auto info = ¶m->binding; + + if( info->category == SLANG_PARAMETER_CATEGORY_MIXED ) + { + write(writer,"\"bindings\": [\n"); + indent(writer); + + ReflectionSize bindingCount = info->bindingCount; + assert(bindingCount); + ReflectionParameterBindingInfo* bindings = info->bindings; + for( ReflectionSize bb = 0; bb < bindingCount; ++bb ) + { + if (bb != 0) write(writer, ",\n"); + + write(writer,"{"); + auto& binding = bindings[bb]; + emitReflectionVarBindingInfoJSON( + writer, + binding.category, + binding.index, + (ReflectionSize) param->GetTypeLayout()->GetSize(binding.category), + binding.space); + + write(writer,"}"); + } + dedent(writer); + write(writer,"\n]"); + } + else + { + write(writer,"\"binding\": {"); + indent(writer); + + emitReflectionVarBindingInfoJSON( + writer, + info->category, + info->index, + (ReflectionSize) param->GetTypeLayout()->GetSize(info->category), + info->space); + + dedent(writer); + write(writer,"}"); + } +} +#endif + +static void emitReflectionParamJSON( + PrettyWriter& writer, + slang::VariableLayoutReflection* param) +{ + write(writer, "{\n"); + indent(writer); + + emitReflectionNameInfoJSON(writer, param->getName()); + write(writer, ",\n"); + + emitReflectionVarBindingInfoJSON(writer, param); + write(writer, ",\n"); + + write(writer, "\"type\": "); + emitReflectionTypeLayoutJSON(writer, param->getTypeLayout()); + + dedent(writer); + write(writer, "\n}"); +} + +template +struct Range +{ +public: + Range( + T begin, + T end) + : mBegin(begin) + , mEnd(end) + {} + + struct Iterator + { + public: + explicit Iterator(T value) + : mValue(value) + {} + + T operator*() const { return mValue; } + void operator++() { mValue++; } + + bool operator!=(Iterator const& other) + { + return mValue != other.mValue; + } + + private: + T mValue; + }; + + Iterator begin() const { return Iterator(mBegin); } + Iterator end() const { return Iterator(mEnd); } + +private: + T mBegin; + T mEnd; +}; + +template +Range range(T begin, T end) +{ + return Range(begin, end); +} + +template +Range range(T end) +{ + return Range(T(0), end); +} + +static void emitReflectionJSON( + PrettyWriter& writer, + slang::ShaderReflection* programReflection) +{ + write(writer, "{\n"); + indent(writer); + write(writer, "\"parameters\": [\n"); + indent(writer); + + auto parameterCount = programReflection->getParameterCount(); + for( auto pp : range(parameterCount) ) + { + if(pp != 0) write(writer, ",\n"); + + auto parameter = programReflection->getParameterByIndex(pp); + emitReflectionParamJSON(writer, parameter); + } + + dedent(writer); + write(writer, "\n]"); + dedent(writer); + write(writer, "\n}\n"); +} + +#if 0 +ReflectionBlob* ReflectionBlob::Create( + CollectionOfTranslationUnits* program) +{ + ReflectionGenerationContext context; + ReflectionBlob* blob = GenerateReflectionBlob(&context, program); +#if 0 + String debugDump = blob->emitAsJSON(); + OutputDebugStringA("REFLECTION BLOB\n"); + OutputDebugStringA(debugDump.begin()); +#endif + return blob; +} +#endif + +// JSON emit logic + + + +String emitReflectionJSON( + ProgramLayout* programLayout) +{ + auto programReflection = (slang::ShaderReflection*) programLayout; + + PrettyWriter writer; + emitReflectionJSON(writer, programReflection); + return writer.sb.ProduceString(); +} + +}} diff --git a/source/slang/reflection.h b/source/slang/reflection.h new file mode 100644 index 000000000..4d2c53084 --- /dev/null +++ b/source/slang/reflection.h @@ -0,0 +1,39 @@ +#ifndef SLANG_REFLECTION_H +#define SLANG_REFLECTION_H + +#include "../core/basic.h" +#include "syntax.h" + +#include "../../slang.h" + +namespace Slang { + +// TODO(tfoley): Need to move these somewhere universal + +typedef intptr_t Int; +typedef int64_t Int64; + +typedef uintptr_t UInt; +typedef uint64_t UInt64; + +namespace Compiler { + +class ProgramLayout; +class TypeLayout; + +String emitReflectionJSON( + ProgramLayout* programLayout); + +// + +SlangTypeKind getReflectionTypeKind(ExpressionType* type); + +SlangTypeKind getReflectionParameterCategory(TypeLayout* typeLayout); + +UInt getReflectionFieldCount(ExpressionType* type); +UInt getReflectionFieldByIndex(ExpressionType* type, UInt index); +UInt getReflectionFieldByIndex(TypeLayout* typeLayout, UInt index); + +}} + +#endif // SLANG_REFLECTION_H diff --git a/source/slang/slang-stdlib.cpp b/source/slang/slang-stdlib.cpp new file mode 100644 index 000000000..f74fcd603 --- /dev/null +++ b/source/slang/slang-stdlib.cpp @@ -0,0 +1,1855 @@ +// slang-stdlib.cpp + +#include "slang-stdlib.h" +#include "syntax.h" + +#define STRINGIZE(x) STRINGIZE2(x) +#define STRINGIZE2(x) #x +#define LINE_STRING STRINGIZE(__LINE__) + +enum { kLibIncludeStringLine = __LINE__+1 }; +const char * LibIncludeStringChunks[] = { R"( + +typedef uint UINT; + +__generic __intrinsic(Assign) T operator=(out T left, T right); + +__generic __intrinsic(Sequence) U operator,(T left, U right); + +__generic __intrinsic(Select) T operator?:(bool condition, T ifTrue, T ifFalse); +__generic __intrinsic(Select) vector operator?:(vector condition, vector ifTrue, vector ifFalse); + +__generic __magic_type(HLSLAppendStructuredBufferType) struct AppendStructuredBuffer +{ + __intrinsic void Append(T value); + + __intrinsic void GetDimensions( + out uint numStructs, + out uint stride); +}; + +__generic __magic_type(HLSLBufferType) struct Buffer +{ + __intrinsic void GetDimensions( + out uint dim); + + __intrinsic T Load(int location); + __intrinsic T Load(int location, out uint status); + + __intrinsic __subscript(uint index) -> T; +}; + +__magic_type(HLSLByteAddressBufferType) struct ByteAddressBuffer +{ + __intrinsic void GetDimensions( + out uint dim); + + __intrinsic uint Load(int location); + __intrinsic uint Load(int location, out uint status); + + __intrinsic uint2 Load2(int location); + __intrinsic uint2 Load2(int location, out uint status); + + __intrinsic uint3 Load3(int location); + __intrinsic uint3 Load3(int location, out uint status); + + __intrinsic uint4 Load4(int location); + __intrinsic uint4 Load4(int location, out uint status); +}; + +__generic __magic_type(HLSLStructuredBufferType) struct StructuredBuffer +{ + __intrinsic void GetDimensions( + out uint numStructs, + out uint stride); + + __intrinsic T Load(int location); + __intrinsic T Load(int location, out uint status); + + __intrinsic __subscript(uint index) -> T; +}; + +__generic __magic_type(HLSLConsumeStructuredBufferType) struct ConsumeStructuredBuffer +{ + __intrinsic T Consume(); + + __intrinsic void GetDimensions( + out uint numStructs, + out uint stride); +}; + +__generic __magic_type(HLSLInputPatchType) struct InputPatch +{ + __intrinsic __subscript(uint index) -> T; +}; + +__generic __magic_type(HLSLOutputPatchType) struct OutputPatch +{ + __intrinsic __subscript(uint index) -> T { set; } +}; + +__generic __magic_type(HLSLRWBufferType) struct RWBuffer +{ + // Note(tfoley): duplication with declaration of `Buffer` + + __intrinsic void GetDimensions( + out uint dim); + + __intrinsic T Load(int location); + __intrinsic T Load(int location, out uint status); + + __intrinsic __subscript(uint index) -> T { get; set; } +}; + +__magic_type(HLSLRWByteAddressBufferType) struct RWByteAddressBuffer +{ + // Note(tfoley): supports alll operations from `ByteAddressBuffer` + // TODO(tfoley): can this be made a sub-type? + + __intrinsic void GetDimensions( + out uint dim); + + __intrinsic uint Load(int location); + __intrinsic uint Load(int location, out uint status); + + __intrinsic uint2 Load2(int location); + __intrinsic uint2 Load2(int location, out uint status); + + __intrinsic uint3 Load3(int location); + __intrinsic uint3 Load3(int location, out uint status); + + __intrinsic uint4 Load4(int location); + __intrinsic uint4 Load4(int location, out uint status); + + // Added operations: + + __intrinsic void InterlockedAdd( + UINT dest, + UINT value, + out UINT original_value); + __intrinsic void InterlockedAdd( + UINT dest, + UINT value); + + __intrinsic void InterlockedAnd( + UINT dest, + UINT value, + out UINT original_value); + __intrinsic void InterlockedAnd( + UINT dest, + UINT value); + + __intrinsic void InterlockedCompareExchange( + UINT dest, + UINT compare_value, + UINT value, + out UINT original_value); + __intrinsic void InterlockedCompareExchange( + UINT dest, + UINT compare_value, + UINT value); + + __intrinsic void InterlockedCompareStore( + UINT dest, + UINT compare_value, + UINT value); + __intrinsic void InterlockedCompareStore( + UINT dest, + UINT compare_value); + + __intrinsic void InterlockedExchange( + UINT dest, + UINT value, + out UINT original_value); + __intrinsic void InterlockedExchange( + UINT dest, + UINT value); + + __intrinsic void InterlockedMax( + UINT dest, + UINT value, + out UINT original_value); + __intrinsic void InterlockedMax( + UINT dest, + UINT value); + + __intrinsic void InterlockedMin( + UINT dest, + UINT value, + out UINT original_value); + __intrinsic void InterlockedMin( + UINT dest, + UINT value); + + __intrinsic void InterlockedOr( + UINT dest, + UINT value, + out UINT original_value); + __intrinsic void InterlockedOr( + UINT dest, + UINT value); + + __intrinsic void InterlockedXor( + UINT dest, + UINT value, + out UINT original_value); + __intrinsic void InterlockedXor( + UINT dest, + UINT value); + + __intrinsic void Store( + uint address, + uint value); + + __intrinsic void Store2( + uint address, + uint2 value); + + __intrinsic void Store3( + uint address, + uint3 value); + + __intrinsic void Store4( + uint address, + uint4 value); +}; + +__generic __magic_type(HLSLRWStructuredBufferType) struct RWStructuredBuffer +{ + __intrinsic uint DecrementCounter(); + + __intrinsic void GetDimensions( + out uint numStructs, + out uint stride); + + __intrinsic void IncrementCounter(); + + __intrinsic T Load(int location); + __intrinsic T Load(int location, out uint status); + + __intrinsic __subscript(uint index) -> T { get; set; } +}; + +__generic __magic_type(HLSLPointStreamType) struct PointStream {}; +__generic __magic_type(HLSLLineStreamType) struct LineStream {}; +__generic __magic_type(HLSLLineStreamType) struct TriangleStream {}; + +)", R"( + +// Note(tfoley): Trying to systematically add all the HLSL builtins + +// A type that can be used as an operand for builtins +__trait __BuiltinType {} + +// A type that can be used for arithmetic operations +__trait __BuiltinArithmeticType : __BuiltinType {} + +// A type that logically has a sign (positive/negative/zero) +__trait __BuiltinSignedArithmeticType : __BuiltinArithmeticType {} + +// A type that can represent integers +__trait __BuiltinIntegerType : __BuiltinArithmeticType {} + +// A type that can represent non-integers +__trait __BuiltinRealType : __BuiltinArithmeticType {} + +// A type that uses a floating-point representation +__trait __BuiltinFloatingPointType : __BuiltinRealType, __BuiltinSignedType {} + +// Try to terminate the current draw or dispatch call (HLSL SM 4.0) +__intrinsic void abort(); + +// Absolute value (HLSL SM 1.0) +__generic __intrinsic T abs(T x); +__generic __intrinsic vector abs(vector x); +__generic __intrinsic matrix abs(matrix x); + +// Inverse cosine (HLSL SM 1.0) +__generic __intrinsic T acos(T x); +__generic __intrinsic vector acos(vector x); +__generic __intrinsic matrix acos(matrix x); + +// Test if all components are non-zero (HLSL SM 1.0) +__generic __intrinsic T all(T x); +__generic __intrinsic vector all(vector x); +__generic __intrinsic matrix all(matrix x); + +// Barrier for writes to all memory spaces (HLSL SM 5.0) +__intrinsic void AllMemoryBarrier(); + +// Thread-group sync and barrier for writes to all memory spaces (HLSL SM 5.0) +__intrinsic void AllMemoryBarrierWithGroupSync(); + +// Test if any components is non-zero (HLSL SM 1.0) +__generic __intrinsic T any(T x); +__generic __intrinsic vector any(vector x); +__generic __intrinsic matrix any(matrix x); + + +// Reinterpret bits as a double (HLSL SM 5.0) +__intrinsic double asdouble(uint lowbits, uint highbits); + +// Reinterpret bits as a float (HLSL SM 4.0) +__intrinsic float asfloat( int x); +__intrinsic float asfloat(uint x); +__generic __intrinsic vector asfloat(vector< int,N> x); +__generic __intrinsic vector asfloat(vector x); +__generic __intrinsic matrix asfloat(matrix< int,N,M> x); +__generic __intrinsic matrix asfloat(matrix x); + + +// Inverse sine (HLSL SM 1.0) +__generic __intrinsic T asin(T x); +__generic __intrinsic vector asin(vector x); +__generic __intrinsic matrix asin(matrix x); + +// Reinterpret bits as an int (HLSL SM 4.0) +__intrinsic int asint(float x); +__intrinsic int asint(uint x); +__generic __intrinsic vector asint(vector x); +__generic __intrinsic vector asint(vector x); +__generic __intrinsic matrix asint(matrix x); +__generic __intrinsic matrix asint(matrix x); + +// Reinterpret bits of double as a uint (HLSL SM 5.0) +__intrinsic void asuint(double value, out uint lowbits, out uint highbits); + +// Reinterpret bits as a uint (HLSL SM 4.0) +__intrinsic uint asuint(float x); +__intrinsic uint asuint(int x); +__generic __intrinsic vector asuint(vector x); +__generic __intrinsic vector asuint(vector x); +__generic __intrinsic matrix asuint(matrix x); +__generic __intrinsic matrix asuint(matrix x); + +// Inverse tangent (HLSL SM 1.0) +__generic __intrinsic T atan(T x); +__generic __intrinsic vector atan(vector x); +__generic __intrinsic matrix atan(matrix x); + +__generic __intrinsic T atan2(T y, T x); +__generic __intrinsic vector atan2(vector y, vector x); +__generic __intrinsic matrix atan2(matrix y, matrix x); + +// Ceiling (HLSL SM 1.0) +__generic __intrinsic T ceil(T x); +__generic __intrinsic vector ceil(vector x); +__generic __intrinsic matrix ceil(matrix x); + + +// Check access status to tiled resource +__intrinsic bool CheckAccessFullyMapped(uint status); + +// Clamp (HLSL SM 1.0) +__generic __intrinsic T clamp(T x, T min, T max); +__generic __intrinsic vector clamp(vector x, vector min, vector max); +__generic __intrinsic matrix clamp(matrix x, matrix min, matrix max); + +// Clip (discard) fragment conditionally +__generic __intrinsic void clip(T x); +__generic __intrinsic void clip(vector x); +__generic __intrinsic void clip(matrix x); + +// Cosine +__generic __intrinsic T cos(T x); +__generic __intrinsic vector cos(vector x); +__generic __intrinsic matrix cos(matrix x); + +// Hyperbolic cosine +__generic __intrinsic T cosh(T x); +__generic __intrinsic vector cosh(vector x); +__generic __intrinsic matrix cosh(matrix x); + +// Population count +__intrinsic uint countbits(uint value); + +// Cross product +__generic __intrinsic vector cross(vector x, vector y); + +// Convert encoded color +__intrinsic int4 D3DCOLORtoUBYTE4(float4 x); + +// Partial-difference derivatives +__generic __intrinsic T ddx(T x); +__generic __intrinsic vector ddx(vector x); +__generic __intrinsic matrix ddx(matrix x); + +__generic __intrinsic T ddx_coarse(T x); +__generic __intrinsic vector ddx_coarse(vector x); +__generic __intrinsic matrix ddx_coarse(matrix x); + +__generic __intrinsic T ddx_fine(T x); +__generic __intrinsic vector ddx_fine(vector x); +__generic __intrinsic matrix ddx_fine(matrix x); + +__generic __intrinsic T ddy(T x); +__generic __intrinsic vector ddy(vector x); +__generic __intrinsic matrix ddy(matrix x); + +__generic __intrinsic T ddy_coarse(T x); +__generic __intrinsic vector ddy_coarse(vector x); +__generic __intrinsic matrix ddy_coarse(matrix x); + +__generic __intrinsic T ddy_fine(T x); +__generic __intrinsic vector ddy_fine(vector x); +__generic __intrinsic matrix ddy_fine(matrix x); + + +// Radians to degrees +__generic __intrinsic T degrees(T x); +__generic __intrinsic vector degrees(vector x); +__generic __intrinsic matrix degrees(matrix x); + +// Matrix determinant + +__generic __intrinsic T determinant(matrix m); + +// Barrier for device memory +__intrinsic void DeviceMemoryBarrier(); +__intrinsic void DeviceMemoryBarrierWithGroupSync(); + +// Vector distance + +__generic __intrinsic T distance(vector x, vector y); + +// Vector dot product + +__generic __intrinsic T dot(vector x, vector y); + +// Helper for computing distance terms for lighting (obsolete) + +__generic __intrinsic vector dst(vector x, vector y); + +// Error message + +// __intrinsic void errorf( string format, ... ); + +// Attribute evaluation + +__generic __intrinsic T EvaluateAttributeAtCentroid(T x); +__generic __intrinsic vector EvaluateAttributeAtCentroid(vector x); +__generic __intrinsic matrix EvaluateAttributeAtCentroid(matrix x); + +__generic __intrinsic T EvaluateAttributeAtSample(T x, uint sampleindex); +__generic __intrinsic vector EvaluateAttributeAtSample(vector x, uint sampleindex); +__generic __intrinsic matrix EvaluateAttributeAtSample(matrix x, uint sampleindex); + +__generic __intrinsic T EvaluateAttributeSnapped(T x, int2 offset); +__generic __intrinsic vector EvaluateAttributeSnapped(vector x, int2 offset); +__generic __intrinsic matrix EvaluateAttributeSnapped(matrix x, int2 offset); + +// Base-e exponent +__generic __intrinsic T exp(T x); +__generic __intrinsic vector exp(vector x); +__generic __intrinsic matrix exp(matrix x); + +// Base-2 exponent +__generic __intrinsic T exp2(T x); +__generic __intrinsic vector exp2(vector x); +__generic __intrinsic matrix exp2(matrix x); + +// Convert 16-bit float stored in low bits of integer +__intrinsic float f16tof32(uint value); +__generic __intrinsic vector f16tof32(vector value); + +// Convert to 16-bit float stored in low bits of integer +__intrinsic uint f32tof16(float value); +__generic __intrinsic vector f32tof16(vector value); + +// Flip surface normal to face forward, if needed +__generic __intrinsic vector faceforward(vector n, vector i, vector ng); + +// Find first set bit starting at high bit and working down +__intrinsic int firstbithigh(int value); +__generic __intrinsic vector firstbithigh(vector value); + +__intrinsic uint firstbithigh(uint value); +__generic __intrinsic vector firstbithigh(vector value); + +// Find first set bit starting at low bit and working up +__intrinsic int firstbitlow(int value); +__generic __intrinsic vector firstbitlow(vector value); + +__intrinsic uint firstbitlow(uint value); +__generic __intrinsic vector firstbitlow(vector value); + +// Floor (HLSL SM 1.0) +__generic __intrinsic T floor(T x); +__generic __intrinsic vector floor(vector x); +__generic __intrinsic matrix floor(matrix x); + +// Fused multiply-add for doubles +__intrinsic double fma(double a, double b, double c); +__generic __intrinsic vector fma(vector a, vector b, vector c); +__generic __intrinsic matrix fma(matrix a, matrix b, matrix c); + +// Floating point remainder of x/y +__generic __intrinsic T fmod(T x, T y); +__generic __intrinsic vector fmod(vector x, vector y); +__generic __intrinsic matrix fmod(matrix x, matrix y); + +// Fractional part +__generic __intrinsic T frac(T x); +__generic __intrinsic vector frac(vector x); +__generic __intrinsic matrix frac(matrix x); + +// Split float into mantissa and exponent +__generic __intrinsic T frexp(T x, out T exp); +__generic __intrinsic vector frexp(vector x, out vector exp); +__generic __intrinsic matrix frexp(matrix x, out matrix exp); + +// Texture filter width +__generic __intrinsic T fwidth(T x); +__generic __intrinsic vector fwidth(vector x); +__generic __intrinsic matrix fwidth(matrix x); + +)", R"( + +// Get number of samples in render target +__intrinsic uint GetRenderTargetSampleCount(); + +// Get position of given sample +__intrinsic float2 GetRenderTargetSamplePosition(int Index); + +// Group memory barrier +__intrinsic void GroupMemoryBarrier(); +__intrinsic void GroupMemoryBarrierWithGroupSync(); + +// Atomics +__intrinsic void InterlockedAdd(in out int dest, int value, out int original_value); +__intrinsic void InterlockedAdd(in out uint dest, uint value, out uint original_value); + +__intrinsic void InterlockedAnd(in out int dest, int value, out int original_value); +__intrinsic void InterlockedAnd(in out uint dest, uint value, out uint original_value); + +__intrinsic void InterlockedCompareExchange(in out int dest, int compare_value, int value, out int original_value); +__intrinsic void InterlockedCompareExchange(in out uint dest, uint compare_value, uint value, out uint original_value); + +__intrinsic void InterlockedCompareStore(in out int dest, int compare_value, int value); +__intrinsic void InterlockedCompareStore(in out uint dest, uint compare_value, uint value); + +__intrinsic void InterlockedExchange(in out int dest, int value, out int original_value); +__intrinsic void InterlockedExchange(in out uint dest, uint value, out uint original_value); + +__intrinsic void InterlockedMax(in out int dest, int value, out int original_value); +__intrinsic void InterlockedMax(in out uint dest, uint value, out uint original_value); + +__intrinsic void InterlockedMin(in out int dest, int value, out int original_value); +__intrinsic void InterlockedMin(in out uint dest, uint value, out uint original_value); + +__intrinsic void InterlockedOr(in out int dest, int value, out int original_value); +__intrinsic void InterlockedOr(in out uint dest, uint value, out uint original_value); + +__intrinsic void InterlockedXor(in out int dest, int value, out int original_value); +__intrinsic void InterlockedXor(in out uint dest, uint value, out uint original_value); + +// Is floating-point value finite? +__generic __intrinsic bool isfinite(T x); +__generic __intrinsic vector isfinite(vector x); +__generic __intrinsic matrix isfinite(matrix x); + +// Is floating-point value infinite? +__generic __intrinsic bool isinf(T x); +__generic __intrinsic vector isinf(vector x); +__generic __intrinsic matrix isinf(matrix x); + +// Is floating-point value not-a-number? +__generic __intrinsic bool isnan(T x); +__generic __intrinsic vector isnan(vector x); +__generic __intrinsic matrix isnan(matrix x); + +// Construct float from mantissa and exponent +__generic __intrinsic T ldexp(T x, T exp); +__generic __intrinsic vector ldexp(vector x, vector exp); +__generic __intrinsic matrix ldexp(matrix x, matrix exp); + +// Vector length +__generic __intrinsic T length(vector x); + +// Linear interpolation +__generic __intrinsic T lerp(T x, T y, T s); +__generic __intrinsic vector lerp(vector x, vector y, vector s); +__generic __intrinsic matrix lerp(matrix x, matrix y, matrix s); + +// Legacy lighting function (obsolete) +__intrinsic float4 lit(float n_dot_l, float n_dot_h, float m); + +// Base-e logarithm +__generic __intrinsic T log(T x); +__generic __intrinsic vector log(vector x); +__generic __intrinsic matrix log(matrix x); + +// Base-10 logarithm +__generic __intrinsic T log10(T x); +__generic __intrinsic vector log10(vector x); +__generic __intrinsic matrix log10(matrix x); + +// Base-2 logarithm +__generic __intrinsic T log2(T x); +__generic __intrinsic vector log2(vector x); +__generic __intrinsic matrix log2(matrix x); + +// multiply-add +__generic __intrinsic T mad(T mvalue, T avalue, T bvalue); +__generic __intrinsic vector mad(vector mvalue, vector avalue, vector bvalue); +__generic __intrinsic matrix mad(matrix mvalue, matrix avalue, matrix bvalue); + +// maximum +__generic __intrinsic T max(T x, T y); +__generic __intrinsic vector max(vector x, vector y); +__generic __intrinsic matrix max(matrix x, matrix y); + +// minimum +__generic __intrinsic T min(T x, T y); +__generic __intrinsic vector min(vector x, vector y); +__generic __intrinsic matrix min(matrix x, matrix y); + +// split into integer and fractional parts (both with same sign) +__generic __intrinsic T modf(T x, out T ip); +__generic __intrinsic vector modf(vector x, out vector ip); +__generic __intrinsic matrix modf(matrix x, out matrix ip); + +// msad4 (whatever that is) +__intrinsic uint4 msad4(uint reference, uint2 source, uint4 accum); + +// General inner products + +// scalar-scalar +__generic __intrinsic(Mul_Scalar_Scalar) T mul(T x, T y); + +// scalar-vector and vector-scalar +__generic __intrinsic(Mul_Vector_Scalar) vector mul(vector x, T y); +__generic __intrinsic(Mul_Scalar_Vector) vector mul(T x, vector y); + +// scalar-matrix and matrix-scalar +__generic __intrinsic(Mul_Matrix_Scalar) matrix mul(matrix x, T y); +__generic __intrinsic(Mul_Scalar_Matrix) matrix mul(T x, matrix y); + +// vector-vector (dot product) +__generic __intrinsic(InnerProduct_Vector_Vector) T mul(vector x, vector y); + +// vector-matrix +__generic __intrinsic(InnerProduct_Vector_Matrix) vector mul(vector x, matrix y); + +// matrix-vector +__generic __intrinsic(InnerProduct_Matrix_Vector) vector mul(matrix x, vector y); + +// matrix-matrix +__generic __intrinsic(InnerProduct_Matrix_Matrix) matrix mul(matrix x, matrix y); + +// noise (deprecated) +__intrinsic float noise(float x); +__generic __intrinsic float noise(vector x); + +// Normalize a vector +__generic __intrinsic vector normalize(vector x); + +// Raise to a power +__generic __intrinsic T pow(T x, T y); +__generic __intrinsic vector pow(vector x, vector y); +__generic __intrinsic matrix pow(matrix x, matrix y); + +// Output message + +// __intrinsic void printf( string format, ... ); + +// Tessellation factor fixup routines + +__intrinsic void Process2DQuadTessFactorsAvg( + in float4 RawEdgeFactors, + in float2 InsideScale, + out float4 RoundedEdgeTessFactors, + out float2 RoundedInsideTessFactors, + out float2 UnroundedInsideTessFactors); + +__intrinsic void Process2DQuadTessFactorsMax( + in float4 RawEdgeFactors, + in float2 InsideScale, + out float4 RoundedEdgeTessFactors, + out float2 RoundedInsideTessFactors, + out float2 UnroundedInsideTessFactors); + +__intrinsic void Process2DQuadTessFactorsMin( + in float4 RawEdgeFactors, + in float2 InsideScale, + out float4 RoundedEdgeTessFactors, + out float2 RoundedInsideTessFactors, + out float2 UnroundedInsideTessFactors); + +__intrinsic void ProcessIsolineTessFactors( + in float RawDetailFactor, + in float RawDensityFactor, + out float RoundedDetailFactor, + out float RoundedDensityFactor); + +__intrinsic void ProcessQuadTessFactorsAvg( + in float4 RawEdgeFactors, + in float InsideScale, + out float4 RoundedEdgeTessFactors, + out float2 RoundedInsideTessFactors, + out float2 UnroundedInsideTessFactors); + +__intrinsic void ProcessQuadTessFactorsMax( + in float4 RawEdgeFactors, + in float InsideScale, + out float4 RoundedEdgeTessFactors, + out float2 RoundedInsideTessFactors, + out float2 UnroundedInsideTessFactors); + +__intrinsic void ProcessQuadTessFactorsMin( + in float4 RawEdgeFactors, + in float InsideScale, + out float4 RoundedEdgeTessFactors, + out float2 RoundedInsideTessFactors, + out float2 UnroundedInsideTessFactors); + +__intrinsic void ProcessTriTessFactorsAvg( + in float3 RawEdgeFactors, + in float InsideScale, + out float3 RoundedEdgeTessFactors, + out float RoundedInsideTessFactor, + out float UnroundedInsideTessFactor); + +__intrinsic void ProcessTriTessFactorsMax( + in float3 RawEdgeFactors, + in float InsideScale, + out float3 RoundedEdgeTessFactors, + out float RoundedInsideTessFactor, + out float UnroundedInsideTessFactor); + +__intrinsic void ProcessTriTessFactorsMin( + in float3 RawEdgeFactors, + in float InsideScale, + out float3 RoundedEdgeTessFactors, + out float RoundedInsideTessFactors, + out float UnroundedInsideTessFactors); + +// Degrees to radians +__generic __intrinsic T radians(T x); +__generic __intrinsic vector radians(vector x); +__generic __intrinsic matrix radians(matrix x); + +// Approximate reciprocal +__generic __intrinsic T rcp(T x); +__generic __intrinsic vector rcp(vector x); +__generic __intrinsic matrix rcp(matrix x); + +// Reflect incident vector across plane with given normal +__generic +__intrinsic +vector reflect(vector i, vector n); + +// Refract incident vector given surface normal and index of refraction +__generic +__intrinsic +vector refract(vector i, vector n, float eta); + +// Reverse order of bits +__intrinsic uint reversebits(uint value); +__generic vector reversebits(vector value); + +// Round-to-nearest +__generic __intrinsic T round(T x); +__generic __intrinsic vector round(vector x); +__generic __intrinsic matrix round(matrix x); + +// Reciprocal of square root +__generic __intrinsic T rsqrt(T x); +__generic __intrinsic vector rsqrt(vector x); +__generic __intrinsic matrix rsqrt(matrix x); + +// Clamp value to [0,1] range +__generic __intrinsic T saturate(T x); +__generic __intrinsic vector saturate(vector x); +__generic __intrinsic matrix saturate(matrix x); + + +// Extract sign of value +__generic __intrinsic int sign(T x); +__generic __intrinsic vector sign(vector x); +__generic __intrinsic matrix sign(matrix x); + +)", R"( + + +// Sine +__generic __intrinsic T sin(T x); +__generic __intrinsic vector sin(vector x); +__generic __intrinsic matrix sin(matrix x); + +// Sine and cosine +__generic __intrinsic void sincos(T x, out T s, out T c); +__generic __intrinsic void sincos(vector x, out vector s, out vector c); +__generic __intrinsic void sincos(matrix x, out matrix s, out matrix c); + +// Hyperbolic Sine +__generic __intrinsic T sinh(T x); +__generic __intrinsic vector sinh(vector x); +__generic __intrinsic matrix sinh(matrix x); + +// Smooth step (Hermite interpolation) +__generic __intrinsic T smoothstep(T min, T max, T x); +__generic __intrinsic vector smoothstep(vector min, vector max, vector x); +__generic __intrinsic matrix smoothstep(matrix min, matrix max, matrix x); + +// Square root +__generic __intrinsic T sqrt(T x); +__generic __intrinsic vector sqrt(vector x); +__generic __intrinsic matrix sqrt(matrix x); + +// Step function +__generic __intrinsic T step(T y, T x); +__generic __intrinsic vector step(vector y, vector x); +__generic __intrinsic matrix step(matrix y, matrix x); + +// Tangent +__generic __intrinsic T tan(T x); +__generic __intrinsic vector tan(vector x); +__generic __intrinsic matrix tan(matrix x); + +// Hyperbolic tangent +__generic __intrinsic T tanh(T x); +__generic __intrinsic vector tanh(vector x); +__generic __intrinsic matrix tanh(matrix x); + +// Legacy texture-fetch operations + +/* +__intrinsic float4 tex1D(sampler1D s, float t); +__intrinsic float4 tex1D(sampler1D s, float t, float ddx, float ddy); +__intrinsic float4 tex1Dbias(sampler1D s, float4 t); +__intrinsic float4 tex1Dgrad(sampler1D s, float t, float ddx, float ddy); +__intrinsic float4 tex1Dlod(sampler1D s, float4 t); +__intrinsic float4 tex1Dproj(sampler1D s, float4 t); + +__intrinsic float4 tex2D(sampler2D s, float2 t); +__intrinsic float4 tex2D(sampler2D s, float2 t, float2 ddx, float2 ddy); +__intrinsic float4 tex2Dbias(sampler2D s, float4 t); +__intrinsic float4 tex2Dgrad(sampler2D s, float2 t, float2 ddx, float2 ddy); +__intrinsic float4 tex2Dlod(sampler2D s, float4 t); +__intrinsic float4 tex2Dproj(sampler2D s, float4 t); + +__intrinsic float4 tex3D(sampler3D s, float3 t); +__intrinsic float4 tex3D(sampler3D s, float3 t, float3 ddx, float3 ddy); +__intrinsic float4 tex3Dbias(sampler3D s, float4 t); +__intrinsic float4 tex3Dgrad(sampler3D s, float3 t, float3 ddx, float3 ddy); +__intrinsic float4 tex3Dlod(sampler3D s, float4 t); +__intrinsic float4 tex3Dproj(sampler3D s, float4 t); + +__intrinsic float4 texCUBE(samplerCUBE s, float3 t); +__intrinsic float4 texCUBE(samplerCUBE s, float3 t, float3 ddx, float3 ddy); +__intrinsic float4 texCUBEbias(samplerCUBE s, float4 t); +__intrinsic float4 texCUBEgrad(samplerCUBE s, float3 t, float3 ddx, float3 ddy); +__intrinsic float4 texCUBElod(samplerCUBE s, float4 t); +__intrinsic float4 texCUBEproj(samplerCUBE s, float4 t); +*/ + +// Matrix transpose +__generic __intrinsic matrix transpose(matrix x); + +// Truncate to integer +__generic __intrinsic T trunc(T x); +__generic __intrinsic vector trunc(vector x); +__generic __intrinsic matrix trunc(matrix x); + + +)", R"( + +// Shader model 6.0 stuff + +__intrinsic uint GlobalOrderedCountIncrement(uint countToAppendForThisLane); + +__generic __intrinsic T QuadReadLaneAt(T sourceValue, int quadLaneID); +__generic __intrinsic vector QuadReadLaneAt(vector sourceValue, int quadLaneID); +__generic __intrinsic matrix QuadReadLaneAt(matrix sourceValue, int quadLaneID); + +__generic __intrinsic T QuadSwapX(T localValue); +__generic __intrinsic vector QuadSwapX(vector localValue); +__generic __intrinsic matrix QuadSwapX(matrix localValue); + +__generic __intrinsic T QuadSwapY(T localValue); +__generic __intrinsic vector QuadSwapY(vector localValue); +__generic __intrinsic matrix QuadSwapY(matrix localValue); + +__generic __intrinsic T WaveAllBitAnd(T expr); +__generic __intrinsic vector WaveAllBitAnd(vector expr); +__generic __intrinsic matrix WaveAllBitAnd(matrix expr); + +__generic __intrinsic T WaveAllBitOr(T expr); +__generic __intrinsic vector WaveAllBitOr(vector expr); +__generic __intrinsic matrix WaveAllBitOr(matrix expr); + +__generic __intrinsic T WaveAllBitXor(T expr); +__generic __intrinsic vector WaveAllBitXor(vector expr); +__generic __intrinsic matrix WaveAllBitXor(matrix expr); + +__generic __intrinsic T WaveAllMax(T expr); +__generic __intrinsic vector WaveAllMax(vector expr); +__generic __intrinsic matrix WaveAllMax(matrix expr); + +__generic __intrinsic T WaveAllMin(T expr); +__generic __intrinsic vector WaveAllMin(vector expr); +__generic __intrinsic matrix WaveAllMin(matrix expr); + +__generic __intrinsic T WaveAllProduct(T expr); +__generic __intrinsic vector WaveAllProduct(vector expr); +__generic __intrinsic matrix WaveAllProduct(matrix expr); + +__generic __intrinsic T WaveAllSum(T expr); +__generic __intrinsic vector WaveAllSum(vector expr); +__generic __intrinsic matrix WaveAllSum(matrix expr); + +__intrinsic bool WaveAllEqual(bool expr); +__intrinsic bool WaveAllTrue(bool expr); +__intrinsic bool WaveAnyTrue(bool expr); + +uint64_t WaveBallot(bool expr); + +uint WaveGetLaneCount(); +uint WaveGetLaneIndex(); +uint WaveGetOrderedIndex(); + +bool WaveIsHelperLane(); + +bool WaveOnce(); + +__generic __intrinsic T WavePrefixProduct(T expr); +__generic __intrinsic vector WavePrefixProduct(vector expr); +__generic __intrinsic matrix WavePrefixProduct(matrix expr); + +__generic __intrinsic T WavePrefixSum(T expr); +__generic __intrinsic vector WavePrefixSum(vector expr); +__generic __intrinsic matrix WavePrefixSum(matrix expr); + +__generic __intrinsic T WaveReadFirstLane(T expr); +__generic __intrinsic vector WaveReadFirstLane(vector expr); +__generic __intrinsic matrix WaveReadFirstLane(matrix expr); + +__generic __intrinsic T WaveReadLaneAt(T expr, int laneIndex); +__generic __intrinsic vector WaveReadLaneAt(vector expr, int laneIndex); +__generic __intrinsic matrix WaveReadLaneAt(matrix expr, int laneIndex); + + +)", R"( + +// `typedef`s to help with the fact that HLSL has been sorta-kinda case insensitive at various points +typedef Texture2D texture2D; + +#line default +)" }; + + +using namespace CoreLib::Basic; + +namespace Slang +{ + namespace Compiler + { + static String stdlibPath; + + String getStdlibPath() + { + if(stdlibPath.Length() != 0) + return stdlibPath; + + StringBuilder pathBuilder; + for( auto cc = __FILE__; *cc; ++cc ) + { + switch( *cc ) + { + case '\n': + case '\t': + case '\\': + pathBuilder << "\\"; + default: + pathBuilder << *cc; + break; + } + } + stdlibPath = pathBuilder.ProduceString(); + + return stdlibPath; + } + + String SlangStdLib::code; + + enum + { + SINT_MASK = 1 << 0, + FLOAT_MASK = 1 << 1, + COMPARISON = 1 << 2, + BOOL_MASK = 1 << 3, + UINT_MASK = 1 << 4, + ASSIGNMENT = 1 << 5, + POSTFIX = 1 << 6, + + INT_MASK = SINT_MASK | UINT_MASK, + ARITHMETIC_MASK = INT_MASK | FLOAT_MASK, + LOGICAL_MASK = INT_MASK | BOOL_MASK, + ANY_MASK = INT_MASK | FLOAT_MASK | BOOL_MASK, + }; + + String SlangStdLib::GetCode() + { + if (code.Length() > 0) + return code; + StringBuilder sb; + + // generate operator overloads + + + + struct OpInfo { IntrinsicOp opCode; char const* opName; unsigned flags; }; + + OpInfo unaryOps[] = { + { IntrinsicOp::Neg, "-", ARITHMETIC_MASK }, + { IntrinsicOp::Not, "!", ANY_MASK }, + { IntrinsicOp::Not, "~", INT_MASK }, + { IntrinsicOp::PreInc, "++", ARITHMETIC_MASK | ASSIGNMENT }, + { IntrinsicOp::PreDec, "--", ARITHMETIC_MASK | ASSIGNMENT }, + { IntrinsicOp::PostInc, "++", ARITHMETIC_MASK | ASSIGNMENT | POSTFIX }, + { IntrinsicOp::PostDec, "--", ARITHMETIC_MASK | ASSIGNMENT | POSTFIX }, + }; + + OpInfo binaryOps[] = { + { IntrinsicOp::Add, "+", ARITHMETIC_MASK }, + { IntrinsicOp::Sub, "-", ARITHMETIC_MASK }, + { IntrinsicOp::Mul, "*", ARITHMETIC_MASK }, + { IntrinsicOp::Div, "/", ARITHMETIC_MASK }, + { IntrinsicOp::Mod, "%", INT_MASK }, + + { IntrinsicOp::And, "&&", LOGICAL_MASK }, + { IntrinsicOp::Or, "||", LOGICAL_MASK }, + + { IntrinsicOp::BitAnd, "&", LOGICAL_MASK }, + { IntrinsicOp::BitOr, "|", LOGICAL_MASK }, + { IntrinsicOp::BitXor, "^", LOGICAL_MASK }, + + { IntrinsicOp::Lsh, "<<", INT_MASK }, + { IntrinsicOp::Rsh, ">>", INT_MASK }, + + { IntrinsicOp::Eql, "==", ANY_MASK | COMPARISON }, + { IntrinsicOp::Neq, "!=", ANY_MASK | COMPARISON }, + + { IntrinsicOp::Greater, ">", ARITHMETIC_MASK | COMPARISON }, + { IntrinsicOp::Less, "<", ARITHMETIC_MASK | COMPARISON }, + { IntrinsicOp::Geq, ">=", ARITHMETIC_MASK | COMPARISON }, + { IntrinsicOp::Leq, "<=", ARITHMETIC_MASK | COMPARISON }, + + { IntrinsicOp::AddAssign, "+=", ASSIGNMENT | ARITHMETIC_MASK }, + { IntrinsicOp::SubAssign, "-=", ASSIGNMENT | ARITHMETIC_MASK }, + { IntrinsicOp::MulAssign, "*=", ASSIGNMENT | ARITHMETIC_MASK }, + { IntrinsicOp::DivAssign, "/=", ASSIGNMENT | ARITHMETIC_MASK }, + { IntrinsicOp::ModAssign, "%=", ASSIGNMENT | ARITHMETIC_MASK }, + { IntrinsicOp::AndAssign, "&=", ASSIGNMENT | LOGICAL_MASK }, + { IntrinsicOp::OrAssign, "|=", ASSIGNMENT | LOGICAL_MASK }, + { IntrinsicOp::XorAssign, "^=", ASSIGNMENT | LOGICAL_MASK }, + { IntrinsicOp::LshAssign, "<<=", ASSIGNMENT | INT_MASK }, + { IntrinsicOp::RshAssign, ">>=", ASSIGNMENT | INT_MASK }, + + + }; + + /* + String floatTypes[] = { "float", "float2", "float3", "float4" }; + String intTypes[] = { "int", "int2", "int3", "int4" }; + String uintTypes[] = { "uint", "uint2", "uint3", "uint4" }; + */ + + String path = getStdlibPath(); + + + +#define EMIT_LINE_DIRECTIVE() sb << "#line " << (__LINE__+1) << " \"" << path << "\"\n" + + // Generate declarations for all the base types + + static const struct { + char const* name; + BaseType tag; + unsigned flags; + } kBaseTypes[] = { + { "void", BaseType::Void, 0 }, + { "int", BaseType::Int, SINT_MASK }, + { "float", BaseType::Float, FLOAT_MASK }, + { "uint", BaseType::UInt, UINT_MASK }, + { "bool", BaseType::Bool, BOOL_MASK }, + { "uint64_t", BaseType::UInt64, UINT_MASK }, + }; + static const int kBaseTypeCount = sizeof(kBaseTypes) / sizeof(kBaseTypes[0]); + for (int tt = 0; tt < kBaseTypeCount; ++tt) + { + EMIT_LINE_DIRECTIVE(); + sb << "__builtin_type(" << int(kBaseTypes[tt].tag) << ") struct " << kBaseTypes[tt].name << "\n{\n"; + + // Declare trait conformances for this type + + sb << "__conforms __BuiltinType;\n"; + + switch( kBaseTypes[tt].tag ) + { + case BaseType::Float: + sb << "__conforms __BuiltinFloatingPointType;\n"; + sb << "__conforms __BuiltinRealType;\n"; + // fall through to: + case BaseType::Int: + sb << "__conforms __BuiltinSignedArithmeticType;\n"; + // fall through to: + case BaseType::UInt: + case BaseType::UInt64: + sb << "__conforms __BuiltinArithmeticType;\n"; + // fall through to: + case BaseType::Bool: + sb << "__conforms __BuiltinType;\n"; + break; + + default: + break; + } + + // Declare initializers to convert from various other types + for( int ss = 0; ss < kBaseTypeCount; ++ss ) + { + if( kBaseTypes[ss].tag == BaseType::Void ) + continue; + + EMIT_LINE_DIRECTIVE(); + sb << "__init(" << kBaseTypes[ss].name << " value);\n"; + } + + sb << "};\n"; + } + + // Declare ad hoc aliases for some types, just to get things compiling + // + // TODO(tfoley): At the very least, `double` should be treated as a distinct type. + sb << "typedef float double;\n"; + sb << "typedef float half;\n"; + + // Declare vector and matrix types + + sb << "__generic __magic_type(Vector) struct vector\n{\n"; + sb << " __init(T value);\n"; // initialize from single scalar + sb << "};\n"; + sb << "__generic __magic_type(Matrix) struct matrix {};\n"; + + static const struct { + char const* name; + char const* glslPrefix; + } kTypes[] = + { + {"float", ""}, + {"int", "i"}, + {"uint", "u"}, + {"bool", "b"}, + }; + static const int kTypeCount = sizeof(kTypes) / sizeof(kTypes[0]); + + for (int tt = 0; tt < kTypeCount; ++tt) + { + // Declare HLSL vector types + for (int ii = 1; ii <= 4; ++ii) + { + sb << "typedef vector<" << kTypes[tt].name << "," << ii << "> " << kTypes[tt].name << ii << ";\n"; + } + + // Declare HLSL matrix types + for (int rr = 2; rr <= 4; ++rr) + for (int cc = 2; cc <= 4; ++cc) + { + sb << "typedef matrix<" << kTypes[tt].name << "," << rr << "," << cc << "> " << kTypes[tt].name << rr << "x" << cc << ";\n"; + } + } + + static const char* kComponentNames[]{ "x", "y", "z", "w" }; + static const char* kVectorNames[]{ "", "x", "xy", "xyz", "xyzw" }; + + // Need to add constructors to the types above + for (int N = 2; N <= 4; ++N) + { + sb << "__generic __extension vector\n{\n"; + + // initialize from N scalars + sb << "__init("; + for (int ii = 0; ii < N; ++ii) + { + if (ii != 0) sb << ", "; + sb << "T " << kComponentNames[ii]; + } + sb << ");\n"; + + // Initialize from an M-vector and then scalars + for (int M = 2; M < N; ++M) + { + sb << "__init(vector " << kVectorNames[M]; + for (int ii = M; ii < N; ++ii) + { + sb << ", T " << kComponentNames[ii]; + } + sb << ");\n"; + } + + // initialize from another vector of the same size + // + // TODO(tfoley): this overlaps with implicit conversions. + // We should look for a way that we can define implicit + // conversions directly in the stdlib instead... + sb << "__generic __init(vector);\n"; + + sb << "}\n"; + } + + for( int R = 2; R <= 4; ++R ) + for( int C = 2; C <= 4; ++C ) + { + sb << "__generic __extension matrix\n{\n"; + + // initialize from R*C scalars + sb << "__init("; + for( int ii = 0; ii < R; ++ii ) + for( int jj = 0; jj < C; ++jj ) + { + if ((ii+jj) != 0) sb << ", "; + sb << "T m" << ii << jj; + } + sb << ");\n"; + + // Initialize from R C-vectors + sb << "__init("; + for (int ii = 0; ii < R; ++ii) + { + if(ii != 0) sb << ", "; + sb << "vector row" << ii; + } + sb << ");\n"; + + + // initialize from another matrix of the same size + // + // TODO(tfoley): See comment about how this overlaps + // with implicit conversion, in the `vector` case above + sb << "__generic __init(matrix);\n"; + + sb << "}\n"; + } + + + // Declare built-in texture and sampler types + + sb << "__magic_type(SamplerState," << int(SamplerStateType::Flavor::SamplerState) << ") struct SamplerState {};"; + sb << "__magic_type(SamplerState," << int(SamplerStateType::Flavor::SamplerComparisonState) << ") struct SamplerComparisonState {};"; + + // TODO(tfoley): Need to handle `RW*` variants of texture types as well... + static const struct { + char const* name; + TextureType::Shape baseShape; + int coordCount; + } kBaseTextureTypes[] = { + { "Texture1D", TextureType::Shape1D, 1 }, + { "Texture2D", TextureType::Shape2D, 2 }, + { "Texture3D", TextureType::Shape3D, 3 }, + { "TextureCube", TextureType::ShapeCube, 3 }, + }; + static const int kBaseTextureTypeCount = sizeof(kBaseTextureTypes) / sizeof(kBaseTextureTypes[0]); + + + static const struct { + char const* name; + SlangResourceAccess access; + } kBaseTextureAccessLevels[] = { + { "", SLANG_RESOURCE_ACCESS_READ }, + { "RW", SLANG_RESOURCE_ACCESS_READ_WRITE }, + { "RasterizerOrdered", SLANG_RESOURCE_ACCESS_RASTER_ORDERED }, + }; + static const int kBaseTextureAccessLevelCount = sizeof(kBaseTextureAccessLevels) / sizeof(kBaseTextureAccessLevels[0]); + + for (int tt = 0; tt < kBaseTextureTypeCount; ++tt) + { + char const* name = kBaseTextureTypes[tt].name; + TextureType::Shape baseShape = kBaseTextureTypes[tt].baseShape; + + for (int isArray = 0; isArray < 2; ++isArray) + { + // Arrays of 3D textures aren't allowed + if (isArray && baseShape == TextureType::Shape3D) continue; + + for (int isMultisample = 0; isMultisample < 2; ++isMultisample) + for (int accessLevel = 0; accessLevel < kBaseTextureAccessLevelCount; ++accessLevel) + { + auto access = kBaseTextureAccessLevels[accessLevel].access; + + // TODO: any constraints to enforce on what gets to be multisampled? + + unsigned flavor = baseShape; + if (isArray) flavor |= TextureType::ArrayFlag; + if (isMultisample) flavor |= TextureType::MultisampleFlag; +// if (isShadow) flavor |= TextureType::ShadowFlag; + + flavor |= (access << 8); + + + // emit a generic signature + // TODO: allow for multisample count to come in as well... + sb << "__generic "; + + sb << "__magic_type(Texture," << int(flavor) << ") struct "; + sb << kBaseTextureAccessLevels[accessLevel].name; + sb << name; + if (isMultisample) sb << "MS"; + if (isArray) sb << "Array"; +// if (isShadow) sb << "Shadow"; + sb << "\n{"; + + if( !isMultisample ) + { + sb << "float CalculateLevelOfDetail(SamplerState s, "; + sb << "float" << kBaseTextureTypes[tt].coordCount << " location);\n"; + + sb << "float CalculateLevelOfDetailUnclamped(SamplerState s, "; + sb << "float" << kBaseTextureTypes[tt].coordCount << " location);\n"; + + // TODO: `Gather` operation + // (tricky because it returns a 4-vector of the element type + // of the texture components...) + } + + // TODO: `GetDimensions` operations + + for(int isFloat = 0; isFloat < 2; ++isFloat) + for(int includeMipInfo = 0; includeMipInfo < 2; ++includeMipInfo) + { + char const* t = isFloat ? "out float " : "out UINT "; + + sb << "void GetDimensions("; + if(includeMipInfo) + sb << "UINT mipLevel, "; + + switch(baseShape) + { + case TextureType::Shape1D: + sb << t << "width"; + break; + + case TextureType::Shape2D: + case TextureType::ShapeCube: + sb << t << "width,"; + sb << t << "height"; + break; + + case TextureType::Shape3D: + sb << t << "width,"; + sb << t << "height,"; + sb << t << "depth"; + break; + + default: + assert(!"unexpected"); + break; + } + + if(isArray) + { + sb << ", " << t << "elements"; + } + + if(includeMipInfo) + sb << ", " << t << "numberOfLevels"; + + sb << ");\n"; + } + + // `GetSamplePosition()` + if( isMultisample ) + { + sb << "float2 GetSamplePosition(int s);\n"; + } + + // `Load()` + + if( kBaseTextureTypes[tt].coordCount + isArray < 4 ) + { + sb << "T Load("; + sb << "int" << kBaseTextureTypes[tt].coordCount + isArray + 1 << " location);\n"; + + if( !isMultisample ) + { + sb << "T Load("; + sb << "int" << kBaseTextureTypes[tt].coordCount + isArray + 1 << " location, "; + sb << "int" << kBaseTextureTypes[tt].coordCount << " offset);\n"; + } + else + { + sb << "T Load("; + sb << "int" << kBaseTextureTypes[tt].coordCount + isArray + 1 << " location, "; + sb << "int sampleIndex, "; + sb << "int" << kBaseTextureTypes[tt].coordCount << " offset);\n"; + } + } + + if(baseShape != TextureType::ShapeCube) + { + // subscript operator + sb << "__intrinsic __subscript(uint" << kBaseTextureTypes[tt].coordCount + isArray << " location) -> T;\n"; + } + + if( !isMultisample ) + { + // `Sample()` + + sb << "T Sample(SamplerState s, "; + sb << "float" << kBaseTextureTypes[tt].coordCount + isArray << " location);\n"; + + if( baseShape != TextureType::ShapeCube ) + { + sb << "T Sample(SamplerState s, "; + sb << "float" << kBaseTextureTypes[tt].coordCount + isArray << " location, "; + sb << "int" << kBaseTextureTypes[tt].coordCount << " offset);\n"; + } + + sb << "T Sample(SamplerState s, "; + sb << "float" << kBaseTextureTypes[tt].coordCount + isArray << " location, "; + if( baseShape != TextureType::ShapeCube ) + { + sb << "int" << kBaseTextureTypes[tt].coordCount << " offset, "; + } + sb << "float clamp);\n"; + + sb << "T Sample(SamplerState s, "; + sb << "float" << kBaseTextureTypes[tt].coordCount + isArray << " location, "; + if( baseShape != TextureType::ShapeCube ) + { + sb << "int" << kBaseTextureTypes[tt].coordCount << " offset, "; + } + sb << "float clamp, out uint status);\n"; + + + // `SampleBias()` + sb << "T SampleBias(SamplerState s, "; + sb << "float" << kBaseTextureTypes[tt].coordCount + isArray << " location, float bias);\n"; + + if( baseShape != TextureType::ShapeCube ) + { + sb << "T SampleBias(SamplerState s, "; + sb << "float" << kBaseTextureTypes[tt].coordCount + isArray << " location, float bias, "; + sb << "int" << kBaseTextureTypes[tt].coordCount << " offset);\n"; + } + + // `SampleCmp()` and `SampleCmpLevelZero` + sb << "T SampleCmp(SamplerComparisonState s, "; + sb << "float" << kBaseTextureTypes[tt].coordCount + isArray << " location, "; + sb << "float compareValue"; + sb << ");\n"; + + sb << "T SampleCmpLevelZero(SamplerComparisonState s, "; + sb << "float" << kBaseTextureTypes[tt].coordCount + isArray << " location, "; + sb << "float compareValue"; + sb << ");\n"; + + if( baseShape != TextureType::ShapeCube ) + { + // Note(tfoley): MSDN seems confused, and claims that the `offset` + // parameter for `SampleCmp` is available for everything but 3D + // textures, while `Sample` and `SampleBias` are consistent in + // saying they only exclude `offset` for cube maps (which makes + // sense). I'm going to assume the documentation for `SampleCmp` + // is just wrong. + + sb << "T SampleCmp(SamplerState s, "; + sb << "float" << kBaseTextureTypes[tt].coordCount + isArray << " location, "; + sb << "float compareValue, "; + sb << "int" << kBaseTextureTypes[tt].coordCount << " offset);\n"; + + sb << "T SampleCmpLevelZero(SamplerState s, "; + sb << "float" << kBaseTextureTypes[tt].coordCount + isArray << " location, "; + sb << "float compareValue, "; + sb << "int" << kBaseTextureTypes[tt].coordCount << " offset);\n"; + } + + sb << "T SampleGrad(SamplerState s, "; + sb << "float" << kBaseTextureTypes[tt].coordCount + isArray << " location, "; + sb << "float" << kBaseTextureTypes[tt].coordCount << " gradX, "; + sb << "float" << kBaseTextureTypes[tt].coordCount << " gradY"; + sb << ");\n"; + + if( baseShape != TextureType::ShapeCube ) + { + sb << "T SampleGrad(SamplerState s, "; + sb << "float" << kBaseTextureTypes[tt].coordCount + isArray << " location, "; + sb << "float" << kBaseTextureTypes[tt].coordCount << " gradX, "; + sb << "float" << kBaseTextureTypes[tt].coordCount << " gradY, "; + sb << "int" << kBaseTextureTypes[tt].coordCount << " offset);\n"; + } + + // `SampleLevel` + + sb << "T SampleLevel(SamplerState s, "; + sb << "float" << kBaseTextureTypes[tt].coordCount + isArray << " location, "; + sb << "float level);\n"; + + if( baseShape != TextureType::ShapeCube ) + { + sb << "T SampleLevel(SamplerState s, "; + sb << "float" << kBaseTextureTypes[tt].coordCount + isArray << " location, "; + sb << "float level, "; + sb << "int" << kBaseTextureTypes[tt].coordCount << " offset);\n"; + } + } + + sb << "\n};\n"; + } + } + } + + // Declare additional built-in generic types + + sb << "__generic __magic_type(ConstantBuffer) struct ConstantBuffer {};\n"; + sb << "__generic __magic_type(TextureBuffer) struct TextureBuffer {};\n"; + + sb << "__generic __magic_type(PackedBuffer) struct PackedBuffer {};\n"; + sb << "__generic __magic_type(Uniform) struct Uniform {};\n"; + sb << "__generic __magic_type(Patch) struct Patch {};\n"; + + + // Stale declarations for GLSL inner-product builtins +#if 0 + sb << "__intrinsic vec3 operator * (vec3, mat3);\n"; + sb << "__intrinsic vec3 operator * (mat3, vec3);\n"; + + sb << "__intrinsic vec4 operator * (vec4, mat4);\n"; + sb << "__intrinsic vec4 operator * (mat4, vec4);\n"; + + sb << "__intrinsic mat3 operator * (mat3, mat3);\n"; + sb << "__intrinsic mat4 operator * (mat4, mat4);\n"; +#endif + +#if 0 + sb << "__intrinsic(And) bool operator && (bool, bool);\n"; + sb << "__intrinsic(Or) bool operator || (bool, bool);\n"; + + for (auto type : intTypes) + { + sb << "__intrinsic(And) bool operator && (bool, " << type << ");\n"; + sb << "__intrinsic(Or) bool operator || (bool, " << type << ");\n"; + sb << "__intrinsic(And) bool operator && (" << type << ", bool);\n"; + sb << "__intrinsic(Or) bool operator || (" << type << ", bool);\n"; + } +#endif + + for (auto op : unaryOps) + { + for (auto type : kBaseTypes) + { + if ((type.flags & op.flags) == 0) + continue; + + char const* fixity = (op.flags & POSTFIX) != 0 ? "__postfix " : "__prefix "; + char const* qual = (op.flags & ASSIGNMENT) != 0 ? "in out " : ""; + + // scalar version + sb << fixity; + sb << "__intrinsic(" << int(op.opCode) << ") " << type.name << " operator" << op.opName << "(" << qual << type.name << " value);\n"; + + // vector version + sb << "__generic "; + sb << fixity; + sb << "__intrinsic(" << int(op.opCode) << ") vector<" << type.name << ",N> operator" << op.opName << "(" << qual << "vector<" << type.name << ",N> value);\n"; + + // matrix version + sb << "__generic "; + sb << fixity; + sb << "__intrinsic(" << int(op.opCode) << ") matrix<" << type.name << ",N,M> operator" << op.opName << "(" << qual << "matrix<" << type.name << ",N,M> value);\n"; + } + } + + for (auto op : binaryOps) + { + for (auto type : kBaseTypes) + { + if ((type.flags & op.flags) == 0) + continue; + + char const* leftType = type.name; + char const* rightType = leftType; + char const* resultType = leftType; + + if (op.flags & COMPARISON) resultType = "bool"; + + char const* leftQual = ""; + if(op.flags & ASSIGNMENT) leftQual = "in out "; + + // TODO: handle `SHIFT` + + // scalar version + sb << "__intrinsic(" << int(op.opCode) << ") " << resultType << " operator" << op.opName << "(" << leftQual << leftType << " left, " << rightType << " right);\n"; + + // vector version + sb << "__generic "; + sb << "__intrinsic(" << int(op.opCode) << ") vector<" << resultType << ",N> operator" << op.opName << "(" << leftQual << "vector<" << leftType << ",N> left, vector<" << rightType << ",N> right);\n"; + + // matrix version + sb << "__generic "; + sb << "__intrinsic(" << int(op.opCode) << ") matrix<" << resultType << ",N,M> operator" << op.opName << "(" << leftQual << "matrix<" << leftType << ",N,M> left, matrix<" << rightType << ",N,M> right);\n"; + } + } + +#if 0 + for (auto op : intUnaryOps) + { + String opName = GetOperatorFunctionName(op); + for (int i = 0; i < 4; i++) + { + auto itype = intTypes[i]; + auto utype = uintTypes[i]; + for (int j = 0; j < 2; j++) + { + auto retType = (op == Operator::Not) ? "bool" : j == 0 ? itype : utype; + sb << "__intrinsic " << retType << " operator " << opName << "(" << (j == 0 ? itype : utype) << ");\n"; + } + } + } + + for (auto op : floatUnaryOps) + { + String opName = GetOperatorFunctionName(op); + for (int i = 0; i < 4; i++) + { + auto type = floatTypes[i]; + auto retType = (op == Operator::Not) ? "bool" : type; + sb << "__intrinsic " << retType << " operator " << opName << "(" << type << ");\n"; + } + } + + for (auto op : floatOps) + { + String opName = GetOperatorFunctionName(op); + for (int i = 0; i < 4; i++) + { + auto type = floatTypes[i]; + auto itype = intTypes[i]; + auto utype = uintTypes[i]; + auto retType = ((op >= Operator::Eql && op <= Operator::Leq) || op == Operator::And || op == Operator::Or) ? "bool" : type; + sb << "__intrinsic " << retType << " operator " << opName << "(" << type << ", " << type << ");\n"; + sb << "__intrinsic " << retType << " operator " << opName << "(" << itype << ", " << type << ");\n"; + sb << "__intrinsic " << retType << " operator " << opName << "(" << utype << ", " << type << ");\n"; + sb << "__intrinsic " << retType << " operator " << opName << "(" << type << ", " << itype << ");\n"; + sb << "__intrinsic " << retType << " operator " << opName << "(" << type << ", " << utype << ");\n"; + if (i > 0) + { + sb << "__intrinsic " << retType << " operator " << opName << "(" << type << ", " << floatTypes[0] << ");\n"; + sb << "__intrinsic " << retType << " operator " << opName << "(" << floatTypes[0] << ", " << type << ");\n"; + + sb << "__intrinsic " << retType << " operator " << opName << "(" << type << ", " << intTypes[0] << ");\n"; + sb << "__intrinsic " << retType << " operator " << opName << "(" << intTypes[0] << ", " << type << ");\n"; + + sb << "__intrinsic " << retType << " operator " << opName << "(" << type << ", " << uintTypes[0] << ");\n"; + sb << "__intrinsic " << retType << " operator " << opName << "(" << uintTypes[0] << ", " << type << ");\n"; + } + } + } + + for (auto op : intOps) + { + String opName = GetOperatorFunctionName(op); + for (int i = 0; i < 4; i++) + { + auto type = intTypes[i]; + auto utype = uintTypes[i]; + auto retType = ((op >= Operator::Eql && op <= Operator::Leq) || op == Operator::And || op == Operator::Or) ? "bool" : type; + sb << "__intrinsic " << retType << " operator " << opName << "(" << type << ", " << type << ");\n"; + sb << "__intrinsic " << retType << " operator " << opName << "(" << utype << ", " << type << ");\n"; + sb << "__intrinsic " << retType << " operator " << opName << "(" << type << ", " << utype << ");\n"; + sb << "__intrinsic " << retType << " operator " << opName << "(" << utype << ", " << utype << ");\n"; + if (i > 0) + { + sb << "__intrinsic " << retType << " operator " << opName << "(" << type << ", " << intTypes[0] << ");\n"; + sb << "__intrinsic " << retType << " operator " << opName << "(" << intTypes[0] << ", " << type << ");\n"; + + sb << "__intrinsic " << retType << " operator " << opName << "(" << type << ", " << uintTypes[0] << ");\n"; + sb << "__intrinsic " << retType << " operator " << opName << "(" << uintTypes[0] << ", " << type << ");\n"; + } + } + } +#endif + + // Output a suitable `#line` directive to point at our raw stdlib code above + sb << "\n#line " << kLibIncludeStringLine << " \"" << path << "\"\n"; + + int chunkCount = sizeof(LibIncludeStringChunks) / sizeof(LibIncludeStringChunks[0]); + for (int cc = 0; cc < chunkCount; ++cc) + { + sb << LibIncludeStringChunks[cc]; + } + + code = sb.ProduceString(); + return code; + } + + + // GLSL-specific library code + + String glslLibraryCode; + + String getGLSLLibraryCode() + { + if(glslLibraryCode.Length() != 0) + return glslLibraryCode; + + String path = getStdlibPath(); + + StringBuilder sb; + +#define RAW(TEXT) \ + EMIT_LINE_DIRECTIVE(); \ + sb << TEXT; + + static const struct { + char const* name; + char const* glslPrefix; + } kTypes[] = + { + {"float", ""}, + {"int", "i"}, + {"uint", "u"}, + {"bool", "b"}, + }; + static const int kTypeCount = sizeof(kTypes) / sizeof(kTypes[0]); + + for( int tt = 0; tt < kTypeCount; ++tt ) + { + // Declare GLSL aliases for HLSL types + for (int vv = 2; vv <= 4; ++vv) + { + sb << "typedef " << kTypes[tt].name << vv << " " << kTypes[tt].glslPrefix << "vec" << vv << ";\n"; + sb << "typedef " << kTypes[tt].name << vv << "x" << vv << " " << kTypes[tt].glslPrefix << "mat" << vv << ";\n"; + } + for (int rr = 2; rr <= 4; ++rr) + for (int cc = 2; cc <= 4; ++cc) + { + sb << "typedef " << kTypes[tt].name << rr << "x" << cc << " " << kTypes[tt].glslPrefix << "mat" << rr << "x" << cc << ";\n"; + } + } + + // TODO(tfoley): Need to handle `RW*` variants of texture types as well... + static const struct { + char const* name; + TextureType::Shape baseShape; + int coordCount; + } kBaseTextureTypes[] = { + { "1D", TextureType::Shape1D, 1 }, + { "2D", TextureType::Shape2D, 2 }, + { "3D", TextureType::Shape3D, 3 }, + { "Cube", TextureType::ShapeCube, 3 }, + }; + static const int kBaseTextureTypeCount = sizeof(kBaseTextureTypes) / sizeof(kBaseTextureTypes[0]); + + + static const struct { + char const* name; + SlangResourceAccess access; + } kBaseTextureAccessLevels[] = { + { "", SLANG_RESOURCE_ACCESS_READ }, + { "RW", SLANG_RESOURCE_ACCESS_READ_WRITE }, + { "RasterizerOrdered", SLANG_RESOURCE_ACCESS_RASTER_ORDERED }, + }; + static const int kBaseTextureAccessLevelCount = sizeof(kBaseTextureAccessLevels) / sizeof(kBaseTextureAccessLevels[0]); + + for (int tt = 0; tt < kBaseTextureTypeCount; ++tt) + { + char const* shapeName = kBaseTextureTypes[tt].name; + TextureType::Shape baseShape = kBaseTextureTypes[tt].baseShape; + + for (int isArray = 0; isArray < 2; ++isArray) + { + // Arrays of 3D textures aren't allowed + if (isArray && baseShape == TextureType::Shape3D) continue; + + for (int isMultisample = 0; isMultisample < 2; ++isMultisample) + { + auto access = SLANG_RESOURCE_ACCESS_READ; + + // TODO: any constraints to enforce on what gets to be multisampled? + + + unsigned flavor = baseShape; + if (isArray) flavor |= TextureType::ArrayFlag; + if (isMultisample) flavor |= TextureType::MultisampleFlag; +// if (isShadow) flavor |= TextureType::ShadowFlag; + + flavor |= (access << 8); + + StringBuilder nameBuilder; + nameBuilder << shapeName; + if (isMultisample) nameBuilder << "MS"; + if (isArray) nameBuilder << "Array"; + auto name = nameBuilder.ProduceString(); + + sb << "__generic "; + sb << "__magic_type(TextureSampler," << int(flavor) << ") struct "; + sb << "__sampler" << name; + sb << " {};\n"; + + sb << "__generic "; + sb << "__magic_type(Texture," << int(flavor) << ") struct "; + sb << "__texture" << name; + sb << " {};\n"; + + sb << "__generic "; + sb << "__magic_type(GLSLImageType," << int(flavor) << ") struct "; + sb << "__image" << name; + sb << " {};\n"; + + // TODO(tfoley): flesh this out for all the available prefixes + static const struct + { + char const* prefix; + char const* elementType; + } kTextureElementTypes[] = { + { "", "vec4" }, + { "i", "ivec4" }, + { "u", "uvec4" }, + { nullptr, nullptr }, + }; + for( auto ee = kTextureElementTypes; ee->prefix; ++ee ) + { + sb << "typedef __sampler" << name << "<" << ee->elementType << "> " << ee->prefix << "sampler" << name << ";\n"; + sb << "typedef __texture" << name << "<" << ee->elementType << "> " << ee->prefix << "texture" << name << ";\n"; + sb << "typedef __image" << name << "<" << ee->elementType << "> " << ee->prefix << "image" << name << ";\n"; + } + } + } + } + + sb << "__generic __magic_type(GLSLInputParameterBlockType) struct __GLSLInputParameterBlock {};\n"; + sb << "__generic __magic_type(GLSLOutputParameterBlockType) struct __GLSLOutputParameterBlock {};\n"; + sb << "__generic __magic_type(GLSLShaderStorageBufferType) struct __GLSLShaderStorageBuffer {};\n"; + + sb << "__magic_type(SamplerState," << int(SamplerStateType::Flavor::SamplerState) << ") struct sampler {};"; + + sb << "__magic_type(GLSLInputAttachmentType) struct subpassInput {};"; + + // Define additional keywords + sb << "__modifier(GLSLBufferModifier) buffer;\n"; + sb << "__modifier(GLSLWriteOnlyModifier) writeonly;\n"; + sb << "__modifier(GLSLReadOnlyModifier) readonly;\n"; + sb << "__modifier(GLSLPatchModifier) patch;\n"; + + sb << "__modifier(SimpleModifier) flat;\n"; + + glslLibraryCode = sb.ProduceString(); + return glslLibraryCode; + } + + + + // + + void SlangStdLib::Finalize() + { + code = nullptr; + stdlibPath = String(); + glslLibraryCode = String(); + } + + } +} + diff --git a/source/slang/slang-stdlib.h b/source/slang/slang-stdlib.h new file mode 100644 index 000000000..65c70ecb5 --- /dev/null +++ b/source/slang/slang-stdlib.h @@ -0,0 +1,23 @@ +#ifndef SHADER_COMPILER_STD_LIB_H +#define SHADER_COMPILER_STD_LIB_H + +#include "../core/basic.h" + +namespace Slang +{ + namespace Compiler + { + class SlangStdLib + { + private: + static CoreLib::String code; + public: + static CoreLib::String GetCode(); + static void Finalize(); + }; + + CoreLib::String getGLSLLibraryCode(); + } +} + +#endif \ No newline at end of file diff --git a/source/slang/slang.cpp b/source/slang/slang.cpp new file mode 100644 index 000000000..2f37981c5 --- /dev/null +++ b/source/slang/slang.cpp @@ -0,0 +1,699 @@ +#include "../../slang.h" + +#include "../core/slang-io.h" +#include "../slang/slang-stdlib.h" +#include "../slang/parser.h" +#include "../slang/preprocessor.h" +#include "../slang/reflection.h" +#include "../slang/type-layout.h" + +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#undef WIN32_LEAN_AND_MEAN +#undef NOMINMAX +#endif + +using namespace CoreLib::Basic; +using namespace CoreLib::IO; +using namespace Slang::Compiler; + +namespace SlangLib +{ + static void stdlibDiagnosticCallback( + char const* message, + void* userData) + { + fputs(message, stderr); + fflush(stderr); +#ifdef WIN32 + OutputDebugStringA(message); +#endif + } + + class Session + { + public: + bool useCache = false; + CoreLib::String cacheDir; + + RefPtr compiler; + + RefPtr slangLanguageScope; + RefPtr hlslLanguageScope; + RefPtr glslLanguageScope; + + List> loadedModuleCode; + + + Session(bool /*pUseCache*/, CoreLib::String /*pCacheDir*/) + { + compiler = CreateShaderCompiler(); + + // Create scopes for various language builtins. + // + // TODO: load these on-demand to avoid parsing + // stdlib code for languages the user won't use. + + slangLanguageScope = new Scope(); + + hlslLanguageScope = new Scope(); + hlslLanguageScope->parent = slangLanguageScope; + + glslLanguageScope = new Scope(); + glslLanguageScope->parent = slangLanguageScope; + + addBuiltinSource(slangLanguageScope, "stdlib", SlangStdLib::GetCode()); + addBuiltinSource(glslLanguageScope, "glsl", getGLSLLibraryCode()); + } + + ~Session() + { + // We need to clean up the strings for the standard library + // code that we might have allocated and loaded into static + // variables (TODO: don't use `static` variables for this stuff) + + SlangStdLib::Finalize(); + + // Ditto for our type represnetation stuff + + ExpressionType::Finalize(); + } + + CompileUnit createPredefUnit() + { + CompileUnit translationUnit; + + + RefPtr translationUnitSyntax = new ProgramSyntaxNode(); + + TranslationUnitOptions translationUnitOptions; + translationUnit.options = translationUnitOptions; + translationUnit.SyntaxNode = translationUnitSyntax; + + return translationUnit; + } + + void addBuiltinSource( + RefPtr const& scope, + String const& path, + String const& source); + }; + + struct CompileRequest + { + // Pointer to parent session + Session* mSession; + + // Input options + CompileOptions Options; + + // Output stuff + DiagnosticSink mSink; + String mDiagnosticOutput; + + RefPtr mCollectionOfTranslationUnits; + + RefPtr mReflectionData; + + CompileResult mResult; + + List mDependencyFilePaths; + + CompileRequest(Session* session) + : mSession(session) + {} + + ~CompileRequest() + {} + + struct IncludeHandlerImpl : IncludeHandler + { + CompileRequest* request; + + List searchDirs; + + virtual bool TryToFindIncludeFile( + CoreLib::String const& pathToInclude, + CoreLib::String const& pathIncludedFrom, + CoreLib::String* outFoundPath, + CoreLib::String* outFoundSource) override + { + String path = Path::Combine(Path::GetDirectoryName(pathIncludedFrom), pathToInclude); + if (File::Exists(path)) + { + *outFoundPath = path; + *outFoundSource = File::ReadAllText(path); + + request->mDependencyFilePaths.Add(path); + + return true; + } + + for (auto & dir : searchDirs) + { + path = Path::Combine(dir, pathToInclude); + if (File::Exists(path)) + { + *outFoundPath = path; + *outFoundSource = File::ReadAllText(path); + + request->mDependencyFilePaths.Add(path); + + return true; + } + } + return false; + } + }; + + + CompileUnit parseTranslationUnit( + TranslationUnitOptions const& translationUnitOptions) + { + auto& options = Options; + + IncludeHandlerImpl includeHandler; + includeHandler.request = this; + + CompileUnit translationUnit; + + RefPtr languageScope; + switch( translationUnitOptions.sourceLanguage ) + { + case SourceLanguage::HLSL: + languageScope = mSession->hlslLanguageScope; + break; + + case SourceLanguage::GLSL: + languageScope = mSession->glslLanguageScope; + break; + + case SourceLanguage::Slang: + default: + languageScope = mSession->slangLanguageScope; + break; + } + + + auto& preprocesorDefinitions = options.PreprocessorDefinitions; + + RefPtr translationUnitSyntax = new ProgramSyntaxNode(); + + for( auto sourceFile : translationUnitOptions.sourceFiles ) + { + auto sourceFilePath = sourceFile->path; + + auto searchDirs = options.SearchDirectories; + searchDirs.Reverse(); + searchDirs.Add(Path::GetDirectoryName(sourceFilePath)); + searchDirs.Reverse(); + includeHandler.searchDirs = searchDirs; + + String source = sourceFile->content; + + auto tokens = preprocessSource( + source, + sourceFilePath, + mResult.GetErrorWriter(), + &includeHandler, + preprocesorDefinitions, + translationUnitSyntax.Ptr()); + + parseSourceFile( + translationUnitSyntax.Ptr(), + options, + tokens, + mResult.GetErrorWriter(), + sourceFilePath, + languageScope); + } + + translationUnit.options = translationUnitOptions; + translationUnit.SyntaxNode = translationUnitSyntax; + + return translationUnit; + } + + int executeCompilerDriverActions() + { + // If we are being asked to do pass-through, then we need to do that here... + if (Options.passThrough != PassThroughMode::None) + { + for( auto& translationUnitOptions : Options.translationUnits ) + { + switch( translationUnitOptions.sourceLanguage ) + { + // We can pass-through code written in a native shading language + case SourceLanguage::GLSL: + case SourceLanguage::HLSL: + break; + + // All other translation units need to be skipped + default: + continue; + } + + auto sourceFile = translationUnitOptions.sourceFiles[0]; + auto sourceFilePath = sourceFile->path; + String source = sourceFile->content; + + mSession->compiler->PassThrough( + source, + sourceFilePath, + Options, + translationUnitOptions); + } + return 0; + } + + // TODO: load the stdlib + + mCollectionOfTranslationUnits = new CollectionOfTranslationUnits(); + + // Parse everything from the input files requested + // + // TODO: this may trigger the loading and/or compilation of additional modules. + for( auto& translationUnitOptions : Options.translationUnits ) + { + auto translationUnit = parseTranslationUnit(translationUnitOptions); + mCollectionOfTranslationUnits->translationUnits.Add(translationUnit); + } + if( mResult.GetErrorCount() != 0 ) + return 1; + + // Now perform semantic checks, emit output, etc. + mSession->compiler->Compile( + mResult, mCollectionOfTranslationUnits.Ptr(), Options); + if(mResult.GetErrorCount() != 0) + return 1; + + mReflectionData = mCollectionOfTranslationUnits->layout; + + return 0; + } + + // Act as expected of the API-based compiler + int executeAPIActions() + { + mResult.mSink = &mSink; + + int err = executeCompilerDriverActions(); + + mDiagnosticOutput = mSink.outputBuffer.ProduceString(); + + if(mSink.GetErrorCount() != 0) + return mSink.GetErrorCount(); + + return err; + } + + int addTranslationUnit(SourceLanguage language, String const& name) + { + int result = Options.translationUnits.Count(); + + TranslationUnitOptions translationUnit; + translationUnit.sourceLanguage = SourceLanguage(language); + + Options.translationUnits.Add(translationUnit); + + return result; + } + + void addTranslationUnitSourceString( + int translationUnitIndex, + String const& path, + String const& source) + { + RefPtr sourceFile = new SourceFile(); + sourceFile->path = path; + sourceFile->content = source; + + Options.translationUnits[translationUnitIndex].sourceFiles.Add(sourceFile); + } + + void addTranslationUnitSourceFile( + int translationUnitIndex, + String const& path) + { + String source; + try + { + source = File::ReadAllText(path); + } + catch( ... ) + { + // Emit a diagnostic! + mSink.diagnose( + CodePosition(0,0,0,path), + Diagnostics::cannotOpenFile, + path); + return; + } + + addTranslationUnitSourceString( + translationUnitIndex, + path, + source); + + mDependencyFilePaths.Add(path); + } + + int addTranslationUnitEntryPoint( + int translationUnitIndex, + String const& name, + Profile profile) + { + EntryPointOption entryPoint; + entryPoint.name = name; + entryPoint.profile = profile; + + // TODO: realistically want this to be global across all TUs... + int result = Options.translationUnits[translationUnitIndex].entryPoints.Count(); + + Options.translationUnits[translationUnitIndex].entryPoints.Add(entryPoint); + return result; + } + }; + + void Session::addBuiltinSource( + RefPtr const& scope, + String const& path, + String const& source) + { + CompileRequest compileRequest(this); + + auto translationUnitIndex = compileRequest.addTranslationUnit(SourceLanguage::Slang, path); + + compileRequest.addTranslationUnitSourceString( + translationUnitIndex, + path, + source); + + int err = compileRequest.executeAPIActions(); + if(err) + { + fprintf(stderr, "%s", compileRequest.mDiagnosticOutput.Buffer()); + +#ifdef _WIN32 + OutputDebugStringA(compileRequest.mDiagnosticOutput.Buffer()); +#endif + + assert(!"error in stdlib"); + } + + // Extract the AST for the code we just parsed + auto syntax = compileRequest.mCollectionOfTranslationUnits->translationUnits[translationUnitIndex].SyntaxNode; + + // HACK(tfoley): mark all declarations in the "stdlib" so + // that we can detect them later (e.g., so we don't emit them) + for (auto m : syntax->Members) + { + auto fromStdLibModifier = new FromStdLibModifier(); + + fromStdLibModifier->next = m->modifiers.first; + m->modifiers.first = fromStdLibModifier; + } + + // Add the resulting code to the appropriate scope + if( !scope->containerDecl ) + { + // We are the first chunk of code to be loaded for this scope + scope->containerDecl = syntax.Ptr(); + } + else + { + // We need to create a new scope to link into the whole thing + auto subScope = new Scope(); + subScope->containerDecl = syntax.Ptr(); + subScope->nextSibling = scope->nextSibling; + scope->nextSibling = subScope; + } + + // We need to retain this AST so that we can use it in other code + // (Note that the `Scope` type does not retain the AST it points to) + loadedModuleCode.Add(syntax); + } +} + +using namespace SlangLib; + +// implementation of C interface + +#define SESSION(x) reinterpret_cast(x) +#define REQ(x) reinterpret_cast(x) + +SLANG_API SlangSession* spCreateSession(const char * cacheDir) +{ + return reinterpret_cast(new SlangLib::Session((cacheDir ? true : false), cacheDir)); +} + +SLANG_API void spDestroySession( + SlangSession* session) +{ + if(!session) return; + delete SESSION(session); +} + +SLANG_API void spAddBuiltins( + SlangSession* session, + char const* sourcePath, + char const* sourceString) +{ + auto s = SESSION(session); + s->addBuiltinSource( + + // TODO(tfoley): Add ability to directly new builtins to the approriate scope + s->slangLanguageScope, + + sourcePath, + sourceString); +} + + +SLANG_API SlangCompileRequest* spCreateCompileRequest( + SlangSession* session) +{ + auto s = SESSION(session); + auto req = new SlangLib::CompileRequest(s); + return reinterpret_cast(req); +} + +/*! +@brief Destroy a compile request. +*/ +SLANG_API void spDestroyCompileRequest( + SlangCompileRequest* request) +{ + if(!request) return; + auto req = REQ(request); + delete req; +} + +SLANG_API void spSetCompileFlags( + SlangCompileRequest* request, + SlangCompileFlags flags) +{ + REQ(request)->Options.flags = flags; +} + +SLANG_API void spSetCodeGenTarget( + SlangCompileRequest* request, + int target) +{ + REQ(request)->Options.Target = (CodeGenTarget)target; +} + +SLANG_API void spSetPassThrough( + SlangCompileRequest* request, + SlangPassThrough passThrough) +{ + REQ(request)->Options.passThrough = PassThroughMode(passThrough); +} + +SLANG_API void spSetDiagnosticCallback( + SlangCompileRequest* request, + SlangDiagnosticCallback callback, + void const* userData) +{ + if(!request) return; + auto req = REQ(request); + + req->mSink.callback = callback; + req->mSink.callbackUserData = (void*) userData; +} + +SLANG_API void spAddSearchPath( + SlangCompileRequest* request, + const char* searchDir) +{ + REQ(request)->Options.SearchDirectories.Add(searchDir); +} + +SLANG_API void spAddPreprocessorDefine( + SlangCompileRequest* request, + const char* key, + const char* value) +{ + REQ(request)->Options.PreprocessorDefinitions[key] = value; +} + +SLANG_API char const* spGetDiagnosticOutput( + SlangCompileRequest* request) +{ + if(!request) return 0; + auto req = REQ(request); + return req->mDiagnosticOutput.begin(); +} + +// New-fangled compilation API + +SLANG_API int spAddTranslationUnit( + SlangCompileRequest* request, + SlangSourceLanguage language, + char const* name) +{ + auto req = REQ(request); + + return req->addTranslationUnit( + SourceLanguage(language), + name ? name : ""); +} + +SLANG_API void spAddTranslationUnitSourceFile( + SlangCompileRequest* request, + int translationUnitIndex, + char const* path) +{ + if(!request) return; + auto req = REQ(request); + if(!path) return; + if(translationUnitIndex < 0) return; + if(translationUnitIndex >= req->Options.translationUnits.Count()) return; + + req->addTranslationUnitSourceFile( + translationUnitIndex, + path); +} + +// Add a source string to the given translation unit +SLANG_API void spAddTranslationUnitSourceString( + SlangCompileRequest* request, + int translationUnitIndex, + char const* path, + char const* source) +{ + if(!request) return; + auto req = REQ(request); + if(!source) return; + if(translationUnitIndex < 0) return; + if(translationUnitIndex >= req->Options.translationUnits.Count()) return; + + if(!path) path = ""; + + req->addTranslationUnitSourceString( + translationUnitIndex, + path, + source); + +} + +SLANG_API SlangProfileID spFindProfile( + SlangSession* session, + char const* name) +{ + return Profile::LookUp(name).raw; +} + +SLANG_API int spAddTranslationUnitEntryPoint( + SlangCompileRequest* request, + int translationUnitIndex, + char const* name, + SlangProfileID profile) +{ + if(!request) return -1; + auto req = REQ(request); + if(!name) return -1; + if(translationUnitIndex < 0) return -1; + if(translationUnitIndex >= req->Options.translationUnits.Count()) return -1; + + + return req->addTranslationUnitEntryPoint( + translationUnitIndex, + name, + Profile(Profile::RawVal(profile))); +} + + +// Compile in a context that already has its translation units specified +SLANG_API int spCompile( + SlangCompileRequest* request) +{ + auto req = REQ(request); + + int anyErrors = req->executeAPIActions(); + return anyErrors; +} + +SLANG_API int +spGetDependencyFileCount( + SlangCompileRequest* request) +{ + if(!request) return 0; + auto req = REQ(request); + return req->mDependencyFilePaths.Count(); +} + +/** Get the path to a file this compilation dependend on. +*/ +SLANG_API char const* +spGetDependencyFilePath( + SlangCompileRequest* request, + int index) +{ + if(!request) return 0; + auto req = REQ(request); + return req->mDependencyFilePaths[index].begin(); +} + +SLANG_API int +spGetTranslationUnitCount( + SlangCompileRequest* request) +{ + auto req = REQ(request); + return req->mResult.translationUnits.Count(); +} + +// Get the output code associated with a specific translation unit +SLANG_API char const* spGetTranslationUnitSource( + SlangCompileRequest* request, + int translationUnitIndex) +{ + auto req = REQ(request); + return req->mResult.translationUnits[translationUnitIndex].outputSource.Buffer(); +} + +SLANG_API char const* spGetEntryPointSource( + SlangCompileRequest* request, + int translationUnitIndex, + int entryPointIndex) +{ + auto req = REQ(request); + return req->mResult.translationUnits[translationUnitIndex].entryPoints[entryPointIndex].outputSource.Buffer(); + +} + +// Reflection API + +SLANG_API SlangReflection* spGetReflection( + SlangCompileRequest* request) +{ + if( !request ) return 0; + + auto req = REQ(request); + return (SlangReflection*) req->mReflectionData.Ptr(); +} + + +// ... rest of reflection API implementation is in `Reflection.cpp` diff --git a/source/slang/slang.natvis b/source/slang/slang.natvis new file mode 100644 index 000000000..bfc1e7317 --- /dev/null +++ b/source/slang/slang.natvis @@ -0,0 +1,14 @@ + + + + {{CFG Basic Block}} + + + kvPairs.FCount + kvPairs.FHead + pNext + Value + + + + \ No newline at end of file diff --git a/source/slang/slang.vcxproj b/source/slang/slang.vcxproj new file mode 100644 index 000000000..df34e40dc --- /dev/null +++ b/source/slang/slang.vcxproj @@ -0,0 +1,427 @@ + + + + + DebugClang + Win32 + + + DebugClang + x64 + + + Debug_VS2013 + Win32 + + + Debug_VS2013 + x64 + + + Debug + Win32 + + + Debug + x64 + + + Release_VS2013 + Win32 + + + Release_VS2013 + x64 + + + Release + Win32 + + + Release + x64 + + + + {DB00DA62-0533-4AFD-B59F-A67D5B3A0808} + Win32Proj + SpireCore + slang + 8.1 + + + + StaticLibrary + true + v140 + Unicode + + + StaticLibrary + true + v120 + Unicode + + + StaticLibrary + true + v140_clang_3_7 + Unicode + + + StaticLibrary + true + v140 + Unicode + + + StaticLibrary + true + v120 + Unicode + + + StaticLibrary + true + v140_Clang_3_7 + Unicode + + + StaticLibrary + false + v140 + true + Unicode + + + StaticLibrary + false + v120 + true + Unicode + + + StaticLibrary + false + v140 + true + Unicode + + + StaticLibrary + false + v120 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + + + true + + + true + + + true + + + true + + + true + + + false + + + false + + + false + + + false + + + + + + Level4 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + ../ + MultiThreadedDebug + false + + + Console + true + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + ../ + MultiThreadedDebug + false + + + Console + true + + + + + + + EnableAllWarnings + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + ../ + MultiThreadedDebug + false + true + + + Console + true + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + ../ + MultiThreadedDebug + true + false + + + Console + true + + + true + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + ../ + MultiThreadedDebug + true + false + + + Console + true + + + true + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + ../ + MultiThreadedDebug + true + false + + + Console + true + + + true + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + ../ + MultiThreaded + false + + + Console + true + true + true + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + ../ + MultiThreaded + false + + + Console + true + true + true + + + + + Level4 + + + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + ../ + MultiThreaded + false + + + Console + true + true + true + + + + + Level4 + + + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + ../ + MultiThreaded + false + + + Console + true + true + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source/slang/slang.vcxproj.filters b/source/slang/slang.vcxproj.filters new file mode 100644 index 000000000..dac58bbf7 --- /dev/null +++ b/source/slang/slang.vcxproj.filters @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source/slang/source-loc.h b/source/slang/source-loc.h new file mode 100644 index 000000000..dc353f402 --- /dev/null +++ b/source/slang/source-loc.h @@ -0,0 +1,47 @@ +// source-loc.h +#ifndef SLANG_SOURCE_LOC_H_INCLUDED +#define SLANG_SOURCE_LOC_H_INCLUDED + +#include "../core/basic.h" + +namespace Slang { +namespace Compiler { + +using namespace CoreLib::Basic; + +class CodePosition +{ +public: + int Line = -1, Col = -1, Pos = -1; + String FileName; + String ToString() + { + StringBuilder sb(100); + sb << FileName; + if (Line != -1) + sb << "(" << Line << ")"; + return sb.ProduceString(); + } + CodePosition() = default; + CodePosition(int line, int col, int pos, String fileName) + { + Line = line; + Col = col; + Pos = pos; + this->FileName = fileName; + } + bool operator < (const CodePosition & pos) const + { + return FileName < pos.FileName || (FileName == pos.FileName && Line < pos.Line) || + (FileName == pos.FileName && Line == pos.Line && Col < pos.Col); + } + bool operator == (const CodePosition & pos) const + { + return FileName == pos.FileName && Line == pos.Line && Col == pos.Col; + } +}; + + +}} + +#endif diff --git a/source/slang/syntax-visitors.h b/source/slang/syntax-visitors.h new file mode 100644 index 000000000..565ac3ace --- /dev/null +++ b/source/slang/syntax-visitors.h @@ -0,0 +1,21 @@ +#ifndef RASTER_RENDERER_SYNTAX_PRINTER_H +#define RASTER_RENDERER_SYNTAX_PRINTER_H + +#include "diagnostics.h" +#include "syntax.h" +#include "compiled-program.h" + +namespace Slang +{ + namespace Compiler + { + class CompileOptions; + class ShaderCompiler; + class ShaderLinkInfo; + class ShaderSymbol; + + SyntaxVisitor * CreateSemanticsVisitor(DiagnosticSink * err, CompileOptions const& options); + } +} + +#endif \ No newline at end of file diff --git a/source/slang/syntax.cpp b/source/slang/syntax.cpp new file mode 100644 index 000000000..3050afff6 --- /dev/null +++ b/source/slang/syntax.cpp @@ -0,0 +1,1484 @@ +#include "syntax.h" +#include "syntax-visitors.h" +#include +#include + +namespace Slang +{ + namespace Compiler + { + // BasicExpressionType + + bool BasicExpressionType::EqualsImpl(ExpressionType * type) + { + auto basicType = dynamic_cast(type); + if (basicType == nullptr) + return false; + return basicType->BaseType == BaseType; + } + + ExpressionType* BasicExpressionType::CreateCanonicalType() + { + // A basic type is already canonical, in our setup + return this; + } + + CoreLib::Basic::String BasicExpressionType::ToString() + { + CoreLib::Basic::StringBuilder res; + + switch (BaseType) + { + case Compiler::BaseType::Int: + res.Append("int"); + break; + case Compiler::BaseType::UInt: + res.Append("uint"); + break; + case Compiler::BaseType::UInt64: + res.Append("uint64_t"); + break; + case Compiler::BaseType::Bool: + res.Append("bool"); + break; + case Compiler::BaseType::Float: + res.Append("float"); + break; + case Compiler::BaseType::Void: + res.Append("void"); + break; + default: + break; + } + return res.ProduceString(); + } + + RefPtr ProgramSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitProgram(this); + } + + RefPtr FunctionSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitFunction(this); + } + + // + + RefPtr ScopeDecl::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitScopeDecl(this); + } + + // + + RefPtr BlockStatementSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitBlockStatement(this); + } + + RefPtr BreakStatementSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitBreakStatement(this); + } + + RefPtr ContinueStatementSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitContinueStatement(this); + } + + RefPtr DoWhileStatementSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitDoWhileStatement(this); + } + + RefPtr EmptyStatementSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitEmptyStatement(this); + } + + RefPtr ForStatementSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitForStatement(this); + } + + RefPtr IfStatementSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitIfStatement(this); + } + + RefPtr ReturnStatementSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitReturnStatement(this); + } + + RefPtr VarDeclrStatementSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitVarDeclrStatement(this); + } + + RefPtr Variable::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitDeclrVariable(this); + } + + RefPtr WhileStatementSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitWhileStatement(this); + } + + RefPtr ExpressionStatementSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitExpressionStatement(this); + } + + RefPtr ConstantExpressionSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitConstantExpression(this); + } + + RefPtr IndexExpressionSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitIndexExpression(this); + } + RefPtr MemberExpressionSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitMemberExpression(this); + } + + // SwizzleExpr + + RefPtr SwizzleExpr::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitSwizzleExpression(this); + } + + // DerefExpr + + RefPtr DerefExpr::Accept(SyntaxVisitor * /*visitor*/) + { + // throw "unimplemented"; + return this; + } + + // + + RefPtr InvokeExpressionSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitInvokeExpression(this); + } + + RefPtr TypeCastExpressionSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitTypeCastExpression(this); + } + + RefPtr VarExpressionSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitVarExpression(this); + } + + // OverloadedExpr + + RefPtr OverloadedExpr::Accept(SyntaxVisitor * /*visitor*/) + { +// throw "unimplemented"; + return this; + } + + // + + RefPtr ParameterSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitParameter(this); + } + + // UsingFileDecl + + RefPtr UsingFileDecl::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitUsingFileDecl(this); + } + + // + + RefPtr StructField::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitStructField(this); + } + RefPtr StructSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitStruct(this); + } + RefPtr ClassSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitClass(this); + } + RefPtr TypeDefDecl::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitTypeDefDecl(this); + } + + RefPtr DiscardStatementSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitDiscardStatement(this); + } + + // BasicExpressionType + + BasicExpressionType* BasicExpressionType::GetScalarType() + { + return this; + } + + // + + bool ExpressionType::Equals(ExpressionType * type) + { + return GetCanonicalType()->EqualsImpl(type->GetCanonicalType()); + } + + bool ExpressionType::Equals(RefPtr type) + { + return Equals(type.Ptr()); + } + + bool ExpressionType::EqualsVal(Val* val) + { + if (auto type = dynamic_cast(val)) + return const_cast(this)->Equals(type); + return false; + } + + NamedExpressionType* ExpressionType::AsNamedType() + { + return dynamic_cast(this); + } + + RefPtr ExpressionType::SubstituteImpl(Substitutions* subst, int* ioDiff) + { + int diff = 0; + auto canSubst = GetCanonicalType()->SubstituteImpl(subst, &diff); + + // If nothing changed, then don't drop any sugar that is applied + if (!diff) + return this; + + // If the canonical type changed, then we return a canonical type, + // rather than try to re-construct any amount of sugar + (*ioDiff)++; + return canSubst; + } + + + ExpressionType* ExpressionType::GetCanonicalType() + { + if (!this) return nullptr; + ExpressionType* et = const_cast(this); + if (!et->canonicalType) + { + // TODO(tfoley): worry about thread safety here? + et->canonicalType = et->CreateCanonicalType(); + assert(et->canonicalType); + } + return et->canonicalType; + } + + bool ExpressionType::IsTextureOrSampler() + { + return IsTexture() || IsSampler(); + } + bool ExpressionType::IsStruct() + { + auto declRefType = AsDeclRefType(); + if (!declRefType) return false; + auto structDeclRef = declRefType->declRef.As(); + if (!structDeclRef) return false; + return true; + } + + bool ExpressionType::IsClass() + { + auto declRefType = AsDeclRefType(); + if (!declRefType) return false; + auto classDeclRef = declRefType->declRef.As(); + if (!classDeclRef) return false; + return true; + } + +#if 0 + RefPtr ExpressionType::Bool; + RefPtr ExpressionType::UInt; + RefPtr ExpressionType::Int; + RefPtr ExpressionType::Float; + RefPtr ExpressionType::Float2; + RefPtr ExpressionType::Void; +#endif + RefPtr ExpressionType::Error; + RefPtr ExpressionType::initializerListType; + RefPtr ExpressionType::Overloaded; + + Dictionary> ExpressionType::sBuiltinTypes; + Dictionary ExpressionType::sMagicDecls; + List> ExpressionType::sCanonicalTypes; + + void ExpressionType::Init() + { + Error = new ErrorType(); + initializerListType = new InitializerListType(); + Overloaded = new OverloadGroupType(); + } + void ExpressionType::Finalize() + { + Error = nullptr; + initializerListType = nullptr; + Overloaded = nullptr; + // Note(tfoley): This seems to be just about the only way to clear out a List + sCanonicalTypes = List>(); + sBuiltinTypes = Dictionary>(); + sMagicDecls = Dictionary(); + } + bool ArrayExpressionType::EqualsImpl(ExpressionType * type) + { + auto arrType = type->AsArrayType(); + if (!arrType) + return false; + return (ArrayLength == arrType->ArrayLength && BaseType->Equals(arrType->BaseType.Ptr())); + } + ExpressionType* ArrayExpressionType::CreateCanonicalType() + { + auto canonicalBaseType = BaseType->GetCanonicalType(); + auto canonicalArrayType = new ArrayExpressionType(); + sCanonicalTypes.Add(canonicalArrayType); + canonicalArrayType->BaseType = canonicalBaseType; + canonicalArrayType->ArrayLength = ArrayLength; + return canonicalArrayType; + } + int ArrayExpressionType::GetHashCode() + { + if (ArrayLength) + return (BaseType->GetHashCode() * 16777619) ^ ArrayLength->GetHashCode(); + else + return BaseType->GetHashCode(); + } + CoreLib::Basic::String ArrayExpressionType::ToString() + { + if (ArrayLength) + return BaseType->ToString() + "[" + ArrayLength->ToString() + "]"; + else + return BaseType->ToString() + "[]"; + } + RefPtr GenericAppExpr::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitGenericApp(this); + } + + // DeclRefType + + String DeclRefType::ToString() + { + return declRef.GetName(); + } + + int DeclRefType::GetHashCode() + { + return (declRef.GetHashCode() * 16777619) ^ (int)(typeid(this).hash_code()); + } + + bool DeclRefType::EqualsImpl(ExpressionType * type) + { + if (auto declRefType = type->AsDeclRefType()) + { + return declRef.Equals(declRefType->declRef); + } + return false; + } + + ExpressionType* DeclRefType::CreateCanonicalType() + { + // A declaration reference is already canonical + return this; + } + + RefPtr DeclRefType::SubstituteImpl(Substitutions* subst, int* ioDiff) + { + if (!subst) return this; + + // the case we especially care about is when this type references a declaration + // of a generic parameter, since that is what we might be substituting... + if (auto genericTypeParamDecl = dynamic_cast(declRef.GetDecl())) + { + // search for a substitution that might apply to us + for (auto s = subst; s; s = s->outer.Ptr()) + { + // the generic decl associated with the substitution list must be + // the generic decl that declared this parameter + auto genericDecl = s->genericDecl; + if (genericDecl != genericTypeParamDecl->ParentDecl) + continue; + + int index = 0; + for (auto m : genericDecl->Members) + { + if (m.Ptr() == genericTypeParamDecl) + { + // We've found it, so return the corresponding specialization argument + (*ioDiff)++; + return s->args[index]; + } + else if(auto typeParam = m.As()) + { + index++; + } + else if(auto valParam = m.As()) + { + index++; + } + else + { + } + } + + } + } + + + int diff = 0; + DeclRef substDeclRef = declRef.SubstituteImpl(subst, &diff); + + if (!diff) + return this; + + // Make sure to record the difference! + *ioDiff += diff; + + // Re-construct the type in case we are using a specialized sub-class + return DeclRefType::Create(substDeclRef); + } + + static RefPtr ExtractGenericArgType(RefPtr val) + { + auto type = val.As(); + assert(type.Ptr()); + return type; + } + + static RefPtr ExtractGenericArgInteger(RefPtr val) + { + auto intVal = val.As(); + assert(intVal.Ptr()); + return intVal; + } + + // TODO: need to figure out how to unify this with the logic + // in the generic case... + DeclRefType* DeclRefType::Create(DeclRef declRef) + { + if (auto builtinMod = declRef.GetDecl()->FindModifier()) + { + auto type = new BasicExpressionType(builtinMod->tag); + type->declRef = declRef; + return type; + } + else if (auto magicMod = declRef.GetDecl()->FindModifier()) + { + Substitutions* subst = declRef.substitutions.Ptr(); + + if (magicMod->name == "SamplerState") + { + auto type = new SamplerStateType(); + type->declRef = declRef; + type->flavor = SamplerStateType::Flavor(magicMod->tag); + return type; + } + else if (magicMod->name == "Vector") + { + assert(subst && subst->args.Count() == 2); + auto vecType = new VectorExpressionType(); + vecType->declRef = declRef; + vecType->elementType = ExtractGenericArgType(subst->args[0]); + vecType->elementCount = ExtractGenericArgInteger(subst->args[1]); + return vecType; + } + else if (magicMod->name == "Matrix") + { + assert(subst && subst->args.Count() == 3); + auto matType = new MatrixExpressionType(); + matType->declRef = declRef; + return matType; + } + else if (magicMod->name == "Texture") + { + assert(subst && subst->args.Count() >= 1); + auto textureType = new TextureType( + TextureType::Flavor(magicMod->tag), + ExtractGenericArgType(subst->args[0])); + textureType->declRef = declRef; + return textureType; + } + else if (magicMod->name == "TextureSampler") + { + assert(subst && subst->args.Count() >= 1); + auto textureType = new TextureSamplerType( + TextureType::Flavor(magicMod->tag), + ExtractGenericArgType(subst->args[0])); + textureType->declRef = declRef; + return textureType; + } + else if (magicMod->name == "GLSLImageType") + { + assert(subst && subst->args.Count() >= 1); + auto textureType = new GLSLImageType( + TextureType::Flavor(magicMod->tag), + ExtractGenericArgType(subst->args[0])); + textureType->declRef = declRef; + return textureType; + } + + #define CASE(n,T) \ + else if(magicMod->name == #n) { \ + assert(subst && subst->args.Count() == 1); \ + auto type = new T(); \ + type->elementType = ExtractGenericArgType(subst->args[0]); \ + type->declRef = declRef; \ + return type; \ + } + + CASE(ConstantBuffer, ConstantBufferType) + CASE(TextureBuffer, TextureBufferType) + CASE(GLSLInputParameterBlockType, GLSLInputParameterBlockType) + CASE(GLSLOutputParameterBlockType, GLSLOutputParameterBlockType) + CASE(GLSLShaderStorageBufferType, GLSLShaderStorageBufferType) + + CASE(PackedBuffer, PackedBufferType) + CASE(Uniform, UniformBufferType) + CASE(Patch, PatchType) + + CASE(HLSLBufferType, HLSLBufferType) + CASE(HLSLStructuredBufferType, HLSLStructuredBufferType) + CASE(HLSLRWBufferType, HLSLRWBufferType) + CASE(HLSLRWStructuredBufferType, HLSLRWStructuredBufferType) + CASE(HLSLAppendStructuredBufferType, HLSLAppendStructuredBufferType) + CASE(HLSLConsumeStructuredBufferType, HLSLConsumeStructuredBufferType) + CASE(HLSLInputPatchType, HLSLInputPatchType) + CASE(HLSLOutputPatchType, HLSLOutputPatchType) + + CASE(HLSLPointStreamType, HLSLPointStreamType) + CASE(HLSLLineStreamType, HLSLPointStreamType) + CASE(HLSLTriangleStreamType, HLSLPointStreamType) + + #undef CASE + + // "magic" builtin types which have no generic parameters + #define CASE(n,T) \ + else if(magicMod->name == #n) { \ + auto type = new T(); \ + type->declRef = declRef; \ + return type; \ + } + + CASE(HLSLByteAddressBufferType, HLSLByteAddressBufferType) + CASE(HLSLRWByteAddressBufferType, HLSLRWByteAddressBufferType) + CASE(UntypedBufferResourceType, UntypedBufferResourceType) + + CASE(GLSLInputAttachmentType, GLSLInputAttachmentType) + + #undef CASE + + else + { + throw "unimplemented"; + } + } + else + { + return new DeclRefType(declRef); + } + } + + // OverloadGroupType + + String OverloadGroupType::ToString() + { + return "overload group"; + } + + bool OverloadGroupType::EqualsImpl(ExpressionType * /*type*/) + { + return false; + } + + ExpressionType* OverloadGroupType::CreateCanonicalType() + { + return this; + } + + int OverloadGroupType::GetHashCode() + { + return (int)(int64_t)(void*)this; + } + + // InitializerListType + + String InitializerListType::ToString() + { + return "initializer list"; + } + + bool InitializerListType::EqualsImpl(ExpressionType * /*type*/) + { + return false; + } + + ExpressionType* InitializerListType::CreateCanonicalType() + { + return this; + } + + int InitializerListType::GetHashCode() + { + return (int)(int64_t)(void*)this; + } + + // ErrorType + + String ErrorType::ToString() + { + return "error"; + } + + bool ErrorType::EqualsImpl(ExpressionType* type) + { + if (auto errorType = type->As()) + return true; + return false; + } + + ExpressionType* ErrorType::CreateCanonicalType() + { + return this; + } + + int ErrorType::GetHashCode() + { + return (int)(int64_t)(void*)this; + } + + + // NamedExpressionType + + String NamedExpressionType::ToString() + { + return declRef.GetName(); + } + + bool NamedExpressionType::EqualsImpl(ExpressionType * /*type*/) + { + assert(!"unreachable"); + return false; + } + + ExpressionType* NamedExpressionType::CreateCanonicalType() + { + return declRef.GetType()->GetCanonicalType(); + } + + int NamedExpressionType::GetHashCode() + { + assert(!"unreachable"); + return 0; + } + + // FuncType + + String FuncType::ToString() + { + // TODO: a better approach than this + if (declRef) + return declRef.GetName(); + else + return "/* unknown FuncType */"; + } + + bool FuncType::EqualsImpl(ExpressionType * type) + { + if (auto funcType = type->As()) + { + return declRef == funcType->declRef; + } + return false; + } + + ExpressionType* FuncType::CreateCanonicalType() + { + return this; + } + + int FuncType::GetHashCode() + { + return declRef.GetHashCode(); + } + + // TypeType + + String TypeType::ToString() + { + StringBuilder sb; + sb << "typeof(" << type->ToString() << ")"; + return sb.ProduceString(); + } + + bool TypeType::EqualsImpl(ExpressionType * t) + { + if (auto typeType = t->As()) + { + return t->Equals(typeType->type); + } + return false; + } + + ExpressionType* TypeType::CreateCanonicalType() + { + auto canType = new TypeType(type->GetCanonicalType()); + sCanonicalTypes.Add(canType); + return canType; + } + + int TypeType::GetHashCode() + { + assert(!"unreachable"); + return 0; + } + + // GenericDeclRefType + + String GenericDeclRefType::ToString() + { + // TODO: what is appropriate here? + return ""; + } + + bool GenericDeclRefType::EqualsImpl(ExpressionType * type) + { + if (auto genericDeclRefType = type->As()) + { + return declRef.Equals(genericDeclRefType->declRef); + } + return false; + } + + int GenericDeclRefType::GetHashCode() + { + return declRef.GetHashCode(); + } + + ExpressionType* GenericDeclRefType::CreateCanonicalType() + { + return this; + } + + // ArithmeticExpressionType + + // VectorExpressionType + + String VectorExpressionType::ToString() + { + StringBuilder sb; + sb << "vector<" << elementType->ToString() << "," << elementCount->ToString() << ">"; + return sb.ProduceString(); + } + + BasicExpressionType* VectorExpressionType::GetScalarType() + { + return elementType->AsBasicType(); + } + + // MatrixExpressionType + + String MatrixExpressionType::ToString() + { + StringBuilder sb; + sb << "matrix<" << getElementType()->ToString() << "," << getRowCount()->ToString() << "," << getColumnCount()->ToString() << ">"; + return sb.ProduceString(); + } + + BasicExpressionType* MatrixExpressionType::GetScalarType() + { + return getElementType()->AsBasicType(); + } + + ExpressionType* MatrixExpressionType::getElementType() + { + return this->declRef.substitutions->args[0].As().Ptr(); + } + + IntVal* MatrixExpressionType::getRowCount() + { + return this->declRef.substitutions->args[1].As().Ptr(); + } + + IntVal* MatrixExpressionType::getColumnCount() + { + return this->declRef.substitutions->args[2].As().Ptr(); + } + + // + +#if 0 + String GetOperatorFunctionName(Operator op) + { + switch (op) + { + case Operator::Add: + case Operator::AddAssign: + return "+"; + case Operator::Sub: + case Operator::SubAssign: + return "-"; + case Operator::Neg: + return "-"; + case Operator::Not: + return "!"; + case Operator::BitNot: + return "~"; + case Operator::PreInc: + case Operator::PostInc: + return "++"; + case Operator::PreDec: + case Operator::PostDec: + return "--"; + case Operator::Mul: + case Operator::MulAssign: + return "*"; + case Operator::Div: + case Operator::DivAssign: + return "/"; + case Operator::Mod: + case Operator::ModAssign: + return "%"; + case Operator::Lsh: + case Operator::LshAssign: + return "<<"; + case Operator::Rsh: + case Operator::RshAssign: + return ">>"; + case Operator::Eql: + return "=="; + case Operator::Neq: + return "!="; + case Operator::Greater: + return ">"; + case Operator::Less: + return "<"; + case Operator::Geq: + return ">="; + case Operator::Leq: + return "<="; + case Operator::BitAnd: + case Operator::AndAssign: + return "&"; + case Operator::BitXor: + case Operator::XorAssign: + return "^"; + case Operator::BitOr: + case Operator::OrAssign: + return "|"; + case Operator::And: + return "&&"; + case Operator::Or: + return "||"; + case Operator::Sequence: + return ","; + case Operator::Select: + return "?:"; + case Operator::Assign: + return "="; + default: + return ""; + } + } +#endif + String OperatorToString(Operator op) + { + switch (op) + { + case Slang::Compiler::Operator::Neg: + return "-"; + case Slang::Compiler::Operator::Not: + return "!"; + case Slang::Compiler::Operator::PreInc: + return "++"; + case Slang::Compiler::Operator::PreDec: + return "--"; + case Slang::Compiler::Operator::PostInc: + return "++"; + case Slang::Compiler::Operator::PostDec: + return "--"; + case Slang::Compiler::Operator::Mul: + case Slang::Compiler::Operator::MulAssign: + return "*"; + case Slang::Compiler::Operator::Div: + case Slang::Compiler::Operator::DivAssign: + return "/"; + case Slang::Compiler::Operator::Mod: + case Slang::Compiler::Operator::ModAssign: + return "%"; + case Slang::Compiler::Operator::Add: + case Slang::Compiler::Operator::AddAssign: + return "+"; + case Slang::Compiler::Operator::Sub: + case Slang::Compiler::Operator::SubAssign: + return "-"; + case Slang::Compiler::Operator::Lsh: + case Slang::Compiler::Operator::LshAssign: + return "<<"; + case Slang::Compiler::Operator::Rsh: + case Slang::Compiler::Operator::RshAssign: + return ">>"; + case Slang::Compiler::Operator::Eql: + return "=="; + case Slang::Compiler::Operator::Neq: + return "!="; + case Slang::Compiler::Operator::Greater: + return ">"; + case Slang::Compiler::Operator::Less: + return "<"; + case Slang::Compiler::Operator::Geq: + return ">="; + case Slang::Compiler::Operator::Leq: + return "<="; + case Slang::Compiler::Operator::BitAnd: + case Slang::Compiler::Operator::AndAssign: + return "&"; + case Slang::Compiler::Operator::BitXor: + case Slang::Compiler::Operator::XorAssign: + return "^"; + case Slang::Compiler::Operator::BitOr: + case Slang::Compiler::Operator::OrAssign: + return "|"; + case Slang::Compiler::Operator::And: + return "&&"; + case Slang::Compiler::Operator::Or: + return "||"; + case Slang::Compiler::Operator::Assign: + return "="; + default: + return "ERROR"; + } + } + + // TypeExp + + TypeExp TypeExp::Accept(SyntaxVisitor* visitor) + { + return visitor->VisitTypeExp(*this); + } + + // BuiltinTypeModifier + + // MagicTypeModifier + + // GenericDecl + + RefPtr GenericDecl::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitGenericDecl(this); + } + + // GenericTypeParamDecl + + RefPtr GenericTypeParamDecl::Accept(SyntaxVisitor * /*visitor*/) { + //throw "unimplemented"; + return this; + } + + // GenericTypeConstraintDecl + + RefPtr GenericTypeConstraintDecl::Accept(SyntaxVisitor * visitor) + { + return this; + } + + // GenericValueParamDecl + + RefPtr GenericValueParamDecl::Accept(SyntaxVisitor * /*visitor*/) { + //throw "unimplemented"; + return this; + } + + // GenericParamIntVal + + bool GenericParamIntVal::EqualsVal(Val* val) + { + if (auto genericParamVal = dynamic_cast(val)) + { + return declRef.Equals(genericParamVal->declRef); + } + return false; + } + + String GenericParamIntVal::ToString() + { + return declRef.GetName(); + } + + int GenericParamIntVal::GetHashCode() + { + return declRef.GetHashCode() ^ 0xFFFF; + } + + RefPtr GenericParamIntVal::SubstituteImpl(Substitutions* subst, int* ioDiff) + { + // search for a substitution that might apply to us + for (auto s = subst; s; s = s->outer.Ptr()) + { + // the generic decl associated with the substitution list must be + // the generic decl that declared this parameter + auto genericDecl = s->genericDecl; + if (genericDecl != declRef.GetDecl()->ParentDecl) + continue; + + int index = 0; + for (auto m : genericDecl->Members) + { + if (m.Ptr() == declRef.GetDecl()) + { + // We've found it, so return the corresponding specialization argument + (*ioDiff)++; + return s->args[index]; + } + else if(auto typeParam = m.As()) + { + index++; + } + else if(auto valParam = m.As()) + { + index++; + } + else + { + } + } + } + + // Nothing found: don't substittue. + return this; + } + + // ExtensionDecl + + RefPtr ExtensionDecl::Accept(SyntaxVisitor * visitor) + { + visitor->VisitExtensionDecl(this); + return this; + } + + // ConstructorDecl + + RefPtr ConstructorDecl::Accept(SyntaxVisitor * visitor) + { + visitor->VisitConstructorDecl(this); + return this; + } + + // SubscriptDecl + + RefPtr SubscriptDecl::Accept(SyntaxVisitor * visitor) + { + visitor->visitSubscriptDecl(this); + return this; + } + + // AccessorDecl + + RefPtr AccessorDecl::Accept(SyntaxVisitor * visitor) + { + visitor->visitAccessorDecl(this); + return this; + } + + // Substitutions + + RefPtr Substitutions::SubstituteImpl(Substitutions* subst, int* ioDiff) + { + if (!this) return nullptr; + + int diff = 0; + auto outerSubst = outer->SubstituteImpl(subst, &diff); + + List> substArgs; + for (auto a : args) + { + substArgs.Add(a->SubstituteImpl(subst, &diff)); + } + + if (!diff) return this; + + (*ioDiff)++; + auto substSubst = new Substitutions(); + substSubst->genericDecl = genericDecl; + substSubst->args = substArgs; + return substSubst; + } + + bool Substitutions::Equals(Substitutions* subst) + { + // both must be NULL, or non-NULL + if (!this || !subst) + return !this && !subst; + + if (genericDecl != subst->genericDecl) + return false; + + int argCount = args.Count(); + assert(args.Count() == subst->args.Count()); + for (int aa = 0; aa < argCount; ++aa) + { + if (!args[aa]->EqualsVal(subst->args[aa].Ptr())) + return false; + } + + if (!outer->Equals(subst->outer.Ptr())) + return false; + + return true; + } + + + // DeclRef + + RefPtr DeclRef::Substitute(RefPtr type) const + { + // No substitutions? Easy. + if (!substitutions) + return type; + + // Otherwise we need to recurse on the type structure + // and apply substitutions where it makes sense + + return type->Substitute(substitutions.Ptr()).As(); + } + + DeclRef DeclRef::Substitute(DeclRef declRef) const + { + if(!substitutions) + return declRef; + + int diff = 0; + return declRef.SubstituteImpl(substitutions.Ptr(), &diff); + } + + RefPtr DeclRef::Substitute(RefPtr expr) const + { + // No substitutions? Easy. + if (!substitutions) + return expr; + + assert(!"unimplemented"); + + return expr; + } + + + DeclRef DeclRef::SubstituteImpl(Substitutions* subst, int* ioDiff) + { + if (!substitutions) return *this; + + int diff = 0; + RefPtr substSubst = substitutions->SubstituteImpl(subst, &diff); + + if (!diff) + return *this; + + *ioDiff += diff; + + DeclRef substDeclRef; + substDeclRef.decl = decl; + substDeclRef.substitutions = substSubst; + return substDeclRef; + } + + + // Check if this is an equivalent declaration reference to another + bool DeclRef::Equals(DeclRef const& declRef) const + { + if (decl != declRef.decl) + return false; + + if (!substitutions->Equals(declRef.substitutions.Ptr())) + return false; + + return true; + } + + // Convenience accessors for common properties of declarations + String const& DeclRef::GetName() const + { + return decl->Name.Content; + } + + DeclRef DeclRef::GetParent() const + { + auto parentDecl = decl->ParentDecl; + if (auto parentGeneric = dynamic_cast(parentDecl)) + { + // We need to strip away one layer of specialization + assert(substitutions); + return DeclRef(parentGeneric, substitutions->outer); + } + else + { + // If the parent isn't a generic, then it must + // use the same specializations as this declaration + return DeclRef(parentDecl, substitutions); + } + + } + + int DeclRef::GetHashCode() const + { + auto rs = PointerHash<1>::GetHashCode(decl); + if (substitutions) + { + rs *= 16777619; + rs ^= substitutions->GetHashCode(); + } + return rs; + } + + // Val + + RefPtr Val::Substitute(Substitutions* subst) + { + if (!this) return nullptr; + if (!subst) return this; + int diff = 0; + return SubstituteImpl(subst, &diff); + } + + RefPtr Val::SubstituteImpl(Substitutions* /*subst*/, int* /*ioDiff*/) + { + // Default behavior is to not substitute at all + return this; + } + + // IntVal + + int GetIntVal(RefPtr val) + { + if (auto constantVal = val.As()) + { + return constantVal->value; + } + assert(!"unexpected"); + return 0; + } + + // ConstantIntVal + + bool ConstantIntVal::EqualsVal(Val* val) + { + if (auto intVal = dynamic_cast(val)) + return value == intVal->value; + return false; + } + + String ConstantIntVal::ToString() + { + return String(value); + } + + int ConstantIntVal::GetHashCode() + { + return value; + } + + // SwitchStmt + + RefPtr SwitchStmt::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitSwitchStmt(this); + } + + RefPtr CaseStmt::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitCaseStmt(this); + } + + RefPtr DefaultStmt::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitDefaultStmt(this); + } + + // TraitDecl + + RefPtr TraitDecl::Accept(SyntaxVisitor * visitor) + { + visitor->VisitTraitDecl(this); + return this; + } + + // TraitConformanceDecl + + RefPtr TraitConformanceDecl::Accept(SyntaxVisitor * visitor) + { + visitor->VisitTraitConformanceDecl(this); + return this; + } + + // SharedTypeExpr + + RefPtr SharedTypeExpr::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitSharedTypeExpr(this); + } + + // OperatorExpressionSyntaxNode + +#if 0 + void OperatorExpressionSyntaxNode::SetOperator(RefPtr scope, Slang::Compiler::Operator op) + { + this->Operator = op; + auto opExpr = new VarExpressionSyntaxNode(); + opExpr->Variable = GetOperatorFunctionName(Operator); + opExpr->scope = scope; + opExpr->Position = this->Position; + this->FunctionExpr = opExpr; + } +#endif + + RefPtr OperatorExpressionSyntaxNode::Accept(SyntaxVisitor * visitor) + { + return visitor->VisitOperatorExpression(this); + } + + // DeclGroup + + RefPtr DeclGroup::Accept(SyntaxVisitor * visitor) + { + visitor->VisitDeclGroup(this); + return this; + } + + // + + void RegisterBuiltinDecl( + RefPtr decl, + RefPtr modifier) + { + auto type = DeclRefType::Create(DeclRef(decl.Ptr(), nullptr)); + ExpressionType::sBuiltinTypes[(int)modifier->tag] = type; + } + + void RegisterMagicDecl( + RefPtr decl, + RefPtr modifier) + { + ExpressionType::sMagicDecls[modifier->name] = decl.Ptr(); + } + + RefPtr findMagicDecl( + String const& name) + { + return ExpressionType::sMagicDecls[name].GetValue(); + } + + ExpressionType* ExpressionType::GetBool() + { + return sBuiltinTypes[(int)BaseType::Bool].GetValue().Ptr(); + } + + ExpressionType* ExpressionType::GetFloat() + { + return sBuiltinTypes[(int)BaseType::Float].GetValue().Ptr(); + } + + ExpressionType* ExpressionType::GetInt() + { + return sBuiltinTypes[(int)BaseType::Int].GetValue().Ptr(); + } + + ExpressionType* ExpressionType::GetUInt() + { + return sBuiltinTypes[(int)BaseType::UInt].GetValue().Ptr(); + } + + ExpressionType* ExpressionType::GetVoid() + { + return sBuiltinTypes[(int)BaseType::Void].GetValue().Ptr(); + } + + ExpressionType* ExpressionType::getInitializerListType() + { + return initializerListType.Ptr(); + } + + ExpressionType* ExpressionType::GetError() + { + return ExpressionType::Error.Ptr(); + } + + // + + RefPtr UnparsedStmt::Accept(SyntaxVisitor * visitor) + { + return this; + } + + // + + RefPtr InitializerListExpr::Accept(SyntaxVisitor * visitor) + { + return visitor->visitInitializerListExpr(this); + } + + // + + RefPtr ModifierDecl::Accept(SyntaxVisitor * visitor) + { + return this; + } + + // + + RefPtr EmptyDecl::Accept(SyntaxVisitor * visitor) + { + return this; + } + + // + + SyntaxNodeBase* createInstanceOfSyntaxClassByName( + String const& name) + { + if(0) {} + #define CASE(NAME) \ + else if(name == #NAME) return new NAME() + + CASE(GLSLBufferModifier); + CASE(GLSLWriteOnlyModifier); + CASE(GLSLReadOnlyModifier); + CASE(GLSLPatchModifier); + CASE(SimpleModifier); + + #undef CASE + else + { + assert(!"unexpected"); + return nullptr; + } + } + + IntrinsicOp findIntrinsicOp(char const* name) + { + // TODO: need to make this faster by using a dictionary... + + if (0) {} +#define INTRINSIC(NAME) else if(strcmp(name, #NAME) == 0) return IntrinsicOp::NAME; +#include "intrinsic-defs.h" + + return IntrinsicOp::Unknown; + } + + } +} \ No newline at end of file diff --git a/source/slang/syntax.h b/source/slang/syntax.h new file mode 100644 index 000000000..9e4486d4e --- /dev/null +++ b/source/slang/syntax.h @@ -0,0 +1,2771 @@ +#ifndef RASTER_RENDERER_SYNTAX_H +#define RASTER_RENDERER_SYNTAX_H + +#include "../core/basic.h" +#include "Lexer.h" +#include "Profile.h" + +#include "../../Slang.h" + +#include + +namespace Slang +{ + namespace Compiler + { + using namespace CoreLib::Basic; + class SyntaxVisitor; + class FunctionSyntaxNode; + + class SyntaxNodeBase : public RefObject + { + public: + CodePosition Position; + }; + + + + + // + // Other modifiers may have more elaborate data, and so + // are represented as heap-allocated objects, in a linked + // list. + // + class Modifier : public SyntaxNodeBase + { + public: + // Next modifier in linked list of modifiers on same piece of syntax + RefPtr next; + + // The token that was used to name this modifier. + Token nameToken; + }; + +#define SIMPLE_MODIFIER(NAME) \ + class NAME##Modifier : public Modifier {} + + SIMPLE_MODIFIER(Uniform); + SIMPLE_MODIFIER(In); + SIMPLE_MODIFIER(Out); + SIMPLE_MODIFIER(Const); + SIMPLE_MODIFIER(Instance); + SIMPLE_MODIFIER(Builtin); + SIMPLE_MODIFIER(Inline); + SIMPLE_MODIFIER(Public); + SIMPLE_MODIFIER(Require); + SIMPLE_MODIFIER(Param); + SIMPLE_MODIFIER(Extern); + SIMPLE_MODIFIER(Input); + SIMPLE_MODIFIER(Transparent); + SIMPLE_MODIFIER(FromStdLib); + SIMPLE_MODIFIER(Prefix); + SIMPLE_MODIFIER(Postfix); + +#undef SIMPLE_MODIFIER + + enum class IntrinsicOp + { + Unknown = 0, +#define INTRINSIC(NAME) NAME, +#include "intrinsic-defs.h" + }; + + IntrinsicOp findIntrinsicOp(char const* name); + + class IntrinsicModifier : public Modifier + { + public: + // token that names the intrinsic op + Token opToken; + + // The opcode for the intrinsic operation + IntrinsicOp op = IntrinsicOp::Unknown; + }; + + + class InOutModifier : public OutModifier {}; + + // This is a special sentinel modifier that gets added + // to the list when we have multiple variable declarations + // all sharing the same modifiers: + // + // static uniform int a : FOO, *b : register(x0); + // + // In this case both `a` and `b` share the syntax + // for part of their modifier list, but then have + // their own modifiers as well: + // + // a: SemanticModifier("FOO") --> SharedModifiers --> StaticModifier --> UniformModifier + // / + // b: RegisterModifier("x0") / + // + class SharedModifiers : public Modifier {}; + + // A GLSL `layout` modifier + // + // We use a distinct modifier for each key that + // appears within the `layout(...)` construct, + // and each key might have an optional value token. + // + // TODO: We probably want a notion of "modifier groups" + // so that we can recover good source location info + // for modifiers that were part of the same vs. + // different constructs. + class GLSLLayoutModifier : public Modifier + { + public: + // THe token used to introduce the modifier is stored + // as the `nameToken` field. + + // TODO: may want to accept a full expression here + Token valToken; + }; + + // We divide GLSL `layout` modifiers into those we have parsed + // (in the sense of having some notion of their semantics), and + // those we have not. + class GLSLParsedLayoutModifier : public GLSLLayoutModifier {}; + class GLSLUnparsedLayoutModifier : public GLSLLayoutModifier {}; + + // Specific cases for known GLSL `layout` modifiers that we need to work with + class GLSLConstantIDLayoutModifier : public GLSLParsedLayoutModifier {}; + class GLSLBindingLayoutModifier : public GLSLParsedLayoutModifier {}; + class GLSLSetLayoutModifier : public GLSLParsedLayoutModifier {}; + class GLSLLocationLayoutModifier : public GLSLParsedLayoutModifier {}; + + // A catch-all for single-keyword modifiers + class SimpleModifier : public Modifier {}; + + // Some GLSL-specific modifiers + class GLSLBufferModifier : public SimpleModifier {}; + class GLSLWriteOnlyModifier : public SimpleModifier {}; + class GLSLReadOnlyModifier : public SimpleModifier {}; + class GLSLPatchModifier : public SimpleModifier {}; + + // Indicates that this is a variable declaration that corresponds to + // a parameter block declaration in the source program. + class ImplicitParameterBlockVariableModifier : public Modifier {}; + + // Indicates that this is a type that corresponds to the element + // type of a parameter block declaration in the source program. + class ImplicitParameterBlockElementTypeModifier : public Modifier {}; + + // An HLSL semantic + class HLSLSemantic : public Modifier + { + public: + Token name; + }; + + + // An HLSL semantic that affects layout + class HLSLLayoutSemantic : public HLSLSemantic + { + public: + Token registerName; + Token componentMask; + }; + + // An HLSL `register` semantic + class HLSLRegisterSemantic : public HLSLLayoutSemantic + { + }; + + // TODO(tfoley): `packoffset` + class HLSLPackOffsetSemantic : public HLSLLayoutSemantic + { + }; + + // An HLSL semantic that just associated a declaration with a semantic name + class HLSLSimpleSemantic : public HLSLSemantic + { + }; + + // GLSL + + // Directives that came in via the preprocessor, but + // that we need to keep around for later steps + class GLSLPreprocessorDirective : public Modifier + { + }; + + // A GLSL `#version` directive + class GLSLVersionDirective : public GLSLPreprocessorDirective + { + public: + // Token giving the version number to use + Token versionNumberToken; + + // Optional token giving the sub-profile to be used + Token glslProfileToken; + }; + + // A GLSL `#extension` directive + class GLSLExtensionDirective : public GLSLPreprocessorDirective + { + public: + // Token giving the version number to use + Token extensionNameToken; + + // Optional token giving the sub-profile to be used + Token dispositionToken; + }; + + class ParameterBlockReflectionName : public Modifier + { + public: + Token nameToken; + }; + + // Helper class for iterating over a list of heap-allocated modifiers + struct ModifierList + { + struct Iterator + { + Modifier* current; + + Modifier* operator*() + { + return current; + } + + void operator++() + { + current = current->next.Ptr(); + } + + bool operator!=(Iterator other) + { + return current != other.current; + }; + + Iterator() + : current(nullptr) + {} + + Iterator(Modifier* modifier) + : current(modifier) + {} + }; + + ModifierList() + : modifiers(nullptr) + {} + + ModifierList(Modifier* modifiers) + : modifiers(modifiers) + {} + + Iterator begin() { return Iterator(modifiers); } + Iterator end() { return Iterator(nullptr); } + + Modifier* modifiers; + }; + + // Helper class for iterating over heap-allocated modifiers + // of a specific type. + template + struct FilteredModifierList + { + struct Iterator + { + Modifier* current; + + T* operator*() + { + return (T*)current; + } + + void operator++() + { + current = Adjust(current->next.Ptr()); + } + + bool operator!=(Iterator other) + { + return current != other.current; + }; + + Iterator() + : current(nullptr) + {} + + Iterator(Modifier* modifier) + : current(modifier) + {} + }; + + FilteredModifierList() + : modifiers(nullptr) + {} + + FilteredModifierList(Modifier* modifiers) + : modifiers(Adjust(modifiers)) + {} + + Iterator begin() { return Iterator(modifiers); } + Iterator end() { return Iterator(nullptr); } + + static Modifier* Adjust(Modifier* modifier) + { + Modifier* m = modifier; + for (;;) + { + if (!m) return m; + if (dynamic_cast(m)) return m; + m = m->next.Ptr(); + } + } + + Modifier* modifiers; + }; + + // A set of modifiers attached to a syntax node + struct Modifiers + { + // The first modifier in the linked list of heap-allocated modifiers + RefPtr first; + + template + FilteredModifierList getModifiersOfType() { return FilteredModifierList(first.Ptr()); } + + // Find the first modifier of a given type, or return `nullptr` if none is found. + template + T* findModifier() + { + return *getModifiersOfType().begin(); + } + + template + bool hasModifier() { return findModifier() != nullptr; } + + FilteredModifierList::Iterator begin() { return FilteredModifierList::Iterator(first.Ptr()); } + FilteredModifierList::Iterator end() { return FilteredModifierList::Iterator(nullptr); } + }; + + + enum class BaseType + { + // Note(tfoley): These are ordered in terms of promotion rank, so be vareful when messing with this + + Void = 0, + Bool, + Int, + UInt, + UInt64, + Float, +#if 0 + Texture2D = 48, + TextureCube = 49, + Texture2DArray = 50, + Texture2DShadow = 51, + TextureCubeShadow = 52, + Texture2DArrayShadow = 53, + Texture3D = 54, + SamplerState = 4096, SamplerComparisonState = 4097, + Error = 16384, +#endif + }; + + class Decl; + class StructSyntaxNode; + class BasicExpressionType; + class ArrayExpressionType; + class TypeDefDecl; + class DeclRefType; + class NamedExpressionType; + class TypeType; + class GenericDeclRefType; + class VectorExpressionType; + class MatrixExpressionType; + class ArithmeticExpressionType; + class GenericDecl; + class Substitutions; + class TextureType; + class SamplerStateType; + + // A compile-time constant value (usually a type) + class Val : public RefObject + { + public: + // construct a new value by applying a set of parameter + // substitutions to this one + RefPtr Substitute(Substitutions* subst); + + // Lower-level interface for substition. Like the basic + // `Substitute` above, but also takes a by-reference + // integer parameter that should be incremented when + // returning a modified value (this can help the caller + // decide whether they need to do anything). + virtual RefPtr SubstituteImpl(Substitutions* subst, int* ioDiff); + + virtual bool EqualsVal(Val* val) = 0; + virtual String ToString() = 0; + virtual int GetHashCode() = 0; + bool operator == (const Val & v) + { + return EqualsVal(const_cast(&v)); + } + }; + + // A compile-time integer (may not have a specific concrete value) + class IntVal : public Val + { + }; + + // Try to extract a simple integer value from an `IntVal`. + // This fill assert-fail if the object doesn't represent a literal value. + int GetIntVal(RefPtr val); + + // Trivial case of a value that is just a constant integer + class ConstantIntVal : public IntVal + { + public: + int value; + + ConstantIntVal(int value) + : value(value) + {} + + virtual bool EqualsVal(Val* val) override; + virtual String ToString() override; + virtual int GetHashCode() override; + }; + + // TODO(tfoley): classes for more general compile-time integers, + // including references to template parameters + + // A type, representing a classifier for some term in the AST. + // + // Types can include "sugar" in that they may refer to a + // `typedef` which gives them a good name when printed as + // part of diagnostic messages. + // + // In order to operation on types, though, we often want + // to look past any sugar, and operate on an underlying + // "canonical" type. The reprsentation caches a pointer to + // a canonical type on every type, so we can easily + // operate on the raw representation when needed. + class ExpressionType : public Val + { + public: + static RefPtr Error; + static RefPtr initializerListType; + static RefPtr Overloaded; + + static Dictionary> sBuiltinTypes; + static Dictionary sMagicDecls; + + // Note: just exists to make sure we can clean up + // canonical types we create along the way + static List> sCanonicalTypes; + + + + static ExpressionType* GetBool(); + static ExpressionType* GetFloat(); + static ExpressionType* GetInt(); + static ExpressionType* GetUInt(); + static ExpressionType* GetVoid(); + static ExpressionType* getInitializerListType(); + static ExpressionType* GetError(); + + public: + virtual String ToString() = 0; + + bool Equals(ExpressionType * type); + bool Equals(RefPtr type); + + bool IsVectorType() { return As() != nullptr; } + bool IsArray() { return As() != nullptr; } + + template + T* As() + { + return dynamic_cast(GetCanonicalType()); + } + + // Convenience/legacy wrappers for `As<>` + ArithmeticExpressionType * AsArithmeticType() { return As(); } + BasicExpressionType * AsBasicType() { return As(); } + VectorExpressionType * AsVectorType() { return As(); } + MatrixExpressionType * AsMatrixType() { return As(); } + ArrayExpressionType * AsArrayType() { return As(); } + + DeclRefType* AsDeclRefType() { return As(); } + + NamedExpressionType* AsNamedType(); + + bool IsTextureOrSampler(); + bool IsTexture() { return As() != nullptr; } + bool IsSampler() { return As() != nullptr; } + bool IsStruct(); + bool IsClass(); + static void Init(); + static void Finalize(); + ExpressionType* GetCanonicalType(); + + virtual RefPtr SubstituteImpl(Substitutions* subst, int* ioDiff) override; + + virtual bool EqualsVal(Val* val) override; + protected: + virtual bool EqualsImpl(ExpressionType * type) = 0; + + virtual ExpressionType* CreateCanonicalType() = 0; + ExpressionType* canonicalType = nullptr; + }; + + // A substitution represents a binding of certain + // type-level variables to concrete argument values + class Substitutions : public RefObject + { + public: + // The generic declaration that defines the + // parametesr we are binding to arguments + GenericDecl* genericDecl; + + // The actual values of the arguments + List> args; + + // Any further substitutions, relating to outer generic declarations + RefPtr outer; + + // Apply a set of substitutions to the bindings in this substitution + RefPtr SubstituteImpl(Substitutions* subst, int* ioDiff); + + // Check if these are equivalent substitutiosn to another set + bool Equals(Substitutions* subst); + bool operator == (const Substitutions & subst) + { + return Equals(const_cast(&subst)); + } + int GetHashCode() const + { + int rs = 0; + for (auto && v : args) + { + rs ^= v->GetHashCode(); + rs *= 16777619; + } + return rs; + } + }; + + class SyntaxNode : public SyntaxNodeBase + { + public: + virtual RefPtr Accept(SyntaxVisitor * visitor) = 0; + }; + + class ContainerDecl; + class SpecializeModifier; + + // Represents how much checking has been applied to a declaration. + enum class DeclCheckState : uint8_t + { + // The declaration has been parsed, but not checked + Unchecked, + + // We are in the process of checking the declaration "header" + // (those parts of the declaration needed in order to + // reference it) + CheckingHeader, + + // We are done checking the declaration header. + CheckedHeader, + + // We have checked the declaration fully. + Checked, + }; + + // A syntax node which can have modifiers appled + class ModifiableSyntaxNode : public SyntaxNode + { + public: + Modifiers modifiers; + + template + FilteredModifierList GetModifiersOfType() { return FilteredModifierList(modifiers.first.Ptr()); } + + // Find the first modifier of a given type, or return `nullptr` if none is found. + template + T* FindModifier() + { + return *GetModifiersOfType().begin(); + } + + template + bool HasModifier() { return FindModifier() != nullptr; } + }; + + void addModifier( + RefPtr syntax, + RefPtr modifier); + + + // An intermediate type to represent either a single declaration, or a group of declarations + class DeclBase : public ModifiableSyntaxNode + { + public: + }; + + class Decl : public DeclBase + { + public: + ContainerDecl* ParentDecl; + + Token Name; + String const& getName() { return Name.Content; } + Token const& getNameToken() { return Name; } + + + DeclCheckState checkState = DeclCheckState::Unchecked; + + // The next declaration defined in the same container with the same name + Decl* nextInContainerWithSameName = nullptr; + + bool IsChecked(DeclCheckState state) { return checkState >= state; } + void SetCheckState(DeclCheckState state) + { + assert(state >= checkState); + checkState = state; + } + }; + + struct QualType + { + RefPtr type; + bool IsLeftValue; + + QualType() + : IsLeftValue(false) + {} + + QualType(RefPtr type) + : type(type) + , IsLeftValue(false) + {} + + QualType(ExpressionType* type) + : type(type) + , IsLeftValue(false) + {} + + void operator=(RefPtr t) + { + *this = QualType(t); + } + + void operator=(ExpressionType* t) + { + *this = QualType(t); + } + + ExpressionType* Ptr() { return type.Ptr(); } + + operator RefPtr() { return type; } + RefPtr operator->() { return type; } + }; + + class ExpressionSyntaxNode : public SyntaxNode + { + public: + QualType Type; + ExpressionSyntaxNode() + {} + }; + + + + + // A reference to a declaration, which may include + // substitutions for generic parameters. + struct DeclRef + { + typedef Decl DeclType; + + // The underlying declaration + Decl* decl = nullptr; + Decl* GetDecl() const { return decl; } + + // Optionally, a chain of substititions to perform + RefPtr substitutions; + + DeclRef() + {} + + DeclRef(Decl* decl, RefPtr substitutions) + : decl(decl) + , substitutions(substitutions) + {} + + // Apply substitutions to a type or ddeclaration + RefPtr Substitute(RefPtr type) const; + DeclRef Substitute(DeclRef declRef) const; + + // Apply substitutions to an expression + RefPtr Substitute(RefPtr expr) const; + + // Apply substitutions to this declaration reference + DeclRef SubstituteImpl(Substitutions* subst, int* ioDiff); + + // Check if this is an equivalent declaration reference to another + bool Equals(DeclRef const& declRef) const; + bool operator == (const DeclRef& other) const + { + return Equals(other); + } + + // Convenience accessors for common properties of declarations + String const& GetName() const; + DeclRef GetParent() const; + + // "dynamic cast" to a more specific declaration reference type + template + T As() const + { + T result; + result.decl = dynamic_cast(decl); + result.substitutions = substitutions; + return result; + } + + // Implicit conversion mostly so we can use a `DeclRef` + // in a conditional context + operator Decl*() const + { + return decl; + } + + int GetHashCode() const; + }; + + // Helper macro for defining `DeclRef` subtypes + #define SLANG_DECLARE_DECL_REF(D) \ + typedef D DeclType; \ + D* GetDecl() const { return (D*) decl; } \ + /* */ + + + + // The type of a reference to an overloaded name + class OverloadGroupType : public ExpressionType + { + public: + virtual String ToString() override; + + protected: + virtual bool EqualsImpl(ExpressionType * type) override; + virtual ExpressionType* CreateCanonicalType() override; + virtual int GetHashCode() override; + }; + + // The type of an initializer-list expression (before it has + // been coerced to some other type) + class InitializerListType : public ExpressionType + { + public: + virtual String ToString() override; + + protected: + virtual bool EqualsImpl(ExpressionType * type) override; + virtual ExpressionType* CreateCanonicalType() override; + virtual int GetHashCode() override; + }; + + // The type of an expression that was erroneous + class ErrorType : public ExpressionType + { + public: + virtual String ToString() override; + + protected: + virtual bool EqualsImpl(ExpressionType * type) override; + virtual ExpressionType* CreateCanonicalType() override; + virtual int GetHashCode() override; + }; + + // A type that takes the form of a reference to some declaration + class DeclRefType : public ExpressionType + { + public: + DeclRef declRef; + + virtual String ToString() override; + virtual RefPtr SubstituteImpl(Substitutions* subst, int* ioDiff) override; + + static DeclRefType* Create(DeclRef declRef); + + protected: + DeclRefType() + {} + DeclRefType(DeclRef declRef) + : declRef(declRef) + {} + virtual int GetHashCode() override; + virtual bool EqualsImpl(ExpressionType * type) override; + virtual ExpressionType* CreateCanonicalType() override; + }; + + // Base class for types that can be used in arithmetic expressions + class ArithmeticExpressionType : public DeclRefType + { + public: + virtual BasicExpressionType* GetScalarType() = 0; + }; + + class FunctionDeclBase; + + class BasicExpressionType : public ArithmeticExpressionType + { + public: + BaseType BaseType; + + BasicExpressionType() + { + BaseType = Compiler::BaseType::Int; + } + BasicExpressionType(Compiler::BaseType baseType) + { + BaseType = baseType; + } + virtual CoreLib::Basic::String ToString() override; + protected: + virtual BasicExpressionType* GetScalarType() override; + virtual bool EqualsImpl(ExpressionType * type) override; + virtual ExpressionType* CreateCanonicalType() override; + }; + + + class TextureTypeBase : public DeclRefType + { + public: + // The type that results from fetching an element from this texture + RefPtr elementType; + + // Bits representing the kind of texture type we are looking at + // (e.g., `Texture2DMS` vs. `TextureCubeArray`) + typedef uint16_t Flavor; + Flavor flavor; + + enum + { + // Mask for the overall "shape" of the texture + ShapeMask = SLANG_RESOURCE_BASE_SHAPE_MASK, + + // Flag for whether the shape has "array-ness" + ArrayFlag = SLANG_TEXTURE_ARRAY_FLAG, + + // Whether or not the texture stores multiple samples per pixel + MultisampleFlag = SLANG_TEXTURE_MULTISAMPLE_FLAG, + + // Whether or not this is a shadow texture + // + // TODO(tfoley): is this even meaningful/used? + // ShadowFlag = 0x80, + }; + + enum Shape : uint8_t + { + Shape1D = SLANG_TEXTURE_1D, + Shape2D = SLANG_TEXTURE_2D, + Shape3D = SLANG_TEXTURE_3D, + ShapeCube = SLANG_TEXTURE_CUBE, + + Shape1DArray = Shape1D | ArrayFlag, + Shape2DArray = Shape2D | ArrayFlag, + // No Shape3DArray + ShapeCubeArray = ShapeCube | ArrayFlag, + }; + + + Shape GetBaseShape() const { return Shape(flavor & ShapeMask); } + bool isArray() const { return (flavor & ArrayFlag) != 0; } + bool isMultisample() const { return (flavor & MultisampleFlag) != 0; } +// bool isShadow() const { return (flavor & ShadowFlag) != 0; } + + SlangResourceShape getShape() const { return flavor & 0xFF; } + SlangResourceAccess getAccess() const { return (flavor >> 8) & 0xFF; } + + TextureTypeBase( + Flavor flavor, + RefPtr elementType) + : elementType(elementType) + , flavor(flavor) + {} + }; + + class TextureType : public TextureTypeBase + { + public: + TextureType( + Flavor flavor, + RefPtr elementType) + : TextureTypeBase(flavor, elementType) + {} + }; + + // This is a base type for texture/sampler pairs, + // as they exist in, e.g., GLSL + class TextureSamplerType : public TextureTypeBase + { + public: + TextureSamplerType( + Flavor flavor, + RefPtr elementType) + : TextureTypeBase(flavor, elementType) + {} + }; + + // This is a base type for `image*` types, as they exist in GLSL + class GLSLImageType : public TextureTypeBase + { + public: + GLSLImageType( + Flavor flavor, + RefPtr elementType) + : TextureTypeBase(flavor, elementType) + {} + }; + + class SamplerStateType : public DeclRefType + { + public: + // What flavor of sampler state is this + enum class Flavor : uint8_t + { + SamplerState, + SamplerComparisonState, + }; + Flavor flavor; + }; + + // Other cases of generic types known to the compiler + class BuiltinGenericType : public DeclRefType + { + public: + RefPtr elementType; + }; + + // Types that behave like pointers, in that they can be + // dereferenced (implicitly) to access members defined + // in the element type. + class PointerLikeType : public BuiltinGenericType + {}; + + // Generic types used in existing Slang code + // TODO(tfoley): check that these are actually working right... + class PatchType : public PointerLikeType {}; + class StorageBufferType : public BuiltinGenericType {}; + class UniformBufferType : public PointerLikeType {}; + class PackedBufferType : public BuiltinGenericType {}; + + // HLSL buffer-type resources + + class HLSLBufferType : public BuiltinGenericType {}; + class HLSLRWBufferType : public BuiltinGenericType {}; + class HLSLStructuredBufferType : public BuiltinGenericType {}; + class HLSLRWStructuredBufferType : public BuiltinGenericType {}; + + class UntypedBufferResourceType : public DeclRefType {}; + class HLSLByteAddressBufferType : public UntypedBufferResourceType {}; + class HLSLRWByteAddressBufferType : public UntypedBufferResourceType {}; + + class HLSLAppendStructuredBufferType : public BuiltinGenericType {}; + class HLSLConsumeStructuredBufferType : public BuiltinGenericType {}; + + class HLSLInputPatchType : public BuiltinGenericType {}; + class HLSLOutputPatchType : public BuiltinGenericType {}; + + // HLSL geometry shader output stream types + + class HLSLStreamOutputType : public BuiltinGenericType {}; + class HLSLPointStreamType : public HLSLStreamOutputType {}; + class HLSLLineStreamType : public HLSLStreamOutputType {}; + class HLSLTriangleStreamType : public HLSLStreamOutputType {}; + + // + class GLSLInputAttachmentType : public DeclRefType {}; + + // Base class for types used when desugaring parameter block + // declarations, includeing HLSL `cbuffer` or GLSL `uniform` blocks. + class ParameterBlockType : public PointerLikeType {}; + + class UniformParameterBlockType : public ParameterBlockType {}; + class VaryingParameterBlockType : public ParameterBlockType {}; + + // Type for HLSL `cbuffer` declarations, and `ConstantBuffer` + // ALso used for GLSL `uniform` blocks. + class ConstantBufferType : public UniformParameterBlockType {}; + + // Type for HLSL `tbuffer` declarations, and `TextureBuffer` + class TextureBufferType : public UniformParameterBlockType {}; + + // Type for GLSL `in` and `out` blocks + class GLSLInputParameterBlockType : public VaryingParameterBlockType {}; + class GLSLOutputParameterBlockType : public VaryingParameterBlockType {}; + + // Type for GLLSL `buffer` blocks + class GLSLShaderStorageBufferType : public UniformParameterBlockType {}; + + class ArrayExpressionType : public ExpressionType + { + public: + RefPtr BaseType; + RefPtr ArrayLength; + virtual CoreLib::Basic::String ToString() override; + protected: + virtual bool EqualsImpl(ExpressionType * type) override; + virtual ExpressionType* CreateCanonicalType() override; + virtual int GetHashCode() override; + }; + + // The "type" of an expression that resolves to a type. + // For example, in the expression `float(2)` the sub-expression, + // `float` would have the type `TypeType(float)`. + class TypeType : public ExpressionType + { + public: + TypeType(RefPtr type) + : type(type) + {} + + // The type that this is the type of... + RefPtr type; + + + virtual String ToString() override; + + protected: + virtual bool EqualsImpl(ExpressionType * type) override; + virtual ExpressionType* CreateCanonicalType() override; + virtual int GetHashCode() override; + }; + + class GenericDecl; + + // A vector type, e.g., `vector` + class VectorExpressionType : public ArithmeticExpressionType + { + public: +#if 0 + VectorExpressionType( + RefPtr elementType, + RefPtr elementCount) + : elementType(elementType) + , elementCount(elementCount) + {} +#endif + + // The type of vector elements. + // As an invariant, this should be a basic type or an alias. + RefPtr elementType; + + // The number of elements + RefPtr elementCount; + + virtual String ToString() override; + + protected: + virtual BasicExpressionType* GetScalarType() override; + }; + + // A matrix type, e.g., `matrix` + class MatrixExpressionType : public ArithmeticExpressionType + { + public: + // TODO: consider adding these back for convenience, + // with a way to initialize them on-demand from the + // real storage (which is in the `DeclRefType` +#if 0 + // The type of vector elements. + // As an invariant, this should be a basic type or an alias. + RefPtr elementType; + + // The type of the matrix rows + RefPtr rowType; + + // The number of rows and columns + RefPtr rowCount; + RefPtr colCount; +#endif + ExpressionType* getElementType(); + IntVal* getRowCount(); + IntVal* getColumnCount(); + + + virtual String ToString() override; + + protected: + virtual BasicExpressionType* GetScalarType() override; + }; + + inline BaseType GetVectorBaseType(VectorExpressionType* vecType) { + return vecType->elementType->AsBasicType()->BaseType; + } + + inline int GetVectorSize(VectorExpressionType* vecType) + { + auto constantVal = vecType->elementCount.As(); + if (constantVal) + return constantVal->value; + // TODO: what to do in this case? + return 0; + } + + class Type + { + public: + RefPtr DataType; + // ContrainedWorlds: Implementation must be defined at at least one of of these worlds in order to satisfy global dependency + // FeasibleWorlds: The component can be computed at any of these worlds + EnumerableHashSet ConstrainedWorlds, FeasibleWorlds; + EnumerableHashSet PinnedWorlds; + }; + + class ContainerDecl; + + + // A group of declarations that should be treated as a unit + class DeclGroup : public DeclBase + { + public: + List> decls; + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + template + struct FilteredMemberList + { + typedef RefPtr Element; + + FilteredMemberList() + : mBegin(NULL) + , mEnd(NULL) + {} + + explicit FilteredMemberList( + List const& list) + : mBegin(Adjust(list.begin(), list.end())) + , mEnd(list.end()) + {} + + struct Iterator + { + Element* mCursor; + Element* mEnd; + + bool operator!=(Iterator const& other) + { + return mCursor != other.mCursor; + } + + void operator++() + { + mCursor = Adjust(mCursor + 1, mEnd); + } + + RefPtr& operator*() + { + return *(RefPtr*)mCursor; + } + }; + + Iterator begin() + { + Iterator iter = { mBegin, mEnd }; + return iter; + } + + Iterator end() + { + Iterator iter = { mEnd, mEnd }; + return iter; + } + + static Element* Adjust(Element* cursor, Element* end) + { + while (cursor != end) + { + if ((*cursor).As()) + return cursor; + cursor++; + } + return cursor; + } + + // TODO(tfoley): It is ugly to have these. + // We should probably fix the call sites instead. + RefPtr& First() { return *begin(); } + int Count() + { + int count = 0; + for (auto iter : (*this)) + { + (void)iter; + count++; + } + return count; + } + + List> ToArray() + { + List> result; + for (auto element : (*this)) + { + result.Add(element); + } + return result; + } + + Element* mBegin; + Element* mEnd; + }; + + struct TransparentMemberInfo + { + // The declaration of the transparent member + Decl* decl; + }; + + // A "container" decl is a parent to other declarations + class ContainerDecl : public Decl + { + public: + List> Members; + + template + FilteredMemberList GetMembersOfType() + { + return FilteredMemberList(Members); + } + + + // Dictionary for looking up members by name. + // This is built on demand before performing lookup. + Dictionary memberDictionary; + + // Whether the `memberDictionary` is valid. + // Should be set to `false` if any members get added/remoed. + bool memberDictionaryIsValid = false; + + // A list of transparent members, to be used in lookup + // Note: this is only valid if `memberDictionaryIsValid` is true + List transparentMembers; + }; + + template + struct FilteredMemberRefList + { + List> const& decls; + RefPtr substitutions; + + FilteredMemberRefList( + List> const& decls, + RefPtr substitutions) + : decls(decls) + , substitutions(substitutions) + {} + + int Count() const + { + int count = 0; + for (auto d : *this) + count++; + return count; + } + + List ToArray() const + { + List result; + for (auto d : *this) + result.Add(d); + return result; + } + + struct Iterator + { + FilteredMemberRefList const* list; + RefPtr* ptr; + RefPtr* end; + + Iterator() : list(nullptr), ptr(nullptr) {} + Iterator( + FilteredMemberRefList const* list, + RefPtr* ptr, + RefPtr* end) + : list(list) + , ptr(ptr) + , end(end) + {} + + bool operator!=(Iterator other) + { + return ptr != other.ptr; + } + + void operator++() + { + ptr = list->Adjust(ptr + 1, end); + } + + T operator*() + { + return DeclRef(ptr->Ptr(), list->substitutions).As(); + } + }; + + Iterator begin() const { return Iterator(this, Adjust(decls.begin(), decls.end()), decls.end()); } + Iterator end() const { return Iterator(this, decls.end(), decls.end()); } + + RefPtr* Adjust(RefPtr* ptr, RefPtr* end) const + { + while (ptr != end) + { + DeclRef declRef(ptr->Ptr(), substitutions); + if (declRef.As()) + return ptr; + ptr++; + } + return end; + } + }; + + struct ContainerDeclRef : DeclRef + { + SLANG_DECLARE_DECL_REF(ContainerDecl); + + FilteredMemberRefList GetMembers() const + { + return FilteredMemberRefList(GetDecl()->Members, substitutions); + } + + template + FilteredMemberRefList GetMembersOfType() const + { + return FilteredMemberRefList(GetDecl()->Members, substitutions); + } + + }; + + // + // Type Expressions + // + + // A "type expression" is a term that we expect to resolve to a type during checking. + // We store both the original syntax and the resolved type here. + struct TypeExp + { + TypeExp() {} + TypeExp(TypeExp const& other) + : exp(other.exp) + , type(other.type) + {} + explicit TypeExp(RefPtr exp) + : exp(exp) + {} + TypeExp(RefPtr exp, RefPtr type) + : exp(exp) + , type(type) + {} + + RefPtr exp; + RefPtr type; + + bool Equals(ExpressionType* other) { + return type->Equals(other); + } + bool Equals(RefPtr other) { + return type->Equals(other.Ptr()); + } + ExpressionType* Ptr() { return type.Ptr(); } + operator RefPtr() + { + return type; + } + ExpressionType* operator->() { return Ptr(); } + + TypeExp Accept(SyntaxVisitor* visitor); + }; + + + // + // Declarations + // + + // Base class for all variable-like declarations + class VarDeclBase : public Decl + { + public: + // Type of the variable + TypeExp Type; + + ExpressionType* getType() { return Type.type.Ptr(); } + + // Initializer expression (optional) + RefPtr Expr; + }; + + struct VarDeclBaseRef : DeclRef + { + SLANG_DECLARE_DECL_REF(VarDeclBase); + + RefPtr GetType() const { return Substitute(GetDecl()->Type); } + + RefPtr getInitExpr() const { return Substitute(GetDecl()->Expr); } + }; + + // A field of a `struct` type + class StructField : public VarDeclBase + { + public: + StructField() + {} + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + struct FieldDeclRef : VarDeclBaseRef + { + SLANG_DECLARE_DECL_REF(StructField) + }; + + // An extension to apply to an existing type + class ExtensionDecl : public ContainerDecl + { + public: + TypeExp targetType; + + // next extension attached to the same nominal type + ExtensionDecl* nextCandidateExtension = nullptr; + + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + struct ExtensionDeclRef : ContainerDeclRef + { + SLANG_DECLARE_DECL_REF(ExtensionDecl); + + RefPtr GetTargetType() const { return Substitute(GetDecl()->targetType); } + }; + + // Declaration of a type that represents some sort of aggregate + class AggTypeDecl : public ContainerDecl + { + public: + // extensions that might apply to this declaration + ExtensionDecl* candidateExtensions = nullptr; + FilteredMemberList GetFields() + { + return GetMembersOfType(); + } + StructField* FindField(String name) + { + for (auto field : GetFields()) + { + if (field->Name.Content == name) + return field.Ptr(); + } + return nullptr; + } + int FindFieldIndex(String name) + { + int index = 0; + for (auto field : GetFields()) + { + if (field->Name.Content == name) + return index; + index++; + } + return -1; + } + }; + + struct AggTypeDeclRef : public ContainerDeclRef + { + SLANG_DECLARE_DECL_REF(AggTypeDecl); + + ExtensionDecl* GetCandidateExtensions() const { return GetDecl()->candidateExtensions; } + }; + + class StructSyntaxNode : public AggTypeDecl + { + public: + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + struct StructDeclRef : public AggTypeDeclRef + { + SLANG_DECLARE_DECL_REF(StructSyntaxNode); + + FilteredMemberRefList GetFields() const { return GetMembersOfType(); } + }; + + class ClassSyntaxNode : public AggTypeDecl + { + public: + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + struct ClassDeclRef : public AggTypeDeclRef + { + SLANG_DECLARE_DECL_REF(ClassSyntaxNode); + + FilteredMemberRefList GetFields() const { return GetMembersOfType(); } + }; + + // A trait which other types can conform to + class TraitDecl : public AggTypeDecl + { + public: + List bases; + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + struct TraitDeclRef : public AggTypeDeclRef + { + SLANG_DECLARE_DECL_REF(TraitDecl); + }; + + + // A declaration that states that the enclosing type supports a given trait + // + // TODO: this same construct might be used for represent other inheritance-like cases + class TraitConformanceDecl : public Decl + { + public: + // The type expression as written + TypeExp base; + + // The trait that we found we conform to... + TraitDeclRef traitDeclRef; + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + struct TraitConformanceDeclRef : public DeclRef + { + SLANG_DECLARE_DECL_REF(TraitConformanceDecl); + + TraitDeclRef GetTraitDeclRef() { return Substitute(GetDecl()->traitDeclRef).As(); } + }; + + // A declaration that represents a simple (non-aggregate) type + class SimpleTypeDecl : public Decl + { + }; + + struct SimpleTypeDeclRef : DeclRef + { + SLANG_DECLARE_DECL_REF(SimpleTypeDecl) + }; + + // A `typedef` declaration + class TypeDefDecl : public SimpleTypeDecl + { + public: + TypeExp Type; + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + struct TypeDefDeclRef : SimpleTypeDeclRef + { + SLANG_DECLARE_DECL_REF(TypeDefDecl); + + RefPtr GetType() const { return Substitute(GetDecl()->Type); } + }; + + // A type alias of some kind (e.g., via `typedef`) + class NamedExpressionType : public ExpressionType + { + public: + NamedExpressionType(TypeDefDeclRef declRef) + : declRef(declRef) + {} + + TypeDefDeclRef declRef; + + virtual String ToString() override; + + protected: + virtual bool EqualsImpl(ExpressionType * type) override; + virtual ExpressionType* CreateCanonicalType() override; + virtual int GetHashCode() override; + }; + + + class StatementSyntaxNode : public ModifiableSyntaxNode + { + public: + }; + + // A scope for local declarations (e.g., as part of a statement) + class ScopeDecl : public ContainerDecl + { + public: + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class ScopeStmt : public StatementSyntaxNode + { + public: + RefPtr scopeDecl; + }; + + class BlockStatementSyntaxNode : public ScopeStmt + { + public: + List> Statements; + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class UnparsedStmt : public StatementSyntaxNode + { + public: + // The tokens that were contained between `{` and `}` + List tokens; + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class ParameterSyntaxNode : public VarDeclBase + { + public: + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + struct ParamDeclRef : VarDeclBaseRef + { + SLANG_DECLARE_DECL_REF(ParameterSyntaxNode); + }; + + // Base class for things that have parameter lists and can thus be applied to arguments ("called") + class CallableDecl : public ContainerDecl + { + public: + FilteredMemberList GetParameters() + { + return GetMembersOfType(); + } + TypeExp ReturnType; + }; + + struct CallableDeclRef : ContainerDeclRef + { + SLANG_DECLARE_DECL_REF(CallableDecl); + + RefPtr GetResultType() const + { + return Substitute(GetDecl()->ReturnType.type.Ptr()); + } + + FilteredMemberRefList GetParameters() + { + return GetMembersOfType(); + } + }; + + // Base class for callable things that may also have a body that is evaluated to produce their result + class FunctionDeclBase : public CallableDecl + { + public: + RefPtr Body; + }; + + struct FuncDeclBaseRef : CallableDeclRef + { + SLANG_DECLARE_DECL_REF(FunctionDeclBase); + }; + + // Function types are currently used for references to symbols that name + // either ordinary functions, or "component functions." + // We do not directly store a representation of the type, and instead + // use a reference to the symbol to stand in for its logical type + class FuncType : public ExpressionType + { + public: + CallableDeclRef declRef; + + virtual String ToString() override; + protected: + virtual bool EqualsImpl(ExpressionType * type) override; + virtual ExpressionType* CreateCanonicalType() override; + virtual int GetHashCode() override; + }; + + // A constructor/initializer to create instances of a type + class ConstructorDecl : public FunctionDeclBase + { + public: + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + struct ConstructorDeclRef : FuncDeclBaseRef + { + SLANG_DECLARE_DECL_REF(ConstructorDecl); + }; + + // A subscript operation used to index instances of a type + class SubscriptDecl : public CallableDecl + { + public: + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + struct SubscriptDeclRef : CallableDeclRef + { + SLANG_DECLARE_DECL_REF(SubscriptDecl); + }; + + // An "accessor" for a subscript or property + class AccessorDecl : public FunctionDeclBase + { + public: + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class GetterDecl : public AccessorDecl + { + }; + + class SetterDecl : public AccessorDecl + { + }; + + // + + class FunctionSyntaxNode : public FunctionDeclBase + { + public: + String InternalName; + bool IsInline() { return HasModifier(); } + bool IsExtern() { return HasModifier(); } + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + FunctionSyntaxNode() + { + } + }; + + struct FuncDeclRef : FuncDeclBaseRef + { + SLANG_DECLARE_DECL_REF(FunctionSyntaxNode); + }; + + + struct Scope : public RefObject + { + // The parent of this scope (where lookup should go if nothing is found locally) + RefPtr parent; + + // The next sibling of this scope (a peer for lookup) + RefPtr nextSibling; + + // The container to use for lookup + // + // Note(tfoley): This is kept as an unowned pointer + // so that a scope can't keep parts of the AST alive, + // but the opposite it allowed. + ContainerDecl* containerDecl; + }; + + // Base class for expressions that will reference declarations + class DeclRefExpr : public ExpressionSyntaxNode + { + public: + // The scope in which to perform lookup + RefPtr scope; + + // The declaration of the symbol being referenced + DeclRef declRef; + }; + + class VarExpressionSyntaxNode : public DeclRefExpr + { + public: + // The name of the symbol being referenced + String Variable; + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + // Masks to be applied when lookup up declarations + enum class LookupMask : uint8_t + { + Type = 0x1, + Function = 0x2, + Value = 0x4, + + All = Type | Function | Value, + }; + + // Represents one item found during lookup + struct LookupResultItem + { + // Sometimes lookup finds an item, but there were additional + // "hops" taken to reach it. We need to remember these steps + // so that if/when we consturct a full expression we generate + // appropriate AST nodes for all the steps. + // + // We build up a list of these "breadcrumbs" while doing + // lookup, and store them alongside each item found. + class Breadcrumb : public RefObject + { + public: + enum class Kind + { + Member, // A member was references + Deref, // A value with pointer(-like) type was dereferenced + }; + + Kind kind; + DeclRef declRef; + RefPtr next; + + Breadcrumb(Kind kind, DeclRef declRef, RefPtr next) + : kind(kind) + , declRef(declRef) + , next(next) + {} + }; + + // A properly-specialized reference to the declaration that was found. + DeclRef declRef; + + // Any breadcrumbs needed in order to turn that declaration + // reference into a well-formed expression. + // + // This is unused in the simple case where a declaration + // is being referenced directly (rather than through + // transparent members). + RefPtr breadcrumbs; + + LookupResultItem() = default; + explicit LookupResultItem(DeclRef declRef) + : declRef(declRef) + {} + LookupResultItem(DeclRef declRef, RefPtr breadcrumbs) + : declRef(declRef) + , breadcrumbs(breadcrumbs) + {} + }; + + + // Result of looking up a name in some lexical/semantic environment. + // Can be used to enumerate all the declarations matching that name, + // in the case where the result is overloaded. + struct LookupResult + { + // The one item that was found, in the smple case + LookupResultItem item; + + // All of the items that were found, in the complex case. + // Note: if there was no overloading, then this list isn't + // used at all, to avoid allocation. + List items; + + // Was at least one result found? + bool isValid() const { return item.declRef.GetDecl() != nullptr; } + + bool isOverloaded() const { return items.Count() > 1; } + }; + + struct LookupRequest + { + RefPtr scope = nullptr; + RefPtr endScope = nullptr; + + LookupMask mask = LookupMask::All; + }; + + // An expression that references an overloaded set of declarations + // having the same name. + class OverloadedExpr : public ExpressionSyntaxNode + { + public: + // Optional: the base expression is this overloaded result + // arose from a member-reference expression. + RefPtr base; + + // The lookup result that was ambiguous + LookupResult lookupResult2; + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + typedef double FloatingPointLiteralValue; + + class ConstantExpressionSyntaxNode : public ExpressionSyntaxNode + { + public: + enum class ConstantType + { + Int, Bool, Float + }; + ConstantType ConstType; + union + { + int IntValue; + FloatingPointLiteralValue FloatValue; + }; + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + enum class Operator + { + Neg, Not, BitNot, PreInc, PreDec, PostInc, PostDec, + Mul, Div, Mod, + Add, Sub, + Lsh, Rsh, + Eql, Neq, Greater, Less, Geq, Leq, + BitAnd, BitXor, BitOr, + And, + Or, + Sequence, + Select, + Assign = 200, AddAssign, SubAssign, MulAssign, DivAssign, ModAssign, + LshAssign, RshAssign, OrAssign, AndAssign, XorAssign, + }; + String GetOperatorFunctionName(Operator op); + String OperatorToString(Operator op); + + // An initializer list, e.g. `{ 1, 2, 3 }` + class InitializerListExpr : public ExpressionSyntaxNode + { + public: + List> args; + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + // A base expression being applied to arguments: covers + // both ordinary `()` function calls and `<>` generic application + class AppExprBase : public ExpressionSyntaxNode + { + public: + RefPtr FunctionExpr; + List> Arguments; + }; + + + class InvokeExpressionSyntaxNode : public AppExprBase + { + public: + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class OperatorExpressionSyntaxNode : public InvokeExpressionSyntaxNode + { + public: +// Operator Operator; +// void SetOperator(RefPtr scope, Slang::Compiler::Operator op); + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class InfixExpr : public OperatorExpressionSyntaxNode {}; + class PrefixExpr : public OperatorExpressionSyntaxNode {}; + class PostfixExpr : public OperatorExpressionSyntaxNode {}; + + class IndexExpressionSyntaxNode : public ExpressionSyntaxNode + { + public: + RefPtr BaseExpression; + RefPtr IndexExpression; + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class MemberExpressionSyntaxNode : public DeclRefExpr + { + public: + RefPtr BaseExpression; + String MemberName; + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class SwizzleExpr : public ExpressionSyntaxNode + { + public: + RefPtr base; + int elementCount; + int elementIndices[4]; + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + // A dereference of a pointer or pointer-like type + class DerefExpr : public ExpressionSyntaxNode + { + public: + RefPtr base; + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class TypeCastExpressionSyntaxNode : public ExpressionSyntaxNode + { + public: + TypeExp TargetType; + RefPtr Expression; + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class SelectExpressionSyntaxNode : public OperatorExpressionSyntaxNode + { + public: + }; + + + class EmptyStatementSyntaxNode : public StatementSyntaxNode + { + public: + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class DiscardStatementSyntaxNode : public StatementSyntaxNode + { + public: + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + struct Variable : public VarDeclBase + { + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class VarDeclrStatementSyntaxNode : public StatementSyntaxNode + { + public: + RefPtr decl; + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class UsingFileDecl : public Decl + { + public: + Token fileName; + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class ProgramSyntaxNode : public ContainerDecl + { + public: + // Access members of specific types + FilteredMemberList GetUsings() + { + return GetMembersOfType(); + } + FilteredMemberList GetFunctions() + { + return GetMembersOfType(); + } + + FilteredMemberList GetClasses() + { + return GetMembersOfType(); + } + FilteredMemberList GetStructs() + { + return GetMembersOfType(); + } + FilteredMemberList GetTypeDefs() + { + return GetMembersOfType(); + } +#if 0 + void Include(ProgramSyntaxNode * other) + { + Members.AddRange(other->Members); + } +#endif + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class IfStatementSyntaxNode : public StatementSyntaxNode + { + public: + RefPtr Predicate; + RefPtr PositiveStatement; + RefPtr NegativeStatement; + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + // A statement that can be escaped with a `break` + class BreakableStmt : public ScopeStmt + {}; + + class SwitchStmt : public BreakableStmt + { + public: + RefPtr condition; + RefPtr body; + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + // A statement that is expected to appear lexically nested inside + // some other construct, and thus needs to keep track of the + // outer statement that it is associated with... + class ChildStmt : public StatementSyntaxNode + { + public: + StatementSyntaxNode* parentStmt = nullptr; + }; + + // a `case` or `default` statement inside a `switch` + // + // Note(tfoley): A correct AST for a C-like language would treat + // these as a labelled statement, and so they would contain a + // sub-statement. I'm leaving that out for now for simplicity. + class CaseStmtBase : public ChildStmt + { + public: + }; + + // a `case` statement inside a `switch` + class CaseStmt : public CaseStmtBase + { + public: + RefPtr expr; + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + // a `default` statement inside a `switch` + class DefaultStmt : public CaseStmtBase + { + public: + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + // A statement that represents a loop, and can thus be escaped with a `continue` + class LoopStmt : public BreakableStmt + {}; + + class ForStatementSyntaxNode : public LoopStmt + { + public: + RefPtr InitialStatement; + RefPtr SideEffectExpression, PredicateExpression; + RefPtr Statement; + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class WhileStatementSyntaxNode : public LoopStmt + { + public: + RefPtr Predicate; + RefPtr Statement; + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class DoWhileStatementSyntaxNode : public LoopStmt + { + public: + RefPtr Statement; + RefPtr Predicate; + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + // The case of child statements that do control flow relative + // to their parent statement. + class JumpStmt : public ChildStmt + { + public: + StatementSyntaxNode* parentStmt = nullptr; + }; + + class BreakStatementSyntaxNode : public JumpStmt + { + public: + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class ContinueStatementSyntaxNode : public JumpStmt + { + public: + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class ReturnStatementSyntaxNode : public StatementSyntaxNode + { + public: + RefPtr Expression; + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + class ExpressionStatementSyntaxNode : public StatementSyntaxNode + { + public: + RefPtr Expression; + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + // Note(tfoley): Moved this further down in the file because it depends on + // `ExpressionSyntaxNode` and a forward reference just isn't good enough + // for `RefPtr`. + // + class GenericAppExpr : public AppExprBase + { + public: + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + // An expression representing re-use of the syntax for a type in more + // than once conceptually-distinct declaration + class SharedTypeExpr : public ExpressionSyntaxNode + { + public: + // The underlying type expression that we want to share + TypeExp base; + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + + // A modifier that indicates a built-in base type (e.g., `float`) + class BuiltinTypeModifier : public Modifier + { + public: + BaseType tag; + }; + + // A modifier that indicates a built-in type that isn't a base type (e.g., `vector`) + // + // TODO(tfoley): This deserves a better name than "magic" + class MagicTypeModifier : public Modifier + { + public: + String name; + uint32_t tag; + }; + + // Modifiers that affect the storage layout for matrices + class MatrixLayoutModifier : public Modifier {}; + + // Modifiers that specify row- and column-major layout, respectively + class RowMajorLayoutModifier : public MatrixLayoutModifier {}; + class ColumnMajorLayoutModifier : public MatrixLayoutModifier {}; + + // The HLSL flavor of those modifiers + class HLSLRowMajorLayoutModifier : public RowMajorLayoutModifier {}; + class HLSLColumnMajorLayoutModifier : public ColumnMajorLayoutModifier {}; + + // The GLSL flavor of those modifiers + // + // Note(tfoley): The GLSL versions of these modifiers are "backwards" + // in the sense that when a GLSL programmer requests row-major layout, + // we actually interpret that as requesting column-major. This makes + // sense because we interpret matrix conventions backwards from how + // GLSL specifies them. + class GLSLRowMajorLayoutModifier : public ColumnMajorLayoutModifier {}; + class GLSLColumnMajorLayoutModifier : public RowMajorLayoutModifier {}; + + // More HLSL Keyword + + // HLSL `nointerpolation` modifier + class HLSLNoInterpolationModifier : public Modifier {}; + + // HLSL `linear` modifier + class HLSLLinearModifier : public Modifier {}; + + // HLSL `sample` modifier + class HLSLSampleModifier : public Modifier {}; + + // HLSL `centroid` modifier + class HLSLCentroidModifier : public Modifier {}; + + // HLSL `precise` modifier + class HLSLPreciseModifier : public Modifier {}; + + // HLSL `shared` modifier (which is used by the effect system, + // and shouldn't be confused with `groupshared`) + class HLSLEffectSharedModifier : public Modifier {}; + + // HLSL `groupshared` modifier + class HLSLGroupSharedModifier : public Modifier {}; + + // HLSL `static` modifier (probably doesn't need to be + // treated as HLSL-specific) + class HLSLStaticModifier : public Modifier {}; + + // HLSL `uniform` modifier (distinct meaning from GLSL + // use of the keyword) + class HLSLUniformModifier : public Modifier {}; + + // HLSL `volatile` modifier (ignored) + class HLSLVolatileModifier : public Modifier {}; + + // An HLSL `[name(arg0, ...)]` style attribute. + class HLSLAttribute : public Modifier + { + public: + Token nameToken; + List> args; + }; + + // An HLSL `[name(...)]` attribute that hasn't undergone + // any semantic analysis. + // After analysis, this might be transformed into a more specific case. + class HLSLUncheckedAttribute : public HLSLAttribute + { + public: + }; + + // An HLSL `[numthreads(x,y,z)]` attribute + class HLSLNumThreadsAttribute : public HLSLAttribute + { + public: + // The number of threads to use along each axis + int32_t x; + int32_t y; + int32_t z; + }; + + // HLSL modifiers for geometry shader input topology + class HLSLGeometryShaderInputPrimitiveTypeModifier : public Modifier {}; + class HLSLPointModifier : public HLSLGeometryShaderInputPrimitiveTypeModifier {}; + class HLSLLineModifier : public HLSLGeometryShaderInputPrimitiveTypeModifier {}; + class HLSLTriangleModifier : public HLSLGeometryShaderInputPrimitiveTypeModifier {}; + class HLSLLineAdjModifier : public HLSLGeometryShaderInputPrimitiveTypeModifier {}; + class HLSLTriangleAdjModifier : public HLSLGeometryShaderInputPrimitiveTypeModifier {}; + + // + + // A generic declaration, parameterized on types/values + class GenericDecl : public ContainerDecl + { + public: + // The decl that is genericized... + RefPtr inner; + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + struct GenericDeclRef : ContainerDeclRef + { + SLANG_DECLARE_DECL_REF(GenericDecl); + + Decl* GetInner() const { return GetDecl()->inner.Ptr(); } + }; + + // The "type" of an expression that names a generic declaration. + class GenericDeclRefType : public ExpressionType + { + public: + GenericDeclRefType(GenericDeclRef declRef) + : declRef(declRef) + {} + + GenericDeclRef declRef; + GenericDeclRef const& GetDeclRef() const { return declRef; } + + virtual String ToString() override; + + protected: + virtual bool EqualsImpl(ExpressionType * type) override; + virtual int GetHashCode() override; + virtual ExpressionType* CreateCanonicalType() override; + }; + + + + class GenericTypeParamDecl : public SimpleTypeDecl + { + public: + // The bound for the type parameter represents a trait that any + // type used as this parameter must conform to +// TypeExp bound; + + // The "initializer" for the parameter represents a default value + TypeExp initType; + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + struct GenericTypeParamDeclRef : SimpleTypeDeclRef + { + SLANG_DECLARE_DECL_REF(GenericTypeParamDecl); + }; + + // A constraint placed as part of a generic declaration + class GenericTypeConstraintDecl : public Decl + { + public: + // A type constraint like `T : U` is constraining `T` to be "below" `U` + // on a lattice of types. This may not be a subtyping relationship + // per se, but it makes sense to use that terminology here, so we + // think of these fields as the sub-type and sup-ertype, respectively. + TypeExp sub; + TypeExp sup; + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + struct GenericTypeConstraintDeclRef : DeclRef + { + SLANG_DECLARE_DECL_REF(GenericTypeConstraintDecl); + + RefPtr GetSub() { return Substitute(GetDecl()->sub); } + RefPtr GetSup() { return Substitute(GetDecl()->sup); } + }; + + + class GenericValueParamDecl : public VarDeclBase + { + public: + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + struct GenericValueParamDeclRef : VarDeclBaseRef + { + SLANG_DECLARE_DECL_REF(GenericValueParamDecl); + }; + + // The logical "value" of a rererence to a generic value parameter + class GenericParamIntVal : public IntVal + { + public: + VarDeclBaseRef declRef; + + GenericParamIntVal(VarDeclBaseRef declRef) + : declRef(declRef) + {} + + virtual bool EqualsVal(Val* val) override; + virtual String ToString() override; + virtual int GetHashCode() override; + virtual RefPtr SubstituteImpl(Substitutions* subst, int* ioDiff) override; + }; + + // Declaration of a user-defined modifier + class ModifierDecl : public Decl + { + public: + // The name of the C++ class to instantiate + // (this is a reference to a class in the compiler source code, + // and not the user's source code) + Token classNameToken; + + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + // An empty declaration (which might still have modifiers attached). + // + // An empty declaration is uncommon in HLSL, but + // in GLSL it is often used at the global scope + // to declare metadata that logically belongs + // to the entry point, e.g.: + // + // layout(local_size_x = 16) in; + // + class EmptyDecl : public Decl + { + public: + virtual RefPtr Accept(SyntaxVisitor * visitor) override; + }; + + // + + class SyntaxVisitor : public Object + { + protected: + DiagnosticSink * sink = nullptr; + DiagnosticSink* getSink() { return sink; } + + SourceLanguage sourceLanguage = SourceLanguage::Unknown; + public: + void setSourceLanguage(SourceLanguage language) + { + sourceLanguage = language; + } + + SyntaxVisitor(DiagnosticSink * sink) + : sink(sink) + {} + virtual RefPtr VisitProgram(ProgramSyntaxNode* program) + { + for (auto & m : program->Members) + m = m->Accept(this).As(); + return program; + } + + virtual RefPtr VisitUsingFileDecl(UsingFileDecl * decl) + { + return decl; + } + + virtual RefPtr VisitFunction(FunctionSyntaxNode* func) + { + func->ReturnType = func->ReturnType.Accept(this); + for (auto & member : func->Members) + member = member->Accept(this).As(); + if (func->Body) + func->Body = func->Body->Accept(this).As(); + return func; + } + virtual RefPtr VisitScopeDecl(ScopeDecl* decl) + { + // By default don't visit children, because they will always + // be encountered in the ordinary flow of the corresponding statement. + return decl; + } + virtual RefPtr VisitStruct(StructSyntaxNode * s) + { + for (auto & f : s->Members) + f = f->Accept(this).As(); + return s; + } + virtual RefPtr VisitClass(ClassSyntaxNode * s) + { + for (auto & f : s->Members) + f = f->Accept(this).As(); + return s; + } + virtual RefPtr VisitGenericDecl(GenericDecl * decl) + { + for (auto & m : decl->Members) + m = m->Accept(this).As(); + decl->inner = decl->inner->Accept(this).As(); + return decl; + } + virtual RefPtr VisitTypeDefDecl(TypeDefDecl* decl) + { + decl->Type = decl->Type.Accept(this); + return decl; + } + virtual RefPtr VisitDiscardStatement(DiscardStatementSyntaxNode * stmt) + { + return stmt; + } + virtual RefPtr VisitStructField(StructField * f) + { + f->Type = f->Type.Accept(this); + return f; + } + virtual RefPtr VisitBlockStatement(BlockStatementSyntaxNode* stmt) + { + for (auto & s : stmt->Statements) + s = s->Accept(this).As(); + return stmt; + } + virtual RefPtr VisitBreakStatement(BreakStatementSyntaxNode* stmt) + { + return stmt; + } + virtual RefPtr VisitContinueStatement(ContinueStatementSyntaxNode* stmt) + { + return stmt; + } + + virtual RefPtr VisitDoWhileStatement(DoWhileStatementSyntaxNode* stmt) + { + if (stmt->Predicate) + stmt->Predicate = stmt->Predicate->Accept(this).As(); + if (stmt->Statement) + stmt->Statement = stmt->Statement->Accept(this).As(); + return stmt; + } + virtual RefPtr VisitEmptyStatement(EmptyStatementSyntaxNode* stmt) + { + return stmt; + } + virtual RefPtr VisitForStatement(ForStatementSyntaxNode* stmt) + { + if (stmt->InitialStatement) + stmt->InitialStatement = stmt->InitialStatement->Accept(this).As(); + if (stmt->PredicateExpression) + stmt->PredicateExpression = stmt->PredicateExpression->Accept(this).As(); + if (stmt->SideEffectExpression) + stmt->SideEffectExpression = stmt->SideEffectExpression->Accept(this).As(); + if (stmt->Statement) + stmt->Statement = stmt->Statement->Accept(this).As(); + return stmt; + } + virtual RefPtr VisitIfStatement(IfStatementSyntaxNode* stmt) + { + if (stmt->Predicate) + stmt->Predicate = stmt->Predicate->Accept(this).As(); + if (stmt->PositiveStatement) + stmt->PositiveStatement = stmt->PositiveStatement->Accept(this).As(); + if (stmt->NegativeStatement) + stmt->NegativeStatement = stmt->NegativeStatement->Accept(this).As(); + return stmt; + } + virtual RefPtr VisitSwitchStmt(SwitchStmt* stmt) + { + if (stmt->condition) + stmt->condition = stmt->condition->Accept(this).As(); + if (stmt->body) + stmt->body = stmt->body->Accept(this).As(); + return stmt; + } + virtual RefPtr VisitCaseStmt(CaseStmt* stmt) + { + if (stmt->expr) + stmt->expr = stmt->expr->Accept(this).As(); + return stmt; + } + virtual RefPtr VisitDefaultStmt(DefaultStmt* stmt) + { + return stmt; + } + virtual RefPtr VisitReturnStatement(ReturnStatementSyntaxNode* stmt) + { + if (stmt->Expression) + stmt->Expression = stmt->Expression->Accept(this).As(); + return stmt; + } + virtual RefPtr VisitVarDeclrStatement(VarDeclrStatementSyntaxNode* stmt) + { + stmt->decl = stmt->decl->Accept(this).As(); + return stmt; + } + virtual RefPtr VisitWhileStatement(WhileStatementSyntaxNode* stmt) + { + if (stmt->Predicate) + stmt->Predicate = stmt->Predicate->Accept(this).As(); + if (stmt->Statement) + stmt->Statement = stmt->Statement->Accept(this).As(); + return stmt; + } + virtual RefPtr VisitExpressionStatement(ExpressionStatementSyntaxNode* stmt) + { + if (stmt->Expression) + stmt->Expression = stmt->Expression->Accept(this).As(); + return stmt; + } + + virtual RefPtr VisitOperatorExpression(OperatorExpressionSyntaxNode* expr) + { + for (auto && child : expr->Arguments) + child->Accept(this); + return expr; + } + virtual RefPtr VisitConstantExpression(ConstantExpressionSyntaxNode* expr) + { + return expr; + } + virtual RefPtr VisitIndexExpression(IndexExpressionSyntaxNode* expr) + { + if (expr->BaseExpression) + expr->BaseExpression = expr->BaseExpression->Accept(this).As(); + if (expr->IndexExpression) + expr->IndexExpression = expr->IndexExpression->Accept(this).As(); + return expr; + } + virtual RefPtr VisitMemberExpression(MemberExpressionSyntaxNode * stmt) + { + if (stmt->BaseExpression) + stmt->BaseExpression = stmt->BaseExpression->Accept(this).As(); + return stmt; + } + virtual RefPtr VisitSwizzleExpression(SwizzleExpr * expr) + { + if (expr->base) + expr->base->Accept(this); + return expr; + } + virtual RefPtr VisitInvokeExpression(InvokeExpressionSyntaxNode* stmt) + { + stmt->FunctionExpr->Accept(this); + for (auto & arg : stmt->Arguments) + arg = arg->Accept(this).As(); + return stmt; + } + virtual RefPtr VisitTypeCastExpression(TypeCastExpressionSyntaxNode * stmt) + { + if (stmt->Expression) + stmt->Expression = stmt->Expression->Accept(this).As(); + return stmt->Expression; + } + virtual RefPtr VisitVarExpression(VarExpressionSyntaxNode* expr) + { + return expr; + } + + virtual RefPtr VisitParameter(ParameterSyntaxNode* param) + { + return param; + } + virtual RefPtr VisitGenericApp(GenericAppExpr* type) + { + return type; + } + + virtual RefPtr VisitDeclrVariable(Variable* dclr) + { + if (dclr->Expr) + dclr->Expr = dclr->Expr->Accept(this).As(); + return dclr; + } + + virtual TypeExp VisitTypeExp(TypeExp const& typeExp) + { + TypeExp result = typeExp; + result.exp = typeExp.exp->Accept(this).As(); + if (auto typeType = result.exp->Type.type.As()) + { + result.type = typeType->type; + } + return result; + } + + virtual void VisitExtensionDecl(ExtensionDecl* /*decl*/) + {} + + virtual void VisitConstructorDecl(ConstructorDecl* /*decl*/) + {} + + virtual void visitSubscriptDecl(SubscriptDecl* decl) = 0; + + virtual void visitAccessorDecl(AccessorDecl* decl) = 0; + + virtual void VisitTraitDecl(TraitDecl* /*decl*/) + {} + + virtual void VisitTraitConformanceDecl(TraitConformanceDecl* /*decl*/) + {} + + virtual RefPtr VisitSharedTypeExpr(SharedTypeExpr* typeExpr) + { + return typeExpr; + } + + virtual void VisitDeclGroup(DeclGroup* declGroup) + { + for (auto decl : declGroup->decls) + { + decl->Accept(this); + } + } + + virtual RefPtr visitInitializerListExpr(InitializerListExpr* expr) = 0; + }; + + // Note(tfoley): These logically belong to `ExpressionType`, + // but order-of-declaration stuff makes that tricky + // + // TODO(tfoley): These should really belong to the compilation context! + // + void RegisterBuiltinDecl( + RefPtr decl, + RefPtr modifier); + void RegisterMagicDecl( + RefPtr decl, + RefPtr modifier); + + // Look up a magic declaration by its name + RefPtr findMagicDecl( + String const& name); + + // Create an instance of a syntax class by name + SyntaxNodeBase* createInstanceOfSyntaxClassByName( + String const& name); + + } +} + +#endif \ No newline at end of file diff --git a/source/slang/token-defs.h b/source/slang/token-defs.h new file mode 100644 index 000000000..f29574bbb --- /dev/null +++ b/source/slang/token-defs.h @@ -0,0 +1,93 @@ +// token-defs.h + +// This file is meant to be included multiple times, to produce different +// pieces of code related to tokens +// +// Each token is declared here with: +// +// TOKEN(id, desc) +// +// where `id` is the identifier that will be used for the token in +// ordinary code, while `desc` is name we should print when +// referring to this token in diagnostic messages. + + +#ifndef TOKEN +#error Need to define TOKEN(ID, DESC) before including "token-defs.h" +#endif + +TOKEN(Unknown, "") +TOKEN(EndOfFile, "end of file") +TOKEN(EndOfDirective, "end of line") +TOKEN(Invalid, "invalid character") +TOKEN(Identifier, "identifier") +TOKEN(IntLiterial, "integer literal") +TOKEN(DoubleLiterial, "floating-point literal") +TOKEN(StringLiterial, "string literal") +TOKEN(CharLiterial, "character literal") +TOKEN(WhiteSpace, "whitespace") +TOKEN(NewLine, "newline") +TOKEN(LineComment, "line comment") +TOKEN(BlockComment, "block comment") + +#define PUNCTUATION(id, text) \ + TOKEN(id, "'" text "'") + +PUNCTUATION(Semicolon, ";") +PUNCTUATION(Comma, ",") +PUNCTUATION(Dot, ".") + +PUNCTUATION(LBrace, "{") +PUNCTUATION(RBrace, "}") +PUNCTUATION(LBracket, "[") +PUNCTUATION(RBracket, "]") +PUNCTUATION(LParent, "(") +PUNCTUATION(RParent, ")") + +PUNCTUATION(OpAssign, "=") +PUNCTUATION(OpAdd, "+") +PUNCTUATION(OpSub, "-") +PUNCTUATION(OpMul, "*") +PUNCTUATION(OpDiv, "/") +PUNCTUATION(OpMod, "%") +PUNCTUATION(OpNot, "!") +PUNCTUATION(OpBitNot, "~") +PUNCTUATION(OpLsh, "<<") +PUNCTUATION(OpRsh, ">>") +PUNCTUATION(OpEql, "==") +PUNCTUATION(OpNeq, "!=") +PUNCTUATION(OpGreater, ">") +PUNCTUATION(OpLess, "<") +PUNCTUATION(OpGeq, ">=") +PUNCTUATION(OpLeq, "<=") +PUNCTUATION(OpAnd, "&&") +PUNCTUATION(OpOr, "||") +PUNCTUATION(OpBitAnd, "&") +PUNCTUATION(OpBitOr, "|") +PUNCTUATION(OpBitXor, "^") +PUNCTUATION(OpInc, "++") +PUNCTUATION(OpDec, "--") + +PUNCTUATION(OpAddAssign, "+=") +PUNCTUATION(OpSubAssign, "-=") +PUNCTUATION(OpMulAssign, "*=") +PUNCTUATION(OpDivAssign, "/=") +PUNCTUATION(OpModAssign, "%=") +PUNCTUATION(OpShlAssign, "<<=") +PUNCTUATION(OpShrAssign, ">>=") +PUNCTUATION(OpAndAssign, "&=") +PUNCTUATION(OpOrAssign, "|=") +PUNCTUATION(OpXorAssign, "^=") + +PUNCTUATION(QuestionMark, "?") +PUNCTUATION(Colon, ":") +PUNCTUATION(RightArrow, "->") +PUNCTUATION(At, "@") +PUNCTUATION(Dollar, "$") +PUNCTUATION(Pound, "#") +PUNCTUATION(PoundPound, "##") + +#undef PUNCTUATION + +// Un-define the `TOKEN` macro so that client doesn't have to +#undef TOKEN diff --git a/source/slang/token.cpp b/source/slang/token.cpp new file mode 100644 index 000000000..436a3a740 --- /dev/null +++ b/source/slang/token.cpp @@ -0,0 +1,22 @@ +// token.cpp +#include "token.h" + +#include + +namespace Slang { +namespace Compiler { + +char const* TokenTypeToString(TokenType type) +{ + switch( type ) + { + default: + assert(!"unexpected"); + return ""; + +#define TOKEN(NAME, DESC) case TokenType::NAME: return DESC; +#include "token-defs.h" + } +} + +}} diff --git a/source/slang/token.h b/source/slang/token.h new file mode 100644 index 000000000..00a55feb1 --- /dev/null +++ b/source/slang/token.h @@ -0,0 +1,50 @@ +// token.h +#ifndef SLANG_TOKEN_H_INCLUDED +#define SLANG_TOKEN_H_INCLUDED + +#include "../core/basic.h" + +#include "source-loc.h" + +namespace Slang { +namespace Compiler { + +using namespace CoreLib::Basic; + +enum class TokenType +{ +#define TOKEN(NAME, DESC) NAME, +#include "token-defs.h" +}; + +char const* TokenTypeToString(TokenType type); + +enum TokenFlag : unsigned int +{ + AtStartOfLine = 1 << 0, + AfterWhitespace = 1 << 1, +}; +typedef unsigned int TokenFlags; + +class Token +{ +public: + TokenType Type = TokenType::Unknown; + String Content; + CodePosition Position; + TokenFlags flags = 0; + Token() = default; + Token(TokenType type, const String & content, int line, int col, int pos, String fileName, TokenFlags flags = 0) + : flags(flags) + { + Type = type; + Content = content; + Position = CodePosition(line, col, pos, fileName); + } +}; + + + +}} + +#endif diff --git a/source/slang/type-layout.cpp b/source/slang/type-layout.cpp new file mode 100644 index 000000000..4e5c98ed5 --- /dev/null +++ b/source/slang/type-layout.cpp @@ -0,0 +1,1125 @@ +// TypeLayout.cpp +#include "type-layout.h" + +#include "syntax.h" + +#include + +namespace Slang { +namespace Compiler { + +size_t RoundToAlignment(size_t offset, size_t alignment) +{ + size_t remainder = offset % alignment; + if (remainder == 0) + return offset; + else + return offset + (alignment - remainder); +} + +static size_t RoundUpToPowerOfTwo( size_t value ) +{ + // TODO(tfoley): I know this isn't a fast approach + size_t result = 1; + while (result < value) + result *= 2; + return result; +} + +struct DefaultLayoutRulesImpl : SimpleLayoutRulesImpl +{ + // Get size and alignment for a single value of base type. + SimpleLayoutInfo GetScalarLayout(BaseType baseType) override + { + switch (baseType) + { + case BaseType::Int: + case BaseType::UInt: + case BaseType::Float: + case BaseType::Bool: + return SimpleLayoutInfo( LayoutResourceKind::Uniform, 4, 4 ); + + default: + assert(!"unimplemented"); + return SimpleLayoutInfo( LayoutResourceKind::Uniform, 0, 1 ); + } + } + + virtual SimpleLayoutInfo GetScalarLayout(slang::TypeReflection::ScalarType scalarType) + { + switch( scalarType ) + { + case slang::TypeReflection::ScalarType::Void: return SimpleLayoutInfo(); + case slang::TypeReflection::ScalarType::None: return SimpleLayoutInfo(); + + // TODO(tfoley): At some point we don't want to lay out `bool` as 4 bytes by default... + case slang::TypeReflection::ScalarType::Bool: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 4,4); + case slang::TypeReflection::ScalarType::Int32: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 4,4); + case slang::TypeReflection::ScalarType::UInt32: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 4,4); + case slang::TypeReflection::ScalarType::Int64: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 8,8); + case slang::TypeReflection::ScalarType::UInt64: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 8,8); + + // TODO(tfoley): What actually happens if you use `half` in a constant buffer? + case slang::TypeReflection::ScalarType::Float16: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 2,2); + case slang::TypeReflection::ScalarType::Float32: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 4,4); + case slang::TypeReflection::ScalarType::Float64: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 8,8); + + default: + assert(!"unimplemented"); + return SimpleLayoutInfo(); + } + } + + SimpleArrayLayoutInfo GetArrayLayout( SimpleLayoutInfo elementInfo, size_t elementCount) override + { + size_t stride = elementInfo.size; + + SimpleArrayLayoutInfo arrayInfo; + arrayInfo.kind = elementInfo.kind; + arrayInfo.size = stride * elementCount; + arrayInfo.alignment = elementInfo.alignment; + arrayInfo.elementStride = stride; + return arrayInfo; + } + + SimpleLayoutInfo GetVectorLayout(SimpleLayoutInfo elementInfo, size_t elementCount) override + { + SimpleLayoutInfo vectorInfo; + vectorInfo.kind = elementInfo.kind; + vectorInfo.size = elementInfo.size * elementCount; + vectorInfo.alignment = elementInfo.alignment; + return vectorInfo; + } + + SimpleLayoutInfo GetMatrixLayout(SimpleLayoutInfo elementInfo, size_t rowCount, size_t columnCount) override + { + return GetArrayLayout( + GetVectorLayout(elementInfo, columnCount), + rowCount); + } + + UniformLayoutInfo BeginStructLayout() override + { + UniformLayoutInfo structInfo(0, 1); + return structInfo; + } + + size_t AddStructField(UniformLayoutInfo* ioStructInfo, UniformLayoutInfo fieldInfo) override + { + // Skip zero-size fields + if(fieldInfo.size == 0) + return ioStructInfo->size; + + ioStructInfo->alignment = std::max(ioStructInfo->alignment, fieldInfo.alignment); + ioStructInfo->size = RoundToAlignment(ioStructInfo->size, fieldInfo.alignment); + size_t fieldOffset = ioStructInfo->size; + ioStructInfo->size += fieldInfo.size; + return fieldOffset; + } + + + void EndStructLayout(UniformLayoutInfo* ioStructInfo) override + { + ioStructInfo->size = RoundToAlignment(ioStructInfo->size, ioStructInfo->alignment); + } +}; + +// Capture common behavior betwen HLSL and GLSL (`std140`) constnat buffer rules +struct DefaultConstantBufferLayoutRulesImpl : DefaultLayoutRulesImpl +{ + // The `std140` rules require that all array elements + // be a multiple of 16 bytes. + // + // HLSL agrees. + SimpleArrayLayoutInfo GetArrayLayout(SimpleLayoutInfo elementInfo, size_t elementCount) override + { + if(elementInfo.kind == LayoutResourceKind::Uniform) + { + if (elementInfo.alignment < 16) + elementInfo.alignment = 16; + elementInfo.size = RoundToAlignment(elementInfo.size, elementInfo.alignment); + } + return DefaultLayoutRulesImpl::GetArrayLayout(elementInfo, elementCount); + } + + // The `std140` rules require that a `struct` type be + // aligned to at least 16. + // + // HLSL agrees. + UniformLayoutInfo BeginStructLayout() override + { + return UniformLayoutInfo(0, 16); + } +}; + +struct GLSLConstantBufferLayoutRulesImpl : DefaultConstantBufferLayoutRulesImpl +{ +}; + +struct Std140LayoutRulesImpl : GLSLConstantBufferLayoutRulesImpl +{ + // The `std140` rules require vectors to be aligned to the next power of two + // up from their size (so a `float2` is 8-byte aligned, and a `float3` is + // 16-byte aligned). + SimpleLayoutInfo GetVectorLayout(SimpleLayoutInfo elementInfo, size_t elementCount) override + { + assert(elementInfo.kind == LayoutResourceKind::Uniform); + SimpleLayoutInfo vectorInfo( + LayoutResourceKind::Uniform, + elementInfo.size * elementCount, + RoundUpToPowerOfTwo(elementInfo.size * elementInfo.alignment)); + return vectorInfo; + } +}; + +struct HLSLConstantBufferLayoutRulesImpl : DefaultConstantBufferLayoutRulesImpl +{ + // Can't let a `struct` field straddle a register (16-byte) boundary + size_t AddStructField(UniformLayoutInfo* ioStructInfo, UniformLayoutInfo fieldInfo) override + { + // Skip zero-size fields + if(fieldInfo.size == 0) + return ioStructInfo->size; + + ioStructInfo->alignment = std::max(ioStructInfo->alignment, fieldInfo.alignment); + ioStructInfo->size = RoundToAlignment(ioStructInfo->size, fieldInfo.alignment); + + size_t fieldOffset = ioStructInfo->size; + size_t fieldSize = fieldInfo.size; + + // Would this field cross a 16-byte boundary? + auto registerSize = 16; + auto startRegister = fieldOffset / registerSize; + auto endRegister = (fieldOffset + fieldSize - 1) / registerSize; + if (startRegister != endRegister) + { + ioStructInfo->size = RoundToAlignment(ioStructInfo->size, size_t(registerSize)); + fieldOffset = ioStructInfo->size; + } + + ioStructInfo->size += fieldInfo.size; + return fieldOffset; + } +}; + +struct HLSLStructuredBufferLayoutRulesImpl : DefaultLayoutRulesImpl +{ + // TODO: customize these to be correct... +}; + +struct Std430LayoutRulesImpl : GLSLConstantBufferLayoutRulesImpl +{ +}; + +struct DefaultVaryingLayoutRulesImpl : DefaultLayoutRulesImpl +{ + LayoutResourceKind kind; + + DefaultVaryingLayoutRulesImpl(LayoutResourceKind kind) + : kind(kind) + {} + + + // hook to allow differentiating for input/output + virtual LayoutResourceKind getKind() + { + return kind; + } + + SimpleLayoutInfo GetScalarLayout(BaseType baseType) override + { + // Assume that all scalars take up one "slot" + return SimpleLayoutInfo( + getKind(), + 1); + } + + virtual SimpleLayoutInfo GetScalarLayout(slang::TypeReflection::ScalarType scalarType) + { + // Assume that all scalars take up one "slot" + return SimpleLayoutInfo( + getKind(), + 1); + } + + SimpleLayoutInfo GetVectorLayout(SimpleLayoutInfo elementInfo, size_t elementCount) override + { + // Vectors take up one slot by default + // + // TODO: some platforms may decide that vectors of `double` need + // special handling + return SimpleLayoutInfo( + getKind(), + 1); + } +}; + +struct GLSLVaryingLayoutRulesImpl : DefaultVaryingLayoutRulesImpl +{ + GLSLVaryingLayoutRulesImpl(LayoutResourceKind kind) + : DefaultVaryingLayoutRulesImpl(kind) + {} +}; + +struct HLSLVaryingLayoutRulesImpl : DefaultVaryingLayoutRulesImpl +{ + HLSLVaryingLayoutRulesImpl(LayoutResourceKind kind) + : DefaultVaryingLayoutRulesImpl(kind) + {} +}; + +// + +struct GLSLSpecializationConstantLayoutRulesImpl : DefaultLayoutRulesImpl +{ + LayoutResourceKind getKind() + { + return LayoutResourceKind::SpecializationConstant; + } + + SimpleLayoutInfo GetScalarLayout(BaseType baseType) override + { + // Assume that all scalars take up one "slot" + return SimpleLayoutInfo( + getKind(), + 1); + } + + virtual SimpleLayoutInfo GetScalarLayout(slang::TypeReflection::ScalarType scalarType) + { + // Assume that all scalars take up one "slot" + return SimpleLayoutInfo( + getKind(), + 1); + } + + SimpleLayoutInfo GetVectorLayout(SimpleLayoutInfo elementInfo, size_t elementCount) override + { + // GLSL doesn't support vectors of specialization constants, + // but we will assume that, if supported, they would use one slot per element. + return SimpleLayoutInfo( + getKind(), + elementCount); + } +}; + +GLSLSpecializationConstantLayoutRulesImpl kGLSLSpecializationConstantLayoutRulesImpl; + +// + +struct GLSLObjectLayoutRulesImpl : ObjectLayoutRulesImpl +{ + virtual SimpleLayoutInfo GetObjectLayout(ShaderParameterKind kind) override + { + // In Vulkan GLSL, pretty much every object is just a descriptor-table slot. + // We can refine this method once we support a case where this isn't true. + return SimpleLayoutInfo(LayoutResourceKind::DescriptorTableSlot, 1); + } +}; +GLSLObjectLayoutRulesImpl kGLSLObjectLayoutRulesImpl; + +struct HLSLObjectLayoutRulesImpl : ObjectLayoutRulesImpl +{ + virtual SimpleLayoutInfo GetObjectLayout(ShaderParameterKind kind) override + { + switch( kind ) + { + case ShaderParameterKind::ConstantBuffer: + return SimpleLayoutInfo(LayoutResourceKind::ConstantBuffer, 1); + + case ShaderParameterKind::TextureUniformBuffer: + case ShaderParameterKind::StructuredBuffer: + case ShaderParameterKind::SampledBuffer: + case ShaderParameterKind::RawBuffer: + case ShaderParameterKind::Buffer: + case ShaderParameterKind::Texture: + return SimpleLayoutInfo(LayoutResourceKind::ShaderResource, 1); + + case ShaderParameterKind::MutableStructuredBuffer: + case ShaderParameterKind::MutableSampledBuffer: + case ShaderParameterKind::MutableRawBuffer: + case ShaderParameterKind::MutableBuffer: + case ShaderParameterKind::MutableTexture: + return SimpleLayoutInfo(LayoutResourceKind::UnorderedAccess, 1); + + case ShaderParameterKind::SamplerState: + return SimpleLayoutInfo(LayoutResourceKind::SamplerState, 1); + + case ShaderParameterKind::TextureSampler: + case ShaderParameterKind::MutableTextureSampler: + case ShaderParameterKind::InputRenderTarget: + // TODO: how to handle these? + default: + assert(!"unimplemented"); + return SimpleLayoutInfo(); + } + } +}; +HLSLObjectLayoutRulesImpl kHLSLObjectLayoutRulesImpl; + +Std140LayoutRulesImpl kStd140LayoutRulesImpl; +Std430LayoutRulesImpl kStd430LayoutRulesImpl; +HLSLConstantBufferLayoutRulesImpl kHLSLConstantBufferLayoutRulesImpl; +HLSLStructuredBufferLayoutRulesImpl kHLSLStructuredBufferLayoutRulesImpl; + +GLSLVaryingLayoutRulesImpl kGLSLVaryingInputLayoutRulesImpl(LayoutResourceKind::VertexInput); +GLSLVaryingLayoutRulesImpl kGLSLVaryingOutputLayoutRulesImpl(LayoutResourceKind::FragmentOutput); + +HLSLVaryingLayoutRulesImpl kHLSLVaryingInputLayoutRulesImpl(LayoutResourceKind::VertexInput); +HLSLVaryingLayoutRulesImpl kHLSLVaryingOutputLayoutRulesImpl(LayoutResourceKind::FragmentOutput); + +// + +struct GLSLLayoutRulesFamilyImpl : LayoutRulesFamilyImpl +{ + virtual LayoutRulesImpl* getConstantBufferRules() override; + virtual LayoutRulesImpl* getTextureBufferRules() override; + virtual LayoutRulesImpl* getVaryingInputRules() override; + virtual LayoutRulesImpl* getVaryingOutputRules() override; + virtual LayoutRulesImpl* getSpecializationConstantRules() override; + virtual LayoutRulesImpl* getShaderStorageBufferRules() override; +}; + +struct HLSLLayoutRulesFamilyImpl : LayoutRulesFamilyImpl +{ + virtual LayoutRulesImpl* getConstantBufferRules() override; + virtual LayoutRulesImpl* getTextureBufferRules() override; + virtual LayoutRulesImpl* getVaryingInputRules() override; + virtual LayoutRulesImpl* getVaryingOutputRules() override; + virtual LayoutRulesImpl* getSpecializationConstantRules() override; + virtual LayoutRulesImpl* getShaderStorageBufferRules() override; +}; + +GLSLLayoutRulesFamilyImpl kGLSLLayoutRulesFamilyImpl; +HLSLLayoutRulesFamilyImpl kHLSLLayoutRulesFamilyImpl; + + +// GLSL cases + +LayoutRulesImpl kStd140LayoutRulesImpl_ = { + &kGLSLLayoutRulesFamilyImpl, &kStd140LayoutRulesImpl, &kGLSLObjectLayoutRulesImpl, +}; + +LayoutRulesImpl kStd430LayoutRulesImpl_ = { + &kGLSLLayoutRulesFamilyImpl, &kStd430LayoutRulesImpl, &kGLSLObjectLayoutRulesImpl, +}; + +LayoutRulesImpl kGLSLVaryingInputLayoutRulesImpl_ = { + &kGLSLLayoutRulesFamilyImpl, &kGLSLVaryingInputLayoutRulesImpl, &kGLSLObjectLayoutRulesImpl, +}; + +LayoutRulesImpl kGLSLVaryingOutputLayoutRulesImpl_ = { + &kGLSLLayoutRulesFamilyImpl, &kGLSLVaryingOutputLayoutRulesImpl, &kGLSLObjectLayoutRulesImpl, +}; + +LayoutRulesImpl kGLSLSpecializationConstantLayoutRulesImpl_ = { + &kGLSLLayoutRulesFamilyImpl, &kGLSLSpecializationConstantLayoutRulesImpl, &kGLSLObjectLayoutRulesImpl, +}; + +// HLSL cases + +LayoutRulesImpl kHLSLConstantBufferLayoutRulesImpl_ = { + &kHLSLLayoutRulesFamilyImpl, &kHLSLConstantBufferLayoutRulesImpl, &kHLSLObjectLayoutRulesImpl, +}; + +LayoutRulesImpl kHLSLStructuredBufferLayoutRulesImpl_ = { + &kHLSLLayoutRulesFamilyImpl, &kHLSLStructuredBufferLayoutRulesImpl, &kHLSLObjectLayoutRulesImpl, +}; + +LayoutRulesImpl kHLSLVaryingInputLayoutRulesImpl_ = { + &kHLSLLayoutRulesFamilyImpl, &kHLSLVaryingInputLayoutRulesImpl, &kHLSLObjectLayoutRulesImpl, +}; + +LayoutRulesImpl kHLSLVaryingOutputLayoutRulesImpl_ = { + &kHLSLLayoutRulesFamilyImpl, &kHLSLVaryingOutputLayoutRulesImpl, &kHLSLObjectLayoutRulesImpl, +}; + +// + +LayoutRulesImpl* GLSLLayoutRulesFamilyImpl::getConstantBufferRules() +{ + return &kStd140LayoutRulesImpl_; +} + +LayoutRulesImpl* GLSLLayoutRulesFamilyImpl::getTextureBufferRules() +{ + return nullptr; +} + +LayoutRulesImpl* GLSLLayoutRulesFamilyImpl::getVaryingInputRules() +{ + return &kGLSLVaryingInputLayoutRulesImpl_; +} + +LayoutRulesImpl* GLSLLayoutRulesFamilyImpl::getVaryingOutputRules() +{ + return &kGLSLVaryingOutputLayoutRulesImpl_; +} + +LayoutRulesImpl* GLSLLayoutRulesFamilyImpl::getSpecializationConstantRules() +{ + return &kGLSLSpecializationConstantLayoutRulesImpl_; +} + +LayoutRulesImpl* GLSLLayoutRulesFamilyImpl::getShaderStorageBufferRules() +{ + return &kStd430LayoutRulesImpl_; +} + +// + +LayoutRulesImpl* HLSLLayoutRulesFamilyImpl::getConstantBufferRules() +{ + return &kHLSLConstantBufferLayoutRulesImpl_; +} + +LayoutRulesImpl* HLSLLayoutRulesFamilyImpl::getTextureBufferRules() +{ + return nullptr; +} + +LayoutRulesImpl* HLSLLayoutRulesFamilyImpl::getVaryingInputRules() +{ + return &kHLSLVaryingInputLayoutRulesImpl_; +} + +LayoutRulesImpl* HLSLLayoutRulesFamilyImpl::getVaryingOutputRules() +{ + return &kHLSLVaryingOutputLayoutRulesImpl_; +} + +LayoutRulesImpl* HLSLLayoutRulesFamilyImpl::getSpecializationConstantRules() +{ + return nullptr; +} + +LayoutRulesImpl* HLSLLayoutRulesFamilyImpl::getShaderStorageBufferRules() +{ + return nullptr; +} + +// + +LayoutRulesImpl* GetLayoutRulesImpl(LayoutRule rule) +{ + switch (rule) + { + case LayoutRule::Std140: return &kStd140LayoutRulesImpl_; + case LayoutRule::Std430: return &kStd430LayoutRulesImpl_; + case LayoutRule::HLSLConstantBuffer: return &kHLSLConstantBufferLayoutRulesImpl_; + case LayoutRule::HLSLStructuredBuffer: return &kHLSLStructuredBufferLayoutRulesImpl_; + default: + return nullptr; + } +} + +LayoutRulesFamilyImpl* GetLayoutRulesFamilyImpl(LayoutRulesFamily rule) +{ + switch (rule) + { + case LayoutRulesFamily::HLSL: return &kHLSLLayoutRulesFamilyImpl; + case LayoutRulesFamily::GLSL: return &kGLSLLayoutRulesFamilyImpl; + default: + return nullptr; + } +} + +LayoutRulesFamilyImpl* GetLayoutRulesFamilyImpl(SourceLanguage language) +{ + switch (language) + { + case SourceLanguage::Slang: + case SourceLanguage::HLSL: + return &kHLSLLayoutRulesFamilyImpl; + + case SourceLanguage::GLSL: + return &kGLSLLayoutRulesFamilyImpl; + + default: + return nullptr; + } +} + + +static int GetElementCount(RefPtr val) +{ + if (auto constantVal = val.As()) + { + return constantVal->value; + } + else if( auto varRefVal = val.As() ) + { + // TODO(tfoley): do something sensible in this case + return 0; + } + assert(!"unexpected"); + return 0; +} + +bool IsResourceKind(LayoutResourceKind kind) +{ + switch (kind) + { + case LayoutResourceKind::None: + case LayoutResourceKind::Uniform: + return false; + + default: + return true; + } + +} + +SimpleLayoutInfo GetSimpleLayoutImpl( + SimpleLayoutInfo info, + RefPtr type, + LayoutRulesImpl* rules, + RefPtr* outTypeLayout) +{ + if (outTypeLayout) + { + RefPtr typeLayout = new TypeLayout(); + *outTypeLayout = typeLayout; + + typeLayout->type = type; + typeLayout->rules = rules; + + typeLayout->uniformAlignment = info.alignment; + + typeLayout->addResourceUsage(info.kind, info.size); + } + + return info; +} + +static SimpleLayoutInfo getParameterBlockLayoutInfo( + RefPtr type, + LayoutRulesImpl* rules) +{ + if( type->As() ) + { + return rules->GetObjectLayout(ShaderParameterKind::ConstantBuffer); + } + else if( type->As() ) + { + return rules->GetObjectLayout(ShaderParameterKind::TextureUniformBuffer); + } + else if( type->As() ) + { + return rules->GetObjectLayout(ShaderParameterKind::ShaderStorageBuffer); + } + // TODO: the vertex-input and fragment-output cases should + // only actually apply when we are at the appropriate stage in + // the pipeline... + else if( type->As() ) + { + return SimpleLayoutInfo(LayoutResourceKind::VertexInput, 0); + } + else if( type->As() ) + { + return SimpleLayoutInfo(LayoutResourceKind::FragmentOutput, 0); + } + else + { + assert(!"unexpected"); + return SimpleLayoutInfo(); + } +} + + +RefPtr +createParameterBlockTypeLayout( + RefPtr parameterBlockType, + RefPtr elementTypeLayout, + LayoutRulesImpl* rules) +{ + auto info = getParameterBlockLayoutInfo( + parameterBlockType, + rules); + + auto typeLayout = new ParameterBlockTypeLayout(); + + typeLayout->type = parameterBlockType; + typeLayout->rules = rules; + + typeLayout->elementTypeLayout = elementTypeLayout; + + // The layout of the constant buffer if it gets stored + // in another constant buffer is just what we computed + // originally (which should be a single binding "slot" + // and hence no uniform data). + // + typeLayout->uniformAlignment = info.alignment; + assert(!typeLayout->FindResourceInfo(LayoutResourceKind::Uniform)); + assert(typeLayout->uniformAlignment == 1); + + // TODO(tfoley): There is a subtle question here of whether + // a constant buffer declaration that then contains zero + // bytes of uniform data should actually allocate a CB + // binding slot. For now I'm going to try to ignore it, + // but handling this robustly could let other code + // simply handle the "global scope" as a giant outer + // CB declaration... + + // Make sure that we allocate resource usage for the + // parameter block itself. + if( info.size ) + { + typeLayout->addResourceUsage( + info.kind, + info.size); + } + + // Now, if the element type itself had any resources, then + // we need to make these part of the layout for our block + // + // TODO: re-consider this decision, since it creates + // complications... + for( auto elementResourceInfo : elementTypeLayout->resourceInfos ) + { + // Skip uniform data, since that is encapsualted behind the constant buffer + if(elementResourceInfo.kind == LayoutResourceKind::Uniform) + break; + + typeLayout->addResourceUsage(elementResourceInfo); + } + + return typeLayout; +} + +LayoutRulesImpl* getParameterBufferElementTypeLayoutRules( + RefPtr parameterBlockType, + LayoutRulesImpl* rules) +{ + if( parameterBlockType->As() ) + { + return rules->getLayoutRulesFamily()->getConstantBufferRules(); + } + else if( parameterBlockType->As() ) + { + return rules->getLayoutRulesFamily()->getTextureBufferRules(); + } + else if( parameterBlockType->As() ) + { + return rules->getLayoutRulesFamily()->getVaryingInputRules(); + } + else if( parameterBlockType->As() ) + { + return rules->getLayoutRulesFamily()->getVaryingOutputRules(); + } + else if( parameterBlockType->As() ) + { + return rules->getLayoutRulesFamily()->getShaderStorageBufferRules(); + } + else + { + assert(!"unexpected"); + return nullptr; + } +} + +RefPtr +createParameterBlockTypeLayout( + RefPtr parameterBlockType, + LayoutRulesImpl* rules) +{ + // Determine the layout rules to use for the contents of the block + auto parameterBlockLayoutRules = getParameterBufferElementTypeLayoutRules( + parameterBlockType, + rules); + + // Create and save type layout for the buffer contents. + auto elementTypeLayout = CreateTypeLayout( + parameterBlockType->elementType.Ptr(), + parameterBlockLayoutRules); + + return createParameterBlockTypeLayout( + parameterBlockType, + elementTypeLayout, + rules); +} + +// Create a type layout for a structured buffer type. +RefPtr +createStructuredBufferTypeLayout( + ShaderParameterKind kind, + RefPtr structuredBufferType, + RefPtr elementTypeLayout, + LayoutRulesImpl* rules) +{ + auto info = rules->GetObjectLayout(kind); + + auto typeLayout = new StructuredBufferTypeLayout(); + + typeLayout->type = structuredBufferType; + typeLayout->rules = rules; + + typeLayout->elementTypeLayout = elementTypeLayout; + + typeLayout->uniformAlignment = info.alignment; + assert(!typeLayout->FindResourceInfo(LayoutResourceKind::Uniform)); + assert(typeLayout->uniformAlignment == 1); + + if( info.size != 0 ) + { + typeLayout->addResourceUsage(info.kind, info.size); + } + + // Note: for now we don't deal with the case of a structured + // buffer that might contain anything other than "uniform" data, + // because there really isn't a way to implement that. + + return typeLayout; +} + +// Create a type layout for a structured buffer type. +RefPtr +createStructuredBufferTypeLayout( + ShaderParameterKind kind, + RefPtr structuredBufferType, + RefPtr elementType, + LayoutRulesImpl* rules) +{ + // TODO(tfoley): need to compute the layout for the constant + // buffer's contents... + auto structuredBufferLayoutRules = GetLayoutRulesImpl( + LayoutRule::HLSLStructuredBuffer); + + // Create and save type layout for the buffer contents. + auto elementTypeLayout = CreateTypeLayout( + elementType.Ptr(), + structuredBufferLayoutRules); + + return createStructuredBufferTypeLayout( + kind, + structuredBufferType, + elementTypeLayout, + rules); + +} + +SimpleLayoutInfo GetLayoutImpl( + ExpressionType* type, + LayoutRulesImpl* rules, + RefPtr* outTypeLayout) +{ + if (auto parameterBlockType = type->As()) + { + // If the user is just interested in uniform layout info, + // then this is easy: a `ConstantBuffer` is really no + // different from a `Texture2D` in terms of how it + // should be handled as a member of a container. + // + auto info = getParameterBlockLayoutInfo(parameterBlockType, rules); + + // The more interesting case, though, is when the user + // is requesting us to actually create a `TypeLayout`, + // since in that case we need to: + // + // 1. Compute a layout for the data inside the constant + // buffer, including offsets, etc. + // + // 2. Compute information about any object types inside + // the constant buffer, which need to be surfaces out + // to the top level. + // + if (outTypeLayout) + { + *outTypeLayout = createParameterBlockTypeLayout( + parameterBlockType, + rules); + } + + return info; + } + else if (auto samplerStateType = type->As()) + { + return GetSimpleLayoutImpl( + rules->GetObjectLayout(ShaderParameterKind::SamplerState), + type, + rules, + outTypeLayout); + } + else if (auto textureType = type->As()) + { + // TODO: the logic here should really be defined by the rules, + // and not at this top level... + ShaderParameterKind kind; + switch( textureType->getAccess() ) + { + default: + kind = ShaderParameterKind::MutableTexture; + break; + + case SLANG_RESOURCE_ACCESS_READ: + kind = ShaderParameterKind::Texture; + break; + } + + return GetSimpleLayoutImpl( + rules->GetObjectLayout(kind), + type, + rules, + outTypeLayout); + } + else if (auto textureSamplerType = type->As()) + { + // TODO: the logic here should really be defined by the rules, + // and not at this top level... + ShaderParameterKind kind; + switch( textureSamplerType->getAccess() ) + { + default: + kind = ShaderParameterKind::MutableTextureSampler; + break; + + case SLANG_RESOURCE_ACCESS_READ: + kind = ShaderParameterKind::TextureSampler; + break; + } + + return GetSimpleLayoutImpl( + rules->GetObjectLayout(kind), + type, + rules, + outTypeLayout); + } + + // TODO: need a better way to handle this stuff... +#define CASE(TYPE, KIND) \ + else if(auto type_##TYPE = type->As()) do { \ + auto info = rules->GetObjectLayout(ShaderParameterKind::KIND); \ + if (outTypeLayout) \ + { \ + *outTypeLayout = createStructuredBufferTypeLayout( \ + ShaderParameterKind::KIND, \ + type_##TYPE, \ + type_##TYPE->elementType.Ptr(), \ + rules); \ + } \ + return info; \ + } while(0) + + CASE(HLSLStructuredBufferType, StructuredBuffer); + CASE(HLSLRWStructuredBufferType, MutableStructuredBuffer); + CASE(HLSLAppendStructuredBufferType, MutableStructuredBuffer); + CASE(HLSLConsumeStructuredBufferType, MutableStructuredBuffer); + +#undef CASE + + + // TODO: need a better way to handle this stuff... +#define CASE(TYPE, KIND) \ + else if(type->As()) do { \ + return GetSimpleLayoutImpl( \ + rules->GetObjectLayout(ShaderParameterKind::KIND), \ + type, rules, outTypeLayout); \ + } while(0) + + CASE(HLSLBufferType, SampledBuffer); + CASE(HLSLRWBufferType, MutableSampledBuffer); + CASE(HLSLByteAddressBufferType, RawBuffer); + CASE(HLSLRWByteAddressBufferType, MutableRawBuffer); + + CASE(GLSLInputAttachmentType, InputRenderTarget); + + // This case is mostly to allow users to add new resource types... + CASE(UntypedBufferResourceType, RawBuffer); + +#undef CASE + + // + // TODO(tfoley): Need to recognize any UAV types here + // + else if(auto basicType = type->As()) + { + return GetSimpleLayoutImpl( + rules->GetScalarLayout(basicType->BaseType), + type, + rules, + outTypeLayout); + } + else if(auto vecType = type->As()) + { + return GetSimpleLayoutImpl( + rules->GetVectorLayout( + GetLayout(vecType->elementType.Ptr(), rules), + GetIntVal(vecType->elementCount)), + type, + rules, + outTypeLayout); + } + else if(auto matType = type->As()) + { + return GetSimpleLayoutImpl( + rules->GetMatrixLayout( + GetLayout(matType->getElementType(), rules), + GetIntVal(matType->getRowCount()), + GetIntVal(matType->getColumnCount())), + type, + rules, + outTypeLayout); + } + else if (auto arrayType = type->As()) + { + RefPtr elementTypeLayout; + auto elementInfo = GetLayoutImpl( + arrayType->BaseType.Ptr(), + rules, + outTypeLayout ? &elementTypeLayout : nullptr); + + // For layout purposes, we treat an unsized array as an array of zero elements. + // + // TODO: Longer term we are going to need to be careful to include some indication + // that a type has logically "infinite" size in some resource kind. In particular + // this affects how we would allocate space for parameter binding purposes. + auto elementCount = arrayType->ArrayLength ? GetElementCount(arrayType->ArrayLength) : 0; + auto arrayUniformInfo = rules->GetArrayLayout( + elementInfo, + elementCount).getUniformLayout(); + + if (outTypeLayout) + { + RefPtr typeLayout = new ArrayTypeLayout(); + *outTypeLayout = typeLayout; + + typeLayout->type = type; + typeLayout->elementTypeLayout = elementTypeLayout; + typeLayout->rules = rules; + + typeLayout->uniformAlignment = arrayUniformInfo.alignment; + typeLayout->uniformStride = arrayUniformInfo.elementStride; + + typeLayout->addResourceUsage(LayoutResourceKind::Uniform, arrayUniformInfo.size); + + // translate element-type resources into array-type resources + for( auto elementResourceInfo : elementTypeLayout->resourceInfos ) + { + // The uniform case was already handled above + if( elementResourceInfo.kind == LayoutResourceKind::Uniform ) + continue; + + typeLayout->addResourceUsage( + elementResourceInfo.kind, + elementResourceInfo.count * elementCount); + } + } + return arrayUniformInfo; + } + else if (auto declRefType = type->As()) + { + auto declRef = declRefType->declRef; + + if (auto structDeclRef = declRef.As()) + { + RefPtr typeLayout; + if (outTypeLayout) + { + typeLayout = new StructTypeLayout(); + typeLayout->type = type; + typeLayout->rules = rules; + *outTypeLayout = typeLayout; + } + + UniformLayoutInfo info = rules->BeginStructLayout(); + + for (auto field : structDeclRef.GetFields()) + { + RefPtr fieldTypeLayout; + UniformLayoutInfo fieldInfo = GetLayoutImpl( + field.GetType().Ptr(), + rules, + outTypeLayout ? &fieldTypeLayout : nullptr).getUniformLayout(); + + // Note: we don't add any zero-size fields + // when computing structure layout, just + // to avoid having a resource type impact + // the final layout. + // + // This means that the code to generate final + // declarations needs to *also* eliminate zero-size + // fields to be safe... + size_t uniformOffset = info.size; + if(fieldInfo.size != 0) + { + uniformOffset = rules->AddStructField(&info, fieldInfo); + } + + if (outTypeLayout) + { + // If we are computing a complete layout, + // then we need to create variable layouts + // for each field of the structure. + RefPtr fieldLayout = new VarLayout(); + fieldLayout->varDecl = field; + fieldLayout->typeLayout = fieldTypeLayout; + typeLayout->fields.Add(fieldLayout); + typeLayout->mapVarToLayout.Add(field.GetDecl(), fieldLayout); + + // Set up uniform offset information, if there is any uniform data in the field + if( fieldTypeLayout->FindResourceInfo(LayoutResourceKind::Uniform) ) + { + fieldLayout->AddResourceInfo(LayoutResourceKind::Uniform)->index = uniformOffset; + } + + // Add offset information for any other resource kinds + for( auto fieldTypeResourceInfo : fieldTypeLayout->resourceInfos ) + { + // Uniforms were dealt with above + if(fieldTypeResourceInfo.kind == LayoutResourceKind::Uniform) + continue; + + // We should not have already processed this resource type + assert(!fieldLayout->FindResourceInfo(fieldTypeResourceInfo.kind)); + + // The field will need offset information for this kind + auto fieldResourceInfo = fieldLayout->AddResourceInfo(fieldTypeResourceInfo.kind); + + // Check how many slots of the given kind have already been added to the type + auto structTypeResourceInfo = typeLayout->findOrAddResourceInfo(fieldTypeResourceInfo.kind); + fieldResourceInfo->index = structTypeResourceInfo->count; + structTypeResourceInfo->count += fieldTypeResourceInfo.count; + } + } + } + + rules->EndStructLayout(&info); + if (outTypeLayout) + { + typeLayout->uniformAlignment = info.alignment; + typeLayout->addResourceUsage(LayoutResourceKind::Uniform, info.size); + } + + return info; + } + } + + // catch-all case in case nothing matched + assert(!"unimplemented"); + SimpleLayoutInfo info; + return GetSimpleLayoutImpl( + info, + type, + rules, + outTypeLayout); +} + +SimpleLayoutInfo GetLayout(ExpressionType* inType, LayoutRulesImpl* rules) +{ + return GetLayoutImpl(inType, rules, nullptr); +} + +RefPtr CreateTypeLayout(ExpressionType* type, LayoutRulesImpl* rules) +{ + RefPtr typeLayout; + GetLayoutImpl(type, rules, &typeLayout); + return typeLayout; +} + +SimpleLayoutInfo GetLayout(ExpressionType* type, LayoutRule rule) +{ + LayoutRulesImpl* rulesImpl = GetLayoutRulesImpl(rule); + return GetLayout(type, rulesImpl); +} + +}} diff --git a/source/slang/type-layout.h b/source/slang/type-layout.h new file mode 100644 index 000000000..be54bbf53 --- /dev/null +++ b/source/slang/type-layout.h @@ -0,0 +1,550 @@ +#ifndef SLANG_TYPE_LAYOUT_H +#define SLANG_TYPE_LAYOUT_H + +#include "../core/basic.h" +#include "profile.h" +#include "syntax.h" + +#include "../../slang.h" + +namespace Slang { + +typedef intptr_t Int; +typedef uintptr_t UInt; + +namespace Compiler { + +// Forward declarations + +enum class BaseType; +class ExpressionType; + +// + +enum class LayoutRule +{ + Std140, + Std430, + HLSLConstantBuffer, + HLSLStructuredBuffer, +}; + +enum class LayoutRulesFamily +{ + HLSL, + GLSL, +}; + +// Layout appropriate to "just memory" scenarios, +// such as laying out the members of a constant buffer. +struct UniformLayoutInfo +{ + size_t size; + size_t alignment; + + UniformLayoutInfo() + : size(0) + , alignment(1) + {} + + UniformLayoutInfo( + size_t size, + size_t alignment) + : size(size) + , alignment(alignment) + {} +}; + +// Extended information required for an array of uniform data, +// including the "stride" of the array (the space between +// consecutive elements). +struct UniformArrayLayoutInfo : UniformLayoutInfo +{ + size_t elementStride; + + UniformArrayLayoutInfo() + : elementStride(0) + {} + + UniformArrayLayoutInfo( + size_t size, + size_t alignment, + size_t elementStride) + : UniformLayoutInfo(size, alignment) + , elementStride(elementStride) + {} +}; + +typedef slang::ParameterCategory LayoutResourceKind; + +// Layout information for a value that only consumes +// a single reosurce kind. +struct SimpleLayoutInfo +{ + // What kind of resource should we consume? + LayoutResourceKind kind; + + // How many resources of that kind? + size_t size; + + // only useful in the uniform case + size_t alignment; + + SimpleLayoutInfo() + : kind(LayoutResourceKind::None) + , size(0) + , alignment(1) + {} + + SimpleLayoutInfo( + UniformLayoutInfo uniformInfo) + : kind(LayoutResourceKind::Uniform) + , size(uniformInfo.size) + , alignment(uniformInfo.alignment) + {} + + SimpleLayoutInfo(LayoutResourceKind kind, size_t size, size_t alignment=1) + : kind(kind) + , size(size) + , alignment(alignment) + {} + + // Convert to layout for uniform data + UniformLayoutInfo getUniformLayout() + { + if(kind == LayoutResourceKind::Uniform) + { + return UniformLayoutInfo(size, alignment); + } + else + { + return UniformLayoutInfo(0, 1); + } + } +}; + +// Only useful in the case of a homogeneous array +struct SimpleArrayLayoutInfo : SimpleLayoutInfo +{ + // This field is only useful in the uniform case + size_t elementStride; + + // Convert to layout for uniform data + UniformArrayLayoutInfo getUniformLayout() + { + if(kind == LayoutResourceKind::Uniform) + { + return UniformArrayLayoutInfo(size, alignment, elementStride); + } + else + { + return UniformArrayLayoutInfo(0, 1, 0); + } + } +}; + +struct LayoutRulesImpl; + +// A reified reprsentation of a particular laid-out type +class TypeLayout : public RefObject +{ +public: + // The type that was laid out + RefPtr type; + ExpressionType* getType() { return type.Ptr(); } + + // The layout rules that were used to produce this type + LayoutRulesImpl* rules; + + struct ResourceInfo + { + // What kind of register was it? + LayoutResourceKind kind = LayoutResourceKind::None; + + // How many registers of the above kind did we use? + UInt count; + }; + + List resourceInfos; + + // For uniform data, alignment matters, but not for + // any other resource category, so we don't waste + // the space storing it in the above array + UInt uniformAlignment = 1; + + ResourceInfo* FindResourceInfo(LayoutResourceKind kind) + { + for(auto& rr : resourceInfos) + { + if(rr.kind == kind) + return &rr; + } + return nullptr; + } + + ResourceInfo* findOrAddResourceInfo(LayoutResourceKind kind) + { + auto existing = FindResourceInfo(kind); + if(existing) return existing; + + ResourceInfo info; + info.kind = kind; + info.count = 0; + resourceInfos.Add(info); + return &resourceInfos.Last(); + } + + void addResourceUsage(ResourceInfo info) + { + if(info.count == 0) return; + + findOrAddResourceInfo(info.kind)->count += info.count; + } + + void addResourceUsage(LayoutResourceKind kind, UInt count) + { + ResourceInfo info; + info.kind = kind; + info.count = count; + addResourceUsage(info); + } +}; + +typedef unsigned int VarLayoutFlags; +enum VarLayoutFlag : VarLayoutFlags +{ + IsRedeclaration = 1 << 0, ///< This is a redeclaration of some shader parameter +}; + +// A reified layout for a particular variable, field, etc. +class VarLayout : public RefObject +{ +public: + // The variable we are laying out + VarDeclBaseRef varDecl; + VarDeclBase* getVariable() { return varDecl.GetDecl(); } + + String const& getName() { return getVariable()->getName(); } + + // The result of laying out the variable's type + RefPtr typeLayout; + TypeLayout* getTypeLayout() { return typeLayout.Ptr(); } + + // Additional flags + VarLayoutFlags flags = 0; + + // The start register(s) for any resources + struct ResourceInfo + { + // What kind of register was it? + LayoutResourceKind kind = LayoutResourceKind::None; + + // What binding space (HLSL) or set (Vulkan) are we placed in? + UInt space; + + // What is our starting register in that space? + // + // (In the case of uniform data, this is a byte offset) + UInt index; + }; + List resourceInfos; + + ResourceInfo* FindResourceInfo(LayoutResourceKind kind) + { + for(auto& rr : resourceInfos) + { + if(rr.kind == kind) + return &rr; + } + return nullptr; + } + + ResourceInfo* AddResourceInfo(LayoutResourceKind kind) + { + ResourceInfo info; + info.kind = kind; + info.space = 0; + info.index = 0; + + resourceInfos.Add(info); + return &resourceInfos.Last(); + } + + ResourceInfo* findOrAddResourceInfo(LayoutResourceKind kind) + { + auto existing = FindResourceInfo(kind); + if(existing) return existing; + + return AddResourceInfo(kind); + } +}; + +// Type layout for a variable that has a constant-buffer type +class ParameterBlockTypeLayout : public TypeLayout +{ +public: + RefPtr elementTypeLayout; +}; + +// Type layout for a variable that has a constant-buffer type +class StructuredBufferTypeLayout : public TypeLayout +{ +public: + RefPtr elementTypeLayout; +}; + +// Specific case of type layout for an array +class ArrayTypeLayout : public TypeLayout +{ +public: + // The layout used for the element type + RefPtr elementTypeLayout; + + // the stride between elements when used in + // a uniform buffer + size_t uniformStride; +}; + +// Specific case of type layout for a struct +class StructTypeLayout : public TypeLayout +{ +public: + // An ordered list of layouts for the known fields + List> fields; + + // Map a variable to its layout directly. + // + // Note that in the general case, there may be entries + // in the `fields` array that came from multiple + // translation units, and in cases where there are + // multiple declarations of the same parameter, only + // one will appear in `fields`, while all of + // them will be reflected in `mapVarToLayout`. + // + Dictionary> mapVarToLayout; +}; + +// Layout information for a single shader entry point +// within a program +class EntryPointLayout : public RefObject +{ +public: + // The corresponding function declaration + RefPtr entryPoint; + + // The shader profile that was used to compile the entry point + Profile profile; +}; + +// Layout information for the global scope of a program +class ProgramLayout : public RefObject +{ +public: + // We store a layout for the declarations at the global + // scope. Note that this will *either* be a single + // `StructTypeLayout` with the fields stored directly, + // or it will be a single `ParameterBlockTypeLayout`, + // where the global-scope fields are the members of + // that constant buffer. + // + // The `struct` case will be used if there are no + // "naked" global-scope uniform variables, and the + // constant-buffer case will be used if there are + // (since a constant buffer will have to be allocated + // to store them). + // + RefPtr globalScopeLayout; + + // We catalog the requested entry points here, + // and any entry-point-specific parameter data + // will (eventually) belong there... + List> entryPoints; +}; + +// A modifier to be attached to syntax after we've computed layout +class ComputedLayoutModifier : public Modifier +{ +public: + RefPtr typeLayout; +}; + + +struct LayoutRulesFamilyImpl; + +// A delineation of shader parameter types into fine-grained +// categories that can then be mapped down to actual resources +// by a given set of rules. +// +// TODO(tfoley): `SlangParameterCategory` and `slang::ParameterCategory` +// are badly named, and need to be revised so they can't be confused +// with this concept. +enum class ShaderParameterKind +{ + ConstantBuffer, + TextureUniformBuffer, + ShaderStorageBuffer, + + StructuredBuffer, + MutableStructuredBuffer, + + SampledBuffer, + MutableSampledBuffer, + + RawBuffer, + MutableRawBuffer, + + Buffer, + MutableBuffer, + + Texture, + MutableTexture, + + TextureSampler, + MutableTextureSampler, + + InputRenderTarget, + + SamplerState, +}; + +struct SimpleLayoutRulesImpl +{ + // Get size and alignment for a single value of base type. + virtual SimpleLayoutInfo GetScalarLayout(BaseType baseType) = 0; + virtual SimpleLayoutInfo GetScalarLayout(slang::TypeReflection::ScalarType scalarType) = 0; + + // Get size and alignment for an array of elements + virtual SimpleArrayLayoutInfo GetArrayLayout(SimpleLayoutInfo elementInfo, size_t elementCount) = 0; + + // Get layout for a vector or matrix type + virtual SimpleLayoutInfo GetVectorLayout(SimpleLayoutInfo elementInfo, size_t elementCount) = 0; + virtual SimpleLayoutInfo GetMatrixLayout(SimpleLayoutInfo elementInfo, size_t rowCount, size_t columnCount) = 0; + + // Begin doing layout on a `struct` type + virtual UniformLayoutInfo BeginStructLayout() = 0; + + // Add a field to a `struct` type, and return the offset for the field + virtual size_t AddStructField(UniformLayoutInfo* ioStructInfo, UniformLayoutInfo fieldInfo) = 0; + + // End layout for a struct, and finalize its size/alignment. + virtual void EndStructLayout(UniformLayoutInfo* ioStructInfo) = 0; +}; + +struct ObjectLayoutRulesImpl +{ + // Compute layout info for an object type + virtual SimpleLayoutInfo GetObjectLayout(ShaderParameterKind kind) = 0; +}; + +struct LayoutRulesImpl +{ + LayoutRulesFamilyImpl* family; + SimpleLayoutRulesImpl* simpleRules; + ObjectLayoutRulesImpl* objectRules; + + // Forward `SimpleLayoutRulesImpl` interface + + SimpleLayoutInfo GetScalarLayout(BaseType baseType) + { + return simpleRules->GetScalarLayout(baseType); + } + + SimpleLayoutInfo GetScalarLayout(slang::TypeReflection::ScalarType scalarType) + { + return simpleRules->GetScalarLayout(scalarType); + } + + SimpleArrayLayoutInfo GetArrayLayout(SimpleLayoutInfo elementInfo, size_t elementCount) + { + return simpleRules->GetArrayLayout(elementInfo, elementCount); + } + + SimpleLayoutInfo GetVectorLayout(SimpleLayoutInfo elementInfo, size_t elementCount) + { + return simpleRules->GetVectorLayout(elementInfo, elementCount); + } + + SimpleLayoutInfo GetMatrixLayout(SimpleLayoutInfo elementInfo, size_t rowCount, size_t columnCount) + { + return simpleRules->GetMatrixLayout(elementInfo, rowCount, columnCount); + } + + UniformLayoutInfo BeginStructLayout() + { + return simpleRules->BeginStructLayout(); + } + + size_t AddStructField(UniformLayoutInfo* ioStructInfo, UniformLayoutInfo fieldInfo) + { + return simpleRules->AddStructField(ioStructInfo, fieldInfo); + } + + void EndStructLayout(UniformLayoutInfo* ioStructInfo) + { + return simpleRules->EndStructLayout(ioStructInfo); + } + + // Forward `ObjectLayoutRulesImpl` interface + + SimpleLayoutInfo GetObjectLayout(ShaderParameterKind kind) + { + return objectRules->GetObjectLayout(kind); + } + + // + + LayoutRulesFamilyImpl* getLayoutRulesFamily() { return family; } +}; + +struct LayoutRulesFamilyImpl +{ + virtual LayoutRulesImpl* getConstantBufferRules() = 0; + virtual LayoutRulesImpl* getTextureBufferRules() = 0; + virtual LayoutRulesImpl* getVaryingInputRules() = 0; + virtual LayoutRulesImpl* getVaryingOutputRules() = 0; + virtual LayoutRulesImpl* getSpecializationConstantRules() = 0; + virtual LayoutRulesImpl* getShaderStorageBufferRules() = 0; +}; + +LayoutRulesImpl* GetLayoutRulesImpl(LayoutRule rule); +LayoutRulesFamilyImpl* GetLayoutRulesFamilyImpl(LayoutRulesFamily rule); +LayoutRulesFamilyImpl* GetLayoutRulesFamilyImpl(SourceLanguage language); + +SimpleLayoutInfo GetLayout(ExpressionType* type, LayoutRulesImpl* rules); + +SimpleLayoutInfo GetLayout(ExpressionType* type, LayoutRule rule = LayoutRule::Std430); + +RefPtr CreateTypeLayout(ExpressionType* type, LayoutRulesImpl* rules); + +// + +// Create a type layout for a parameter block type. +RefPtr +createParameterBlockTypeLayout( + RefPtr parameterBlockType, + LayoutRulesImpl* rules); + +// Create a type layout for a constant buffer type, +// in the case where we already know the layout +// for the element type. +RefPtr +createParameterBlockTypeLayout( + RefPtr parameterBlockType, + RefPtr elementTypeLayout, + LayoutRulesImpl* rules); + + +// Create a type layout for a structured buffer type. +RefPtr +createStructuredBufferTypeLayout( + ShaderParameterKind kind, + RefPtr structuredBufferType, + RefPtr elementType, + LayoutRulesImpl* rules); + + +// + +}} + +#endif \ No newline at end of file diff --git a/source/slangc/main.cpp b/source/slangc/main.cpp new file mode 100644 index 000000000..b0ddc7ab6 --- /dev/null +++ b/source/slangc/main.cpp @@ -0,0 +1,644 @@ +// main.cpp + +#include "../slang.h" + +#include "core/slang-io.h" + +#include + +// Currently only used for looking up `Profile::` values that aren't +// exported by the public API +#include "../slang/profile.h" + +using namespace CoreLib::Basic; +using namespace CoreLib::IO; + +// Try to read an argument for a command-line option. +wchar_t const* tryReadCommandLineArgumentRaw(wchar_t const* option, wchar_t***ioCursor, wchar_t**end) +{ + wchar_t**& cursor = *ioCursor; + if (cursor == end) + { + fprintf(stderr, "expected an argument for command-line option '%S'", option); + exit(1); + } + else + { + return *cursor++; + } +} + +String tryReadCommandLineArgument(wchar_t const* option, wchar_t***ioCursor, wchar_t**end) +{ + return String::FromWString(tryReadCommandLineArgumentRaw(option, ioCursor, end)); +} + +struct OptionsParser +{ + SlangSession* session = nullptr; + SlangCompileRequest* compileRequest = nullptr; + + struct RawTranslationUnit + { + SlangSourceLanguage sourceLanguage; + SlangProfileID implicitProfile; + int translationUnitIndex; + }; + + // Collect translation units so that we can futz with them later + List rawTranslationUnits; + + struct RawEntryPoint + { + String name; + SlangProfileID profileID = SLANG_PROFILE_UNKNOWN; + int translationUnitIndex = -1; + }; + + // Collect entry point names, so that we can associate them + // with entry points later... + List rawEntryPoints; + + // The number of input files that have been specified + int inputPathCount = 0; + + // If we already have a translation unit for Slang code, then this will give its index. + // If not, it will be `-1`. + int slangTranslationUnit = -1; + + int translationUnitCount = 0; + int currentTranslationUnitIndex = -1; + + SlangProfileID currentProfileID = SLANG_PROFILE_UNKNOWN; + + SlangCompileFlags flags = 0; + + int addTranslationUnit( + SlangSourceLanguage language, + SlangProfileID implicitProfile = SLANG_PROFILE_UNKNOWN) + { + auto translationUnitIndex = spAddTranslationUnit(compileRequest, language, nullptr); + + assert(translationUnitIndex == rawTranslationUnits.Count()); + + RawTranslationUnit rawTranslationUnit; + rawTranslationUnit.sourceLanguage = language; + rawTranslationUnit.implicitProfile = implicitProfile; + rawTranslationUnit.translationUnitIndex = translationUnitIndex; + + rawTranslationUnits.Add(rawTranslationUnit); + + return translationUnitIndex; + } + + void addInputSlangPath( + String const& path) + { + // All of the input .slang files will be grouped into a single logical translation unit, + // which we create lazily when the first .slang file is encountered. + if( slangTranslationUnit == -1 ) + { + translationUnitCount++; + slangTranslationUnit = addTranslationUnit(SLANG_SOURCE_LANGUAGE_SLANG); + } + + spAddTranslationUnitSourceFile( + compileRequest, + slangTranslationUnit, + path.begin()); + + // Set the translation unit to be used by subsequent entry points + currentTranslationUnitIndex = slangTranslationUnit; + } + + void addInputForeignShaderPath( + String const& path, + SlangSourceLanguage language, + SlangProfileID implicitProfile = SLANG_PROFILE_UNKNOWN) + { + translationUnitCount++; + currentTranslationUnitIndex = addTranslationUnit(language, implicitProfile); + + spAddTranslationUnitSourceFile( + compileRequest, + currentTranslationUnitIndex, + path.begin()); + } + + void addInputPath( + wchar_t const* inPath) + { + inputPathCount++; + + // look at the extension on the file name to determine + // how we should handle it. + String path = String::FromWString(inPath); + + if( path.EndsWith(".slang") ) + { + // Plain old slang code + addInputSlangPath(path); + } +#define CASE(EXT, LANG) \ + else if(path.EndsWith(EXT)) do { addInputForeignShaderPath(path, SLANG_SOURCE_LANGUAGE_##LANG); } while(0) + + CASE(".hlsl", HLSL); + CASE(".fx", HLSL); + + CASE(".glsl", GLSL); +#undef CASE + +#define CASE(EXT, LANG, PROFILE) \ + else if(path.EndsWith(EXT)) do { addInputForeignShaderPath(path, SLANG_SOURCE_LANGUAGE_##LANG, SlangProfileID(Slang::Compiler::Profile::PROFILE)); } while(0) + // TODO: need a way to pass along stage/profile and entry-point info for these cases... + CASE(".vert", GLSL, GLSL_Vertex); + CASE(".frag", GLSL, GLSL_Fragment); + CASE(".geom", GLSL, GLSL_Geometry); + CASE(".tesc", GLSL, GLSL_TessControl); + CASE(".tese", GLSL, GLSL_TessEval); + CASE(".comp", GLSL, GLSL_Compute); + +#undef CASE + + else + { + fprintf(stderr, "error: can't deduce language for input file '%S'\n", inPath); + exit(1); + } + } + + void parse( + int argc, + wchar_t** argv) + { + wchar_t** argCursor = &argv[1]; + wchar_t** argEnd = &argv[argc]; + while (argCursor != argEnd) + { + wchar_t const* arg = *argCursor++; + if (arg[0] == '-') + { + String argStr = String::FromWString(arg); + + // The argument looks like an option, so try to parse it. +// if (argStr == "-outdir") +// outputDir = tryReadCommandLineArgument(arg, &argCursor, argEnd); +// if (argStr == "-out") +// options.outputName = tryReadCommandLineArgument(arg, &argCursor, argEnd); +// else if (argStr == "-symbo") +// options.SymbolToCompile = tryReadCommandLineArgument(arg, &argCursor, argEnd); + //else + if (argStr == "-no-checking") + flags |= SLANG_COMPILE_FLAG_NO_CHECKING; + else if (argStr == "-backend" || argStr == "-target") + { + String name = tryReadCommandLineArgument(arg, &argCursor, argEnd); + SlangCompileTarget target = SLANG_TARGET_UNKNOWN; + + if (name == "glsl") + { + target = SLANG_GLSL; + } + else if (name == "glsl_vk") + { + target = SLANG_GLSL_VULKAN; + } +// else if (name == "glsl_vk_onedesc") +// { +// options.Target = CodeGenTarget::GLSL_Vulkan_OneDesc; +// } + else if (name == "hlsl") + { + target = SLANG_HLSL; + } + else if (name == "spriv") + { + target = SLANG_SPIRV; + } + else if (name == "dxbc") + { + target = SLANG_DXBC; + } + else if (name == "dxbc-assembly") + { + target = SLANG_DXBC_ASM; + } + #define CASE(NAME, TARGET) \ + else if(name == #NAME) do { target = SLANG_##TARGET; } while(0) + + CASE(spirv, SPIRV); + CASE(spirv-assembly, SPIRV_ASM); + + #undef CASE + + else if (name == "reflection-json") + { + target = SLANG_REFLECTION_JSON; + } + else + { + fprintf(stderr, "unknown code generation target '%S'\n", name.ToWString()); + exit(1); + } + + spSetCodeGenTarget(compileRequest, target); + } + // A "profile" specifies both a specific target stage and a general level + // of capability required by the program. + else if (argStr == "-profile") + { + String name = tryReadCommandLineArgument(arg, &argCursor, argEnd); + + SlangProfileID profileID = spFindProfile(session, name.begin()); + if( profileID == SLANG_PROFILE_UNKNOWN ) + { + fprintf(stderr, "unknown profile '%s'\n", name.begin()); + } + else + { + currentProfileID = profileID; + } + } + else if (argStr == "-entry") + { + String name = tryReadCommandLineArgument(arg, &argCursor, argEnd); + + RawEntryPoint entry; + entry.name = name; + entry.translationUnitIndex = currentTranslationUnitIndex; + + // TODO(tfoley): Allow user to fold a specification of a profile into the entry-point name, + // for the case where they might be compiling multiple entry points in one invocation... + // + // For now, just use the last profile set on the command-line to specify this + + entry.profileID = currentProfileID; + + rawEntryPoints.Add(entry); + } +#if 0 + else if (argStr == "-stage") + { + String name = tryReadCommandLineArgument(arg, &argCursor, argEnd); + StageTarget stage = StageTarget::Unknown; + if (name == "vertex") { stage = StageTarget::VertexShader; } + else if (name == "fragment") { stage = StageTarget::FragmentShader; } + else if (name == "hull") { stage = StageTarget::HullShader; } + else if (name == "domain") { stage = StageTarget::DomainShader; } + else if (name == "compute") { stage = StageTarget::ComputeShader; } + else + { + fprintf(stderr, "unknown stage '%S'\n", name.ToWString()); + } + options.stage = stage; + } +#endif + else if (argStr == "-pass-through") + { + String name = tryReadCommandLineArgument(arg, &argCursor, argEnd); + SlangPassThrough passThrough = SLANG_PASS_THROUGH_NONE; + if (name == "fxc") { passThrough = SLANG_PASS_THROUGH_FXC; } + else if (name == "glslang") { passThrough = SLANG_PASS_THROUGH_GLSLANG; } + else + { + fprintf(stderr, "unknown pass-through target '%S'\n", name.ToWString()); + exit(1); + } + + spSetPassThrough( + compileRequest, + passThrough); + } +// else if (argStr == "-genchoice") +// options.Mode = CompilerMode::GenerateChoice; + else if (argStr[1] == 'D') + { + // The value to be defined might be part of the same option, as in: + // -DFOO + // or it might come separately, as in: + // -D FOO + wchar_t const* defineStr = arg + 2; + if (defineStr[0] == 0) + { + // Need to read another argument from the command line + defineStr = tryReadCommandLineArgumentRaw(arg, &argCursor, argEnd); + } + // The string that sets up the define can have an `=` between + // the name to be defined and its value, so we search for one. + wchar_t const* eqPos = nullptr; + for(wchar_t const* dd = defineStr; *dd; ++dd) + { + if (*dd == '=') + { + eqPos = dd; + break; + } + } + + // Now set the preprocessor define + // + if (eqPos) + { + // If we found an `=`, we split the string... + + spAddPreprocessorDefine( + compileRequest, + String::FromWString(defineStr, eqPos).begin(), + String::FromWString(eqPos+1).begin()); + } + else + { + // If there was no `=`, then just #define it to an empty string + + spAddPreprocessorDefine( + compileRequest, + String::FromWString(defineStr).begin(), + ""); + } + } + else if (argStr[1] == 'I') + { + // The value to be defined might be part of the same option, as in: + // -IFOO + // or it might come separately, as in: + // -I FOO + // (see handling of `-D` above) + wchar_t const* includeDirStr = arg + 2; + if (includeDirStr[0] == 0) + { + // Need to read another argument from the command line + includeDirStr = tryReadCommandLineArgumentRaw(arg, &argCursor, argEnd); + } + + spAddSearchPath( + compileRequest, + String::FromWString(includeDirStr).begin()); + } + else if (argStr == "--") + { + // The `--` option causes us to stop trying to parse options, + // and treat the rest of the command line as input file names: + while (argCursor != argEnd) + { + addInputPath(*argCursor++); + } + break; + } + else + { + fprintf(stderr, "unknown command-line option '%S'\n", argStr.ToWString()); + // TODO: print a usage message + exit(1); + } + } + else + { + addInputPath(arg); + } + } + + spSetCompileFlags(compileRequest, flags); + + if (inputPathCount == 0) + { + fprintf(stderr, "error: no input file specified\n"); + exit(1); + } + + // No point in moving forward if there is nothing to compile + if( translationUnitCount == 0 ) + { + fprintf(stderr, "error: no compilation requested\n"); + exit(1); + } + + // If the user didn't list any explicit entry points, then we can + // try to infer one from the type of input file + if(rawEntryPoints.Count() == 0) + { + for(auto rawTranslationUnit : rawTranslationUnits) + { + // Dont' add implicit entry points when compiling from Slang files, + // since Slang doesn't require entry points to be named on the + // command line. + if(rawTranslationUnit.sourceLanguage == SLANG_SOURCE_LANGUAGE_SLANG ) + continue; + + // Use a default entry point name + char const* entryPointName = "main"; + + // Try to determine a profile + SlangProfileID entryPointProfile = SLANG_PROFILE_UNKNOWN; + + // If a profile was specified on the command line, then we use it + if(currentProfileID != SLANG_PROFILE_UNKNOWN) + { + entryPointProfile = currentProfileID; + } + // Otherwise, check if the translation unit implied a profile + // (e.g., a `*.vert` file implies the `GLSL_Vertex` profile) + else if(rawTranslationUnit.implicitProfile != SLANG_PROFILE_UNKNOWN) + { + entryPointProfile = rawTranslationUnit.implicitProfile; + } + + RawEntryPoint entry; + entry.name = entryPointName; + entry.translationUnitIndex = rawTranslationUnit.translationUnitIndex; + entry.profileID = entryPointProfile; + rawEntryPoints.Add(entry); + } + } + + // For any entry points that were given without an explicit profile, we can now apply + // the profile that was given to them. + if( rawEntryPoints.Count() != 0 ) + { + bool anyEntryPointWithoutProfile = false; + for( auto& entryPoint : rawEntryPoints ) + { + // Skip entry points that are already associated with a translation unit... + if( entryPoint.profileID != SLANG_PROFILE_UNKNOWN ) + continue; + + anyEntryPointWithoutProfile = true; + break; + } + + if( anyEntryPointWithoutProfile ) + { + fprintf(stderr, "error: no profile specified; use the '-profile ' option"); + exit(1); + } + // TODO: issue an error if we have multiple `-profile` options *and* + // there are entry points that didn't get a profile. + else + { + for( auto& e : rawEntryPoints ) + { + if( e.profileID == SLANG_PROFILE_UNKNOWN ) + { + e.profileID = currentProfileID; + } + } + } + } + + // Next, we want to make sure that entry points get attached to the appropriate translation + // unit that will provide them. + { + bool anyEntryPointWithoutTranslationUnit = false; + for( auto& entryPoint : rawEntryPoints ) + { + // Skip entry points that are already associated with a translation unit... + if( entryPoint.translationUnitIndex != -1 ) + continue; + + anyEntryPointWithoutTranslationUnit = true; + entryPoint.translationUnitIndex = 0; + } + + if( anyEntryPointWithoutTranslationUnit && translationUnitCount != 1 ) + { + fprintf(stderr, "error: when using multiple translation units, entry points must be specified after their translation unit file(s)"); + exit(1); + } + + // Now place all those entry points where they belong + for( auto& entryPoint : rawEntryPoints ) + { + spAddTranslationUnitEntryPoint( + compileRequest, + entryPoint.translationUnitIndex, + entryPoint.name.begin(), + entryPoint.profileID); + } + } + +#if 0 + // Automatically derive an output directory based on the first file specified. + // + // TODO: require manual specification if there are multiple input files, in different directories + String fileName = options.translationUnits[0].sourceFilePaths[0]; + if (outputDir.Length() == 0) + { + outputDir = Path::GetDirectoryName(fileName); + } +#endif + } + +}; + + +void parseOptions( + SlangCompileRequest* compileRequest, + int argc, + wchar_t** argv) +{ + OptionsParser parser; + parser.compileRequest = compileRequest; + parser.parse(argc, argv); +} + +static void diagnosticCallback( + char const* message, + void* userData) +{ + fputs(message, stderr); + fflush(stderr); +} + +int wmain(int argc, wchar_t* argv[]) +{ + // Parse any command-line options + + SlangSession* session = spCreateSession(nullptr); + SlangCompileRequest* compileRequest = spCreateCompileRequest(session); + + parseOptions(compileRequest, argc, argv); + + spSetDiagnosticCallback( + compileRequest, + &diagnosticCallback, + nullptr); + + // Invoke the compiler + +#ifndef _DEBUG + try +#endif + { + // Run the compiler (this will produce any diagnostics through + // our callback above). + int result = spCompile(compileRequest); + if( result != 0 ) + { + // If the compilation failed, then get out of here... + exit(-1); + } + + // Now dump the output from the compilation to stdout. + // + // TODO: Need a way to control where output goes so that + // we can actually use the standalone compiler as something + // more than a testing tool. + // + + int translationUnitCount = spGetTranslationUnitCount(compileRequest); + for(int tt = 0; tt < translationUnitCount; ++tt) + { + auto output = spGetTranslationUnitSource(compileRequest, tt); + fputs(output, stdout); + } + fflush(stdout); + + // Now that we are done, clean up after ourselves + + spDestroyCompileRequest(compileRequest); + spDestroySession(session); + } +#ifndef _DEBUG + catch (Exception & e) + { + printf("internal compiler error: %S\n", e.Message.ToWString()); + return 1; + } +#endif + +#if 0 + int returnValue = -1; + { + + + auto sourceDir = Path::GetDirectoryName(fileName); + CompileResult result; + try + { + auto files = SlangLib::CompileShaderSourceFromFile(result, fileName, options); + for (auto & f : files) + { + try + { + f.SaveToFile(Path::Combine(outputDir, f.MetaData.ShaderName + ".cse")); + } + catch (Exception &) + { + result.GetErrorWriter()->diagnose(CodePosition(0, 0, 0, ""), Diagnostics::cannotWriteOutputFile, Path::Combine(outputDir, f.MetaData.ShaderName + ".cse")); + } + } + } + catch (Exception & e) + { + printf("internal compiler error: %S\n", e.Message.ToWString()); + } + result.PrintDiagnostics(); + if (result.GetErrorCount() == 0) + returnValue = 0; + } +#endif + +#ifdef _MSC_VER + _CrtDumpMemoryLeaks(); +#endif + return 0; +} \ No newline at end of file diff --git a/source/slangc/slangc.vcxproj b/source/slangc/slangc.vcxproj new file mode 100644 index 000000000..3433f7db6 --- /dev/null +++ b/source/slangc/slangc.vcxproj @@ -0,0 +1,391 @@ + + + + + DebugClang + Win32 + + + DebugClang + x64 + + + Debug_VS2013 + Win32 + + + Debug_VS2013 + x64 + + + Debug + Win32 + + + Debug + x64 + + + Release_VS2013 + Win32 + + + Release_VS2013 + x64 + + + Release + Win32 + + + Release + x64 + + + + {D56CBCEB-1EB5-4CA8-AEC4-48EA35ED61C7} + Win32Proj + SpireCompiler + slangc + 8.1 + + + + Application + true + v140 + Unicode + + + Application + true + v120 + Unicode + + + Application + true + v140_clang_3_7 + Unicode + + + Application + true + v140 + Unicode + + + Application + true + v120 + Unicode + + + Application + true + v140_Clang_3_7 + Unicode + + + Application + false + v140 + true + Unicode + + + Application + false + v120 + true + Unicode + + + Application + false + v140 + true + Unicode + + + Application + false + v120 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + + + true + + + true + + + true + + + true + + + true + + + false + + + false + + + false + + + false + + + + + + Level4 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreadedDebug + ../;../SpireLib + false + + + Console + true + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreadedDebug + ../;../SpireLib + false + + + Console + true + + + + + + + EnableAllWarnings + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreadedDebug + ../;../SpireLib + false + true + + + Console + true + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreadedDebug + ../;../SpireLib + false + + + Console + true + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreadedDebug + ../;../SpireLib + false + + + Console + true + + + + + + + Level4 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreadedDebug + ../;../SpireLib + false + + + Console + true + + + + + Level4 + + + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreaded + ../;../SpireLib + false + + + Console + true + true + true + + + + + Level4 + + + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreaded + ../;../SpireLib + false + + + Console + true + true + true + + + + + Level4 + + + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreaded + ../;../SpireLib + false + + + Console + true + true + true + + + + + Level4 + + + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreaded + ../;../SpireLib + false + + + Console + true + true + true + + + + + {f9be7957-8399-899e-0c49-e714fddd4b65} + + + {f9be7957-8399-899e-0c49-e714fddd4b65} + + + {db00da62-0533-4afd-b59f-a67d5b3a0808} + + + {db00da62-0533-4afd-b59f-a67d5b3a0808} + + + {1168c449-66a5-4d23-80e2-2c1a07e58f83} + + + + + + + + + \ No newline at end of file diff --git a/source/slangc/slangc.vcxproj.filters b/source/slangc/slangc.vcxproj.filters new file mode 100644 index 000000000..0d8d9e457 --- /dev/null +++ b/source/slangc/slangc.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + \ No newline at end of file diff --git a/test.bat b/test.bat new file mode 100644 index 000000000..b4398b991 --- /dev/null +++ b/test.bat @@ -0,0 +1,34 @@ +@echo off +setlocal +pushd %~dp0 + +:: Argument parsing loop, for arguments that we need to handle at the .bat level + +:ARGLOOP + +if "%1"=="-debug" ( + set SLANG_TEST_CONFIG=Debug + shift + goto :ARGLOOP +) +if "%1"=="-release" ( + set SLANG_TEST_CONFIG=Release + shift + goto :ARGLOOP +) + +:: When done with arguments, we'll just fall through here + +SET "SLANG_TEST_ROOT=%~dp0" + +IF "%SLANG_TEST_PLATFORM%" == "" ( SET "SLANG_TEST_PLATFORM=x86" ) +IF "%SLANG_TEST_CONFIG%" == "" ( SET "SLANG_TEST_CONFIG=Debug" ) + +set "SLANG_TEST_BIN_DIR=%SLANG_TEST_ROOT%bin\%SLANG_TEST_PLATFORM%\%SLANG_TEST_CONFIG%\\" + +:: ensure that any built tools are visible +SET "PATH=%PATH%;%SLANG_TEST_BIN_DIR%" + +:: TODO: ensure that everything is built? + +"%SSLANG_TEST_BIN_DIR%slang-test.exe" --bindir "%SLANG_TEST_BIN_DIR%" %* diff --git a/tests/bindings/README.md b/tests/bindings/README.md new file mode 100644 index 000000000..ccc9fecb9 --- /dev/null +++ b/tests/bindings/README.md @@ -0,0 +1,29 @@ +Binding Generation Tests +======================== + +These tests ensure that the compiler can correctly add explicit binding information (e.g., HLSL `register` semantics) to code that does not originally have them. + +Example +------- + +Given code like: + + Texture2D ta; + Texture2D tb; + +We expect to produce output like: + + Texture2D ta : register(t0); + Texture2D tb : register(t1); + +The resulting code guarantees that `tb` will always be assigned to the same location, regardless of how these values are (or are not) used in later shader code. + +Methodology +----------- + +These tests currently rely on the ability to run the same HLSL code through the Spire compiler driver and execute either Spire, or HLSL. We write an example like the above by wrapping explicit `register` semantics in a macro: + + Texture2D ta R(: register(t0)); + Texture2D tb R(: register(t1)); + +In the HLSL case, these annotations will manually place things where we want them, while in the Spire case, we define the macro to have an empty expansion, so that the annotations express our expectation for what the compiler will auto-generate. \ No newline at end of file diff --git a/tests/bindings/binding0.hlsl b/tests/bindings/binding0.hlsl new file mode 100644 index 000000000..3f965bef0 --- /dev/null +++ b/tests/bindings/binding0.hlsl @@ -0,0 +1,27 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile ps_4_0 -entry main + +// Let's first confirm that Spire can reproduce what the +// HLSL compiler would already do in the simple case (when +// all shader parameters are actually used). + +#ifdef __SPIRE__ +#define R(X) /**/ +#else +#define R(X) X +#endif + +float4 use(float4 val) { return val; }; +float4 use(Texture2D t, SamplerState s) { return t.Sample(s, 0.0); } + +Texture2D t R(: register(t0)); +SamplerState s R(: register(s0)); + +cbuffer C R(: register(b0)) +{ + float c; +} + +float4 main() : SV_Target +{ + return use(t,s) + use(c); +} \ No newline at end of file diff --git a/tests/bindings/binding1.hlsl b/tests/bindings/binding1.hlsl new file mode 100644 index 000000000..d9e74e918 --- /dev/null +++ b/tests/bindings/binding1.hlsl @@ -0,0 +1,41 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile ps_4_0 -entry main + +// We want to make sure that the registers that Spire generates +// are used, even if there are "dead" parameter earlier in the program. +// +// In this case, we declare two each of textures, samplers, and constant +// buffers, and then only use the second one. +// Left to its own devices, the HLSL compiler would usually shift the +// object that was used up to binding slot zero, and eliminate the one +// that wasn't used. +// We expect Spire to generate explicit annotations that stop this from +// happening. + +#ifdef __SPIRE__ +#define R(X) /**/ +#else +#define R(X) X +#endif + +float4 use(float4 val) { return val; }; +float4 use(Texture2D t, SamplerState s) { return t.Sample(s, 0.0); } + +Texture2D t0 R(: register(t0)); +Texture2D t1 R(: register(t1)); +SamplerState s0 R(: register(s0)); +SamplerState s1 R(: register(s1)); + +cbuffer C0 R(: register(b0)) +{ + float c0; +} + +cbuffer C1 R(: register(b1)) +{ + float c1; +} + +float4 main() : SV_Target +{ + return use(t1,s1) + use(c1); +} \ No newline at end of file diff --git a/tests/bindings/explicit-binding.hlsl b/tests/bindings/explicit-binding.hlsl new file mode 100644 index 000000000..ac23c6556 --- /dev/null +++ b/tests/bindings/explicit-binding.hlsl @@ -0,0 +1,55 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile ps_4_0 -entry main + +// We need to allow the user to add explicit bindings to their parameters, +// and we can't go and auto-assign anything to use the same locations. + +#ifdef __SPIRE__ +#define R(X) /**/ +#else +#define R(X) X +#endif + +float4 use(float4 val) { return val; }; +float4 use(Texture2D t, SamplerState s) { return t.Sample(s, 0.0); } + +// We'll make three textures, but explicit assign the third one +// to the slot `t0`. We expect the others to shift further along +// to "make room". +Texture2D ta R(: register(t1)); +Texture2D tb R(: register(t2)); +Texture2D tc : register(t0); + + +// The explicit binding may "split" the range of register available +// for automatic placement. We use a "first-fit" approach to pack +// things in: +SamplerState sa R(: register(s0)); +SamplerState sb R(: register(s2)); +SamplerState sc : register(s1); + +// It's also okay to use a register that *doesn't* conflict, +// and even to make things non-contiguous. Here we bind +// the third constnat buffer to register `b9` +// +cbuffer CA R(: register(b0)) +{ + float ca; +} +// +cbuffer CB R(: register(b1)) +{ + float cb; +} +// +cbuffer CC : register(b9) +{ + float cc; +} + +float4 main() : SV_Target +{ + // Go ahead and use everything in this case: + return use(ta, sa) + use(ca) + + use(tb, sb) + use(cb) + + use(tc, sc) + use(cc); +} \ No newline at end of file diff --git a/tests/bindings/multi-file-extra.hlsl b/tests/bindings/multi-file-extra.hlsl new file mode 100644 index 000000000..45837c984 --- /dev/null +++ b/tests/bindings/multi-file-extra.hlsl @@ -0,0 +1,60 @@ +//TEST_IGNORE_FILE: + +// Here we are going to test that we can correctly generating bindings when we +// are presented with a program spanning multiple input files (and multiple entry points) + +// This file provides the fragment shader, and is only meant to be tested in combination with `multi-file.hlsl` + +#ifdef __SPIRE__ +#define R(X) /**/ +#else +#define R(X) X +#endif + +float4 use(float val) { return val; }; +float4 use(float2 val) { return float4(val,0.0,0.0); }; +float4 use(float3 val) { return float4(val,0.0); }; +float4 use(float4 val) { return val; }; +float4 use(Texture2D t, SamplerState s) { return t.Sample(s, 0.0); } + +// Start with some parameters that will appear in both shaders +Texture2D sharedT R(: register(t0)); +SamplerState sharedS R(: register(s0)); +cbuffer sharedC R(: register(b0)) +{ + float3 sharedCA R(: packoffset(c0)); + float sharedCB R(: packoffset(c0.w)); + float3 sharedCC R(: packoffset(c1)); + float2 sharedCD R(: packoffset(c2)); +} + +// Then some parameters specific to this shader. +// These will be placed *after* the ones from the main file, +// and even after the parameters further down in this file +// that end up being shared between the two files. + +Texture2D fragmentT R(: register(t4)); +SamplerState fragmentS R(: register(s2)); +cbuffer fragmentC R(: register(b2)) +{ + float3 fragmentCA R(: packoffset(c0)); + float fragmentCB R(: packoffset(c0.w)); + float3 fragmentCC R(: packoffset(c1)); + float2 fragmentCD R(: packoffset(c2)); +} + +// And end with some shared parameters again +Texture2D sharedTV R(: register(t2)); +Texture2D sharedTF R(: register(t3)); + + +float4 main() : SV_Target +{ + // Go ahead and use everything here, just to make sure things got placed correctly + return use(sharedT, sharedS) + + use(sharedCD) + + use(fragmentT, fragmentS) + + use(fragmentCD) + + use(sharedTF, sharedS) + ; +} \ No newline at end of file diff --git a/tests/bindings/multi-file.hlsl b/tests/bindings/multi-file.hlsl new file mode 100644 index 000000000..db193a869 --- /dev/null +++ b/tests/bindings/multi-file.hlsl @@ -0,0 +1,64 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry main Tests/bindings/multi-file-extra.hlsl -profile ps_4_0 -entry main + +// Here we are going to test that we can correctly generating bindings when we +// are presented with a program spanning multiple input files (and multiple entry points) + +// This file provides the vertex shader, while the fragment shader resides in +// the file `multi-file-extra.hlsl` + +#ifdef __SPIRE__ +#define R(X) /**/ +#else +#define R(X) X +#endif + +float4 use(float val) { return val; }; +float4 use(float2 val) { return float4(val,0.0,0.0); }; +float4 use(float3 val) { return float4(val,0.0); }; +float4 use(float4 val) { return val; }; +float4 use(Texture2D t, SamplerState s) +{ + // This is the vertex shader, so we can't do implicit-gradient sampling + return t.SampleGrad(s, 0.0, 0.0, 0.0); +} + +// Start with some parameters that will appear in both shaders +Texture2D sharedT R(: register(t0)); +SamplerState sharedS R(: register(s0)); +cbuffer sharedC R(: register(b0)) +{ + float3 sharedCA R(: packoffset(c0)); + float sharedCB R(: packoffset(c0.w)); + float3 sharedCC R(: packoffset(c1)); + float2 sharedCD R(: packoffset(c2)); +} + +// Then some parameters specific to this shader +// (these will get placed before the ones in the `extra` file, +// based on how they get named on the command-line) + +Texture2D vertexT R(: register(t1)); +SamplerState vertexS R(: register(s1)); +cbuffer vertexC R(: register(b1)) +{ + float3 vertexCA R(: packoffset(c0)); + float vertexCB R(: packoffset(c0.w)); + float3 vertexCC R(: packoffset(c1)); + float2 vertexCD R(: packoffset(c2)); +} + +// And end with some shared parameters again +Texture2D sharedTV R(: register(t2)); +Texture2D sharedTF R(: register(t3)); + + +float4 main() : SV_Position +{ + // Go ahead and use everything here, just to make sure things got placed correctly + return use(sharedT, sharedS) + + use(sharedCD) + + use(vertexT, vertexS) + + use(vertexCD) + + use(sharedTV, vertexS) + ; +} \ No newline at end of file diff --git a/tests/bindings/packoffset.hlsl b/tests/bindings/packoffset.hlsl new file mode 100644 index 000000000..787bbc129 --- /dev/null +++ b/tests/bindings/packoffset.hlsl @@ -0,0 +1,40 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile ps_4_0 -entry main + +// Let's make sure we generate correct output in cases +// where there are non-trivial `packoffset`s needed + +#ifdef __SPIRE__ +#define R(X) /**/ +#else +#define R(X) X +#endif + +float4 use(float val) { return val; }; +float4 use(float2 val) { return float4(val,0.0,0.0); }; +float4 use(float3 val) { return float4(val,0.0); }; +float4 use(float4 val) { return val; }; +float4 use(Texture2D t, SamplerState s) { return t.Sample(s, 0.0); } + +cbuffer CA R(: register(b0)) +{ + float4 ca R(: packoffset(c0)); + float3 cb R(: packoffset(c1.x)); + float cc R(: packoffset(c1.w)); + float2 cd R(: packoffset(c2.x)); + float2 ce R(: packoffset(c2.z)); + + Texture2D ta R(: register(t0)); + SamplerState sa R(: register(s0)); +} + +float4 main() : SV_Target +{ + // Go ahead and use everything in this case: + return use(ta, sa) + + use(ca) + + use(cb) + + use(cc) + + use(cd) + + use(ce) + ; +} \ No newline at end of file diff --git a/tests/bindings/resources-in-cbuffer.hlsl b/tests/bindings/resources-in-cbuffer.hlsl new file mode 100644 index 000000000..ec35943cc --- /dev/null +++ b/tests/bindings/resources-in-cbuffer.hlsl @@ -0,0 +1,68 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile ps_4_0 -entry main + +// Confirm that resources inside constant buffers get correct locations, +// including the case where there are *multiple* constant buffers +// with reosurces. + +#ifdef __SPIRE__ +#define R(X) /**/ +#else +#define R(X) X +#endif + +float4 use(float val) { return val; }; +float4 use(float2 val) { return float4(val,0.0,0.0); }; +float4 use(float3 val) { return float4(val,0.0); }; +float4 use(float4 val) { return val; }; +float4 use(Texture2D t, SamplerState s) { return t.Sample(s, 0.0); } + +cbuffer CA R(: register(b0)) +{ + float4 caa R(: packoffset(c0)); + float3 cab R(: packoffset(c1.x)); + float cac R(: packoffset(c1.w)); + float2 cad R(: packoffset(c2.x)); + float2 cae R(: packoffset(c2.z)); + + Texture2D ta R(: register(t0)); + SamplerState sa R(: register(s0)); +} + +cbuffer CB R(: register(b1)) +{ + float4 cba R(: packoffset(c0)); + float3 cbb R(: packoffset(c1.x)); + float cbc R(: packoffset(c1.w)); + float2 cbd R(: packoffset(c2.x)); + float2 cbe R(: packoffset(c2.z)); + + Texture2D tbx R(: register(t1)); + Texture2D tby R(: register(t2)); + SamplerState sb R(: register(s1)); +} + +cbuffer CC R(: register(b2)) +{ + float4 cca R(: packoffset(c0)); + float3 ccb R(: packoffset(c1.x)); + float ccc R(: packoffset(c1.w)); + float2 ccd R(: packoffset(c2.x)); + float2 cce R(: packoffset(c2.z)); + + Texture2D tc R(: register(t3)); + SamplerState scx R(: register(s2)); + SamplerState scy R(: register(s3)); +} + +float4 main() : SV_Target +{ + // Go ahead and use everything in this case: + return use(ta, sa) + + use(tbx, sb) + + use(tby, scx) + + use(tc, scy) + + use(cae) + + use(cbe) + + use(cce) + ; +} \ No newline at end of file diff --git a/tests/bindings/resources-in-structs.hlsl.disabled b/tests/bindings/resources-in-structs.hlsl.disabled new file mode 100644 index 000000000..05269d823 --- /dev/null +++ b/tests/bindings/resources-in-structs.hlsl.disabled @@ -0,0 +1,42 @@ +//SPIRE_TEST_OPTS:-target dxbc-assembly -profile ps_5_0 -entry main + +// Confirm that resources inside `struct` types work reasonably well, + +#ifdef __SPIRE__ +#define R(X) /**/ +#else +#define R(X) X +#endif + +float4 use(float val) { return val; }; +float4 use(float2 val) { return float4(val,0.0,0.0); }; +float4 use(float3 val) { return float4(val,0.0); }; +float4 use(float4 val) { return val; }; +float4 use(Texture2D t, SamplerState s) { return t.Sample(s, 0.0); } +float4 use(Texture2D t, SamplerComparisonState s) { return t.SampleCmp(s, 0.0, 0.0); } + +struct FooData +{ + float4 f; + Texture2D t; + SamplerState s; + SamplerComparisonState c; +}; + +cbuffer CA R(: register(b0)) +{ + FooData foo R(: register(c0) : register(t0) : register(s0)); +}; + +Texture2D t R(: register(t1)); +SamplerState s R(: register(s2)); + +float4 main() : SV_Target +{ + // Go ahead and use everything in this case: + return use(foo.t, foo.s) + + use(foo.t, foo.c) + + use(t, s) + + use(foo.f) + ; +} \ No newline at end of file diff --git a/tests/bindings/targets-and-uavs-structure.hlsl b/tests/bindings/targets-and-uavs-structure.hlsl new file mode 100644 index 000000000..dcc053253 --- /dev/null +++ b/tests/bindings/targets-and-uavs-structure.hlsl @@ -0,0 +1,36 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile ps_5_0 -entry main + +// Handle the case where the fragment shader output is +// defined a structure, and the semantics are on the sub-fields + +#ifdef __SPIRE__ +#define R(X) /**/ +#else +#define R(X) X +#endif + +float4 use(float val) { return val; }; +float4 use(float2 val) { return float4(val,0.0,0.0); }; +float4 use(float3 val) { return float4(val,0.0); }; +float4 use(float4 val) { return val; }; +float4 use(Texture2D t, SamplerState s) { return t.Sample(s, 0.0); } + +struct Foo { float2 v; }; + +// This should be allocated a register *after* the render targets +RWStructuredBuffer fooBuffer R(: register(u2)); + +struct Fragment +{ + float4 color : SV_Target0; + float4 extra : SV_Target1; + +}; + +Fragment main() +{ + Fragment output; + output.color = use(fooBuffer[42].v); + output.extra = use(fooBuffer[999].v); + return output; +} \ No newline at end of file diff --git a/tests/bindings/targets-and-uavs.hlsl b/tests/bindings/targets-and-uavs.hlsl new file mode 100644 index 000000000..e5843bed0 --- /dev/null +++ b/tests/bindings/targets-and-uavs.hlsl @@ -0,0 +1,28 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile ps_5_0 -entry main + +// Render target outputs (`SV_Target`) and UAVs are treated +// as sharing the same binding slots in HLSL, so we need to +// make sure that any `u` registers we allocate don't +// interfere with render targets. + +#ifdef __SPIRE__ +#define R(X) /**/ +#else +#define R(X) X +#endif + +float4 use(float val) { return val; }; +float4 use(float2 val) { return float4(val,0.0,0.0); }; +float4 use(float3 val) { return float4(val,0.0); }; +float4 use(float4 val) { return val; }; +float4 use(Texture2D t, SamplerState s) { return t.Sample(s, 0.0); } + +struct Foo { float2 v; }; + +// This should be allocated a register *after* the render target +RWStructuredBuffer fooBuffer R(: register(u1)); + +float4 main() : SV_Target +{ + return use(fooBuffer[12].v); +} \ No newline at end of file diff --git a/tests/diagnostics/break-outside-loop.spire b/tests/diagnostics/break-outside-loop.spire new file mode 100644 index 000000000..f86b0bad6 --- /dev/null +++ b/tests/diagnostics/break-outside-loop.spire @@ -0,0 +1,4 @@ +//TEST:SIMPLE: +// `break` where it isn't allowed + +void foo() { break; } diff --git a/tests/diagnostics/break-outside-loop.spire.expected b/tests/diagnostics/break-outside-loop.spire.expected new file mode 100644 index 000000000..2d56efaa9 --- /dev/null +++ b/tests/diagnostics/break-outside-loop.spire.expected @@ -0,0 +1,6 @@ +result code = -1 +standard error = { +Tests/Diagnostics/break-outside-loop.spire(4): error 30003: 'break' must appear inside loop constructs. +} +standard output = { +} diff --git a/tests/diagnostics/call-argument-type.spire b/tests/diagnostics/call-argument-type.spire new file mode 100644 index 000000000..d9663147f --- /dev/null +++ b/tests/diagnostics/call-argument-type.spire @@ -0,0 +1,11 @@ +//TEST:SIMPLE: +// call function with wrong argument type + +struct A {}; +struct B {}; + +void f(A a) {} +void g(B b) +{ + f(b); +} diff --git a/tests/diagnostics/call-argument-type.spire.expected b/tests/diagnostics/call-argument-type.spire.expected new file mode 100644 index 000000000..09a01a359 --- /dev/null +++ b/tests/diagnostics/call-argument-type.spire.expected @@ -0,0 +1,6 @@ +result code = -1 +standard error = { +Tests/Diagnostics/call-argument-type.spire(10): error 30019: expected an expression of type 'A', got 'B' +} +standard output = { +} diff --git a/tests/diagnostics/continue-outside-loop.spire b/tests/diagnostics/continue-outside-loop.spire new file mode 100644 index 000000000..cad9dce6e --- /dev/null +++ b/tests/diagnostics/continue-outside-loop.spire @@ -0,0 +1,4 @@ +//TEST:SIMPLE: +// `continue` where it isn't allowed + +void foo() { continue; } diff --git a/tests/diagnostics/continue-outside-loop.spire.expected b/tests/diagnostics/continue-outside-loop.spire.expected new file mode 100644 index 000000000..d12cceb78 --- /dev/null +++ b/tests/diagnostics/continue-outside-loop.spire.expected @@ -0,0 +1,6 @@ +result code = -1 +standard error = { +Tests/Diagnostics/continue-outside-loop.spire(4): error 30004: 'continue' must appear inside loop constructs. +} +standard output = { +} diff --git a/tests/diagnostics/expected-token-eof.spire b/tests/diagnostics/expected-token-eof.spire new file mode 100644 index 000000000..99ab161ec --- /dev/null +++ b/tests/diagnostics/expected-token-eof.spire @@ -0,0 +1,6 @@ +//TEST:SIMPLE: +// expected one token, but got EOF + +int foo() +{ + int a = 3 \ No newline at end of file diff --git a/tests/diagnostics/expected-token-eof.spire.expected b/tests/diagnostics/expected-token-eof.spire.expected new file mode 100644 index 000000000..121ac3374 --- /dev/null +++ b/tests/diagnostics/expected-token-eof.spire.expected @@ -0,0 +1,6 @@ +result code = -1 +standard error = { +Tests/Diagnostics/expected-token-eof.spire(6): error 20001: unexpected end of file, expected ';' +} +standard output = { +} diff --git a/tests/diagnostics/expected-token.spire b/tests/diagnostics/expected-token.spire new file mode 100644 index 000000000..db85e7b92 --- /dev/null +++ b/tests/diagnostics/expected-token.spire @@ -0,0 +1,7 @@ +//TEST:SIMPLE: +// expected one token, but got another + +int foo() +{ + int a = 3 ] +} \ No newline at end of file diff --git a/tests/diagnostics/expected-token.spire.expected b/tests/diagnostics/expected-token.spire.expected new file mode 100644 index 000000000..508a06726 --- /dev/null +++ b/tests/diagnostics/expected-token.spire.expected @@ -0,0 +1,6 @@ +result code = -1 +standard error = { +Tests/Diagnostics/expected-token.spire(6): error 20001: unexpected ']', expected ';' +} +standard output = { +} diff --git a/tests/diagnostics/function-redefinition.spire.disabled b/tests/diagnostics/function-redefinition.spire.disabled new file mode 100644 index 000000000..d47cb1bbc --- /dev/null +++ b/tests/diagnostics/function-redefinition.spire.disabled @@ -0,0 +1,5 @@ +//TEST:SIMPLE: +// redefining a function + +int foo(int a) { return 0; } +int foo(int b) { return 1; } diff --git a/tests/diagnostics/function-redefinition.spire.expected b/tests/diagnostics/function-redefinition.spire.expected new file mode 100644 index 000000000..94b0d3626 --- /dev/null +++ b/tests/diagnostics/function-redefinition.spire.expected @@ -0,0 +1,6 @@ +result code = -1 +standard error = { +Tests/Diagnostics/function-redefinition.spire(5): error 30001: 'foo(int)': function redefinition. +} +standard output = { +} diff --git a/tests/diagnostics/hull-shader-invalid-domain.spire.disabled b/tests/diagnostics/hull-shader-invalid-domain.spire.disabled new file mode 100644 index 000000000..a1341631a --- /dev/null +++ b/tests/diagnostics/hull-shader-invalid-domain.spire.disabled @@ -0,0 +1,53 @@ +//TEST:SIMPLE: +// `HullShader` without `Domain` attribute + +pipeline P +{ + world CoarseVertex; + world ControlPoint; + world CornerPoint; + world TessPatch; + world FineVertex; + + require @FineVertex vec4 RS_Position; + require @ControlPoint vec2 tessLevelInner; + require @ControlPoint vec4 tessLevelOuter; + + // implicit import operator CoarseVertex->CornerPoint + extern @CornerPoint CoarseVertex[] CoarseVertex_ControlPoint; + [PerCornerIterator] + extern @CornerPoint int HS_CornerID; + + extern @ControlPoint CoarseVertex[] CoarseVertex_ControlPoint; + extern @TessPatch CoarseVertex[] CoarseVertex_ControlPoint; + [InvocationId] + extern @ControlPoint int invocationId; + extern @FineVertex ControlPoint[] ControlPoint_tes; + extern @FineVertex Patch perPatch_tes; + + extern @FineVertex Patch perCorner_tes; + [TessCoord] + extern @FineVertex vec3 tessCoord; + + stage hs : HullShader + { + PatchWorld: TessPatch; + ControlPointWorld: ControlPoint; + CornerPointWorld: CornerPoint; + InputControlPointCount: 3; + ControlPointCount: 1; + Domain: pentagons; + TessLevelOuter: tessLevelOuter; + TessLevelInner: tessLevelInner; + Partitioning: integer; + OutputTopology: triangle_ccw; + } +} + +shader S + targets P +{ + @FineVertex float4 RS_Position = float4(0.0); + @ControlPoint float2 tessLevelInner = float2(2.0); + @ControlPoint float4 tessLevelOuter = float4(2.0); +} \ No newline at end of file diff --git a/tests/diagnostics/hull-shader-invalid-domain.spire.expected b/tests/diagnostics/hull-shader-invalid-domain.spire.expected new file mode 100644 index 000000000..89b4634aa --- /dev/null +++ b/tests/diagnostics/hull-shader-invalid-domain.spire.expected @@ -0,0 +1,6 @@ +result code = -1 +standard error = { +Tests/Diagnostics/hull-shader-invalid-domain.spire(39): error 50053: 'Domain' should be either 'triangles' or 'quads'. +} +standard output = { +} diff --git a/tests/diagnostics/hull-shader-no-domain.spire.disabled b/tests/diagnostics/hull-shader-no-domain.spire.disabled new file mode 100644 index 000000000..87bf2a81c --- /dev/null +++ b/tests/diagnostics/hull-shader-no-domain.spire.disabled @@ -0,0 +1,53 @@ +//TEST:SIMPLE: +// `HullShader` without `Domain` attribute + +pipeline P +{ + world CoarseVertex; + world ControlPoint; + world CornerPoint; + world TessPatch; + world FineVertex; + + require @FineVertex vec4 RS_Position; + require @ControlPoint vec2 tessLevelInner; + require @ControlPoint vec4 tessLevelOuter; + + // implicit import operator CoarseVertex->CornerPoint + extern @CornerPoint CoarseVertex[] CoarseVertex_ControlPoint; + [PerCornerIterator] + extern @CornerPoint int HS_CornerID; + + extern @ControlPoint CoarseVertex[] CoarseVertex_ControlPoint; + extern @TessPatch CoarseVertex[] CoarseVertex_ControlPoint; + [InvocationId] + extern @ControlPoint int invocationId; + extern @FineVertex ControlPoint[] ControlPoint_tes; + extern @FineVertex Patch perPatch_tes; + + extern @FineVertex Patch perCorner_tes; + [TessCoord] + extern @FineVertex vec3 tessCoord; + + stage hs : HullShader + { + PatchWorld: TessPatch; + ControlPointWorld: ControlPoint; + CornerPointWorld: CornerPoint; + InputControlPointCount: 3; + ControlPointCount: 1; +// Domain: triangles; + TessLevelOuter: tessLevelOuter; + TessLevelInner: tessLevelInner; + Partitioning: integer; + OutputTopology: triangle_ccw; + } +} + +shader S + targets P +{ + @FineVertex float4 RS_Position = float4(0.0); + @ControlPoint float2 tessLevelInner = float2(2.0); + @ControlPoint float4 tessLevelOuter = float4(2.0); +} \ No newline at end of file diff --git a/tests/diagnostics/hull-shader-no-domain.spire.expected b/tests/diagnostics/hull-shader-no-domain.spire.expected new file mode 100644 index 000000000..08a08ad79 --- /dev/null +++ b/tests/diagnostics/hull-shader-no-domain.spire.expected @@ -0,0 +1,6 @@ +result code = -1 +standard error = { +Tests/Diagnostics/hull-shader-no-domain.spire(32): error 50052: 'HullShader' requires attribute 'Domain'. +} +standard output = { +} diff --git a/tests/diagnostics/illegal-character.spire b/tests/diagnostics/illegal-character.spire new file mode 100644 index 000000000..5915e861f --- /dev/null +++ b/tests/diagnostics/illegal-character.spire @@ -0,0 +1,5 @@ +//TEST:SIMPLE: +// illegal character + +` + diff --git a/tests/diagnostics/illegal-character.spire.expected b/tests/diagnostics/illegal-character.spire.expected new file mode 100644 index 000000000..301b99063 --- /dev/null +++ b/tests/diagnostics/illegal-character.spire.expected @@ -0,0 +1,6 @@ +result code = -1 +standard error = { +Tests/Diagnostics/illegal-character.spire(4): error 10000: illegal character '`' +} +standard output = { +} diff --git a/tests/diagnostics/missing-file.spire.disabled b/tests/diagnostics/missing-file.spire.disabled new file mode 100644 index 000000000..f340dd95e --- /dev/null +++ b/tests/diagnostics/missing-file.spire.disabled @@ -0,0 +1,3 @@ +// trying to import a non-existant file + +using "does-not-exist.spire" diff --git a/tests/diagnostics/missing-file.spire.expected b/tests/diagnostics/missing-file.spire.expected new file mode 100644 index 000000000..d4722c0e2 --- /dev/null +++ b/tests/diagnostics/missing-file.spire.expected @@ -0,0 +1,7 @@ +result code = -1 +standard error = { +Tests/Diagnostics/missing-file.spire(1): error 20001: unexpected end of file, expected ';' +Tests/Diagnostics/missing-file.spire(4): error 2: cannot find file 'does-not-exist.spire'. +} +standard output = { +} diff --git a/tests/diagnostics/missing-include-file.spire b/tests/diagnostics/missing-include-file.spire new file mode 100644 index 000000000..9e0f99b9c --- /dev/null +++ b/tests/diagnostics/missing-include-file.spire @@ -0,0 +1,4 @@ +//TEST:SIMPLE: +// trying to include a non-existant file + +#include "does-not-exist.h" diff --git a/tests/diagnostics/missing-include-file.spire.expected b/tests/diagnostics/missing-include-file.spire.expected new file mode 100644 index 000000000..24649c484 --- /dev/null +++ b/tests/diagnostics/missing-include-file.spire.expected @@ -0,0 +1,6 @@ +result code = -1 +standard error = { +Tests/Diagnostics/missing-include-file.spire(4): error 15300: failed to find include file 'does-not-exist.h' +} +standard output = { +} diff --git a/tests/diagnostics/parameter-already-defined.spire b/tests/diagnostics/parameter-already-defined.spire new file mode 100644 index 000000000..860b17e65 --- /dev/null +++ b/tests/diagnostics/parameter-already-defined.spire @@ -0,0 +1,4 @@ +//TEST:SIMPLE: +// re-use parameter name + +int foo( int a, float a ) { return 0; } diff --git a/tests/diagnostics/parameter-already-defined.spire.expected b/tests/diagnostics/parameter-already-defined.spire.expected new file mode 100644 index 000000000..0021afa42 --- /dev/null +++ b/tests/diagnostics/parameter-already-defined.spire.expected @@ -0,0 +1,6 @@ +result code = -1 +standard error = { +Tests/Diagnostics/parameter-already-defined.spire(4): error 30002: parameter 'a' already defined. +} +standard output = { +} diff --git a/tests/diagnostics/undefined-identifier.spire b/tests/diagnostics/undefined-identifier.spire new file mode 100644 index 000000000..6c5a59f75 --- /dev/null +++ b/tests/diagnostics/undefined-identifier.spire @@ -0,0 +1,7 @@ +//TEST:SIMPLE: +// use of undefined identifier + +void foo() +{ + int a = b; +} diff --git a/tests/diagnostics/undefined-identifier.spire.expected b/tests/diagnostics/undefined-identifier.spire.expected new file mode 100644 index 000000000..2eed77baf --- /dev/null +++ b/tests/diagnostics/undefined-identifier.spire.expected @@ -0,0 +1,6 @@ +result code = -1 +standard error = { +Tests/Diagnostics/undefined-identifier.spire(6): error 30015: undefined identifier 'b'. +} +standard output = { +} diff --git a/tests/diagnostics/variable-void-type.spire b/tests/diagnostics/variable-void-type.spire new file mode 100644 index 000000000..926e6401d --- /dev/null +++ b/tests/diagnostics/variable-void-type.spire @@ -0,0 +1,7 @@ +//TEST:SIMPLE: +// variable with `void` type + +void foo() +{ + void a; +} diff --git a/tests/diagnostics/variable-void-type.spire.expected b/tests/diagnostics/variable-void-type.spire.expected new file mode 100644 index 000000000..1f0e6765c --- /dev/null +++ b/tests/diagnostics/variable-void-type.spire.expected @@ -0,0 +1,6 @@ +result code = -1 +standard error = { +Tests/Diagnostics/variable-void-type.spire(6): error 30009: invalid type 'void'. +} +standard output = { +} diff --git a/tests/diagnostics/while-predicate-type.spire b/tests/diagnostics/while-predicate-type.spire new file mode 100644 index 000000000..14ce45533 --- /dev/null +++ b/tests/diagnostics/while-predicate-type.spire @@ -0,0 +1,10 @@ +//TEST:SIMPLE: +// bad type for `while` predicate + +struct S {}; + +void foo() +{ + S s; + while(s) {break;} +} diff --git a/tests/diagnostics/while-predicate-type.spire.expected b/tests/diagnostics/while-predicate-type.spire.expected new file mode 100644 index 000000000..9f94e679e --- /dev/null +++ b/tests/diagnostics/while-predicate-type.spire.expected @@ -0,0 +1,6 @@ +result code = -1 +standard error = { +Tests/Diagnostics/while-predicate-type.spire(9): error 30010: 'while': expression must evaluate to int. +} +standard output = { +} diff --git a/tests/front-end/lexer-comments.spire b/tests/front-end/lexer-comments.spire new file mode 100644 index 000000000..d8c06ca76 --- /dev/null +++ b/tests/front-end/lexer-comments.spire @@ -0,0 +1,13 @@ +//TEST:SIMPLE: +// confirming that the lexer handles comments correctly + +// line comment + +/* block comment +*/ + +/* block comments don't nest + /* +*/ + +float f(float f) { return f; } \ No newline at end of file diff --git a/tests/front-end/parser-decls.spire b/tests/front-end/parser-decls.spire new file mode 100644 index 000000000..bc5a2b13b --- /dev/null +++ b/tests/front-end/parser-decls.spire @@ -0,0 +1,60 @@ +//TEST:SIMPLE: +// test that we can parse all the expected kinds of declarations + +// global-scope `using` is another test + +/* Note(tfoley): disabled during syntax transition +// pipeline +pipeline P +{ + +} +*/ + +// empty declaration +; + +// struct type +struct Pair +{ + int head; + float tail; + +// Note(tfoley): semicolon is expected/required +// here for compatibility with HLSL (C-style +// declarators). +// +// TODO: this could be removed if we treat +// HLSL as a "compatibility mode" +}; + +// function at global scope +float tail(Pair p) { return p.tail; } + +/* Note(tfoley): disabled during syntax transition + +// module +module M +{ + // component declarations + + // using declarations + +} + +// a module can "inherit" from a pipeline +module M2 + targets P +{ +} + +// shader +shader S +{ + // component declarations + + // using declarations + +} + +*/ \ No newline at end of file diff --git a/tests/front-end/parser-empty.spire b/tests/front-end/parser-empty.spire new file mode 100644 index 000000000..bfd66f05b --- /dev/null +++ b/tests/front-end/parser-empty.spire @@ -0,0 +1 @@ +//TEST:SIMPLE: diff --git a/tests/front-end/parser-error-unclosed-curly.spire b/tests/front-end/parser-error-unclosed-curly.spire new file mode 100644 index 000000000..6cfcca456 --- /dev/null +++ b/tests/front-end/parser-error-unclosed-curly.spire @@ -0,0 +1,3 @@ +//TEST:SIMPLE: +void foo() { +// Note: no closing curly brace diff --git a/tests/front-end/parser-error-unclosed-curly.spire.expected b/tests/front-end/parser-error-unclosed-curly.spire.expected new file mode 100644 index 000000000..437b6eab0 --- /dev/null +++ b/tests/front-end/parser-error-unclosed-curly.spire.expected @@ -0,0 +1,6 @@ +result code = -1 +standard error = { +Tests/FrontEnd/parser-error-unclosed-curly.spire(4): error 20001: unexpected end of file, expected '}' +} +standard output = { +} diff --git a/tests/front-end/parser-using-file-a.spireh b/tests/front-end/parser-using-file-a.spireh new file mode 100644 index 000000000..62e6acd06 --- /dev/null +++ b/tests/front-end/parser-using-file-a.spireh @@ -0,0 +1,3 @@ +// this file exists to be included by "parser-using-file.spire" + +float a(float x) { return x * x; } diff --git a/tests/front-end/parser-using-file.spire.disabled b/tests/front-end/parser-using-file.spire.disabled new file mode 100644 index 000000000..f93fb576c --- /dev/null +++ b/tests/front-end/parser-using-file.spire.disabled @@ -0,0 +1,6 @@ +//TEST:SIMPLE: +// test that we can include a file via `using` + +using "parser-using-file-a.spireh"; + +float base( float x ) { return a(x); } \ No newline at end of file diff --git a/tests/front-end/pipeline-simple.spireh b/tests/front-end/pipeline-simple.spireh new file mode 100644 index 000000000..55afd693c --- /dev/null +++ b/tests/front-end/pipeline-simple.spireh @@ -0,0 +1,41 @@ +// pipeline-simple.spireh + + +// TODO(tfoley): strip this down to a minimal pipeline + +pipeline StandardPipeline +{ + [Pinned] + input world MeshVertex; + + world CoarseVertex;// : "glsl(vertex:projCoord)" using projCoord export standardExport; + world Fragment;// : "glsl" export fragmentExport; + + require @CoarseVertex vec4 projCoord; + + [VertexInput] + extern @CoarseVertex MeshVertex vertAttribIn; + import(MeshVertex->CoarseVertex) vertexImport() + { + return project(vertAttribIn); + } + + extern @Fragment CoarseVertex CoarseVertexIn; + import(CoarseVertex->Fragment) standardImport() +// TODO(tfoley): this trait doesn't seem to be implemented on `vec3` +// require trait IsTriviallyPassable(CoarseVertex) + { + return project(CoarseVertexIn); + } + + stage vs : VertexShader + { + World: CoarseVertex; + Position: projCoord; + } + + stage fs : FragmentShader + { + World: Fragment; + } +} \ No newline at end of file diff --git a/tests/front-end/struct.spire b/tests/front-end/struct.spire new file mode 100644 index 000000000..8347f8d58 --- /dev/null +++ b/tests/front-end/struct.spire @@ -0,0 +1,49 @@ +//TEST:SIMPLE: +// test that `struct` decls work + +// Note(tfoley): disabled during syntax transition +// #include "pipeline-simple.spireh" + +// struct declaration +struct Foo +{ + float3 a; + float3 b; +}; + +// function on a struct +Foo makeFoo(float x, float y) +{ + // local of struct type + Foo foo; + foo.a = float3(x); + foo.b = float3(y); + return foo; +} + +/* Note(tfoley): disabled during syntax transition + +template shader Test() +// targets StandardPipeline +{ + // Uniform of struct type + param Foo foo1; + + @MeshVertex float3 position; + @MeshVertex float3 color; + + param mat4 modelViewProjection; + + public vec4 projCoord = modelViewProjection * vec4(position, 1.0); + + // Component of struct type + // Note(tfoley): use of `public` here required to work around parser limitations + public Foo foo2 = makeFoo(color.x, color.y); + + // + float3 result = foo1.a + foo2.b; + + out @Fragment vec4 colorTarget = vec4(result,1); +} + +*/ \ No newline at end of file diff --git a/tests/front-end/typedef.spire b/tests/front-end/typedef.spire new file mode 100644 index 000000000..7e96bead0 --- /dev/null +++ b/tests/front-end/typedef.spire @@ -0,0 +1,15 @@ +//TEST:SIMPLE: +// test that we can `typedef` a type + +typedef float F32; + +F32 foo() +{ + float x = 123.0; + return x; +} + +float bar() +{ + return foo(); +} diff --git a/tests/glsl/sascha-willems/LICENSE.md b/tests/glsl/sascha-willems/LICENSE.md new file mode 100644 index 000000000..2c4cfd5b7 --- /dev/null +++ b/tests/glsl/sascha-willems/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Sascha Willems + +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/tests/glsl/sascha-willems/README.md b/tests/glsl/sascha-willems/README.md new file mode 100644 index 000000000..3060f9b3d --- /dev/null +++ b/tests/glsl/sascha-willems/README.md @@ -0,0 +1,8 @@ +# GLSL Shaders from Sascha Willems' Vulkan Tutorials + + +These shaders are taken from the [repository][VulkanTutorials] of Vulkan examples developed by Sascha Willems. +The original code is licensed according to the terms in the [`LICSENSE.md`](LICENSE.md) file in this directory. + +[VulkanTutorials]: https://github.com/SaschaWillems/Vulkan/ "Vulkan C++ examples and demos" + diff --git a/tests/glsl/sascha-willems/base/textoverlay.frag b/tests/glsl/sascha-willems/base/textoverlay.frag new file mode 100644 index 000000000..e5dbb08de --- /dev/null +++ b/tests/glsl/sascha-willems/base/textoverlay.frag @@ -0,0 +1,14 @@ +#version 450 core +//TEST:COMPARE_GLSL: + +layout (location = 0) in vec2 inUV; + +layout (binding = 0) uniform sampler2D samplerFont; + +layout (location = 0) out vec4 outFragColor; + +void main(void) +{ + float color = texture(samplerFont, inUV).r; + outFragColor = vec4(vec3(color), 1.0); +} diff --git a/tests/glsl/sascha-willems/base/textoverlay.vert b/tests/glsl/sascha-willems/base/textoverlay.vert new file mode 100644 index 000000000..8a20fd8b2 --- /dev/null +++ b/tests/glsl/sascha-willems/base/textoverlay.vert @@ -0,0 +1,18 @@ +#version 450 core +//TEST:COMPARE_GLSL: + +layout (location = 0) in vec2 inPos; +layout (location = 1) in vec2 inUV; + +layout (location = 0) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main(void) +{ + gl_Position = vec4(inPos, 0.0, 1.0); + outUV = inUV; +} diff --git a/tests/glsl/sascha-willems/bloom/colorpass.frag b/tests/glsl/sascha-willems/bloom/colorpass.frag new file mode 100644 index 000000000..63d518d29 --- /dev/null +++ b/tests/glsl/sascha-willems/bloom/colorpass.frag @@ -0,0 +1,18 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D colorMap; + +layout (location = 0) in vec3 inColor; +layout (location = 1) in vec2 inUV; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + outFragColor.rgb = inColor; +// outFragColor = texture(colorMap, inUV);// * vec4(inColor, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/bloom/colorpass.vert b/tests/glsl/sascha-willems/bloom/colorpass.vert new file mode 100644 index 000000000..d2f7f4e6f --- /dev/null +++ b/tests/glsl/sascha-willems/bloom/colorpass.vert @@ -0,0 +1,31 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 view; + mat4 model; +} ubo; + +layout (location = 0) out vec3 outColor; +layout (location = 1) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = inUV; + outColor = inColor; + gl_Position = ubo.projection * ubo.view * ubo.model * inPos; +} diff --git a/tests/glsl/sascha-willems/bloom/gaussblur.frag b/tests/glsl/sascha-willems/bloom/gaussblur.frag new file mode 100644 index 000000000..4cf4696cf --- /dev/null +++ b/tests/glsl/sascha-willems/bloom/gaussblur.frag @@ -0,0 +1,48 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColor; + +layout (binding = 0) uniform UBO +{ + float blurScale; + float blurStrength; +} ubo; + +layout (constant_id = 0) const int blurdirection = 0; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + float weight[5]; + weight[0] = 0.227027; + weight[1] = 0.1945946; + weight[2] = 0.1216216; + weight[3] = 0.054054; + weight[4] = 0.016216; + + vec2 tex_offset = 1.0 / textureSize(samplerColor, 0) * ubo.blurScale; // gets size of single texel + vec3 result = texture(samplerColor, inUV).rgb * weight[0]; // current fragment's contribution + for(int i = 1; i < 5; ++i) + { + if (blurdirection == 1) + { + // H + result += texture(samplerColor, inUV + vec2(tex_offset.x * i, 0.0)).rgb * weight[i] * ubo.blurStrength; + result += texture(samplerColor, inUV - vec2(tex_offset.x * i, 0.0)).rgb * weight[i] * ubo.blurStrength; + } + else + { + // V + result += texture(samplerColor, inUV + vec2(0.0, tex_offset.y * i)).rgb * weight[i] * ubo.blurStrength; + result += texture(samplerColor, inUV - vec2(0.0, tex_offset.y * i)).rgb * weight[i] * ubo.blurStrength; + } + } + outFragColor = vec4(result, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/bloom/gaussblur.vert b/tests/glsl/sascha-willems/bloom/gaussblur.vert new file mode 100644 index 000000000..548284554 --- /dev/null +++ b/tests/glsl/sascha-willems/bloom/gaussblur.vert @@ -0,0 +1,18 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); + gl_Position = vec4(outUV * 2.0f - 1.0f, 0.0f, 1.0f); +} diff --git a/tests/glsl/sascha-willems/bloom/phongpass.frag b/tests/glsl/sascha-willems/bloom/phongpass.frag new file mode 100644 index 000000000..9a449f6d1 --- /dev/null +++ b/tests/glsl/sascha-willems/bloom/phongpass.frag @@ -0,0 +1,34 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D colorMap; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inColor; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec3 ambient = vec3(0.0f); + + // Adjust light calculations for glow color + if ((inColor.r >= 0.9) || (inColor.g >= 0.9) || (inColor.b >= 0.9)) + { + ambient = inColor * 0.25; + } + + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 diffuse = max(dot(N, L), 0.0) * inColor; + vec3 specular = pow(max(dot(R, V), 0.0), 8.0) * vec3(0.75); + outFragColor = vec4(ambient + diffuse + specular, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/bloom/phongpass.vert b/tests/glsl/sascha-willems/bloom/phongpass.vert new file mode 100644 index 000000000..ac0a77ab9 --- /dev/null +++ b/tests/glsl/sascha-willems/bloom/phongpass.vert @@ -0,0 +1,42 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inColor; +layout (location = 3) in vec3 inNormal; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 view; + mat4 model; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec2 outUV; +layout (location = 2) out vec3 outColor; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outNormal = inNormal; + outColor = inColor; + outUV = inUV; + gl_Position = ubo.projection * ubo.view * ubo.model * inPos; + + vec3 lightPos = vec3(-5.0, -5.0, 0.0); + vec4 pos = ubo.view * ubo.model * inPos; + outNormal = mat3(ubo.view * ubo.model) * inNormal; + outLightVec = lightPos - pos.xyz; + outViewVec = -pos.xyz; +} diff --git a/tests/glsl/sascha-willems/bloom/skybox.frag b/tests/glsl/sascha-willems/bloom/skybox.frag new file mode 100644 index 000000000..611eb37db --- /dev/null +++ b/tests/glsl/sascha-willems/bloom/skybox.frag @@ -0,0 +1,16 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform samplerCube samplerCubeMap; + +layout (location = 0) in vec3 inUVW; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + outFragColor = texture(samplerCubeMap, inUVW); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/bloom/skybox.vert b/tests/glsl/sascha-willems/bloom/skybox.vert new file mode 100644 index 000000000..f06b3d38d --- /dev/null +++ b/tests/glsl/sascha-willems/bloom/skybox.vert @@ -0,0 +1,28 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 view; + mat4 model; +} ubo; + +layout (location = 0) out vec3 outUVW; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + + +void main() +{ + outUVW = inPos; + gl_Position = ubo.projection * ubo.view * ubo.model * vec4(inPos.xyz, 1.0); +} diff --git a/tests/glsl/sascha-willems/computecullandlod/cull.comp b/tests/glsl/sascha-willems/computecullandlod/cull.comp new file mode 100644 index 000000000..d04beb2ec --- /dev/null +++ b/tests/glsl/sascha-willems/computecullandlod/cull.comp @@ -0,0 +1,127 @@ +//TEST_IGNORE_FILE: Currently failing due to lack of support for math on specialization constants +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (constant_id = 0) const int MAX_LOD_LEVEL = 5; + +struct InstanceData +{ + vec3 pos; + float scale; +}; + +// Binding 0: Instance input data for culling +layout (binding = 0, std140) buffer Instances +{ + InstanceData instances[ ]; +}; + +// Same layout as VkDrawIndexedIndirectCommand +struct IndexedIndirectCommand +{ + uint indexCount; + uint instanceCount; + uint firstIndex; + uint vertexOffset; + uint firstInstance; +}; + +// Binding 1: Multi draw output +layout (binding = 1, std430) writeonly buffer IndirectDraws +{ + IndexedIndirectCommand indirectDraws[ ]; +}; + +// Binding 2: Uniform block object with matrices +layout (binding = 2) uniform UBO +{ + mat4 projection; + mat4 modelview; + vec4 cameraPos; + vec4 frustumPlanes[6]; +} ubo; + +// Binding 3: Indirect draw stats +layout (binding = 3) buffer UBOOut +{ + uint drawCount; + uint lodCount[MAX_LOD_LEVEL + 1]; +} uboOut; + +// Binding 4: level-of-detail information +struct LOD +{ + uint firstIndex; + uint indexCount; + float distance; + float _pad0; +}; +layout (binding = 4) readonly buffer LODs +{ + LOD lods[ ]; +}; + +layout (local_size_x = 16) in; + +bool frustumCheck(vec4 pos, float radius) +{ + // Check sphere against frustum planes + for (int i = 0; i < 6; i++) + { + if (dot(pos, ubo.frustumPlanes[i]) + radius < 0.0) + { + return false; + } + } + return true; +} + +layout (local_size_x = 16) in; + +void main() +{ + uint idx = gl_GlobalInvocationID.x + gl_GlobalInvocationID.y * gl_NumWorkGroups.x * gl_WorkGroupSize.x; + + // Clear stats on first invocation + if (idx == 0) + { + atomicExchange(uboOut.drawCount, 0); + for (uint i = 0; i < MAX_LOD_LEVEL + 1; i++) + { + atomicExchange(uboOut.lodCount[i], 0); + } + } + + vec4 pos = vec4(instances[idx].pos.xyz, 1.0); + + // Check if object is within current viewing frustum + if (frustumCheck(pos, 1.0)) + { + indirectDraws[idx].instanceCount = 1; + + // Increase number of indirect draw counts + atomicAdd(uboOut.drawCount, 1); + + // Select appropriate LOD level based on distance to camera + uint lodLevel = MAX_LOD_LEVEL; + for (uint i = 0; i < MAX_LOD_LEVEL; i++) + { + if (distance(instances[idx].pos.xyz, ubo.cameraPos.xyz) < lods[i].distance) + { + lodLevel = i; + break; + } + } + indirectDraws[idx].firstIndex = lods[lodLevel].firstIndex; + indirectDraws[idx].indexCount = lods[lodLevel].indexCount; + // Update stats + atomicAdd(uboOut.lodCount[lodLevel], 1); + } + else + { + indirectDraws[idx].instanceCount = 0; + } +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/computecullandlod/indirectdraw.frag b/tests/glsl/sascha-willems/computecullandlod/indirectdraw.frag new file mode 100644 index 000000000..c1e2240f3 --- /dev/null +++ b/tests/glsl/sascha-willems/computecullandlod/indirectdraw.frag @@ -0,0 +1,21 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec3 inViewVec; +layout (location = 3) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 ambient = vec3(0.25); + vec3 diffuse = vec3(max(dot(N, L), 0.0)); + outFragColor = vec4((ambient + diffuse) * inColor, 1.0); +} diff --git a/tests/glsl/sascha-willems/computecullandlod/indirectdraw.vert b/tests/glsl/sascha-willems/computecullandlod/indirectdraw.vert new file mode 100644 index 000000000..3f4a4b8c2 --- /dev/null +++ b/tests/glsl/sascha-willems/computecullandlod/indirectdraw.vert @@ -0,0 +1,46 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +// Vertex attributes +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec3 inColor; + +// Instanced attributes +layout (location = 4) in vec3 instancePos; +layout (location = 5) in float instanceScale; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 modelview; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec3 outViewVec; +layout (location = 3) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outColor = inColor; + + outNormal = inNormal; + + vec4 pos = vec4((inPos.xyz * instanceScale) + instancePos, 1.0); + + gl_Position = ubo.projection * ubo.modelview * pos; + + vec4 wPos = ubo.modelview * vec4(pos.xyz, 1.0); + vec4 lPos = vec4(0.0, 10.0, 50.0, 1.0); + outLightVec = lPos.xyz - pos.xyz; + outViewVec = -pos.xyz; +} diff --git a/tests/glsl/sascha-willems/computenbody/particle.frag b/tests/glsl/sascha-willems/computenbody/particle.frag new file mode 100644 index 000000000..e67d2e00f --- /dev/null +++ b/tests/glsl/sascha-willems/computenbody/particle.frag @@ -0,0 +1,18 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 0) uniform sampler2D samplerColorMap; +layout (binding = 1) uniform sampler2D samplerGradientRamp; + +layout (location = 0) in float inGradientPos; + +layout (location = 0) out vec4 outFragColor; + +void main () +{ + vec3 color = texture(samplerGradientRamp, vec2(inGradientPos, 0.0)).rgb; + outFragColor.rgb = texture(samplerColorMap, gl_PointCoord).rgb * color; +} diff --git a/tests/glsl/sascha-willems/computenbody/particle.vert b/tests/glsl/sascha-willems/computenbody/particle.vert new file mode 100644 index 000000000..eedd185d9 --- /dev/null +++ b/tests/glsl/sascha-willems/computenbody/particle.vert @@ -0,0 +1,36 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec4 inVel; + +layout (location = 0) out float outGradientPos; + +layout (binding = 2) uniform UBO +{ + mat4 projection; + mat4 modelview; + vec2 screendim; +} ubo; + +out gl_PerVertex +{ + vec4 gl_Position; + float gl_PointSize; +}; + +void main () +{ + const float spriteSize = 0.005 * inPos.w; // Point size influenced by mass (stored in inPos.w); + + vec4 eyePos = ubo.modelview * vec4(inPos.x, inPos.y, inPos.z, 1.0); + vec4 projectedCorner = ubo.projection * vec4(0.5 * spriteSize, 0.5 * spriteSize, eyePos.z, eyePos.w); + gl_PointSize = clamp(ubo.screendim.x * projectedCorner.x / projectedCorner.w, 1.0, 128.0); + + gl_Position = ubo.projection * eyePos; + + outGradientPos = inVel.w; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/computenbody/particle_calculate.comp b/tests/glsl/sascha-willems/computenbody/particle_calculate.comp new file mode 100644 index 000000000..82cbe35a0 --- /dev/null +++ b/tests/glsl/sascha-willems/computenbody/particle_calculate.comp @@ -0,0 +1,75 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +struct Particle +{ + vec4 pos; + vec4 vel; +}; + +// Binding 0 : Position storage buffer +layout(std140, binding = 0) buffer Pos +{ + Particle particles[ ]; +}; + +layout (local_size_x = 256) in; + +layout (binding = 1) uniform UBO +{ + float deltaT; + float destX; + float destY; + int particleCount; +} ubo; + +layout (constant_id = 0) const int SHARED_DATA_SIZE = 512; +layout (constant_id = 1) const float GRAVITY = 0.002; +layout (constant_id = 2) const float POWER = 0.75; +layout (constant_id = 3) const float SOFTEN = 0.0075; + +// Share data between computer shader invocations to speed up caluclations +shared vec4 sharedData[SHARED_DATA_SIZE]; + +void main() +{ + // Current SSBO index + uint index = gl_GlobalInvocationID.x; + if (index >= ubo.particleCount) + return; + + vec4 position = particles[index].pos; + vec4 velocity = particles[index].vel; + vec4 acceleration = vec4(0.0); + + for (int i = 0; i < ubo.particleCount; i += SHARED_DATA_SIZE) + { + if (i + gl_LocalInvocationID.x < ubo.particleCount) + { + sharedData[gl_LocalInvocationID.x] = particles[i + gl_LocalInvocationID.x].pos; + } + else + { + sharedData[gl_LocalInvocationID.x] = vec4(0.0); + } + + memoryBarrierShared(); + + for (int j = 0; j < gl_WorkGroupSize.x; j++) + { + vec4 other = sharedData[j]; + vec3 len = other.xyz - position.xyz; + acceleration.xyz += GRAVITY * len * other.w / pow(dot(len, len) + SOFTEN, POWER); + } + } + + particles[index].vel.xyz += ubo.deltaT * acceleration.xyz; + + // Gradient texture position + particles[index].vel.w += 0.1 * ubo.deltaT; + if (particles[index].vel.w > 1.0) + particles[index].vel.w -= 1.0; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/computenbody/particle_integrate.comp b/tests/glsl/sascha-willems/computenbody/particle_integrate.comp new file mode 100644 index 000000000..7085bee01 --- /dev/null +++ b/tests/glsl/sascha-willems/computenbody/particle_integrate.comp @@ -0,0 +1,36 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +struct Particle +{ + vec4 pos; + vec4 vel; +}; + +// Binding 0 : Position storage buffer +layout(std140, binding = 0) buffer Pos +{ + Particle particles[ ]; +}; + +layout (local_size_x = 256) in; + +layout (binding = 1) uniform UBO +{ + float deltaT; + float destX; + float destY; + int particleCount; +} ubo; + +void main() +{ + int index = int(gl_GlobalInvocationID); + vec4 position = particles[index].pos; + vec4 velocity = particles[index].vel; + position += ubo.deltaT * velocity; + particles[index].pos = position; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/computeparticles/particle.comp b/tests/glsl/sascha-willems/computeparticles/particle.comp new file mode 100644 index 000000000..4faf181a4 --- /dev/null +++ b/tests/glsl/sascha-willems/computeparticles/particle.comp @@ -0,0 +1,80 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +struct Particle +{ + vec2 pos; + vec2 vel; + vec4 gradientPos; +}; + +// Binding 0 : Position storage buffer +layout(std140, binding = 0) buffer Pos +{ + Particle particles[ ]; +}; + +layout (local_size_x = 256) in; + +layout (binding = 1) uniform UBO +{ + float deltaT; + float destX; + float destY; + int particleCount; +} ubo; + +vec2 attraction(vec2 pos, vec2 attractPos) +{ + vec2 delta = attractPos - pos; + const float damp = 0.5; + float dDampedDot = dot(delta, delta) + damp; + float invDist = 1.0f / sqrt(dDampedDot); + float invDistCubed = invDist*invDist*invDist; + return delta * invDistCubed * 0.0035; +} + +vec2 repulsion(vec2 pos, vec2 attractPos) +{ + vec2 delta = attractPos - pos; + float targetDistance = sqrt(dot(delta, delta)); + return delta * (1.0 / (targetDistance * targetDistance * targetDistance)) * -0.000035; +} + +void main() +{ + // Current SSBO index + uint index = gl_GlobalInvocationID.x; + // Don't try to write beyond particle count + if (index >= ubo.particleCount) + return; + + // Read position and velocity + vec2 vVel = particles[index].vel.xy; + vec2 vPos = particles[index].pos.xy; + + vec2 destPos = vec2(ubo.destX, ubo.destY); + + vec2 delta = destPos - vPos; + float targetDistance = sqrt(dot(delta, delta)); + vVel += repulsion(vPos, destPos.xy) * 0.05; + + // Move by velocity + vPos += vVel * ubo.deltaT; + + // collide with boundary + if ((vPos.x < -1.0) || (vPos.x > 1.0) || (vPos.y < -1.0) || (vPos.y > 1.0)) + vVel = (-vVel * 0.1) + attraction(vPos, destPos) * 12; + else + particles[index].pos.xy = vPos; + + // Write back + particles[index].vel.xy = vVel; + particles[index].gradientPos.x += 0.02 * ubo.deltaT; + if (particles[index].gradientPos.x > 1.0) + particles[index].gradientPos.x -= 1.0; +} + diff --git a/tests/glsl/sascha-willems/computeparticles/particle.frag b/tests/glsl/sascha-willems/computeparticles/particle.frag new file mode 100644 index 000000000..ac6077261 --- /dev/null +++ b/tests/glsl/sascha-willems/computeparticles/particle.frag @@ -0,0 +1,19 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 0) uniform sampler2D samplerColorMap; +layout (binding = 1) uniform sampler2D samplerGradientRamp; + +layout (location = 0) in vec4 inColor; +layout (location = 1) in float inGradientPos; + +layout (location = 0) out vec4 outFragColor; + +void main () +{ + vec3 color = texture(samplerGradientRamp, vec2(inGradientPos, 0.0)).rgb; + outFragColor.rgb = texture(samplerColorMap, gl_PointCoord).rgb * color; +} diff --git a/tests/glsl/sascha-willems/computeparticles/particle.vert b/tests/glsl/sascha-willems/computeparticles/particle.vert new file mode 100644 index 000000000..b134c4898 --- /dev/null +++ b/tests/glsl/sascha-willems/computeparticles/particle.vert @@ -0,0 +1,25 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec2 inPos; +layout (location = 1) in vec4 inGradientPos; + +layout (location = 0) out vec4 outColor; +layout (location = 1) out float outGradientPos; + +out gl_PerVertex +{ + vec4 gl_Position; + float gl_PointSize; +}; + +void main () +{ + gl_PointSize = 8.0; + outColor = vec4(0.035); + outGradientPos = inGradientPos.x; + gl_Position = vec4(inPos.xy, 1.0, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/computeshader/edgedetect.comp b/tests/glsl/sascha-willems/computeshader/edgedetect.comp new file mode 100644 index 000000000..0c6bb32fa --- /dev/null +++ b/tests/glsl/sascha-willems/computeshader/edgedetect.comp @@ -0,0 +1,48 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (local_size_x = 16, local_size_y = 16) in; +layout (binding = 0, rgba8) uniform readonly image2D inputImage; +layout (binding = 1, rgba8) uniform image2D resultImage; + +float conv(in float[9] kernel, in float[9] data, in float denom, in float offset) +{ + float res = 0.0; + for (int i=0; i<9; ++i) + { + res += kernel[i] * data[i]; + } + return clamp(res/denom + offset, 0.0, 1.0); +} + +struct ImageData +{ + float avg[9]; +} imageData; + +void main() +{ + // Fetch neighbouring texels + int n = -1; + for (int i=-1; i<2; ++i) + { + for(int j=-1; j<2; ++j) + { + n++; + vec3 rgb = imageLoad(inputImage, ivec2(gl_GlobalInvocationID.x + i, gl_GlobalInvocationID.y + j)).rgb; + imageData.avg[n] = (rgb.r + rgb.g + rgb.b) / 3.0; + } + } + + float[9] kernel; + kernel[0] = -1.0/8.0; kernel[1] = -1.0/8.0; kernel[2] = -1.0/8.0; + kernel[3] = -1.0/8.0; kernel[4] = 1.0; kernel[5] = -1.0/8.0; + kernel[6] = -1.0/8.0; kernel[7] = -1.0/8.0; kernel[8] = -1.0/8.0; + + vec4 res = vec4(vec3(conv(kernel, imageData.avg, 0.1, 0.0)), 1.0); + + imageStore(resultImage, ivec2(gl_GlobalInvocationID.xy), res); +} diff --git a/tests/glsl/sascha-willems/computeshader/emboss.comp b/tests/glsl/sascha-willems/computeshader/emboss.comp new file mode 100644 index 000000000..ad0fef510 --- /dev/null +++ b/tests/glsl/sascha-willems/computeshader/emboss.comp @@ -0,0 +1,48 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (local_size_x = 16, local_size_y = 16) in; +layout (binding = 0, rgba8) uniform readonly image2D inputImage; +layout (binding = 1, rgba8) uniform image2D resultImage; + +float conv(in float[9] kernel, in float[9] data, in float denom, in float offset) +{ + float res = 0.0; + for (int i=0; i<9; ++i) + { + res += kernel[i] * data[i]; + } + return clamp(res/denom + offset, 0.0, 1.0); +} + +struct ImageData +{ + float avg[9]; +} imageData; + +void main() +{ + // Fetch neighbouring texels + int n = -1; + for (int i=-1; i<2; ++i) + { + for(int j=-1; j<2; ++j) + { + n++; + vec3 rgb = imageLoad(inputImage, ivec2(gl_GlobalInvocationID.x + i, gl_GlobalInvocationID.y + j)).rgb; + imageData.avg[n] = (rgb.r + rgb.g + rgb.b) / 3.0; + } + } + + float[9] kernel; + kernel[0] = -1.0; kernel[1] = 0.0; kernel[2] = 0.0; + kernel[3] = 0.0; kernel[4] = -1.0; kernel[5] = 0.0; + kernel[6] = 0.0; kernel[7] = 0.0; kernel[8] = 2.0; + + vec4 res = vec4(vec3(conv(kernel, imageData.avg, 1.0, 0.50)), 1.0); + + imageStore(resultImage, ivec2(gl_GlobalInvocationID.xy), res); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/computeshader/sharpen.comp b/tests/glsl/sascha-willems/computeshader/sharpen.comp new file mode 100644 index 000000000..dc71ae447 --- /dev/null +++ b/tests/glsl/sascha-willems/computeshader/sharpen.comp @@ -0,0 +1,57 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (local_size_x = 16, local_size_y = 16) in; +layout (binding = 0, rgba8) uniform readonly image2D inputImage; +layout (binding = 1, rgba8) uniform image2D resultImage; + +float conv(in float[9] kernel, in float[9] data, in float denom, in float offset) +{ + float res = 0.0; + for (int i=0; i<9; ++i) + { + res += kernel[i] * data[i]; + } + return clamp(res/denom + offset, 0.0, 1.0); +} + +struct ImageData +{ + float r[9]; + float g[9]; + float b[9]; +} imageData; + +void main() +{ + + // Fetch neighbouring texels + int n = -1; + for (int i=-1; i<2; ++i) + { + for(int j=-1; j<2; ++j) + { + n++; + vec3 rgb = imageLoad(inputImage, ivec2(gl_GlobalInvocationID.x + i, gl_GlobalInvocationID.y + j)).rgb; + imageData.r[n] = rgb.r; + imageData.g[n] = rgb.g; + imageData.b[n] = rgb.b; + } + } + + float[9] kernel; + kernel[0] = -1.0; kernel[1] = -1.0; kernel[2] = -1.0; + kernel[3] = -1.0; kernel[4] = 9.0; kernel[5] = -1.0; + kernel[6] = -1.0; kernel[7] = -1.0; kernel[8] = -1.0; + + vec4 res = vec4( + conv(kernel, imageData.r, 1.0, 0.0), + conv(kernel, imageData.g, 1.0, 0.0), + conv(kernel, imageData.b, 1.0, 0.0), + 1.0); + + imageStore(resultImage, ivec2(gl_GlobalInvocationID.xy), res); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/computeshader/texture.frag b/tests/glsl/sascha-willems/computeshader/texture.frag new file mode 100644 index 000000000..6d54f2f33 --- /dev/null +++ b/tests/glsl/sascha-willems/computeshader/texture.frag @@ -0,0 +1,16 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColor; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + outFragColor = texture(samplerColor, inUV); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/computeshader/texture.vert b/tests/glsl/sascha-willems/computeshader/texture.vert new file mode 100644 index 000000000..c1ad3e070 --- /dev/null +++ b/tests/glsl/sascha-willems/computeshader/texture.vert @@ -0,0 +1,27 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; +} ubo; + +layout (location = 0) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = inUV; + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); +} diff --git a/tests/glsl/sascha-willems/cubemap/reflect.frag b/tests/glsl/sascha-willems/cubemap/reflect.frag new file mode 100644 index 000000000..2ee1d95e7 --- /dev/null +++ b/tests/glsl/sascha-willems/cubemap/reflect.frag @@ -0,0 +1,36 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform samplerCube samplerColor; + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in float inLodBias; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; +layout (location = 5) in mat4 inInvModelView; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec3 cI = normalize (inPos); + vec3 cR = reflect (cI, normalize(inNormal)); + + cR = vec3(inInvModelView * vec4(cR, 0.0)); + cR.x *= -1.0; + + vec4 color = texture(samplerColor, cR, inLodBias); + + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 ambient = vec3(0.5) * color.rgb; + vec3 diffuse = max(dot(N, L), 0.0) * vec3(1.0); + vec3 specular = pow(max(dot(R, V), 0.0), 16.0) * vec3(0.5); + outFragColor = vec4(ambient + diffuse * color.rgb + specular, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/cubemap/reflect.vert b/tests/glsl/sascha-willems/cubemap/reflect.vert new file mode 100644 index 000000000..dcf746738 --- /dev/null +++ b/tests/glsl/sascha-willems/cubemap/reflect.vert @@ -0,0 +1,42 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + float lodBias; +} ubo; + +layout (location = 0) out vec3 outPos; +layout (location = 1) out vec3 outNormal; +layout (location = 2) out float outLodBias; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; +layout (location = 5) out mat4 outInvModelView; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); + + outPos = vec3(ubo.model * vec4(inPos, 1.0)); + outNormal = mat3(ubo.model) * inNormal; + outLodBias = ubo.lodBias; + + outInvModelView = inverse(ubo.model); + + vec3 lightPos = vec3(0.0f, -5.0f, 5.0f); + outLightVec = lightPos.xyz - outPos.xyz; + outViewVec = -outPos.xyz; +} diff --git a/tests/glsl/sascha-willems/cubemap/skybox.frag b/tests/glsl/sascha-willems/cubemap/skybox.frag new file mode 100644 index 000000000..611eb37db --- /dev/null +++ b/tests/glsl/sascha-willems/cubemap/skybox.frag @@ -0,0 +1,16 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform samplerCube samplerCubeMap; + +layout (location = 0) in vec3 inUVW; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + outFragColor = texture(samplerCubeMap, inUVW); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/cubemap/skybox.vert b/tests/glsl/sascha-willems/cubemap/skybox.vert new file mode 100644 index 000000000..7011212e0 --- /dev/null +++ b/tests/glsl/sascha-willems/cubemap/skybox.vert @@ -0,0 +1,27 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; +} ubo; + +layout (location = 0) out vec3 outUVW; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUVW = inPos; + outUVW.x *= -1.0; + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); +} diff --git a/tests/glsl/sascha-willems/debugmarker/colorpass.frag b/tests/glsl/sascha-willems/debugmarker/colorpass.frag new file mode 100644 index 000000000..de5dcb4dc --- /dev/null +++ b/tests/glsl/sascha-willems/debugmarker/colorpass.frag @@ -0,0 +1,14 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inColor; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + outFragColor.rgb = inColor; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/debugmarker/colorpass.vert b/tests/glsl/sascha-willems/debugmarker/colorpass.vert new file mode 100644 index 000000000..46b93f8dc --- /dev/null +++ b/tests/glsl/sascha-willems/debugmarker/colorpass.vert @@ -0,0 +1,29 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 3) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; +} ubo; + +layout (location = 0) out vec3 outColor; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + { + outColor = inColor; + } + gl_Position = ubo.projection * ubo.model * inPos; +} diff --git a/tests/glsl/sascha-willems/debugmarker/postprocess.frag b/tests/glsl/sascha-willems/debugmarker/postprocess.frag new file mode 100644 index 000000000..0546baaa4 --- /dev/null +++ b/tests/glsl/sascha-willems/debugmarker/postprocess.frag @@ -0,0 +1,43 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColor; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + // Single pass gauss blur + + const vec2 texOffset = vec2(0.01, 0.01); + + vec2 tc0 = inUV + vec2(-texOffset.s, -texOffset.t); + vec2 tc1 = inUV + vec2( 0.0, -texOffset.t); + vec2 tc2 = inUV + vec2(+texOffset.s, -texOffset.t); + vec2 tc3 = inUV + vec2(-texOffset.s, 0.0); + vec2 tc4 = inUV + vec2( 0.0, 0.0); + vec2 tc5 = inUV + vec2(+texOffset.s, 0.0); + vec2 tc6 = inUV + vec2(-texOffset.s, +texOffset.t); + vec2 tc7 = inUV + vec2( 0.0, +texOffset.t); + vec2 tc8 = inUV + vec2(+texOffset.s, +texOffset.t); + + vec4 col0 = texture(samplerColor, tc0); + vec4 col1 = texture(samplerColor, tc1); + vec4 col2 = texture(samplerColor, tc2); + vec4 col3 = texture(samplerColor, tc3); + vec4 col4 = texture(samplerColor, tc4); + vec4 col5 = texture(samplerColor, tc5); + vec4 col6 = texture(samplerColor, tc6); + vec4 col7 = texture(samplerColor, tc7); + vec4 col8 = texture(samplerColor, tc8); + + vec4 sum = (1.0 * col0 + 2.0 * col1 + 1.0 * col2 + + 2.0 * col3 + 4.0 * col4 + 2.0 * col5 + + 1.0 * col6 + 2.0 * col7 + 1.0 * col8) / 16.0; + outFragColor = vec4(sum.rgb, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/debugmarker/postprocess.vert b/tests/glsl/sascha-willems/debugmarker/postprocess.vert new file mode 100644 index 000000000..6a368e9b6 --- /dev/null +++ b/tests/glsl/sascha-willems/debugmarker/postprocess.vert @@ -0,0 +1,18 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); + gl_Position = vec4(outUV * vec2(2.0f, 2.0f) + vec2(-1.0f, -1.0f), 0.0f, 1.0f); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/debugmarker/toon.frag b/tests/glsl/sascha-willems/debugmarker/toon.frag new file mode 100644 index 000000000..ed9832f11 --- /dev/null +++ b/tests/glsl/sascha-willems/debugmarker/toon.frag @@ -0,0 +1,40 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColorMap; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + // Desaturate color + vec3 color = vec3(mix(inColor, vec3(dot(vec3(0.2126,0.7152,0.0722), inColor)), 0.65)); + + // High ambient colors because mesh materials are pretty dark + vec3 ambient = color * vec3(1.0); + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 diffuse = max(dot(N, L), 0.0) * color; + vec3 specular = pow(max(dot(R, V), 0.0), 16.0) * vec3(0.75); + outFragColor = vec4(ambient + diffuse * 1.75 + specular, 1.0); + + float intensity = dot(N,L); + float shade = 1.0; + shade = intensity < 0.5 ? 0.75 : shade; + shade = intensity < 0.35 ? 0.6 : shade; + shade = intensity < 0.25 ? 0.5 : shade; + shade = intensity < 0.1 ? 0.25 : shade; + + outFragColor.rgb = inColor * 3.0 * shade; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/debugmarker/toon.vert b/tests/glsl/sascha-willems/debugmarker/toon.vert new file mode 100644 index 000000000..d0b3be251 --- /dev/null +++ b/tests/glsl/sascha-willems/debugmarker/toon.vert @@ -0,0 +1,42 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + vec4 lightPos; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec2 outUV; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outNormal = inNormal; + outColor = inColor; + outUV = inUV; + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); + + vec4 pos = ubo.model * vec4(inPos, 1.0); + outNormal = mat3(ubo.model) * inNormal; + vec3 lPos = mat3(ubo.model) * ubo.lightPos.xyz; + outLightVec = lPos - pos.xyz; + outViewVec = -pos.xyz; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/deferred/debug.frag b/tests/glsl/sascha-willems/deferred/debug.frag new file mode 100644 index 000000000..6b77990b5 --- /dev/null +++ b/tests/glsl/sascha-willems/deferred/debug.frag @@ -0,0 +1,27 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerPosition; +layout (binding = 2) uniform sampler2D samplerNormal; +layout (binding = 3) uniform sampler2D samplerAlbedo; + +layout (location = 0) in vec3 inUV; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec3 components[3]; + components[0] = texture(samplerPosition, inUV.st).rgb; + components[1] = texture(samplerNormal, inUV.st).rgb; + components[2] = texture(samplerAlbedo, inUV.st).rgb; + // Uncomment to display specular component + //components[2] = vec3(texture(samplerAlbedo, inUV.st).a); + + // Select component depending on z coordinate of quad + highp int index = int(inUV.z); + outFragColor.rgb = components[index]; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/deferred/debug.vert b/tests/glsl/sascha-willems/deferred/debug.vert new file mode 100644 index 000000000..de1b380f6 --- /dev/null +++ b/tests/glsl/sascha-willems/deferred/debug.vert @@ -0,0 +1,28 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec2 inUV; +layout (location = 3) in vec3 inNormal; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; +} ubo; + +layout (location = 0) out vec3 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = vec3(inUV.st, inNormal.z); + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); +} diff --git a/tests/glsl/sascha-willems/deferred/deferred.frag b/tests/glsl/sascha-willems/deferred/deferred.frag new file mode 100644 index 000000000..aead2f872 --- /dev/null +++ b/tests/glsl/sascha-willems/deferred/deferred.frag @@ -0,0 +1,76 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerposition; +layout (binding = 2) uniform sampler2D samplerNormal; +layout (binding = 3) uniform sampler2D samplerAlbedo; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out vec4 outFragcolor; + +struct Light { + vec4 position; + vec3 color; + float radius; +}; + +layout (binding = 4) uniform UBO +{ + Light lights[6]; + vec4 viewPos; +} ubo; + + +void main() +{ + // Get G-Buffer values + vec3 fragPos = texture(samplerposition, inUV).rgb; + vec3 normal = texture(samplerNormal, inUV).rgb; + vec4 albedo = texture(samplerAlbedo, inUV); + + #define lightCount 6 + #define ambient 0.0 + + // Ambient part + vec3 fragcolor = albedo.rgb * ambient; + + for(int i = 0; i < lightCount; ++i) + { + // Vector to light + vec3 L = ubo.lights[i].position.xyz - fragPos; + // Distance from light to fragment position + float dist = length(L); + + // Viewer to fragment + vec3 V = ubo.viewPos.xyz - fragPos; + V = normalize(V); + + //if(dist < ubo.lights[i].radius) + { + // Light to fragment + L = normalize(L); + + // Attenuation + float atten = ubo.lights[i].radius / (pow(dist, 2.0) + 1.0); + + // Diffuse part + vec3 N = normalize(normal); + float NdotL = max(0.0, dot(N, L)); + vec3 diff = ubo.lights[i].color * albedo.rgb * NdotL * atten; + + // Specular part + // Specular map values are stored in alpha of albedo mrt + vec3 R = reflect(-L, N); + float NdotR = max(0.0, dot(R, V)); + vec3 spec = ubo.lights[i].color * albedo.a * pow(NdotR, 16.0) * atten; + + fragcolor += diff + spec; + } + } + + outFragcolor = vec4(fragcolor, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/deferred/deferred.vert b/tests/glsl/sascha-willems/deferred/deferred.vert new file mode 100644 index 000000000..548284554 --- /dev/null +++ b/tests/glsl/sascha-willems/deferred/deferred.vert @@ -0,0 +1,18 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); + gl_Position = vec4(outUV * 2.0f - 1.0f, 0.0f, 1.0f); +} diff --git a/tests/glsl/sascha-willems/deferred/mrt.frag b/tests/glsl/sascha-willems/deferred/mrt.frag new file mode 100644 index 000000000..4bd2a10a5 --- /dev/null +++ b/tests/glsl/sascha-willems/deferred/mrt.frag @@ -0,0 +1,34 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColor; +layout (binding = 2) uniform sampler2D samplerNormalMap; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inColor; +layout (location = 3) in vec3 inWorldPos; +layout (location = 4) in vec3 inTangent; + +layout (location = 0) out vec4 outPosition; +layout (location = 1) out vec4 outNormal; +layout (location = 2) out vec4 outAlbedo; + +void main() +{ + outPosition = vec4(inWorldPos, 1.0); + + // Calculate normal in tangent space + vec3 N = normalize(inNormal); + N.y = -N.y; + vec3 T = normalize(inTangent); + vec3 B = cross(N, T); + mat3 TBN = mat3(T, B, N); + vec3 tnorm = TBN * normalize(texture(samplerNormalMap, inUV).xyz * 2.0 - vec3(1.0)); + outNormal = vec4(tnorm, 1.0); + + outAlbedo = texture(samplerColor, inUV); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/deferred/mrt.vert b/tests/glsl/sascha-willems/deferred/mrt.vert new file mode 100644 index 000000000..26f764176 --- /dev/null +++ b/tests/glsl/sascha-willems/deferred/mrt.vert @@ -0,0 +1,53 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inColor; +layout (location = 3) in vec3 inNormal; +layout (location = 4) in vec3 inTangent; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + mat4 view; + vec4 instancePos[3]; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec2 outUV; +layout (location = 2) out vec3 outColor; +layout (location = 3) out vec3 outWorldPos; +layout (location = 4) out vec3 outTangent; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + vec4 tmpPos = inPos + ubo.instancePos[gl_InstanceIndex]; + + gl_Position = ubo.projection * ubo.view * ubo.model * tmpPos; + + outUV = inUV; + outUV.t = 1.0 - outUV.t; + + // Vertex position in world space + outWorldPos = vec3(ubo.model * tmpPos); + // GL to Vulkan coord space + outWorldPos.y = -outWorldPos.y; + + // Normal in world space + mat3 mNormal = transpose(inverse(mat3(ubo.model))); + outNormal = mNormal * normalize(inNormal); + outTangent = mNormal * normalize(inTangent); + + // Currently just vertex color + outColor = inColor; +} diff --git a/tests/glsl/sascha-willems/deferredmultisampling/debug.frag b/tests/glsl/sascha-willems/deferredmultisampling/debug.frag new file mode 100644 index 000000000..f404711dd --- /dev/null +++ b/tests/glsl/sascha-willems/deferredmultisampling/debug.frag @@ -0,0 +1,56 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2DMS samplerPosition; +layout (binding = 2) uniform sampler2DMS samplerNormal; +layout (binding = 3) uniform sampler2DMS samplerAlbedo; + +layout (location = 0) in vec3 inUV; + +layout (location = 0) out vec4 outFragColor; + +#define NUM_SAMPLES 8 + +vec4 resolve(sampler2DMS tex, ivec2 uv) +{ + vec4 result = vec4(0.0); + int count = 0; + for (int i = 0; i < NUM_SAMPLES; i++) + { + vec4 val = texelFetch(tex, uv, i); + result += val; + count++; + } + return result / float(NUM_SAMPLES); +} + +void main() +{ + ivec2 attDim = textureSize(samplerPosition); + ivec2 UV = ivec2(inUV.st * attDim * 2.0); + + highp int index = 0; + if (inUV.s > 0.5) + { + index = 1; + UV.s -= attDim.x; + } + if (inUV.t > 0.5) + { + index = 2; + UV.t -= attDim.y; + } + + vec3 components[3]; + components[0] = resolve(samplerPosition, UV).rgb; + components[1] = resolve(samplerNormal, UV).rgb; + components[2] = resolve(samplerAlbedo, UV).rgb; + // Uncomment to display specular component + //components[2] = vec3(texture(samplerAlbedo, inUV.st).a); + + // Select component depending on UV + outFragColor.rgb = components[index]; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/deferredmultisampling/debug.vert b/tests/glsl/sascha-willems/deferredmultisampling/debug.vert new file mode 100644 index 000000000..c62c3364a --- /dev/null +++ b/tests/glsl/sascha-willems/deferredmultisampling/debug.vert @@ -0,0 +1,24 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; +} ubo; + +layout (location = 0) out vec3 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = vec3((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2, 0.0); + gl_Position = vec4(outUV.st * 2.0f - 1.0f, 0.0f, 1.0f); +} diff --git a/tests/glsl/sascha-willems/deferredmultisampling/deferred.frag b/tests/glsl/sascha-willems/deferredmultisampling/deferred.frag new file mode 100644 index 000000000..59f855281 --- /dev/null +++ b/tests/glsl/sascha-willems/deferredmultisampling/deferred.frag @@ -0,0 +1,104 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2DMS samplerPosition; +layout (binding = 2) uniform sampler2DMS samplerNormal; +layout (binding = 3) uniform sampler2DMS samplerAlbedo; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out vec4 outFragcolor; + +struct Light { + vec4 position; + vec3 color; + float radius; +}; + +layout (binding = 4) uniform UBO +{ + Light lights[6]; + vec4 viewPos; + ivec2 windowSize; +} ubo; + +layout (constant_id = 0) const int NUM_SAMPLES = 8; + +#define NUM_LIGHTS 6 + +// Manual resolve for MSAA samples +vec4 resolve(sampler2DMS tex, ivec2 uv) +{ + vec4 result = vec4(0.0); + for (int i = 0; i < NUM_SAMPLES; i++) + { + vec4 val = texelFetch(tex, uv, i); + result += val; + } + // Average resolved samples + return result / float(NUM_SAMPLES); +} + +vec3 calculateLighting(vec3 pos, vec3 normal, vec4 albedo) +{ + vec3 result = vec3(0.0); + + for(int i = 0; i < NUM_LIGHTS; ++i) + { + // Vector to light + vec3 L = ubo.lights[i].position.xyz - pos; + // Distance from light to fragment position + float dist = length(L); + + // Viewer to fragment + vec3 V = ubo.viewPos.xyz - pos; + V = normalize(V); + + // Light to fragment + L = normalize(L); + + // Attenuation + float atten = ubo.lights[i].radius / (pow(dist, 2.0) + 1.0); + + // Diffuse part + vec3 N = normalize(normal); + float NdotL = max(0.0, dot(N, L)); + vec3 diff = ubo.lights[i].color * albedo.rgb * NdotL * atten; + + // Specular part + vec3 R = reflect(-L, N); + float NdotR = max(0.0, dot(R, V)); + vec3 spec = ubo.lights[i].color * albedo.a * pow(NdotR, 8.0) * atten; + + result += diff + spec; + } + return result; +} + +void main() +{ + ivec2 attDim = textureSize(samplerPosition); + ivec2 UV = ivec2(inUV * attDim); + + #define ambient 0.15 + + // Ambient part + vec4 alb = resolve(samplerAlbedo, UV); + vec3 fragColor = vec3(0.0); + + // Calualte lighting for every MSAA sample + for (int i = 0; i < NUM_SAMPLES; i++) + { + vec3 pos = texelFetch(samplerPosition, UV, i).rgb; + vec3 normal = texelFetch(samplerNormal, UV, i).rgb; + vec4 albedo = texelFetch(samplerAlbedo, UV, i); + fragColor += calculateLighting(pos, normal, albedo); + } + + fragColor = (alb.rgb * ambient) + fragColor / float(NUM_SAMPLES); + + outFragcolor = vec4(fragColor, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/deferredmultisampling/deferred.vert b/tests/glsl/sascha-willems/deferredmultisampling/deferred.vert new file mode 100644 index 000000000..af8eef6dd --- /dev/null +++ b/tests/glsl/sascha-willems/deferredmultisampling/deferred.vert @@ -0,0 +1,24 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; +} ubo; + +layout (location = 0) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); + gl_Position = vec4(outUV * 2.0f - 1.0f, 0.0f, 1.0f); +} diff --git a/tests/glsl/sascha-willems/deferredmultisampling/mrt.frag b/tests/glsl/sascha-willems/deferredmultisampling/mrt.frag new file mode 100644 index 000000000..4bd2a10a5 --- /dev/null +++ b/tests/glsl/sascha-willems/deferredmultisampling/mrt.frag @@ -0,0 +1,34 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColor; +layout (binding = 2) uniform sampler2D samplerNormalMap; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inColor; +layout (location = 3) in vec3 inWorldPos; +layout (location = 4) in vec3 inTangent; + +layout (location = 0) out vec4 outPosition; +layout (location = 1) out vec4 outNormal; +layout (location = 2) out vec4 outAlbedo; + +void main() +{ + outPosition = vec4(inWorldPos, 1.0); + + // Calculate normal in tangent space + vec3 N = normalize(inNormal); + N.y = -N.y; + vec3 T = normalize(inTangent); + vec3 B = cross(N, T); + mat3 TBN = mat3(T, B, N); + vec3 tnorm = TBN * normalize(texture(samplerNormalMap, inUV).xyz * 2.0 - vec3(1.0)); + outNormal = vec4(tnorm, 1.0); + + outAlbedo = texture(samplerColor, inUV); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/deferredmultisampling/mrt.vert b/tests/glsl/sascha-willems/deferredmultisampling/mrt.vert new file mode 100644 index 000000000..5cc127297 --- /dev/null +++ b/tests/glsl/sascha-willems/deferredmultisampling/mrt.vert @@ -0,0 +1,53 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inColor; +layout (location = 3) in vec3 inNormal; +layout (location = 4) in vec3 inTangent; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + mat4 view; + vec4 instancePos[3]; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec2 outUV; +layout (location = 2) out vec3 outColor; +layout (location = 3) out vec3 outWorldPos; +layout (location = 4) out vec3 outTangent; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + vec4 tmpPos = vec4(inPos.xyz, 1.0) + ubo.instancePos[gl_InstanceIndex]; + + gl_Position = ubo.projection * ubo.view * ubo.model * tmpPos; + + outUV = inUV; + outUV.t = 1.0 - outUV.t; + + // Vertex position in world space + outWorldPos = vec3(ubo.model * tmpPos); + // GL to Vulkan coord space + outWorldPos.y = -outWorldPos.y; + + // Normal in world space + mat3 mNormal = transpose(inverse(mat3(ubo.model))); + outNormal = mNormal * normalize(inNormal); + outTangent = mNormal * normalize(inTangent); + + // Currently just vertex color + outColor = inColor; +} diff --git a/tests/glsl/sascha-willems/deferredshadows/debug.frag b/tests/glsl/sascha-willems/deferredshadows/debug.frag new file mode 100644 index 000000000..f9136b24d --- /dev/null +++ b/tests/glsl/sascha-willems/deferredshadows/debug.frag @@ -0,0 +1,30 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerPosition; +layout (binding = 2) uniform sampler2D samplerNormal; +layout (binding = 3) uniform sampler2D samplerAlbedo; +layout (binding = 5) uniform sampler2DArray samplerDepth; + +layout (location = 0) in vec3 inUV; + +layout (location = 0) out vec4 outFragColor; + +float LinearizeDepth(float depth) +{ + float n = 0.1; // camera z near + float f = 64.0; // camera z far + float z = depth; + return (2.0 * n) / (f + n - z * (f - n)); +} + +void main() +{ + // Display depth from light's point-of-view + // inUV.w = number of light source + float depth = texture(samplerDepth, vec3(inUV)).r; + outFragColor = vec4(vec3(1.0 - LinearizeDepth(depth)), 0.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/deferredshadows/debug.vert b/tests/glsl/sascha-willems/deferredshadows/debug.vert new file mode 100644 index 000000000..8742202c2 --- /dev/null +++ b/tests/glsl/sascha-willems/deferredshadows/debug.vert @@ -0,0 +1,30 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 modelview; +} ubo; + +layout (location = 0) out vec3 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = vec3(inUV.st, gl_InstanceIndex); + vec4 tmpPos = vec4(inPos, 1.0); + tmpPos.y += gl_InstanceIndex; + tmpPos.xy *= vec2(1.0/4.0, 1.0/3.0); + gl_Position = ubo.projection * ubo.modelview * tmpPos; +} diff --git a/tests/glsl/sascha-willems/deferredshadows/deferred.frag b/tests/glsl/sascha-willems/deferredshadows/deferred.frag new file mode 100644 index 000000000..ba3998bd6 --- /dev/null +++ b/tests/glsl/sascha-willems/deferredshadows/deferred.frag @@ -0,0 +1,147 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerposition; +layout (binding = 2) uniform sampler2D samplerNormal; +layout (binding = 3) uniform sampler2D samplerAlbedo; +// Depth from the light's point of view +//layout (binding = 5) uniform sampler2DShadow samplerShadowMap; +layout (binding = 5) uniform sampler2DArray samplerShadowMap; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out vec4 outFragColor; + +#define LIGHT_COUNT 3 +#define SHADOW_FACTOR 0.25 +#define AMBIENT_LIGHT 0.1 +#define USE_PCF + +struct Light +{ + vec4 position; + vec4 target; + vec4 color; + mat4 viewMatrix; +}; + +layout (binding = 4) uniform UBO +{ + vec4 viewPos; + Light lights[LIGHT_COUNT]; + int useShadows; +} ubo; + +float textureProj(vec4 P, float layer, vec2 offset) +{ + float shadow = 1.0; + vec4 shadowCoord = P / P.w; + shadowCoord.st = shadowCoord.st * 0.5 + 0.5; + + if (shadowCoord.z > -1.0 && shadowCoord.z < 1.0) + { + float dist = texture(samplerShadowMap, vec3(shadowCoord.st + offset, layer)).r; + if (shadowCoord.w > 0.0 && dist < shadowCoord.z) + { + shadow = SHADOW_FACTOR; + } + } + return shadow; +} + +float filterPCF(vec4 sc, float layer) +{ + ivec2 texDim = textureSize(samplerShadowMap, 0).xy; + float scale = 1.5; + float dx = scale * 1.0 / float(texDim.x); + float dy = scale * 1.0 / float(texDim.y); + + float shadowFactor = 0.0; + int count = 0; + int range = 1; + + for (int x = -range; x <= range; x++) + { + for (int y = -range; y <= range; y++) + { + shadowFactor += textureProj(sc, layer, vec2(dx*x, dy*y)); + count++; + } + + } + return shadowFactor / count; +} + +void main() +{ + // Get G-Buffer values + vec3 fragPos = texture(samplerposition, inUV).rgb; + vec3 normal = texture(samplerNormal, inUV).rgb; + vec4 albedo = texture(samplerAlbedo, inUV); + + // Ambient part + vec3 fragcolor = albedo.rgb * AMBIENT_LIGHT; + + vec3 N = normalize(normal); + + float shadow = 0.0; + + for(int i = 0; i < LIGHT_COUNT; ++i) + { + // Vector to light + vec3 L = ubo.lights[i].position.xyz - fragPos; + // Distance from light to fragment position + float dist = length(L); + L = normalize(L); + + // Viewer to fragment + vec3 V = ubo.viewPos.xyz - fragPos; + V = normalize(V); + + float lightCosInnerAngle = cos(radians(15.0)); + float lightCosOuterAngle = cos(radians(25.0)); + float lightRange = 100.0; + + // Direction vector from source to target + vec3 dir = normalize(ubo.lights[i].position.xyz - ubo.lights[i].target.xyz); + + // Dual cone spot light with smooth transition between inner and outer angle + float cosDir = dot(L, dir); + float spotEffect = smoothstep(lightCosOuterAngle, lightCosInnerAngle, cosDir); + float heightAttenuation = smoothstep(lightRange, 0.0f, dist); + + // Diffuse lighting + float NdotL = max(0.0, dot(N, L)); + vec3 diff = vec3(NdotL); + + // Specular lighting + vec3 R = reflect(-L, N); + float NdotR = max(0.0, dot(R, V)); + vec3 spec = vec3(pow(NdotR, 16.0) * albedo.a * 2.5); + + fragcolor += vec3((diff + spec) * spotEffect * heightAttenuation) * ubo.lights[i].color.rgb * albedo.rgb; + } + + // Shadow calculations in a separate pass + if (ubo.useShadows > 0) + { + for(int i = 0; i < LIGHT_COUNT; ++i) + { + vec4 shadowClip = ubo.lights[i].viewMatrix * vec4(fragPos, 1.0); + + float shadowFactor; + #ifdef USE_PCF + shadowFactor= filterPCF(shadowClip, i); + #else + shadowFactor = textureProj(shadowClip, i, vec2(0.0)); + #endif + + fragcolor *= shadowFactor; + } + } + + outFragColor.rgb = fragcolor; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/deferredshadows/deferred.vert b/tests/glsl/sascha-willems/deferredshadows/deferred.vert new file mode 100644 index 000000000..cd17f9726 --- /dev/null +++ b/tests/glsl/sascha-willems/deferredshadows/deferred.vert @@ -0,0 +1,27 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 modelview; +} ubo; + +layout (location = 0) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = inUV; + gl_Position = ubo.projection * ubo.modelview * vec4(inPos.xyz, 1.0); +} diff --git a/tests/glsl/sascha-willems/deferredshadows/mrt.frag b/tests/glsl/sascha-willems/deferredshadows/mrt.frag new file mode 100644 index 000000000..7a31f54e9 --- /dev/null +++ b/tests/glsl/sascha-willems/deferredshadows/mrt.frag @@ -0,0 +1,33 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColor; +layout (binding = 2) uniform sampler2D samplerNormalMap; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inColor; +layout (location = 3) in vec3 inWorldPos; +layout (location = 4) in vec3 inTangent; + +layout (location = 0) out vec4 outPosition; +layout (location = 1) out vec4 outNormal; +layout (location = 2) out vec4 outAlbedo; + +void main() +{ + outPosition = vec4(inWorldPos, 1.0); + + // Calculate normal in tangent space + vec3 N = normalize(inNormal); + vec3 T = normalize(inTangent); + vec3 B = cross(N, T); + mat3 TBN = mat3(T, B, N); + vec3 tnorm = TBN * normalize(texture(samplerNormalMap, inUV).xyz * 2.0 - vec3(1.0)); + outNormal = vec4(tnorm, 1.0); + + outAlbedo = texture(samplerColor, inUV); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/deferredshadows/mrt.vert b/tests/glsl/sascha-willems/deferredshadows/mrt.vert new file mode 100644 index 000000000..815c2833f --- /dev/null +++ b/tests/glsl/sascha-willems/deferredshadows/mrt.vert @@ -0,0 +1,51 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inColor; +layout (location = 3) in vec3 inNormal; +layout (location = 4) in vec3 inTangent; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + mat4 view; + vec4 instancePos[3]; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec2 outUV; +layout (location = 2) out vec3 outColor; +layout (location = 3) out vec3 outWorldPos; +layout (location = 4) out vec3 outTangent; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + vec4 tmpPos = inPos + ubo.instancePos[gl_InstanceIndex]; + + gl_Position = ubo.projection * ubo.view * ubo.model * tmpPos; + + outUV = inUV; + outUV.t = 1.0 - outUV.t; + + // Vertex position in world space + outWorldPos = vec3(ubo.model * tmpPos); + + // Normal in world space + mat3 mNormal = transpose(inverse(mat3(ubo.model))); + outNormal = mNormal * normalize(inNormal); + outTangent = mNormal * normalize(inTangent); + + // Currently just vertex color + outColor = inColor; +} diff --git a/tests/glsl/sascha-willems/deferredshadows/shadow.frag b/tests/glsl/sascha-willems/deferredshadows/shadow.frag new file mode 100644 index 000000000..23217ad42 --- /dev/null +++ b/tests/glsl/sascha-willems/deferredshadows/shadow.frag @@ -0,0 +1,12 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout(location = 0) out float fragmentdepth; + +void main() +{ + fragmentdepth = gl_FragCoord.z; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/deferredshadows/shadow.geom b/tests/glsl/sascha-willems/deferredshadows/shadow.geom new file mode 100644 index 000000000..7f71c108a --- /dev/null +++ b/tests/glsl/sascha-willems/deferredshadows/shadow.geom @@ -0,0 +1,36 @@ +#version 420 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +#define LIGHT_COUNT 3 + +layout (triangles, invocations = LIGHT_COUNT) in; +layout (triangle_strip, max_vertices = 3) out; + +layout (binding = 0) uniform UBO +{ + mat4 mvp[LIGHT_COUNT]; + vec4 instancePos[3]; +} ubo; + +layout (location = 0) in int inInstanceIndex[]; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + vec4 instancedPos = ubo.instancePos[inInstanceIndex[0]]; + for (int i = 0; i < gl_in.length(); i++) + { + gl_Layer = gl_InvocationID; + vec4 tmpPos = gl_in[i].gl_Position + instancedPos; + gl_Position = ubo.mvp[gl_InvocationID] * tmpPos; + EmitVertex(); + } + EndPrimitive(); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/deferredshadows/shadow.vert b/tests/glsl/sascha-willems/deferredshadows/shadow.vert new file mode 100644 index 000000000..b16c66414 --- /dev/null +++ b/tests/glsl/sascha-willems/deferredshadows/shadow.vert @@ -0,0 +1,20 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; + +layout (location = 0) out int outInstanceIndex; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outInstanceIndex = gl_InstanceIndex; + gl_Position = inPos; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/displacement/base.frag b/tests/glsl/sascha-willems/displacement/base.frag new file mode 100644 index 000000000..3ab30270c --- /dev/null +++ b/tests/glsl/sascha-willems/displacement/base.frag @@ -0,0 +1,30 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 2) uniform sampler2D colorMap; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inEyePos; +layout (location = 3) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec3 N = normalize(inNormal); + vec3 L = normalize(vec3(1.0)); + + outFragColor.rgb = texture(colorMap, inUV).rgb; + + vec3 Eye = normalize(-inEyePos); + vec3 Reflected = normalize(reflect(-inLightVec, inNormal)); + + vec4 IAmbient = vec4(0.0, 0.0, 0.0, 1.0); + vec4 IDiffuse = vec4(1.0) * max(dot(inNormal, inLightVec), 0.0); + + outFragColor = vec4((IAmbient + IDiffuse) * vec4(texture(colorMap, inUV).rgb, 1.0)); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/displacement/base.vert b/tests/glsl/sascha-willems/displacement/base.vert new file mode 100644 index 000000000..c684afabb --- /dev/null +++ b/tests/glsl/sascha-willems/displacement/base.vert @@ -0,0 +1,19 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec2 outUV; + +void main(void) +{ + gl_Position = vec4(inPos.xyz, 1.0); + outUV = inUV * 3.0; + outNormal = inNormal; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/displacement/displacement.tesc b/tests/glsl/sascha-willems/displacement/displacement.tesc new file mode 100644 index 000000000..73bf237c0 --- /dev/null +++ b/tests/glsl/sascha-willems/displacement/displacement.tesc @@ -0,0 +1,33 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 0) uniform UBO +{ + float tessLevel; +} ubo; + +layout (vertices = 3) out; + +layout (location = 0) in vec3 inNormal[]; +layout (location = 1) in vec2 inUV[]; + +layout (location = 0) out vec3 outNormal[3]; +layout (location = 1) out vec2 outUV[3]; + +void main() +{ + if (gl_InvocationID == 0) + { + gl_TessLevelInner[0] = ubo.tessLevel; + gl_TessLevelOuter[0] = ubo.tessLevel; + gl_TessLevelOuter[1] = ubo.tessLevel; + gl_TessLevelOuter[2] = ubo.tessLevel; + } + + gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position; + outNormal[gl_InvocationID] = inNormal[gl_InvocationID]; + outUV[gl_InvocationID] = inUV[gl_InvocationID]; +} diff --git a/tests/glsl/sascha-willems/displacement/displacement.tese b/tests/glsl/sascha-willems/displacement/displacement.tese new file mode 100644 index 000000000..bd061ec2a --- /dev/null +++ b/tests/glsl/sascha-willems/displacement/displacement.tese @@ -0,0 +1,40 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform UBO +{ + mat4 projection; + mat4 model; + vec4 lightPos; + float tessAlpha; + float tessStrength; +} ubo; + +layout (binding = 2) uniform sampler2D displacementMap; + +layout(triangles, equal_spacing, ccw) in; + +layout (location = 0) in vec3 inNormal[]; +layout (location = 1) in vec2 inUV[]; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec2 outUV; +layout (location = 2) out vec3 outEyesPos; +layout (location = 3) out vec3 outLightVec; + +void main() +{ + gl_Position = (gl_TessCoord.x * gl_in[0].gl_Position) + (gl_TessCoord.y * gl_in[1].gl_Position) + (gl_TessCoord.z * gl_in[2].gl_Position); + outUV = gl_TessCoord.x * inUV[0] + gl_TessCoord.y * inUV[1] + gl_TessCoord.z * inUV[2]; + outNormal = gl_TessCoord.x * inNormal[0] + gl_TessCoord.y * inNormal[1] + gl_TessCoord.z * inNormal[2]; + + gl_Position.xyz += normalize(outNormal) * (max(textureLod(displacementMap, outUV.st, 0.0).a, 0.0) * ubo.tessStrength); + + outEyesPos = (gl_Position).xyz; + outLightVec = normalize(ubo.lightPos.xyz - outEyesPos); + + gl_Position = ubo.projection * ubo.model * gl_Position; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/distancefieldfonts/bitmap.frag b/tests/glsl/sascha-willems/distancefieldfonts/bitmap.frag new file mode 100644 index 000000000..5f6303c3c --- /dev/null +++ b/tests/glsl/sascha-willems/distancefieldfonts/bitmap.frag @@ -0,0 +1,16 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColor; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + outFragColor = vec4(texture(samplerColor, inUV).a); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/distancefieldfonts/bitmap.vert b/tests/glsl/sascha-willems/distancefieldfonts/bitmap.vert new file mode 100644 index 000000000..4ed4e6246 --- /dev/null +++ b/tests/glsl/sascha-willems/distancefieldfonts/bitmap.vert @@ -0,0 +1,22 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; +} ubo; + +layout (location = 0) out vec2 outUV; + +void main() +{ + outUV = inUV; + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); +} diff --git a/tests/glsl/sascha-willems/distancefieldfonts/sdf.frag b/tests/glsl/sascha-willems/distancefieldfonts/sdf.frag new file mode 100644 index 000000000..a0a4babb4 --- /dev/null +++ b/tests/glsl/sascha-willems/distancefieldfonts/sdf.frag @@ -0,0 +1,36 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColor; + +layout (binding = 2) uniform UBO +{ + vec4 outlineColor; + float outlineWidth; + float outline; +} ubo; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + float distance = texture(samplerColor, inUV).a; + float smoothWidth = fwidth(distance); + float alpha = smoothstep(0.5 - smoothWidth, 0.5 + smoothWidth, distance); + vec3 rgb = vec3(alpha); + + if (ubo.outline > 0.0) + { + float w = 1.0 - ubo.outlineWidth; + alpha = smoothstep(w - smoothWidth, w + smoothWidth, distance); + rgb += mix(vec3(alpha), ubo.outlineColor.rgb, alpha); + } + + outFragColor = vec4(rgb, alpha); + +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/distancefieldfonts/sdf.vert b/tests/glsl/sascha-willems/distancefieldfonts/sdf.vert new file mode 100644 index 000000000..4ed4e6246 --- /dev/null +++ b/tests/glsl/sascha-willems/distancefieldfonts/sdf.vert @@ -0,0 +1,22 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; +} ubo; + +layout (location = 0) out vec2 outUV; + +void main() +{ + outUV = inUV; + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); +} diff --git a/tests/glsl/sascha-willems/dynamicuniformbuffer/base.frag b/tests/glsl/sascha-willems/dynamicuniformbuffer/base.frag new file mode 100644 index 000000000..496c70b14 --- /dev/null +++ b/tests/glsl/sascha-willems/dynamicuniformbuffer/base.frag @@ -0,0 +1,14 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inColor; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + outFragColor = vec4(inColor, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/dynamicuniformbuffer/base.vert b/tests/glsl/sascha-willems/dynamicuniformbuffer/base.vert new file mode 100644 index 000000000..5440e88d2 --- /dev/null +++ b/tests/glsl/sascha-willems/dynamicuniformbuffer/base.vert @@ -0,0 +1,34 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inColor; + +layout (binding = 0) uniform UboView +{ + mat4 projection; + mat4 view; +} uboView; + +layout (binding = 1) uniform UboInstance +{ + mat4 model; +} uboInstance; + +layout (location = 0) out vec3 outColor; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outColor = inColor; + mat4 modelView = uboView.view * uboInstance.model; + vec3 worldPos = vec3(modelView * vec4(inPos, 1.0)); + gl_Position = uboView.projection * modelView * vec4(inPos.xyz, 1.0); +} diff --git a/tests/glsl/sascha-willems/gears/gears.frag b/tests/glsl/sascha-willems/gears/gears.frag new file mode 100644 index 000000000..db3dcd5e2 --- /dev/null +++ b/tests/glsl/sascha-willems/gears/gears.frag @@ -0,0 +1,25 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec3 inEyePos; +layout (location = 3) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec3 Eye = normalize(-inEyePos); + vec3 Reflected = normalize(reflect(-inLightVec, inNormal)); + + vec4 IAmbient = vec4(0.2, 0.2, 0.2, 1.0); + vec4 IDiffuse = vec4(0.5, 0.5, 0.5, 0.5) * max(dot(inNormal, inLightVec), 0.0); + float specular = 0.25; + vec4 ISpecular = vec4(0.5, 0.5, 0.5, 1.0) * pow(max(dot(Reflected, Eye), 0.0), 0.8) * specular; + + outFragColor = vec4((IAmbient + IDiffuse) * vec4(inColor, 1.0) + ISpecular); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/gears/gears.vert b/tests/glsl/sascha-willems/gears/gears.vert new file mode 100644 index 000000000..3799e0000 --- /dev/null +++ b/tests/glsl/sascha-willems/gears/gears.vert @@ -0,0 +1,35 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + mat4 normal; + mat4 view; + vec3 lightpos; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec3 outEyePos; +layout (location = 3) out vec3 outLightVec; + +void main() +{ + outNormal = normalize(mat3(ubo.normal) * inNormal); + outColor = inColor; + mat4 modelView = ubo.view * ubo.model; + vec4 pos = modelView * inPos; + outEyePos = vec3(modelView * pos); + vec4 lightPos = vec4(ubo.lightpos, 1.0) * modelView; + outLightVec = normalize(lightPos.xyz - outEyePos); + gl_Position = ubo.projection * pos; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/geometryshader/base.frag b/tests/glsl/sascha-willems/geometryshader/base.frag new file mode 100644 index 000000000..768117a92 --- /dev/null +++ b/tests/glsl/sascha-willems/geometryshader/base.frag @@ -0,0 +1,14 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inColor; + +layout (location = 0) out vec4 outFragColor; + +void main(void) +{ + outFragColor = vec4(inColor, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/geometryshader/base.vert b/tests/glsl/sascha-willems/geometryshader/base.vert new file mode 100644 index 000000000..a3ba3830f --- /dev/null +++ b/tests/glsl/sascha-willems/geometryshader/base.vert @@ -0,0 +1,21 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; + +layout (location = 0) out vec3 outNormal; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main(void) +{ + outNormal = inNormal; + gl_Position = vec4(inPos.xyz, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/geometryshader/mesh.frag b/tests/glsl/sascha-willems/geometryshader/mesh.frag new file mode 100644 index 000000000..d31ff7124 --- /dev/null +++ b/tests/glsl/sascha-willems/geometryshader/mesh.frag @@ -0,0 +1,24 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec3 inViewVec; +layout (location = 3) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 ambient = vec3(0.1); + vec3 diffuse = max(dot(N, L), 0.0) * vec3(1.0); + vec3 specular = pow(max(dot(R, V), 0.0), 16.0) * vec3(0.75); + outFragColor = vec4((ambient + diffuse) * inColor.rgb + specular, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/geometryshader/mesh.vert b/tests/glsl/sascha-willems/geometryshader/mesh.vert new file mode 100644 index 000000000..4caae7b2e --- /dev/null +++ b/tests/glsl/sascha-willems/geometryshader/mesh.vert @@ -0,0 +1,39 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec3 inColor; + +layout (set = 0, binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec3 outViewVec; +layout (location = 3) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outNormal = inNormal; + outColor = inColor; + gl_Position = ubo.projection * ubo.model * inPos; + + vec4 pos = ubo.model * vec4(inPos.xyz, 1.0); + outNormal = mat3(ubo.model) * inNormal; + + vec3 lightPos = vec3(1.0f, -1.0f, 1.0f); + outLightVec = lightPos.xyz - pos.xyz; + outViewVec = -pos.xyz; +} diff --git a/tests/glsl/sascha-willems/geometryshader/normaldebug.geom b/tests/glsl/sascha-willems/geometryshader/normaldebug.geom new file mode 100644 index 000000000..d3c487731 --- /dev/null +++ b/tests/glsl/sascha-willems/geometryshader/normaldebug.geom @@ -0,0 +1,38 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (triangles) in; +layout (line_strip, max_vertices = 6) out; + +layout (binding = 1) uniform UBO +{ + mat4 projection; + mat4 model; +} ubo; + +layout (location = 0) in vec3 inNormal[]; + +layout (location = 0) out vec3 outColor; + +void main(void) +{ + float normalLength = 0.02; + for(int i=0; i> 1) * ar * blurScale); + + vec4 color = vec4(0.0); + for (int i = 0; i < weights.length(); i++) + { + vec2 dv = vec2(0.0, i * blurScale) * ar; + color += texture(samplerColor1, P + dv) * weights[i] * blurStrength; + } + + outColor = color; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/hdr/bloom.vert b/tests/glsl/sascha-willems/hdr/bloom.vert new file mode 100644 index 000000000..548284554 --- /dev/null +++ b/tests/glsl/sascha-willems/hdr/bloom.vert @@ -0,0 +1,18 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); + gl_Position = vec4(outUV * 2.0f - 1.0f, 0.0f, 1.0f); +} diff --git a/tests/glsl/sascha-willems/hdr/composition.frag b/tests/glsl/sascha-willems/hdr/composition.frag new file mode 100644 index 000000000..13f2f5838 --- /dev/null +++ b/tests/glsl/sascha-willems/hdr/composition.frag @@ -0,0 +1,17 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 0) uniform sampler2D samplerColor0; +layout (binding = 1) uniform sampler2D samplerColor1; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out vec4 outColor; + +void main() +{ + outColor = texture(samplerColor0, inUV); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/hdr/composition.vert b/tests/glsl/sascha-willems/hdr/composition.vert new file mode 100644 index 000000000..548284554 --- /dev/null +++ b/tests/glsl/sascha-willems/hdr/composition.vert @@ -0,0 +1,18 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); + gl_Position = vec4(outUV * 2.0f - 1.0f, 0.0f, 1.0f); +} diff --git a/tests/glsl/sascha-willems/hdr/gbuffer.frag b/tests/glsl/sascha-willems/hdr/gbuffer.frag new file mode 100644 index 000000000..476534d76 --- /dev/null +++ b/tests/glsl/sascha-willems/hdr/gbuffer.frag @@ -0,0 +1,95 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform samplerCube samplerEnvMap; + +layout (location = 0) in vec3 inUVW; +layout (location = 1) in vec3 inPos; +layout (location = 2) in vec3 inNormal; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; +layout (location = 5) in mat4 inInvModelView; + +layout (location = 0) out vec4 outColor0; +layout (location = 1) out vec4 outColor1; + +layout (constant_id = 0) const int type = 0; + +#define PI 3.1415926 +#define TwoPI (2.0 * PI) + +layout (binding = 2) uniform UBO { + float exposure; +} ubo; + +void main() +{ + vec4 color; + vec3 wcNormal; + + switch (type) { + case 0: // Skybox + { + vec3 normal = normalize(inUVW); + color = texture(samplerEnvMap, normal); + } + break; + + case 1: // Reflect + { + vec3 wViewVec = mat3(inInvModelView) * normalize(inViewVec); + vec3 normal = normalize(inNormal); + vec3 wNormal = mat3(inInvModelView) * normal; + + float NdotL = max(dot(normal, inLightVec), 0.0); + + vec3 eyeDir = normalize(inViewVec); + vec3 halfVec = normalize(inLightVec + eyeDir); + float NdotH = max(dot(normal, halfVec), 0.0); + float NdotV = max(dot(normal, eyeDir), 0.0); + float VdotH = max(dot(eyeDir, halfVec), 0.0); + + // Geometric attenuation + float NH2 = 2.0 * NdotH; + float g1 = (NH2 * NdotV) / VdotH; + float g2 = (NH2 * NdotL) / VdotH; + float geoAtt = min(1.0, min(g1, g2)); + + const float F0 = 0.6; + const float k = 0.2; + + // Fresnel (schlick approximation) + float fresnel = pow(1.0 - VdotH, 5.0); + fresnel *= (1.0 - F0); + fresnel += F0; + + float spec = (fresnel * geoAtt) / (NdotV * NdotL * 3.14); + + color = texture(samplerEnvMap, reflect(-wViewVec, wNormal)); + + color = vec4(color.rgb * NdotL * (k + spec * (1.0 - k)), 1.0); + } + break; + + case 2: // Refract + { + vec3 wViewVec = mat3(inInvModelView) * normalize(inViewVec); + vec3 wNormal = mat3(inInvModelView) * inNormal; + color = texture(samplerEnvMap, refract(-wViewVec, wNormal, 1.0/1.6)); + } + break; + } + + + // Color with manual exposure into attachment 0 + outColor0.rgb = vec3(1.0) - exp(-color.rgb * ubo.exposure); + + // Bright parts for bloom into attachment 1 + float l = dot(outColor0.rgb, vec3(0.2126, 0.7152, 0.0722)); + float threshold = 0.75; + outColor1.rgb = (l > threshold) ? outColor0.rgb : vec3(0.0); + outColor1.a = 1.0; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/hdr/gbuffer.vert b/tests/glsl/sascha-willems/hdr/gbuffer.vert new file mode 100644 index 000000000..862203774 --- /dev/null +++ b/tests/glsl/sascha-willems/hdr/gbuffer.vert @@ -0,0 +1,51 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; + +layout (constant_id = 0) const int type = 0; + +layout (binding = 0) uniform UBO { + mat4 projection; + mat4 modelview; +} ubo; + +layout (location = 0) out vec3 outUVW; +layout (location = 1) out vec3 outPos; +layout (location = 2) out vec3 outNormal; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; +layout (location = 5) out mat4 outInvModelView; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUVW = inPos; + + switch(type) { + case 0: // Skybox + outPos = vec3(mat3(ubo.modelview) * inPos); + gl_Position = vec4(ubo.projection * vec4(outPos, 1.0)); + break; + case 1: // Object + outPos = vec3(ubo.modelview * vec4(inPos, 1.0)); + gl_Position = ubo.projection * ubo.modelview * vec4(inPos.xyz, 1.0); + break; + } + outPos = vec3(ubo.modelview * vec4(inPos, 1.0)); + outNormal = mat3(ubo.modelview) * inNormal; + + outInvModelView = inverse(ubo.modelview); + + vec3 lightPos = vec3(0.0f, -5.0f, 5.0f); + outLightVec = lightPos.xyz - outPos.xyz; + outViewVec = -outPos.xyz; +} diff --git a/tests/glsl/sascha-willems/imgui/scene.frag b/tests/glsl/sascha-willems/imgui/scene.frag new file mode 100644 index 000000000..77eded98b --- /dev/null +++ b/tests/glsl/sascha-willems/imgui/scene.frag @@ -0,0 +1,23 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec3 inViewVec; +layout (location = 3) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + float diffuse = max(dot(N, L), 0.0); + vec3 specular = pow(max(dot(R, V), 0.0), 16.0) * vec3(0.75); + outFragColor = vec4(diffuse * inColor + specular, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/imgui/scene.vert b/tests/glsl/sascha-willems/imgui/scene.vert new file mode 100644 index 000000000..921b1dbe6 --- /dev/null +++ b/tests/glsl/sascha-willems/imgui/scene.vert @@ -0,0 +1,39 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + vec4 lightPos; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec3 outViewVec; +layout (location = 3) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outNormal = inNormal; + outColor = inColor; + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); + + vec4 pos = ubo.model * vec4(inPos, 1.0); + outNormal = mat3(ubo.model) * inNormal; + vec3 lPos = mat3(ubo.model) * ubo.lightPos.xyz; + outLightVec = lPos - pos.xyz; + outViewVec = -pos.xyz; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/imgui/ui.frag b/tests/glsl/sascha-willems/imgui/ui.frag new file mode 100644 index 000000000..51e89bd7b --- /dev/null +++ b/tests/glsl/sascha-willems/imgui/ui.frag @@ -0,0 +1,14 @@ +#version 450 +//TEST:COMPARE_GLSL: + +layout (binding = 0) uniform sampler2D fontSampler; + +layout (location = 0) in vec2 inUV; +layout (location = 1) in vec4 inColor; + +layout (location = 0) out vec4 outColor; + +void main() +{ + outColor = inColor * texture(fontSampler, inUV); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/imgui/ui.vert b/tests/glsl/sascha-willems/imgui/ui.vert new file mode 100644 index 000000000..cf95e08d3 --- /dev/null +++ b/tests/glsl/sascha-willems/imgui/ui.vert @@ -0,0 +1,26 @@ +#version 450 +//TEST:COMPARE_GLSL: + +layout (location = 0) in vec2 inPos; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec4 inColor; + +layout (push_constant) uniform PushConstants { + vec2 scale; + vec2 translate; +} pushConstants; + +layout (location = 0) out vec2 outUV; +layout (location = 1) out vec4 outColor; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = inUV; + outColor = inColor; + gl_Position = vec4(inPos * pushConstants.scale + pushConstants.translate, 0.0, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/indirectdraw/ground.frag b/tests/glsl/sascha-willems/indirectdraw/ground.frag new file mode 100644 index 000000000..47589e181 --- /dev/null +++ b/tests/glsl/sascha-willems/indirectdraw/ground.frag @@ -0,0 +1,29 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 2) uniform sampler2D samplerColor; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + // Last array layer is terrain tex + vec4 color = texture(samplerColor, inUV); + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 ambient = vec3(0.65); + vec3 diffuse = max(dot(N, L), 0.0) * inColor; + vec3 specular = pow(max(dot(R, V), 0.0), 16.0) * vec3(0.1); + outFragColor = vec4((ambient + diffuse) * color.rgb + specular, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/indirectdraw/ground.vert b/tests/glsl/sascha-willems/indirectdraw/ground.vert new file mode 100644 index 000000000..fa6bbe5c6 --- /dev/null +++ b/tests/glsl/sascha-willems/indirectdraw/ground.vert @@ -0,0 +1,44 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +// Vertex attributes +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 modelview; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec2 outUV; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outColor = inColor; + outUV = inUV * 32.0; + outNormal = inNormal; + + vec4 pos = vec4(inPos.xyz, 1.0); + + gl_Position = ubo.projection * ubo.modelview * pos; + + vec4 wPos = ubo.modelview * vec4(pos.xyz, 1.0); + vec4 lPos = vec4(0.0, -5.0, 0.0, 1.0); + outLightVec = lPos.xyz - pos.xyz; + outViewVec = -pos.xyz; +} diff --git a/tests/glsl/sascha-willems/indirectdraw/indirectdraw.frag b/tests/glsl/sascha-willems/indirectdraw/indirectdraw.frag new file mode 100644 index 000000000..3c7913201 --- /dev/null +++ b/tests/glsl/sascha-willems/indirectdraw/indirectdraw.frag @@ -0,0 +1,31 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2DArray samplerArray; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec3 inUV; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec4 color = texture(samplerArray, inUV); + + if (color.a < 0.5) + { + discard; + } + + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 ambient = vec3(0.65); + vec3 diffuse = max(dot(N, L), 0.0) * inColor; + outFragColor = vec4((ambient + diffuse) * color.rgb, 1.0); +} diff --git a/tests/glsl/sascha-willems/indirectdraw/indirectdraw.vert b/tests/glsl/sascha-willems/indirectdraw/indirectdraw.vert new file mode 100644 index 000000000..a4d7e9132 --- /dev/null +++ b/tests/glsl/sascha-willems/indirectdraw/indirectdraw.vert @@ -0,0 +1,83 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +// Vertex attributes +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inColor; + +// Instanced attributes +layout (location = 4) in vec3 instancePos; +layout (location = 5) in vec3 instanceRot; +layout (location = 6) in float instanceScale; +layout (location = 7) in int instanceTexIndex; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 modelview; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec3 outUV; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outColor = inColor; + outUV = vec3(inUV, instanceTexIndex); + outUV.t = 1.0 - outUV.t; + + mat4 mx, my, mz; + + // rotate around x + float s = sin(instanceRot.x); + float c = cos(instanceRot.x); + + mx[0] = vec4(c, s, 0.0, 0.0); + mx[1] = vec4(-s, c, 0.0, 0.0); + mx[2] = vec4(0.0, 0.0, 1.0, 0.0); + mx[3] = vec4(0.0, 0.0, 0.0, 1.0); + + // rotate around y + s = sin(instanceRot.y); + c = cos(instanceRot.y); + + my[0] = vec4(c, 0.0, s, 0.0); + my[1] = vec4(0.0, 1.0, 0.0, 0.0); + my[2] = vec4(-s, 0.0, c, 0.0); + my[3] = vec4(0.0, 0.0, 0.0, 1.0); + + // rot around z + s = sin(instanceRot.z); + c = cos(instanceRot.z); + + mz[0] = vec4(1.0, 0.0, 0.0, 0.0); + mz[1] = vec4(0.0, c, s, 0.0); + mz[2] = vec4(0.0, -s, c, 0.0); + mz[3] = vec4(0.0, 0.0, 0.0, 1.0); + + mat4 rotMat = mz * my * mx; + + outNormal = inNormal * mat3(rotMat); + + vec4 pos = vec4((inPos.xyz * instanceScale) + instancePos, 1.0) * rotMat; + + gl_Position = ubo.projection * ubo.modelview * pos; + + vec4 wPos = ubo.modelview * vec4(pos.xyz, 1.0); + vec4 lPos = vec4(0.0, -5.0, 0.0, 1.0); + outLightVec = lPos.xyz - pos.xyz; + outViewVec = -pos.xyz; +} diff --git a/tests/glsl/sascha-willems/indirectdraw/skysphere.frag b/tests/glsl/sascha-willems/indirectdraw/skysphere.frag new file mode 100644 index 000000000..5c6f4cc7b --- /dev/null +++ b/tests/glsl/sascha-willems/indirectdraw/skysphere.frag @@ -0,0 +1,18 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 2) uniform sampler2D samplerColor; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + const vec4 gradientStart = vec4(0.93, 0.9, 0.81, 1.0); + const vec4 gradientEnd = vec4(0.35, 0.5, 1.0, 1.0); + outFragColor = mix(gradientStart, gradientEnd, min(0.5 - inUV.t, 0.5)/0.15 + 0.5); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/indirectdraw/skysphere.vert b/tests/glsl/sascha-willems/indirectdraw/skysphere.vert new file mode 100644 index 000000000..03e563b39 --- /dev/null +++ b/tests/glsl/sascha-willems/indirectdraw/skysphere.vert @@ -0,0 +1,29 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +// Vertex attributes +layout (location = 0) in vec4 inPos; +layout (location = 2) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 modelview; +} ubo; + +layout (location = 0) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = vec2(inUV.s, 1.0-inUV.t); + // Skysphere always at center, only use rotation part of modelview matrix + gl_Position = ubo.projection * mat4(mat3(ubo.modelview)) * vec4(inPos.xyz, 1.0); +} diff --git a/tests/glsl/sascha-willems/instancing/instancing.frag b/tests/glsl/sascha-willems/instancing/instancing.frag new file mode 100644 index 000000000..cdec8971b --- /dev/null +++ b/tests/glsl/sascha-willems/instancing/instancing.frag @@ -0,0 +1,27 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2DArray samplerArray; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec3 inUV; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec4 color = texture(samplerArray, inUV) * vec4(inColor, 1.0); + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 diffuse = max(dot(N, L), 0.1) * inColor; + vec3 specular = (dot(N,L) > 0.0) ? pow(max(dot(R, V), 0.0), 16.0) * vec3(0.75) * color.r : vec3(0.0); + outFragColor = vec4(diffuse * color.rgb + specular, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/instancing/instancing.vert b/tests/glsl/sascha-willems/instancing/instancing.vert new file mode 100644 index 000000000..9f7516453 --- /dev/null +++ b/tests/glsl/sascha-willems/instancing/instancing.vert @@ -0,0 +1,85 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +// Vertex attributes +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inColor; + +// Instanced attributes +layout (location = 4) in vec3 instancePos; +layout (location = 5) in vec3 instanceRot; +layout (location = 6) in float instanceScale; +layout (location = 7) in int instanceTexIndex; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 modelview; + vec4 lightPos; + float locSpeed; + float globSpeed; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec3 outUV; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; + +void main() +{ + outColor = inColor; + outUV = vec3(inUV, instanceTexIndex); + + mat3 mx, my, mz; + + // rotate around x + float s = sin(instanceRot.x + ubo.locSpeed); + float c = cos(instanceRot.x + ubo.locSpeed); + + mx[0] = vec3(c, s, 0.0); + mx[1] = vec3(-s, c, 0.0); + mx[2] = vec3(0.0, 0.0, 1.0); + + // rotate around y + s = sin(instanceRot.y + ubo.locSpeed); + c = cos(instanceRot.y + ubo.locSpeed); + + my[0] = vec3(c, 0.0, s); + my[1] = vec3(0.0, 1.0, 0.0); + my[2] = vec3(-s, 0.0, c); + + // rot around z + s = sin(instanceRot.z + ubo.locSpeed); + c = cos(instanceRot.z + ubo.locSpeed); + + mz[0] = vec3(1.0, 0.0, 0.0); + mz[1] = vec3(0.0, c, s); + mz[2] = vec3(0.0, -s, c); + + mat3 rotMat = mz * my * mx; + + mat4 gRotMat; + s = sin(instanceRot.y + ubo.globSpeed); + c = cos(instanceRot.y + ubo.globSpeed); + gRotMat[0] = vec4(c, 0.0, s, 0.0); + gRotMat[1] = vec4(0.0, 1.0, 0.0, 0.0); + gRotMat[2] = vec4(-s, 0.0, c, 0.0); + gRotMat[3] = vec4(0.0, 0.0, 0.0, 1.0); + + vec4 locPos = vec4(inPos.xyz * rotMat, 1.0); + vec4 pos = vec4((locPos.xyz * instanceScale) + instancePos, 1.0); + + gl_Position = ubo.projection * ubo.modelview * gRotMat * pos; + outNormal = mat3(ubo.modelview * gRotMat) * inverse(rotMat) * inNormal; + + pos = ubo.modelview * vec4(inPos.xyz + instancePos, 1.0); + vec3 lPos = mat3(ubo.modelview) * ubo.lightPos.xyz; + outLightVec = lPos - pos.xyz; + outViewVec = -pos.xyz; +} diff --git a/tests/glsl/sascha-willems/instancing/planet.frag b/tests/glsl/sascha-willems/instancing/planet.frag new file mode 100644 index 000000000..eb6d19242 --- /dev/null +++ b/tests/glsl/sascha-willems/instancing/planet.frag @@ -0,0 +1,27 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColorMap; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec4 color = texture(samplerColorMap, inUV) * vec4(inColor, 1.0) * 1.5; + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 diffuse = max(dot(N, L), 0.0) * inColor; + vec3 specular = pow(max(dot(R, V), 0.0), 4.0) * vec3(0.5) * color.r; + outFragColor = vec4(diffuse * color.rgb + specular, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/instancing/planet.vert b/tests/glsl/sascha-willems/instancing/planet.vert new file mode 100644 index 000000000..ad0177933 --- /dev/null +++ b/tests/glsl/sascha-willems/instancing/planet.vert @@ -0,0 +1,36 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 modelview; + vec4 lightPos; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec2 outUV; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; + +void main() +{ + outColor = inColor; + outUV = inUV * vec2(10.0, 6.0); + gl_Position = ubo.projection * ubo.modelview * vec4(inPos.xyz, 1.0); + + vec4 pos = ubo.modelview * vec4(inPos, 1.0); + outNormal = mat3(ubo.modelview) * inNormal; + vec3 lPos = mat3(ubo.modelview) * ubo.lightPos.xyz; + outLightVec = lPos - pos.xyz; + outViewVec = -pos.xyz; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/instancing/starfield.frag b/tests/glsl/sascha-willems/instancing/starfield.frag new file mode 100644 index 000000000..bb4c2823a --- /dev/null +++ b/tests/glsl/sascha-willems/instancing/starfield.frag @@ -0,0 +1,35 @@ +#version 450 +//TEST:COMPARE_GLSL: + +layout (location = 0) in vec3 inUVW; + +layout (location = 0) out vec4 outFragColor; + +#define HASHSCALE3 vec3(443.897, 441.423, 437.195) +#define STARFREQUENCY 0.01 + +// Hash function by Dave Hoskins (https://www.shadertoy.com/view/4djSRW) +float hash33(vec3 p3) +{ + p3 = fract(p3 * HASHSCALE3); + p3 += dot(p3, p3.yxz+vec3(19.19)); + return fract((p3.x + p3.y)*p3.z + (p3.x+p3.z)*p3.y + (p3.y+p3.z)*p3.x); +} + +vec3 starField(vec3 pos) +{ + vec3 color = vec3(0.0); + float threshhold = (1.0 - STARFREQUENCY); + float rnd = hash33(pos); + if (rnd >= threshhold) + { + float starCol = pow((rnd - threshhold) / (1.0 - threshhold), 16.0); + color += vec3(starCol); + } + return color; +} + +void main() +{ + outFragColor = vec4(starField(inUVW), 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/instancing/starfield.vert b/tests/glsl/sascha-willems/instancing/starfield.vert new file mode 100644 index 000000000..82721aefd --- /dev/null +++ b/tests/glsl/sascha-willems/instancing/starfield.vert @@ -0,0 +1,10 @@ +#version 450 +//TEST:COMPARE_GLSL: + +layout (location = 0) out vec3 outUVW; + +void main() +{ + outUVW = vec3((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2, gl_VertexIndex & 2); + gl_Position = vec4(outUVW.st * 2.0f - 1.0f, 0.0f, 1.0f); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/mesh/mesh.frag b/tests/glsl/sascha-willems/mesh/mesh.frag new file mode 100644 index 000000000..01fd2046f --- /dev/null +++ b/tests/glsl/sascha-willems/mesh/mesh.frag @@ -0,0 +1,28 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColorMap; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec4 color = texture(samplerColorMap, inUV) * vec4(inColor, 1.0); + + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 diffuse = max(dot(N, L), 0.0) * inColor; + vec3 specular = pow(max(dot(R, V), 0.0), 16.0) * vec3(0.75); + outFragColor = vec4(diffuse * color.rgb + specular, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/mesh/mesh.vert b/tests/glsl/sascha-willems/mesh/mesh.vert new file mode 100644 index 000000000..d0b3be251 --- /dev/null +++ b/tests/glsl/sascha-willems/mesh/mesh.vert @@ -0,0 +1,42 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + vec4 lightPos; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec2 outUV; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outNormal = inNormal; + outColor = inColor; + outUV = inUV; + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); + + vec4 pos = ubo.model * vec4(inPos, 1.0); + outNormal = mat3(ubo.model) * inNormal; + vec3 lPos = mat3(ubo.model) * ubo.lightPos.xyz; + outLightVec = lPos - pos.xyz; + outViewVec = -pos.xyz; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/multithreading/phong.frag b/tests/glsl/sascha-willems/multithreading/phong.frag new file mode 100644 index 000000000..663fd81b9 --- /dev/null +++ b/tests/glsl/sascha-willems/multithreading/phong.frag @@ -0,0 +1,24 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + + +void main() +{ + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 diffuse = max(dot(N, L), 0.0) * inColor; + vec3 specular = pow(max(dot(R, V), 0.0), 8.0) * vec3(0.75); + outFragColor = vec4(diffuse + specular, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/multithreading/phong.vert b/tests/glsl/sascha-willems/multithreading/phong.vert new file mode 100644 index 000000000..67f803dfd --- /dev/null +++ b/tests/glsl/sascha-willems/multithreading/phong.vert @@ -0,0 +1,43 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec3 inColor; + +layout (std140, push_constant) uniform PushConsts +{ + mat4 mvp; + vec3 color; +} pushConsts; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; + +void main() +{ + outNormal = inNormal; + + if ( (inColor.r == 1.0) && (inColor.g == 0.0) && (inColor.b == 0.0)) + { + outColor = pushConsts.color; + } + else + { + outColor = inColor; + } + + gl_Position = pushConsts.mvp * vec4(inPos.xyz, 1.0); + + vec4 pos = pushConsts.mvp * vec4(inPos, 1.0); + outNormal = mat3(pushConsts.mvp) * inNormal; +// vec3 lPos = ubo.lightPos.xyz; +vec3 lPos = vec3(0.0); + outLightVec = lPos - pos.xyz; + outViewVec = -pos.xyz; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/multithreading/starsphere.frag b/tests/glsl/sascha-willems/multithreading/starsphere.frag new file mode 100644 index 000000000..7136a0499 --- /dev/null +++ b/tests/glsl/sascha-willems/multithreading/starsphere.frag @@ -0,0 +1,43 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inUVW; + +layout (location = 0) out vec4 outFragColor; + +#define HASHSCALE3 vec3(443.897, 441.423, 437.195) +#define STARFREQUENCY 0.01 + +// Hash function by Dave Hoskins (https://www.shadertoy.com/view/4djSRW) +float hash33(vec3 p3) +{ + p3 = fract(p3 * HASHSCALE3); + p3 += dot(p3, p3.yxz+vec3(19.19)); + return fract((p3.x + p3.y)*p3.z + (p3.x+p3.z)*p3.y + (p3.y+p3.z)*p3.x); +} + +vec3 starField(vec3 pos) +{ + vec3 color = vec3(0.0); + float threshhold = (1.0 - STARFREQUENCY); + float rnd = hash33(pos); + if (rnd >= threshhold) + { + float starCol = pow((rnd - threshhold) / (1.0 - threshhold), 16.0); + color += vec3(starCol); + } + return color; +} + +void main() +{ + // Fake atmosphere at the bottom + vec3 atmosphere = clamp(vec3(0.1, 0.15, 0.4) * (inUVW.t - 5.0), 0.0, 1.0); + + vec3 color = starField(inUVW) + atmosphere; + + outFragColor = vec4(color, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/multithreading/starsphere.vert b/tests/glsl/sascha-willems/multithreading/starsphere.vert new file mode 100644 index 000000000..c80106f45 --- /dev/null +++ b/tests/glsl/sascha-willems/multithreading/starsphere.vert @@ -0,0 +1,20 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; + +layout (std140, push_constant) uniform PushConsts +{ + mat4 mvp; +} pushConsts; + +layout (location = 0) out vec3 outUVW; + +void main() +{ + outUVW = inPos; + gl_Position = pushConsts.mvp * vec4(inPos.xyz, 1.0); +} diff --git a/tests/glsl/sascha-willems/occlusionquery/mesh.frag b/tests/glsl/sascha-willems/occlusionquery/mesh.frag new file mode 100644 index 000000000..af644729d --- /dev/null +++ b/tests/glsl/sascha-willems/occlusionquery/mesh.frag @@ -0,0 +1,32 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in float inVisible; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + + +void main() +{ + if (inVisible > 0.0) + { + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 diffuse = max(dot(N, L), 0.0) * inColor; + vec3 specular = pow(max(dot(R, V), 0.0), 8.0) * vec3(0.75); + outFragColor = vec4(diffuse + specular, 1.0); + } + else + { + outFragColor = vec4(vec3(0.1), 1.0); + } +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/occlusionquery/mesh.vert b/tests/glsl/sascha-willems/occlusionquery/mesh.vert new file mode 100644 index 000000000..02a930fe9 --- /dev/null +++ b/tests/glsl/sascha-willems/occlusionquery/mesh.vert @@ -0,0 +1,42 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 modelview; + vec4 lightPos; + float visible; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out float outVisible; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outNormal = inNormal; + outColor = inColor; + outVisible = ubo.visible; + + gl_Position = ubo.projection * ubo.modelview * vec4(inPos.xyz, 1.0); + + vec4 pos = ubo.modelview * vec4(inPos, 1.0); + outNormal = mat3(ubo.modelview) * inNormal; + outLightVec = ubo.lightPos.xyz - pos.xyz; + outViewVec = -pos.xyz; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/occlusionquery/occluder.frag b/tests/glsl/sascha-willems/occlusionquery/occluder.frag new file mode 100644 index 000000000..37b13e5c0 --- /dev/null +++ b/tests/glsl/sascha-willems/occlusionquery/occluder.frag @@ -0,0 +1,14 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inColor; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + outFragColor = vec4(inColor, 0.5); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/occlusionquery/occluder.vert b/tests/glsl/sascha-willems/occlusionquery/occluder.vert new file mode 100644 index 000000000..8adca67d2 --- /dev/null +++ b/tests/glsl/sascha-willems/occlusionquery/occluder.vert @@ -0,0 +1,29 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 modelview; + vec4 lightPos; +} ubo; + +layout (location = 0) out vec3 outColor; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outColor = inColor; + gl_Position = ubo.projection * ubo.modelview * vec4(inPos.xyz, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/occlusionquery/simple.frag b/tests/glsl/sascha-willems/occlusionquery/simple.frag new file mode 100644 index 000000000..108acc1c1 --- /dev/null +++ b/tests/glsl/sascha-willems/occlusionquery/simple.frag @@ -0,0 +1,14 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inColor; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + outFragColor = vec4(1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/occlusionquery/simple.vert b/tests/glsl/sascha-willems/occlusionquery/simple.vert new file mode 100644 index 000000000..b869b7a9c --- /dev/null +++ b/tests/glsl/sascha-willems/occlusionquery/simple.vert @@ -0,0 +1,26 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 modelview; + vec4 lightPos; +} ubo; + +layout (location = 0) out vec3 outColor; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + gl_Position = ubo.projection * ubo.modelview * vec4(inPos.xyz, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/offscreen/mirror.frag b/tests/glsl/sascha-willems/offscreen/mirror.frag new file mode 100644 index 000000000..c8b31bd2b --- /dev/null +++ b/tests/glsl/sascha-willems/offscreen/mirror.frag @@ -0,0 +1,44 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColor; +layout (binding = 2) uniform sampler2D samplerColorMap; + +layout (location = 0) in vec2 inUV; +layout (location = 1) in vec4 inPos; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec4 tmp = vec4(1.0 / inPos.w); + vec4 projCoord = inPos * tmp; + + // Scale and bias + projCoord += vec4(1.0); + projCoord *= vec4(0.5); + + // Slow single pass blur + // For demonstration purposes only + const float blurSize = 1.0 / 512.0; + + vec4 color = texture(samplerColorMap, inUV); + outFragColor = color * 0.25; + + if (gl_FrontFacing) + { + // Only render mirrored scene on front facing (upper) side of mirror surface + vec4 reflection = vec4(0.0); + for (int x = -3; x <= 3; x++) + { + for (int y = -3; y <= 3; y++) + { + reflection += texture(samplerColor, vec2(projCoord.s + x * blurSize, projCoord.t + y * blurSize)) / 49.0; + } + } + outFragColor += reflection * 1.5 * (color.r); + }; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/offscreen/mirror.vert b/tests/glsl/sascha-willems/offscreen/mirror.vert new file mode 100644 index 000000000..a4c0cb7f5 --- /dev/null +++ b/tests/glsl/sascha-willems/offscreen/mirror.vert @@ -0,0 +1,29 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; +} ubo; + +layout (location = 0) out vec2 outUV; +layout (location = 1) out vec4 outPos; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = inUV; + outPos = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); + gl_Position = outPos; +} diff --git a/tests/glsl/sascha-willems/offscreen/phong.frag b/tests/glsl/sascha-willems/offscreen/phong.frag new file mode 100644 index 000000000..43fc662a9 --- /dev/null +++ b/tests/glsl/sascha-willems/offscreen/phong.frag @@ -0,0 +1,30 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec3 inEyePos; +layout (location = 3) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec3 Eye = normalize(-inEyePos); + vec3 Reflected = normalize(reflect(-inLightVec, inNormal)); + + vec4 IAmbient = vec4(0.1, 0.1, 0.1, 1.0); + vec4 IDiffuse = vec4(max(dot(inNormal, inLightVec), 0.0)); + float specular = 0.75; + vec4 ISpecular = vec4(0.0); + if (dot(inEyePos, inNormal) < 0.0) + { + ISpecular = vec4(0.5, 0.5, 0.5, 1.0) * pow(max(dot(Reflected, Eye), 0.0), 16.0) * specular; + } + + outFragColor = vec4((IAmbient + IDiffuse) * vec4(inColor, 1.0) + ISpecular); + +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/offscreen/phong.vert b/tests/glsl/sascha-willems/offscreen/phong.vert new file mode 100644 index 000000000..5bef0fa1e --- /dev/null +++ b/tests/glsl/sascha-willems/offscreen/phong.vert @@ -0,0 +1,40 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 2) in vec3 inColor; +layout (location = 3) in vec3 inNormal; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + vec4 lightPos; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec3 outEyePos; +layout (location = 3) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; + float gl_ClipDistance[]; +}; + +void main() +{ + outNormal = inNormal; + outColor = inColor; + gl_Position = ubo.projection * ubo.model * inPos; + outEyePos = vec3(ubo.model * inPos); + outLightVec = normalize(ubo.lightPos.xyz - outEyePos); + + // Clip against reflection plane + vec4 clipPlane = vec4(0.0, -1.0, 0.0, 1.5); + gl_ClipDistance[0] = dot(inPos, clipPlane); +} diff --git a/tests/glsl/sascha-willems/offscreen/quad.frag b/tests/glsl/sascha-willems/offscreen/quad.frag new file mode 100644 index 000000000..6d54f2f33 --- /dev/null +++ b/tests/glsl/sascha-willems/offscreen/quad.frag @@ -0,0 +1,16 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColor; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + outFragColor = texture(samplerColor, inUV); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/offscreen/quad.vert b/tests/glsl/sascha-willems/offscreen/quad.vert new file mode 100644 index 000000000..c1ad3e070 --- /dev/null +++ b/tests/glsl/sascha-willems/offscreen/quad.vert @@ -0,0 +1,27 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; +} ubo; + +layout (location = 0) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = inUV; + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); +} diff --git a/tests/glsl/sascha-willems/parallax/parallax.frag b/tests/glsl/sascha-willems/parallax/parallax.frag new file mode 100644 index 000000000..79dcab907 --- /dev/null +++ b/tests/glsl/sascha-willems/parallax/parallax.frag @@ -0,0 +1,144 @@ +//TEST:COMPARE_GLSL: +#version 450 + +layout (binding = 1) uniform sampler2D sColorMap; +layout (binding = 2) uniform sampler2D sNormalHeightMap; + +layout (binding = 3) uniform UBO +{ + float heightScale; + float parallaxBias; + float numLayers; + int mappingMode; +} ubo; + +layout (location = 0) in vec2 inUV; +layout (location = 1) in vec3 inTangentLightPos; +layout (location = 2) in vec3 inTangentViewPos; +layout (location = 3) in vec3 inTangentFragPos; + +layout (location = 0) out vec4 outColor; + +vec2 parallax_uv(vec2 uv, vec3 view_dir, int type) +{ + if (type == 2) { + // Parallax mapping + float depth = 1.0 - texture(sNormalHeightMap, uv).a; + vec2 p = view_dir.xy * (depth * (ubo.heightScale * 0.5) + ubo.parallaxBias) / view_dir.z; + return uv - p; + } else { + float layer_depth = 1.0 / ubo.numLayers; + float cur_layer_depth = 0.0; + vec2 delta_uv = view_dir.xy * ubo.heightScale / (view_dir.z * ubo.numLayers); + vec2 cur_uv = uv; + + float depth_from_tex = 1.0 - texture(sNormalHeightMap, cur_uv).a; + + for (int i = 0; i < 32; i++) { + cur_layer_depth += layer_depth; + cur_uv -= delta_uv; + depth_from_tex = 1.0 - texture(sNormalHeightMap, cur_uv).a; + if (depth_from_tex < cur_layer_depth) { + break; + } + } + + if (type == 3) { + // Steep parallax mapping + return cur_uv; + } else { + // Parallax occlusion mapping + vec2 prev_uv = cur_uv + delta_uv; + float next = depth_from_tex - cur_layer_depth; + float prev = 1.0 - texture(sNormalHeightMap, prev_uv).a - cur_layer_depth + layer_depth; + float weight = next / (next - prev); + return mix(cur_uv, prev_uv, weight); + } + } +} + +vec2 parallaxMapping(vec2 uv, vec3 viewDir) +{ + float height = 1.0 - texture(sNormalHeightMap, uv).a; + vec2 p = viewDir.xy * (height * (ubo.heightScale * 0.5) + ubo.parallaxBias) / viewDir.z; + return uv - p; +} + +vec2 steepParallaxMapping(vec2 uv, vec3 viewDir) +{ + float layerDepth = 1.0 / ubo.numLayers; + float currLayerDepth = 0.0; + vec2 deltaUV = viewDir.xy * ubo.heightScale / (viewDir.z * ubo.numLayers); + vec2 currUV = uv; + float height = 1.0 - texture(sNormalHeightMap, currUV).a; + for (int i = 0; i < ubo.numLayers; i++) { + currLayerDepth += layerDepth; + currUV -= deltaUV; + height = 1.0 - texture(sNormalHeightMap, currUV).a; + if (height < currLayerDepth) { + break; + } + } + return currUV; +} + +vec2 parallaxOcclusionMapping(vec2 uv, vec3 viewDir) +{ + float layerDepth = 1.0 / ubo.numLayers; + float currLayerDepth = 0.0; + vec2 deltaUV = viewDir.xy * ubo.heightScale / (viewDir.z * ubo.numLayers); + vec2 currUV = uv; + float height = 1.0 - texture(sNormalHeightMap, currUV).a; + for (int i = 0; i < ubo.numLayers; i++) { + currLayerDepth += layerDepth; + currUV -= deltaUV; + height = 1.0 - texture(sNormalHeightMap, currUV).a; + if (height < currLayerDepth) { + break; + } + } + vec2 prevUV = currUV + deltaUV; + float nextDepth = height - currLayerDepth; + float prevDepth = 1.0 - texture(sNormalHeightMap, prevUV).a - currLayerDepth + layerDepth; + return mix(currUV, prevUV, nextDepth / (nextDepth - prevDepth)); +} + +void main(void) +{ + vec3 V = normalize(inTangentViewPos - inTangentFragPos); + vec2 uv = inUV; + + if (ubo.mappingMode == 0) { + // Color only + outColor = texture(sColorMap, inUV); + } else { + switch(ubo.mappingMode) { + case 2: + uv = parallaxMapping(inUV, V); + break; + case 3: + uv = steepParallaxMapping(inUV, V); + break; + case 4: + uv = parallaxOcclusionMapping(inUV, V); + break; + } + + // Discard fragments at texture border + if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { + discard; + } + + vec3 N = normalize(texture(sNormalHeightMap, uv).rgb * 2.0 - 1.0); + vec3 L = normalize(inTangentLightPos - inTangentFragPos); + vec3 R = reflect(-L, N); + vec3 H = normalize(L + V); + + vec3 color = texture(sColorMap, uv).rgb; + vec3 ambient = 0.2 * color; + vec3 diffuse = max(dot(L, N), 0.0) * color; + vec3 specular = vec3(0.15) * pow(max(dot(N, H), 0.0), 32.0); + + outColor = vec4(ambient + diffuse + specular, 1.0f); + } +} diff --git a/tests/glsl/sascha-willems/parallax/parallax.vert b/tests/glsl/sascha-willems/parallax/parallax.vert new file mode 100644 index 000000000..3032d9c6e --- /dev/null +++ b/tests/glsl/sascha-willems/parallax/parallax.vert @@ -0,0 +1,38 @@ +//TEST:COMPARE_GLSL: +#version 450 + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inNormal; +layout (location = 3) in vec3 inTangent; +layout (location = 4) in vec3 inBiTangent; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 view; + mat4 model; + vec4 lightPos; + vec4 cameraPos; +} ubo; + +layout (location = 0) out vec2 outUV; +layout (location = 1) out vec3 outTangentLightPos; +layout (location = 2) out vec3 outTangentViewPos; +layout (location = 3) out vec3 outTangentFragPos; + +void main(void) +{ + gl_Position = ubo.projection * ubo.view * ubo.model * vec4(inPos, 1.0f); + outTangentFragPos = vec3(ubo.model * vec4(inPos, 1.0)); + outUV = inUV; + + vec3 T = normalize(mat3(ubo.model) * inTangent); + vec3 B = normalize(mat3(ubo.model) * inBiTangent); + vec3 N = normalize(mat3(ubo.model) * inNormal); + mat3 TBN = transpose(mat3(T, B, N)); + + outTangentLightPos = TBN * ubo.lightPos.xyz; + outTangentViewPos = TBN * ubo.cameraPos.xyz; + outTangentFragPos = TBN * outTangentFragPos; +} diff --git a/tests/glsl/sascha-willems/particlefire/normalmap.frag b/tests/glsl/sascha-willems/particlefire/normalmap.frag new file mode 100644 index 000000000..9f3af4cf1 --- /dev/null +++ b/tests/glsl/sascha-willems/particlefire/normalmap.frag @@ -0,0 +1,45 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D sColorMap; +layout (binding = 2) uniform sampler2D sNormalHeightMap; + +#define lightRadius 45.0 + +layout (location = 0) in vec2 inUV; +layout (location = 1) in vec3 inLightVec; +layout (location = 2) in vec3 inLightVecB; +layout (location = 5) in vec3 inLightDir; +layout (location = 6) in vec3 inViewVec; + +layout (location = 0) out vec4 outFragColor; + +void main(void) +{ + vec3 specularColor = vec3(0.85, 0.5, 0.0); + + float invRadius = 1.0/lightRadius; + float ambient = 0.25; + + vec3 rgb, normal; + + rgb = texture(sColorMap, inUV).rgb; + normal = normalize((texture(sNormalHeightMap, inUV).rgb - 0.5) * 2.0); + + float distSqr = dot(inLightVecB, inLightVecB); + vec3 lVec = inLightVecB * inversesqrt(distSqr); + + float atten = max(clamp(1.0 - invRadius * sqrt(distSqr), 0.0, 1.0), ambient); + float diffuse = clamp(dot(lVec, normal), 0.0, 1.0); + + vec3 light = normalize(-inLightVec); + vec3 view = normalize(inViewVec); + vec3 reflectDir = reflect(-light, normal); + + float specular = pow(max(dot(view, reflectDir), 0.0), 4.0); + + outFragColor = vec4((rgb * atten + (diffuse * rgb + 0.5 * specular * specularColor.rgb)) * atten, 1.0); +} diff --git a/tests/glsl/sascha-willems/particlefire/normalmap.vert b/tests/glsl/sascha-willems/particlefire/normalmap.vert new file mode 100644 index 000000000..a93c16b00 --- /dev/null +++ b/tests/glsl/sascha-willems/particlefire/normalmap.vert @@ -0,0 +1,60 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inNormal; +layout (location = 3) in vec3 inTangent; +layout (location = 4) in vec3 inBiTangent; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + mat4 normal; + vec4 lightPos; + vec4 cameraPos; +} ubo; + +out gl_PerVertex +{ + vec4 gl_Position; + float gl_PointSize; +}; + +layout (location = 0) out vec2 outUV; +layout (location = 1) out vec3 outLightVec; +layout (location = 2) out vec3 outLightVecB; +layout (location = 5) out vec3 outLightDir; +layout (location = 6) out vec3 outViewVec; + +void main(void) +{ + vec3 vertexPosition = vec3(ubo.model * vec4(inPos, 1.0)); + outLightDir = normalize(ubo.lightPos.xyz - vertexPosition); + + // Setup (t)angent-(b)inormal-(n)ormal matrix for converting + // object coordinates into tangent space + mat3 tbnMatrix; + tbnMatrix[0] = mat3(ubo.normal) * inTangent; + tbnMatrix[1] = mat3(ubo.normal) * inBiTangent; + tbnMatrix[2] = mat3(ubo.normal) * inNormal; + + outLightVec.xyz = vec3(ubo.lightPos.xyz - vertexPosition.xyz) * tbnMatrix; + + vec3 lightDist = ubo.lightPos.xyz - inPos.xyz; + outLightVecB.x = dot(inTangent.xyz, lightDist); + outLightVecB.y = dot(inBiTangent.xyz, lightDist); + outLightVecB.z = dot(inNormal, lightDist); + + outViewVec.x = dot(inTangent, inPos.xyz); + outViewVec.y = dot(inBiTangent, inPos.xyz); + outViewVec.z = dot(inNormal, inPos.xyz); + + outUV = inUV; + + gl_Position = ubo.projection * ubo.model * vec4(inPos, 1.0); +} diff --git a/tests/glsl/sascha-willems/particlefire/particle.frag b/tests/glsl/sascha-willems/particlefire/particle.frag new file mode 100644 index 000000000..104fe406c --- /dev/null +++ b/tests/glsl/sascha-willems/particlefire/particle.frag @@ -0,0 +1,47 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerSmoke; +layout (binding = 2) uniform sampler2D samplerFire; + +layout (location = 0) in vec4 inColor; +layout (location = 1) in float inAlpha; +layout (location = 2) in flat int inType; +layout (location = 3) in float inRotation; + + +layout (location = 0) out vec4 outFragColor; + +void main () +{ + vec4 color; + float alpha = (inAlpha <= 1.0) ? inAlpha : 2.0 - inAlpha; + + // Rotate texture coordinates + // Rotate UV + float rotCenter = 0.5; + float rotCos = cos(inRotation); + float rotSin = sin(inRotation); + vec2 rotUV = vec2( + rotCos * (gl_PointCoord.x - rotCenter) + rotSin * (gl_PointCoord.y - rotCenter) + rotCenter, + rotCos * (gl_PointCoord.y - rotCenter) - rotSin * (gl_PointCoord.x - rotCenter) + rotCenter); + + + if (inType == 0) + { + // Flame + color = texture(samplerFire, rotUV); + outFragColor.a = 0.0; + } + else + { + // Smoke + color = texture(samplerSmoke, rotUV); + outFragColor.a = color.a * alpha; + } + + outFragColor.rgb = color.rgb * inColor.rgb * alpha; +} diff --git a/tests/glsl/sascha-willems/particlefire/particle.vert b/tests/glsl/sascha-willems/particlefire/particle.vert new file mode 100644 index 000000000..a5d3c561b --- /dev/null +++ b/tests/glsl/sascha-willems/particlefire/particle.vert @@ -0,0 +1,50 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec4 inColor; +layout (location = 2) in float inAlpha; +layout (location = 3) in float inSize; +layout (location = 4) in float inRotation; +layout (location = 5) in int inType; + +layout (location = 0) out vec4 outColor; +layout (location = 1) out float outAlpha; +layout (location = 2) out flat int outType; +layout (location = 3) out float outRotation; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 modelview; + vec2 viewportDim; + float pointSize; +} ubo; + +out gl_PerVertex +{ + vec4 gl_Position; + float gl_PointSize; +}; + +void main () +{ + outColor = inColor; + outAlpha = inAlpha; + outType = inType; + outRotation = inRotation; + + gl_Position = ubo.projection * ubo.modelview * vec4(inPos.xyz, 1.0); + + // Base size of the point sprites + float spriteSize = 8.0 * inSize; + + // Scale particle size depending on camera projection + vec4 eyePos = ubo.modelview * vec4(inPos.xyz, 1.0); + vec4 projectedCorner = ubo.projection * vec4(0.5 * spriteSize, 0.5 * spriteSize, eyePos.z, eyePos.w); + gl_PointSize = ubo.viewportDim.x * projectedCorner.x / projectedCorner.w; + +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/pbrbasic/pbr.frag b/tests/glsl/sascha-willems/pbrbasic/pbr.frag new file mode 100644 index 000000000..06a69e1e9 --- /dev/null +++ b/tests/glsl/sascha-willems/pbrbasic/pbr.frag @@ -0,0 +1,128 @@ +#version 450 +//TEST:COMPARE_GLSL: + +layout (location = 0) in vec3 inWorldPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + mat4 view; + vec3 camPos; +} ubo; + +layout (binding = 1) uniform UBOShared { + vec4 lights[4]; +} uboParams; + +layout (location = 0) out vec4 outColor; + +layout(push_constant) uniform PushConsts { + layout(offset = 12) float roughness; + layout(offset = 16) float metallic; + layout(offset = 20) float r; + layout(offset = 24) float g; + layout(offset = 28) float b; +} material; + +const float PI = 3.14159265359; + +//#define ROUGHNESS_PATTERN 1 + +vec3 materialcolor() +{ + return vec3(material.r, material.g, material.b); +} + +// Normal Distribution function -------------------------------------- +float D_GGX(float dotNH, float roughness) +{ + float alpha = roughness * roughness; + float alpha2 = alpha * alpha; + float denom = dotNH * dotNH * (alpha2 - 1.0) + 1.0; + return (alpha2)/(PI * denom*denom); +} + +// Geometric Shadowing function -------------------------------------- +float G_SchlicksmithGGX(float dotNL, float dotNV, float roughness) +{ + float r = (roughness + 1.0); + float k = (r*r) / 8.0; + float GL = dotNL / (dotNL * (1.0 - k) + k); + float GV = dotNV / (dotNV * (1.0 - k) + k); + return GL * GV; +} + +// Fresnel function ---------------------------------------------------- +vec3 F_Schlick(float cosTheta, float metallic) +{ + vec3 F0 = mix(vec3(0.04), materialcolor(), metallic); // * material.specular + vec3 F = F0 + (1.0 - F0) * pow(1.0 - cosTheta, 5.0); + return F; +} + +// Specular BRDF composition -------------------------------------------- + +vec3 BRDF(vec3 L, vec3 V, vec3 N, float metallic, float roughness) +{ + // Precalculate vectors and dot products + vec3 H = normalize (V + L); + float dotNV = clamp(dot(N, V), 0.0, 1.0); + float dotNL = clamp(dot(N, L), 0.0, 1.0); + float dotLH = clamp(dot(L, H), 0.0, 1.0); + float dotNH = clamp(dot(N, H), 0.0, 1.0); + + // Light color fixed + vec3 lightColor = vec3(1.0); + + vec3 color = vec3(0.0); + + if (dotNL > 0.0) + { + float rroughness = max(0.05, roughness); + // D = Normal distribution (Distribution of the microfacets) + float D = D_GGX(dotNH, roughness); + // G = Geometric shadowing term (Microfacets shadowing) + float G = G_SchlicksmithGGX(dotNL, dotNV, roughness); + // F = Fresnel factor (Reflectance depending on angle of incidence) + vec3 F = F_Schlick(dotNV, metallic); + + vec3 spec = D * F * G / (4.0 * dotNL * dotNV); + + color += spec * dotNL * lightColor; + } + + return color; +} + +// ---------------------------------------------------------------------------- +void main() +{ + vec3 N = normalize(inNormal); + vec3 V = normalize(ubo.camPos - inWorldPos); + + float roughness = material.roughness; + + // Add striped pattern to roughness based on vertex position +#ifdef ROUGHNESS_PATTERN + roughness = max(roughness, step(fract(inWorldPos.y * 2.02), 0.5)); +#endif + + // Specular contribution + vec3 Lo = vec3(0.0); + for (int i = 0; i < uboParams.lights.length(); i++) { + vec3 L = normalize(uboParams.lights[i].xyz - inWorldPos); + Lo += BRDF(L, V, N, material.metallic, roughness); + }; + + // Combine with ambient + vec3 color = materialcolor() * 0.02; + color += Lo; + + // Gamma correct + color = pow(color, vec3(0.4545)); + + outColor = vec4(color, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/pbrbasic/pbr.vert b/tests/glsl/sascha-willems/pbrbasic/pbr.vert new file mode 100644 index 000000000..9a85b892a --- /dev/null +++ b/tests/glsl/sascha-willems/pbrbasic/pbr.vert @@ -0,0 +1,39 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + mat4 view; + vec3 camPos; +} ubo; + +layout (location = 0) out vec3 outWorldPos; +layout (location = 1) out vec3 outNormal; +layout (location = 2) out vec2 outUV; + +layout(push_constant) uniform PushConsts { + vec3 objPos; +} pushConsts; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + vec3 locPos = vec3(ubo.model * vec4(inPos, 1.0)); + outWorldPos = locPos + pushConsts.objPos; + outNormal = mat3(ubo.model) * inNormal; + outUV = inUV; + gl_Position = ubo.projection * ubo.view * vec4(outWorldPos, 1.0); +} diff --git a/tests/glsl/sascha-willems/pbribl/filtercube.vert b/tests/glsl/sascha-willems/pbribl/filtercube.vert new file mode 100644 index 000000000..07f02c8b5 --- /dev/null +++ b/tests/glsl/sascha-willems/pbribl/filtercube.vert @@ -0,0 +1,20 @@ +#version 450 +//TEST:COMPARE_GLSL: + +layout (location = 0) in vec3 inPos; + +layout(push_constant) uniform PushConsts { + layout (offset = 0) mat4 mvp; +} pushConsts; + +layout (location = 0) out vec3 outUVW; + +out gl_PerVertex { + vec4 gl_Position; +}; + +void main() +{ + outUVW = inPos; + gl_Position = pushConsts.mvp * vec4(inPos.xyz, 1.0); +} diff --git a/tests/glsl/sascha-willems/pbribl/genbrdflut.frag b/tests/glsl/sascha-willems/pbribl/genbrdflut.frag new file mode 100644 index 000000000..25f00af1f --- /dev/null +++ b/tests/glsl/sascha-willems/pbribl/genbrdflut.frag @@ -0,0 +1,91 @@ +#version 450 +//TEST:COMPARE_GLSL: + +layout (location = 0) in vec2 inUV; +layout (location = 0) out vec4 outColor; +layout (constant_id = 0) const uint NUM_SAMPLES = 1024u; + +const float PI = 3.1415926536; + +// Based omn http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/ +float random(vec2 co) +{ + float a = 12.9898; + float b = 78.233; + float c = 43758.5453; + float dt= dot(co.xy ,vec2(a,b)); + float sn= mod(dt,3.14); + return fract(sin(sn) * c); +} + +vec2 hammersley2d(uint i, uint N) +{ + // Radical inverse based on http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html + uint bits = (i << 16u) | (i >> 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); + float rdi = float(bits) * 2.3283064365386963e-10; + return vec2(float(i) /float(N), rdi); +} + +// Based on http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_slides.pdf +vec3 importanceSample_GGX(vec2 Xi, float roughness, vec3 normal) +{ + // Maps a 2D point to a hemisphere with spread based on roughness + float alpha = roughness * roughness; + float phi = 2.0 * PI * Xi.x + random(normal.xz) * 0.1; + float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (alpha*alpha - 1.0) * Xi.y)); + float sinTheta = sqrt(1.0 - cosTheta * cosTheta); + vec3 H = vec3(sinTheta * cos(phi), sinTheta * sin(phi), cosTheta); + + // Tangent space + vec3 up = abs(normal.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); + vec3 tangentX = normalize(cross(up, normal)); + vec3 tangentY = normalize(cross(normal, tangentX)); + + // Convert to world Space + return normalize(tangentX * H.x + tangentY * H.y + normal * H.z); +} + +// Geometric Shadowing function +float G_SchlicksmithGGX(float dotNL, float dotNV, float roughness) +{ + float k = (roughness * roughness) / 2.0; + float GL = dotNL / (dotNL * (1.0 - k) + k); + float GV = dotNV / (dotNV * (1.0 - k) + k); + return GL * GV; +} + +vec2 BRDF(float NoV, float roughness) +{ + // Normal always points along z-axis for the 2D lookup + const vec3 N = vec3(0.0, 0.0, 1.0); + vec3 V = vec3(sqrt(1.0 - NoV*NoV), 0.0, NoV); + + vec2 LUT = vec2(0.0); + for(uint i = 0u; i < NUM_SAMPLES; i++) { + vec2 Xi = hammersley2d(i, NUM_SAMPLES); + vec3 H = importanceSample_GGX(Xi, roughness, N); + vec3 L = 2.0 * dot(V, H) * H - V; + + float dotNL = max(dot(N, L), 0.0); + float dotNV = max(dot(N, V), 0.0); + float dotVH = max(dot(V, H), 0.0); + float dotNH = max(dot(H, N), 0.0); + + if (dotNL > 0.0) { + float G = G_SchlicksmithGGX(dotNL, dotNV, roughness); + float G_Vis = (G * dotVH) / (dotNH * dotNV); + float Fc = pow(1.0 - dotVH, 5.0); + LUT += vec2((1.0 - Fc) * G_Vis, Fc * G_Vis); + } + } + return LUT / float(NUM_SAMPLES); +} + +void main() +{ + outColor = vec4(BRDF(inUV.s, 1.0-inUV.t), 0.0, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/pbribl/genbrdflut.vert b/tests/glsl/sascha-willems/pbribl/genbrdflut.vert new file mode 100644 index 000000000..8576b78b4 --- /dev/null +++ b/tests/glsl/sascha-willems/pbribl/genbrdflut.vert @@ -0,0 +1,10 @@ +#version 450 +//TEST:COMPARE_GLSL: + +layout (location = 0) out vec2 outUV; + +void main() +{ + outUV = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); + gl_Position = vec4(outUV * 2.0f - 1.0f, 0.0f, 1.0f); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/pbribl/irradiancecube.frag b/tests/glsl/sascha-willems/pbribl/irradiancecube.frag new file mode 100644 index 000000000..926c68c4c --- /dev/null +++ b/tests/glsl/sascha-willems/pbribl/irradiancecube.frag @@ -0,0 +1,38 @@ +// Generates an irradiance cube from an environment map using convolution + +#version 450 +//TEST:COMPARE_GLSL: + +layout (location = 0) in vec3 inPos; +layout (location = 0) out vec4 outColor; +layout (binding = 0) uniform samplerCube samplerEnv; + +layout(push_constant) uniform PushConsts { + layout (offset = 64) float deltaPhi; + layout (offset = 68) float deltaTheta; +} consts; + +#define PI 3.1415926535897932384626433832795 + +void main() +{ + vec3 N = normalize(inPos); + vec3 up = vec3(0.0, 1.0, 0.0); + vec3 right = normalize(cross(up, N)); + up = cross(N, right); + + const float TWO_PI = PI * 2.0; + const float HALF_PI = PI * 0.5; + + vec3 color = vec3(0.0); + uint sampleCount = 0u; + for (float phi = 0.0; phi < TWO_PI; phi += consts.deltaPhi) { + for (float theta = 0.0; theta < HALF_PI; theta += consts.deltaTheta) { + vec3 tempVec = cos(phi) * right + sin(phi) * up; + vec3 sampleVector = cos(theta) * N + sin(theta) * tempVec; + color += texture(samplerEnv, sampleVector).rgb * cos(theta) * sin(theta); + sampleCount++; + } + } + outColor = vec4(PI * color / float(sampleCount), 1.0); +} diff --git a/tests/glsl/sascha-willems/pbribl/pbribl.frag b/tests/glsl/sascha-willems/pbribl/pbribl.frag new file mode 100644 index 000000000..d04c46256 --- /dev/null +++ b/tests/glsl/sascha-willems/pbribl/pbribl.frag @@ -0,0 +1,163 @@ +#version 450 +//TEST:COMPARE_GLSL: + +layout (location = 0) in vec3 inWorldPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; + +layout (binding = 0) uniform UBO { + mat4 projection; + mat4 model; + mat4 view; + vec3 camPos; +} ubo; + +layout (binding = 1) uniform UBOParams { + vec4 lights[4]; + float exposure; + float gamma; +} uboParams; + +layout(push_constant) uniform PushConsts { + layout(offset = 12) float roughness; + layout(offset = 16) float metallic; + layout(offset = 20) float specular; + layout(offset = 24) float r; + layout(offset = 28) float g; + layout(offset = 32) float b; +} material; + +layout (binding = 2) uniform samplerCube samplerIrradiance; +layout (binding = 3) uniform sampler2D samplerBRDFLUT; +layout (binding = 4) uniform samplerCube prefilteredMap; + +layout (location = 0) out vec4 outColor; + +#define PI 3.1415926535897932384626433832795 +#define ALBEDO vec3(material.r, material.g, material.b) + +// From http://filmicgames.com/archives/75 +vec3 Uncharted2Tonemap(vec3 x) +{ + float A = 0.15; + float B = 0.50; + float C = 0.10; + float D = 0.20; + float E = 0.02; + float F = 0.30; + return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F; +} + +// Normal Distribution function -------------------------------------- +float D_GGX(float dotNH, float roughness) +{ + float alpha = roughness * roughness; + float alpha2 = alpha * alpha; + float denom = dotNH * dotNH * (alpha2 - 1.0) + 1.0; + return (alpha2)/(PI * denom*denom); +} + +// Geometric Shadowing function -------------------------------------- +float G_SchlicksmithGGX(float dotNL, float dotNV, float roughness) +{ + float r = (roughness + 1.0); + float k = (r*r) / 8.0; + float GL = dotNL / (dotNL * (1.0 - k) + k); + float GV = dotNV / (dotNV * (1.0 - k) + k); + return GL * GV; +} + +// Fresnel function ---------------------------------------------------- +vec3 F_Schlick(float cosTheta, vec3 F0) +{ + return F0 + (1.0 - F0) * pow(1.0 - cosTheta, 5.0); +} +vec3 F_SchlickR(float cosTheta, vec3 F0, float roughness) +{ + return F0 + (max(vec3(1.0 - roughness), F0) - F0) * pow(1.0 - cosTheta, 5.0); +} + +vec3 prefilteredReflection(vec3 R, float roughness) +{ + const float MAX_REFLECTION_LOD = 9.0; // todo: param/const + float lod = roughness * MAX_REFLECTION_LOD; + float lodf = floor(lod); + float lodc = ceil(lod); + vec3 a = textureLod(prefilteredMap, R, lodf).rgb; + vec3 b = textureLod(prefilteredMap, R, lodc).rgb; + return mix(a, b, lod - lodf); +} + +vec3 specularContribution(vec3 L, vec3 V, vec3 N, vec3 F0, float metallic, float roughness) +{ + // Precalculate vectors and dot products + vec3 H = normalize (V + L); + float dotNH = clamp(dot(N, H), 0.0, 1.0); + float dotNV = clamp(dot(N, V), 0.0, 1.0); + float dotNL = clamp(dot(N, L), 0.0, 1.0); + + // Light color fixed + vec3 lightColor = vec3(1.0); + + vec3 color = vec3(0.0); + + if (dotNL > 0.0) { + // D = Normal distribution (Distribution of the microfacets) + float D = D_GGX(dotNH, roughness); + // G = Geometric shadowing term (Microfacets shadowing) + float G = G_SchlicksmithGGX(dotNL, dotNV, roughness); + // F = Fresnel factor (Reflectance depending on angle of incidence) + vec3 F = F_Schlick(dotNV, F0); + vec3 spec = D * F * G / (4.0 * dotNL * dotNV + 0.001); + vec3 kD = (vec3(1.0) - F) * (1.0 - metallic); + color += (kD * ALBEDO / PI + spec) * dotNL; + } + + return color; +} + +void main() +{ + vec3 N = normalize(inNormal); + vec3 V = normalize(ubo.camPos - inWorldPos); + vec3 R = reflect(-V, N); + + float metallic = material.metallic; + float roughness = material.roughness; + + vec3 F0 = vec3(0.04); + F0 = mix(F0, ALBEDO, metallic); + + vec3 Lo = vec3(0.0); + for(int i = 0; i < uboParams.lights[i].length(); i++) { + vec3 L = normalize(uboParams.lights[i].xyz - inWorldPos); + Lo += specularContribution(L, V, N, F0, metallic, roughness); + } + + vec2 brdf = texture(samplerBRDFLUT, vec2(max(dot(N, V), 0.0), roughness)).rg; + vec3 reflection = prefilteredReflection(R, roughness).rgb; + vec3 irradiance = texture(samplerIrradiance, N).rgb; + + // Diffuse based on irradiance + vec3 diffuse = irradiance * ALBEDO; + + vec3 F = F_SchlickR(max(dot(N, V), 0.0), F0, roughness); + + // Specular reflectance + vec3 specular = reflection * (F * brdf.x + brdf.y); + + // Ambient part + vec3 kD = 1.0 - F; + kD *= 1.0 - metallic; + vec3 ambient = (kD * diffuse + specular); + + vec3 color = ambient + Lo; + + // Tone mapping + color = Uncharted2Tonemap(color * uboParams.exposure); + color = color * (1.0f / Uncharted2Tonemap(vec3(11.2f))); + // Gamma correction + color = pow(color, vec3(1.0f / uboParams.gamma)); + + outColor = vec4(color, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/pbribl/pbribl.vert b/tests/glsl/sascha-willems/pbribl/pbribl.vert new file mode 100644 index 000000000..c8d65cc32 --- /dev/null +++ b/tests/glsl/sascha-willems/pbribl/pbribl.vert @@ -0,0 +1,40 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + mat4 view; + vec3 camPos; +} ubo; + +layout (location = 0) out vec3 outWorldPos; +layout (location = 1) out vec3 outNormal; +layout (location = 2) out vec2 outUV; + +layout(push_constant) uniform PushConsts { + vec3 objPos; +} pushConsts; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + vec3 locPos = vec3(ubo.model * vec4(inPos, 1.0)); + outWorldPos = locPos + pushConsts.objPos; + outNormal = mat3(ubo.model) * inNormal; + outUV = inUV; + outUV.t = 1.0 - inUV.t; + gl_Position = ubo.projection * ubo.view * vec4(outWorldPos, 1.0); +} diff --git a/tests/glsl/sascha-willems/pbribl/prefilterenvmap.frag b/tests/glsl/sascha-willems/pbribl/prefilterenvmap.frag new file mode 100644 index 000000000..d5231a2d1 --- /dev/null +++ b/tests/glsl/sascha-willems/pbribl/prefilterenvmap.frag @@ -0,0 +1,106 @@ +#version 450 +//TEST:COMPARE_GLSL: + +layout (location = 0) in vec3 inPos; +layout (location = 0) out vec4 outColor; + +layout (binding = 0) uniform samplerCube samplerEnv; + +layout(push_constant) uniform PushConsts { + layout (offset = 64) float roughness; + layout (offset = 68) uint numSamples; +} consts; + +const float PI = 3.1415926536; + +// Based omn http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/ +float random(vec2 co) +{ + float a = 12.9898; + float b = 78.233; + float c = 43758.5453; + float dt= dot(co.xy ,vec2(a,b)); + float sn= mod(dt,3.14); + return fract(sin(sn) * c); +} + +vec2 hammersley2d(uint i, uint N) +{ + // Radical inverse based on http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html + uint bits = (i << 16u) | (i >> 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); + float rdi = float(bits) * 2.3283064365386963e-10; + return vec2(float(i) /float(N), rdi); +} + +// Based on http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_slides.pdf +vec3 importanceSample_GGX(vec2 Xi, float roughness, vec3 normal) +{ + // Maps a 2D point to a hemisphere with spread based on roughness + float alpha = roughness * roughness; + float phi = 2.0 * PI * Xi.x + random(normal.xz) * 0.1; + float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (alpha*alpha - 1.0) * Xi.y)); + float sinTheta = sqrt(1.0 - cosTheta * cosTheta); + vec3 H = vec3(sinTheta * cos(phi), sinTheta * sin(phi), cosTheta); + + // Tangent space + vec3 up = abs(normal.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); + vec3 tangentX = normalize(cross(up, normal)); + vec3 tangentY = normalize(cross(normal, tangentX)); + + // Convert to world Space + return normalize(tangentX * H.x + tangentY * H.y + normal * H.z); +} + +// Normal Distribution function +float D_GGX(float dotNH, float roughness) +{ + float alpha = roughness * roughness; + float alpha2 = alpha * alpha; + float denom = dotNH * dotNH * (alpha2 - 1.0) + 1.0; + return (alpha2)/(PI * denom*denom); +} + +vec3 prefilterEnvMap(vec3 R, float roughness) +{ + vec3 N = R; + vec3 V = R; + vec3 color = vec3(0.0); + float totalWeight = 0.0; + float envMapDim = float(textureSize(samplerEnv, 0).s); + for(uint i = 0u; i < consts.numSamples; i++) { + vec2 Xi = hammersley2d(i, consts.numSamples); + vec3 H = importanceSample_GGX(Xi, roughness, N); + vec3 L = 2.0 * dot(V, H) * H - V; + float dotNL = clamp(dot(N, L), 0.0, 1.0); + if(dotNL > 0.0) { + // Filtering based on https://placeholderart.wordpress.com/2015/07/28/implementation-notes-runtime-environment-map-filtering-for-image-based-lighting/ + + float dotNH = clamp(dot(N, H), 0.0, 1.0); + float dotVH = clamp(dot(V, H), 0.0, 1.0); + + // Probability Distribution Function + float pdf = D_GGX(dotNH, roughness) * dotNH / (4.0 * dotVH) + 0.0001; + // Slid angle of current smple + float omegaS = 1.0 / (float(consts.numSamples) * pdf); + // Solid angle of 1 pixel across all cube faces + float omegaP = 4.0 * PI / (6.0 * envMapDim * envMapDim); + // Biased (+1.0) mip level for better result + float mipLevel = roughness == 0.0 ? 0.0 : max(0.5 * log2(omegaS / omegaP) + 1.0, 0.0f); + color += textureLod(samplerEnv, L, mipLevel).rgb * dotNL; + totalWeight += dotNL; + + } + } + return (color / totalWeight); +} + + +void main() +{ + vec3 N = normalize(inPos); + outColor = vec4(prefilterEnvMap(N, consts.roughness), 1.0); +} diff --git a/tests/glsl/sascha-willems/pbribl/skybox.frag b/tests/glsl/sascha-willems/pbribl/skybox.frag new file mode 100644 index 000000000..a66c8bdaa --- /dev/null +++ b/tests/glsl/sascha-willems/pbribl/skybox.frag @@ -0,0 +1,40 @@ +#version 450 +//TEST:COMPARE_GLSL: + +layout (binding = 2) uniform samplerCube samplerEnv; + +layout (location = 0) in vec3 inUVW; + +layout (location = 0) out vec4 outColor; + +layout (binding = 1) uniform UBOParams { + vec4 lights[4]; + float exposure; + float gamma; +} uboParams; + +// From http://filmicworlds.com/blog/filmic-tonemapping-operators/ +vec3 Uncharted2Tonemap(vec3 color) +{ + float A = 0.15; + float B = 0.50; + float C = 0.10; + float D = 0.20; + float E = 0.02; + float F = 0.30; + float W = 11.2; + return ((color*(A*color+C*B)+D*E)/(color*(A*color+B)+D*F))-E/F; +} + +void main() +{ + vec3 color = texture(samplerEnv, inUVW).rgb; + + // Tone mapping + color = Uncharted2Tonemap(color * uboParams.exposure); + color = color * (1.0f / Uncharted2Tonemap(vec3(11.2f))); + // Gamma correction + color = pow(color, vec3(1.0f / uboParams.gamma)); + + outColor = vec4(color, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/pbribl/skybox.vert b/tests/glsl/sascha-willems/pbribl/skybox.vert new file mode 100644 index 000000000..1802e74e4 --- /dev/null +++ b/tests/glsl/sascha-willems/pbribl/skybox.vert @@ -0,0 +1,28 @@ +#version 450 +//TEST:COMPARE_GLSL: + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; +} ubo; + +layout (location = 0) out vec3 outUVW; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUVW = inPos; + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); +} diff --git a/tests/glsl/sascha-willems/pbrtexture/filtercube.vert b/tests/glsl/sascha-willems/pbrtexture/filtercube.vert new file mode 100644 index 000000000..07f02c8b5 --- /dev/null +++ b/tests/glsl/sascha-willems/pbrtexture/filtercube.vert @@ -0,0 +1,20 @@ +#version 450 +//TEST:COMPARE_GLSL: + +layout (location = 0) in vec3 inPos; + +layout(push_constant) uniform PushConsts { + layout (offset = 0) mat4 mvp; +} pushConsts; + +layout (location = 0) out vec3 outUVW; + +out gl_PerVertex { + vec4 gl_Position; +}; + +void main() +{ + outUVW = inPos; + gl_Position = pushConsts.mvp * vec4(inPos.xyz, 1.0); +} diff --git a/tests/glsl/sascha-willems/pbrtexture/genbrdflut.frag b/tests/glsl/sascha-willems/pbrtexture/genbrdflut.frag new file mode 100644 index 000000000..25f00af1f --- /dev/null +++ b/tests/glsl/sascha-willems/pbrtexture/genbrdflut.frag @@ -0,0 +1,91 @@ +#version 450 +//TEST:COMPARE_GLSL: + +layout (location = 0) in vec2 inUV; +layout (location = 0) out vec4 outColor; +layout (constant_id = 0) const uint NUM_SAMPLES = 1024u; + +const float PI = 3.1415926536; + +// Based omn http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/ +float random(vec2 co) +{ + float a = 12.9898; + float b = 78.233; + float c = 43758.5453; + float dt= dot(co.xy ,vec2(a,b)); + float sn= mod(dt,3.14); + return fract(sin(sn) * c); +} + +vec2 hammersley2d(uint i, uint N) +{ + // Radical inverse based on http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html + uint bits = (i << 16u) | (i >> 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); + float rdi = float(bits) * 2.3283064365386963e-10; + return vec2(float(i) /float(N), rdi); +} + +// Based on http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_slides.pdf +vec3 importanceSample_GGX(vec2 Xi, float roughness, vec3 normal) +{ + // Maps a 2D point to a hemisphere with spread based on roughness + float alpha = roughness * roughness; + float phi = 2.0 * PI * Xi.x + random(normal.xz) * 0.1; + float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (alpha*alpha - 1.0) * Xi.y)); + float sinTheta = sqrt(1.0 - cosTheta * cosTheta); + vec3 H = vec3(sinTheta * cos(phi), sinTheta * sin(phi), cosTheta); + + // Tangent space + vec3 up = abs(normal.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); + vec3 tangentX = normalize(cross(up, normal)); + vec3 tangentY = normalize(cross(normal, tangentX)); + + // Convert to world Space + return normalize(tangentX * H.x + tangentY * H.y + normal * H.z); +} + +// Geometric Shadowing function +float G_SchlicksmithGGX(float dotNL, float dotNV, float roughness) +{ + float k = (roughness * roughness) / 2.0; + float GL = dotNL / (dotNL * (1.0 - k) + k); + float GV = dotNV / (dotNV * (1.0 - k) + k); + return GL * GV; +} + +vec2 BRDF(float NoV, float roughness) +{ + // Normal always points along z-axis for the 2D lookup + const vec3 N = vec3(0.0, 0.0, 1.0); + vec3 V = vec3(sqrt(1.0 - NoV*NoV), 0.0, NoV); + + vec2 LUT = vec2(0.0); + for(uint i = 0u; i < NUM_SAMPLES; i++) { + vec2 Xi = hammersley2d(i, NUM_SAMPLES); + vec3 H = importanceSample_GGX(Xi, roughness, N); + vec3 L = 2.0 * dot(V, H) * H - V; + + float dotNL = max(dot(N, L), 0.0); + float dotNV = max(dot(N, V), 0.0); + float dotVH = max(dot(V, H), 0.0); + float dotNH = max(dot(H, N), 0.0); + + if (dotNL > 0.0) { + float G = G_SchlicksmithGGX(dotNL, dotNV, roughness); + float G_Vis = (G * dotVH) / (dotNH * dotNV); + float Fc = pow(1.0 - dotVH, 5.0); + LUT += vec2((1.0 - Fc) * G_Vis, Fc * G_Vis); + } + } + return LUT / float(NUM_SAMPLES); +} + +void main() +{ + outColor = vec4(BRDF(inUV.s, 1.0-inUV.t), 0.0, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/pbrtexture/genbrdflut.vert b/tests/glsl/sascha-willems/pbrtexture/genbrdflut.vert new file mode 100644 index 000000000..2eeb90cf3 --- /dev/null +++ b/tests/glsl/sascha-willems/pbrtexture/genbrdflut.vert @@ -0,0 +1,10 @@ +//TEST:COMPARE_GLSL: +#version 450 + +layout (location = 0) out vec2 outUV; + +void main() +{ + outUV = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); + gl_Position = vec4(outUV * 2.0f - 1.0f, 0.0f, 1.0f); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/pbrtexture/irradiancecube.frag b/tests/glsl/sascha-willems/pbrtexture/irradiancecube.frag new file mode 100644 index 000000000..e94c0f93c --- /dev/null +++ b/tests/glsl/sascha-willems/pbrtexture/irradiancecube.frag @@ -0,0 +1,38 @@ +//TEST:COMPARE_GLSL: +// Generates an irradiance cube from an environment map using convolution + +#version 450 + +layout (location = 0) in vec3 inPos; +layout (location = 0) out vec4 outColor; +layout (binding = 0) uniform samplerCube samplerEnv; + +layout(push_constant) uniform PushConsts { + layout (offset = 64) float deltaPhi; + layout (offset = 68) float deltaTheta; +} consts; + +#define PI 3.1415926535897932384626433832795 + +void main() +{ + vec3 N = normalize(inPos); + vec3 up = vec3(0.0, 1.0, 0.0); + vec3 right = normalize(cross(up, N)); + up = cross(N, right); + + const float TWO_PI = PI * 2.0; + const float HALF_PI = PI * 0.5; + + vec3 color = vec3(0.0); + uint sampleCount = 0u; + for (float phi = 0.0; phi < TWO_PI; phi += consts.deltaPhi) { + for (float theta = 0.0; theta < HALF_PI; theta += consts.deltaTheta) { + vec3 tempVec = cos(phi) * right + sin(phi) * up; + vec3 sampleVector = cos(theta) * N + sin(theta) * tempVec; + color += texture(samplerEnv, sampleVector).rgb * cos(theta) * sin(theta); + sampleCount++; + } + } + outColor = vec4(PI * color / float(sampleCount), 1.0); +} diff --git a/tests/glsl/sascha-willems/pbrtexture/pbrtexture.frag b/tests/glsl/sascha-willems/pbrtexture/pbrtexture.frag new file mode 100644 index 000000000..eb0a14bcc --- /dev/null +++ b/tests/glsl/sascha-willems/pbrtexture/pbrtexture.frag @@ -0,0 +1,179 @@ +//TEST:COMPARE_GLSL: +#version 450 + +layout (location = 0) in vec3 inWorldPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; + +layout (binding = 0) uniform UBO { + mat4 projection; + mat4 model; + mat4 view; + vec3 camPos; +} ubo; + +layout (binding = 1) uniform UBOParams { + vec4 lights[4]; + float exposure; + float gamma; +} uboParams; + +layout (binding = 2) uniform samplerCube samplerIrradiance; +layout (binding = 3) uniform sampler2D samplerBRDFLUT; +layout (binding = 4) uniform samplerCube prefilteredMap; + +layout (binding = 5) uniform sampler2D albedoMap; +layout (binding = 6) uniform sampler2D normalMap; +layout (binding = 7) uniform sampler2D aoMap; +layout (binding = 8) uniform sampler2D metallicMap; +layout (binding = 9) uniform sampler2D roughnessMap; + + +layout (location = 0) out vec4 outColor; + +#define PI 3.1415926535897932384626433832795 +#define ALBEDO pow(texture(albedoMap, inUV).rgb, vec3(2.2)) + +// From http://filmicgames.com/archives/75 +vec3 Uncharted2Tonemap(vec3 x) +{ + float A = 0.15; + float B = 0.50; + float C = 0.10; + float D = 0.20; + float E = 0.02; + float F = 0.30; + return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F; +} + +// Normal Distribution function -------------------------------------- +float D_GGX(float dotNH, float roughness) +{ + float alpha = roughness * roughness; + float alpha2 = alpha * alpha; + float denom = dotNH * dotNH * (alpha2 - 1.0) + 1.0; + return (alpha2)/(PI * denom*denom); +} + +// Geometric Shadowing function -------------------------------------- +float G_SchlicksmithGGX(float dotNL, float dotNV, float roughness) +{ + float r = (roughness + 1.0); + float k = (r*r) / 8.0; + float GL = dotNL / (dotNL * (1.0 - k) + k); + float GV = dotNV / (dotNV * (1.0 - k) + k); + return GL * GV; +} + +// Fresnel function ---------------------------------------------------- +vec3 F_Schlick(float cosTheta, vec3 F0) +{ + return F0 + (1.0 - F0) * pow(1.0 - cosTheta, 5.0); +} +vec3 F_SchlickR(float cosTheta, vec3 F0, float roughness) +{ + return F0 + (max(vec3(1.0 - roughness), F0) - F0) * pow(1.0 - cosTheta, 5.0); +} + +vec3 prefilteredReflection(vec3 R, float roughness) +{ + const float MAX_REFLECTION_LOD = 9.0; // todo: param/const + float lod = roughness * MAX_REFLECTION_LOD; + float lodf = floor(lod); + float lodc = ceil(lod); + vec3 a = textureLod(prefilteredMap, R, lodf).rgb; + vec3 b = textureLod(prefilteredMap, R, lodc).rgb; + return mix(a, b, lod - lodf); +} + +vec3 specularContribution(vec3 L, vec3 V, vec3 N, vec3 F0, float metallic, float roughness) +{ + // Precalculate vectors and dot products + vec3 H = normalize (V + L); + float dotNH = clamp(dot(N, H), 0.0, 1.0); + float dotNV = clamp(dot(N, V), 0.0, 1.0); + float dotNL = clamp(dot(N, L), 0.0, 1.0); + + // Light color fixed + vec3 lightColor = vec3(1.0); + + vec3 color = vec3(0.0); + + if (dotNL > 0.0) { + // D = Normal distribution (Distribution of the microfacets) + float D = D_GGX(dotNH, roughness); + // G = Geometric shadowing term (Microfacets shadowing) + float G = G_SchlicksmithGGX(dotNL, dotNV, roughness); + // F = Fresnel factor (Reflectance depending on angle of incidence) + vec3 F = F_Schlick(dotNV, F0); + vec3 spec = D * F * G / (4.0 * dotNL * dotNV + 0.001); + vec3 kD = (vec3(1.0) - F) * (1.0 - metallic); + color += (kD * ALBEDO / PI + spec) * dotNL; + } + + return color; +} + +// See http://www.thetenthplanet.de/archives/1180 +vec3 perturbNormal() +{ + vec3 tangentNormal = texture(normalMap, inUV).xyz * 2.0 - 1.0; + + vec3 q1 = dFdx(inWorldPos); + vec3 q2 = dFdy(inWorldPos); + vec2 st1 = dFdx(inUV); + vec2 st2 = dFdy(inUV); + + vec3 N = normalize(inNormal); + vec3 T = normalize(q1 * st2.t - q2 * st1.t); + vec3 B = -normalize(cross(N, T)); + mat3 TBN = mat3(T, B, N); + + return normalize(TBN * tangentNormal); +} + +void main() +{ + vec3 N = perturbNormal(); + vec3 V = normalize(ubo.camPos - inWorldPos); + vec3 R = reflect(-V, N); + + float metallic = texture(metallicMap, inUV).r; + float roughness = texture(roughnessMap, inUV).r; + + vec3 F0 = vec3(0.04); + F0 = mix(F0, ALBEDO, metallic); + + vec3 Lo = vec3(0.0); + for(int i = 0; i < uboParams.lights[i].length(); i++) { + vec3 L = normalize(uboParams.lights[i].xyz - inWorldPos); + Lo += specularContribution(L, V, N, F0, metallic, roughness); + } + + vec2 brdf = texture(samplerBRDFLUT, vec2(max(dot(N, V), 0.0), roughness)).rg; + vec3 reflection = prefilteredReflection(R, roughness).rgb; + vec3 irradiance = texture(samplerIrradiance, N).rgb; + + // Diffuse based on irradiance + vec3 diffuse = irradiance * ALBEDO; + + vec3 F = F_SchlickR(max(dot(N, V), 0.0), F0, roughness); + + // Specular reflectance + vec3 specular = reflection * (F * brdf.x + brdf.y); + + // Ambient part + vec3 kD = 1.0 - F; + kD *= 1.0 - metallic; + vec3 ambient = (kD * diffuse + specular) * texture(aoMap, inUV).rrr; + + vec3 color = ambient + Lo; + + // Tone mapping + color = Uncharted2Tonemap(color * uboParams.exposure); + color = color * (1.0f / Uncharted2Tonemap(vec3(11.2f))); + // Gamma correction + color = pow(color, vec3(1.0f / uboParams.gamma)); + + outColor = vec4(color, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/pbrtexture/pbrtexture.vert b/tests/glsl/sascha-willems/pbrtexture/pbrtexture.vert new file mode 100644 index 000000000..9962220a8 --- /dev/null +++ b/tests/glsl/sascha-willems/pbrtexture/pbrtexture.vert @@ -0,0 +1,36 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + mat4 view; + vec3 camPos; +} ubo; + +layout (location = 0) out vec3 outWorldPos; +layout (location = 1) out vec3 outNormal; +layout (location = 2) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + vec3 locPos = vec3(ubo.model * vec4(inPos, 1.0)); + outWorldPos = locPos; + outNormal = mat3(ubo.model) * inNormal; + outUV = inUV; + outUV.t = 1.0 - inUV.t; + gl_Position = ubo.projection * ubo.view * vec4(outWorldPos, 1.0); +} diff --git a/tests/glsl/sascha-willems/pbrtexture/prefilterenvmap.frag b/tests/glsl/sascha-willems/pbrtexture/prefilterenvmap.frag new file mode 100644 index 000000000..912780c82 --- /dev/null +++ b/tests/glsl/sascha-willems/pbrtexture/prefilterenvmap.frag @@ -0,0 +1,106 @@ +//TEST:COMPARE_GLSL: +#version 450 + +layout (location = 0) in vec3 inPos; +layout (location = 0) out vec4 outColor; + +layout (binding = 0) uniform samplerCube samplerEnv; + +layout(push_constant) uniform PushConsts { + layout (offset = 64) float roughness; + layout (offset = 68) uint numSamples; +} consts; + +const float PI = 3.1415926536; + +// Based omn http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/ +float random(vec2 co) +{ + float a = 12.9898; + float b = 78.233; + float c = 43758.5453; + float dt= dot(co.xy ,vec2(a,b)); + float sn= mod(dt,3.14); + return fract(sin(sn) * c); +} + +vec2 hammersley2d(uint i, uint N) +{ + // Radical inverse based on http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html + uint bits = (i << 16u) | (i >> 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); + float rdi = float(bits) * 2.3283064365386963e-10; + return vec2(float(i) /float(N), rdi); +} + +// Based on http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_slides.pdf +vec3 importanceSample_GGX(vec2 Xi, float roughness, vec3 normal) +{ + // Maps a 2D point to a hemisphere with spread based on roughness + float alpha = roughness * roughness; + float phi = 2.0 * PI * Xi.x + random(normal.xz) * 0.1; + float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (alpha*alpha - 1.0) * Xi.y)); + float sinTheta = sqrt(1.0 - cosTheta * cosTheta); + vec3 H = vec3(sinTheta * cos(phi), sinTheta * sin(phi), cosTheta); + + // Tangent space + vec3 up = abs(normal.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); + vec3 tangentX = normalize(cross(up, normal)); + vec3 tangentY = normalize(cross(normal, tangentX)); + + // Convert to world Space + return normalize(tangentX * H.x + tangentY * H.y + normal * H.z); +} + +// Normal Distribution function +float D_GGX(float dotNH, float roughness) +{ + float alpha = roughness * roughness; + float alpha2 = alpha * alpha; + float denom = dotNH * dotNH * (alpha2 - 1.0) + 1.0; + return (alpha2)/(PI * denom*denom); +} + +vec3 prefilterEnvMap(vec3 R, float roughness) +{ + vec3 N = R; + vec3 V = R; + vec3 color = vec3(0.0); + float totalWeight = 0.0; + float envMapDim = float(textureSize(samplerEnv, 0).s); + for(uint i = 0u; i < consts.numSamples; i++) { + vec2 Xi = hammersley2d(i, consts.numSamples); + vec3 H = importanceSample_GGX(Xi, roughness, N); + vec3 L = 2.0 * dot(V, H) * H - V; + float dotNL = clamp(dot(N, L), 0.0, 1.0); + if(dotNL > 0.0) { + // Filtering based on https://placeholderart.wordpress.com/2015/07/28/implementation-notes-runtime-environment-map-filtering-for-image-based-lighting/ + + float dotNH = clamp(dot(N, H), 0.0, 1.0); + float dotVH = clamp(dot(V, H), 0.0, 1.0); + + // Probability Distribution Function + float pdf = D_GGX(dotNH, roughness) * dotNH / (4.0 * dotVH) + 0.0001; + // Slid angle of current smple + float omegaS = 1.0 / (float(consts.numSamples) * pdf); + // Solid angle of 1 pixel across all cube faces + float omegaP = 4.0 * PI / (6.0 * envMapDim * envMapDim); + // Biased (+1.0) mip level for better result + float mipLevel = roughness == 0.0 ? 0.0 : max(0.5 * log2(omegaS / omegaP) + 1.0, 0.0f); + color += textureLod(samplerEnv, L, mipLevel).rgb * dotNL; + totalWeight += dotNL; + + } + } + return (color / totalWeight); +} + + +void main() +{ + vec3 N = normalize(inPos); + outColor = vec4(prefilterEnvMap(N, consts.roughness), 1.0); +} diff --git a/tests/glsl/sascha-willems/pbrtexture/skybox.frag b/tests/glsl/sascha-willems/pbrtexture/skybox.frag new file mode 100644 index 000000000..d80d44487 --- /dev/null +++ b/tests/glsl/sascha-willems/pbrtexture/skybox.frag @@ -0,0 +1,40 @@ +//TEST:COMPARE_GLSL: +#version 450 + +layout (binding = 2) uniform samplerCube samplerEnv; + +layout (location = 0) in vec3 inUVW; + +layout (location = 0) out vec4 outColor; + +layout (binding = 1) uniform UBOParams { + vec4 lights[4]; + float exposure; + float gamma; +} uboParams; + +// From http://filmicworlds.com/blog/filmic-tonemapping-operators/ +vec3 Uncharted2Tonemap(vec3 color) +{ + float A = 0.15; + float B = 0.50; + float C = 0.10; + float D = 0.20; + float E = 0.02; + float F = 0.30; + float W = 11.2; + return ((color*(A*color+C*B)+D*E)/(color*(A*color+B)+D*F))-E/F; +} + +void main() +{ + vec3 color = texture(samplerEnv, inUVW).rgb; + + // Tone mapping + color = Uncharted2Tonemap(color * uboParams.exposure); + color = color * (1.0f / Uncharted2Tonemap(vec3(11.2f))); + // Gamma correction + color = pow(color, vec3(1.0f / uboParams.gamma)); + + outColor = vec4(color, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/pbrtexture/skybox.vert b/tests/glsl/sascha-willems/pbrtexture/skybox.vert new file mode 100644 index 000000000..e77f89773 --- /dev/null +++ b/tests/glsl/sascha-willems/pbrtexture/skybox.vert @@ -0,0 +1,28 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; +} ubo; + +layout (location = 0) out vec3 outUVW; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUVW = inPos; + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); +} diff --git a/tests/glsl/sascha-willems/pipelines/phong.frag b/tests/glsl/sascha-willems/pipelines/phong.frag new file mode 100644 index 000000000..f8dddd1cf --- /dev/null +++ b/tests/glsl/sascha-willems/pipelines/phong.frag @@ -0,0 +1,31 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColorMap; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + // Desaturate color + vec3 color = vec3(mix(inColor, vec3(dot(vec3(0.2126,0.7152,0.0722), inColor)), 0.65)); + + // High ambient colors because mesh materials are pretty dark + vec3 ambient = color * vec3(1.0); + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 diffuse = max(dot(N, L), 0.0) * color; + vec3 specular = pow(max(dot(R, V), 0.0), 32.0) * vec3(0.35); + outFragColor = vec4(ambient + diffuse * 1.75 + specular, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/pipelines/phong.vert b/tests/glsl/sascha-willems/pipelines/phong.vert new file mode 100644 index 000000000..44fd2e692 --- /dev/null +++ b/tests/glsl/sascha-willems/pipelines/phong.vert @@ -0,0 +1,42 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + vec4 lightPos; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec2 outUV; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outNormal = inNormal; + outColor = inColor; + outUV = inUV; + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); + + vec4 pos = ubo.model * vec4(inPos, 1.0); + outNormal = mat3(ubo.model) * inNormal; + vec3 lPos = mat3(ubo.model) * ubo.lightPos.xyz; + outLightVec = lPos - pos.xyz; + outViewVec = -pos.xyz; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/pipelines/toon.frag b/tests/glsl/sascha-willems/pipelines/toon.frag new file mode 100644 index 000000000..bb19e9a2f --- /dev/null +++ b/tests/glsl/sascha-willems/pipelines/toon.frag @@ -0,0 +1,40 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColorMap; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + // Desaturate color + vec3 color = vec3(mix(inColor, vec3(dot(vec3(0.2126,0.7152,0.0722), inColor)), 0.65)); + + // High ambient colors because mesh materials are pretty dark + vec3 ambient = color * vec3(1.0); + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 diffuse = max(dot(N, L), 0.0) * color; + vec3 specular = pow(max(dot(R, V), 0.0), 16.0) * vec3(0.75); + outFragColor = vec4(ambient + diffuse * 1.75 + specular, 1.0); + + float intensity = dot(N,L); + float shade = 1.0; + shade = intensity < 0.5 ? 0.75 : shade; + shade = intensity < 0.35 ? 0.6 : shade; + shade = intensity < 0.25 ? 0.5 : shade; + shade = intensity < 0.1 ? 0.25 : shade; + + outFragColor.rgb = inColor * 3.0 * shade; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/pipelines/toon.vert b/tests/glsl/sascha-willems/pipelines/toon.vert new file mode 100644 index 000000000..44fd2e692 --- /dev/null +++ b/tests/glsl/sascha-willems/pipelines/toon.vert @@ -0,0 +1,42 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + vec4 lightPos; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec2 outUV; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outNormal = inNormal; + outColor = inColor; + outUV = inUV; + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); + + vec4 pos = ubo.model * vec4(inPos, 1.0); + outNormal = mat3(ubo.model) * inNormal; + vec3 lPos = mat3(ubo.model) * ubo.lightPos.xyz; + outLightVec = lPos - pos.xyz; + outViewVec = -pos.xyz; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/pipelines/wireframe.frag b/tests/glsl/sascha-willems/pipelines/wireframe.frag new file mode 100644 index 000000000..7158d7ac9 --- /dev/null +++ b/tests/glsl/sascha-willems/pipelines/wireframe.frag @@ -0,0 +1,14 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inColor; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + outFragColor.rgb = inColor * 1.5; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/pipelines/wireframe.vert b/tests/glsl/sascha-willems/pipelines/wireframe.vert new file mode 100644 index 000000000..6ec18a4bf --- /dev/null +++ b/tests/glsl/sascha-willems/pipelines/wireframe.vert @@ -0,0 +1,29 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 3) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; +} ubo; + +layout (location = 0) out vec3 outColor; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + { + outColor = inColor; + } + gl_Position = ubo.projection * ubo.model * inPos; +} diff --git a/tests/glsl/sascha-willems/pushconstants/lights.frag b/tests/glsl/sascha-willems/pushconstants/lights.frag new file mode 100644 index 000000000..9624b51be --- /dev/null +++ b/tests/glsl/sascha-willems/pushconstants/lights.frag @@ -0,0 +1,41 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +#define lightCount 6 + +layout (location = 0) in vec3 inNormal; +layout (location = 2) in vec3 inColor; + +layout (location = 3) in vec4 inLightVec[lightCount]; + +layout (location = 0) out vec4 outFragColor; + +#define MAX_LIGHT_DIST 9.0 * 9.0 + +void main() +{ + vec3 lightColor[lightCount]; + lightColor[0] = vec3(1.0, 0.0, 0.0); + lightColor[1] = vec3(0.0, 1.0, 0.0); + lightColor[2] = vec3(0.0, 0.0, 1.0); + lightColor[3] = vec3(1.0, 0.0, 1.0); + lightColor[4] = vec3(0.0, 1.0, 1.0); + lightColor[5] = vec3(1.0, 1.0, 0.0); + + vec3 diffuse = vec3(0.0); + // Just some very basic attenuation + for (int i = 0; i < lightCount; ++i) + { + float lRadius = MAX_LIGHT_DIST * inLightVec[i].w; + + float dist = min(dot(inLightVec[i], inLightVec[i]), lRadius) / lRadius; + float distFactor = 1.0 - dist; + + diffuse += lightColor[i] * distFactor; + } + + outFragColor.rgb = diffuse; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/pushconstants/lights.vert b/tests/glsl/sascha-willems/pushconstants/lights.vert new file mode 100644 index 000000000..693e69d5d --- /dev/null +++ b/tests/glsl/sascha-willems/pushconstants/lights.vert @@ -0,0 +1,48 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 3) in vec3 inColor; + +#define lightCount 6 + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + vec4 lightColor[lightCount]; +} ubo; + +layout(push_constant) uniform PushConsts { + vec4 lightPos[lightCount]; +} pushConsts; + +layout (location = 0) out vec3 outNormal; +layout (location = 2) out vec3 outColor; + +layout (location = 3) out vec4 outLightVec[lightCount]; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outNormal = inNormal; + outColor = inColor; + + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); + + for (int i = 0; i < lightCount; ++i) + { + vec4 worldPos = ubo.model * vec4(inPos.xyz, 1.0); + outLightVec[i].xyz = pushConsts.lightPos[i].xyz - inPos.xyz; + // Store light radius in w + outLightVec[i].w = pushConsts.lightPos[i].w; + } +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/radialblur/colorpass.frag b/tests/glsl/sascha-willems/radialblur/colorpass.frag new file mode 100644 index 000000000..5d56315fd --- /dev/null +++ b/tests/glsl/sascha-willems/radialblur/colorpass.frag @@ -0,0 +1,25 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerGradientRamp; + +layout (location = 0) in vec3 inColor; +layout (location = 1) in vec2 inUV; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + // Use max. color channel value to detect bright glow emitters + if ((inColor.r >= 0.9) || (inColor.g >= 0.9) || (inColor.b >= 0.9)) + { + outFragColor.rgb = texture(samplerGradientRamp, inUV).rgb; + } + else + { + outFragColor.rgb = inColor; + } +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/radialblur/colorpass.vert b/tests/glsl/sascha-willems/radialblur/colorpass.vert new file mode 100644 index 000000000..68d4f2e56 --- /dev/null +++ b/tests/glsl/sascha-willems/radialblur/colorpass.vert @@ -0,0 +1,30 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 2) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + float gradientPos; +} ubo; + +layout (location = 0) out vec3 outColor; +layout (location = 1) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outColor = inColor; + outUV = vec2(ubo.gradientPos, 0.0f); + gl_Position = ubo.projection * ubo.model * vec4(inPos, 1.0); +} diff --git a/tests/glsl/sascha-willems/radialblur/phongpass.frag b/tests/glsl/sascha-willems/radialblur/phongpass.frag new file mode 100644 index 000000000..83e96fc58 --- /dev/null +++ b/tests/glsl/sascha-willems/radialblur/phongpass.frag @@ -0,0 +1,37 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerGradientRamp; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec3 inEyePos; +layout (location = 3) in vec3 inLightVec; +layout (location = 4) in vec2 inUV; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + // No light calculations for glow color + // Use max. color channel value + // to detect bright glow emitters + if ((inColor.r >= 0.9) || (inColor.g >= 0.9) || (inColor.b >= 0.9)) + { + outFragColor.rgb = texture(samplerGradientRamp, inUV).rgb; + } + else + { + vec3 Eye = normalize(-inEyePos); + vec3 Reflected = normalize(reflect(-inLightVec, inNormal)); + + vec4 IAmbient = vec4(0.2, 0.2, 0.2, 1.0); + vec4 IDiffuse = vec4(0.5, 0.5, 0.5, 0.5) * max(dot(inNormal, inLightVec), 0.0); + float specular = 0.25; + vec4 ISpecular = vec4(0.5, 0.5, 0.5, 1.0) * pow(max(dot(Reflected, Eye), 0.0), 4.0) * specular; + outFragColor = vec4((IAmbient + IDiffuse) * vec4(inColor, 1.0) + ISpecular); + } +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/radialblur/phongpass.vert b/tests/glsl/sascha-willems/radialblur/phongpass.vert new file mode 100644 index 000000000..a375c39cf --- /dev/null +++ b/tests/glsl/sascha-willems/radialblur/phongpass.vert @@ -0,0 +1,38 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 pos; +layout (location = 2) in vec3 inColor; +layout (location = 3) in vec3 inNormal; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + float gradientPos; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec3 outEyePos; +layout (location = 3) out vec3 outLightVec; +layout (location = 4) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outNormal = inNormal; + outColor = inColor; + outUV = vec2(ubo.gradientPos, 0.0); + gl_Position = ubo.projection * ubo.model * pos; + outEyePos = vec3(ubo.model * pos); + vec4 lightPos = vec4(0.0, 0.0, -5.0, 1.0);// * ubo.model; + outLightVec = normalize(lightPos.xyz - pos.xyz); +} diff --git a/tests/glsl/sascha-willems/radialblur/radialblur.frag b/tests/glsl/sascha-willems/radialblur/radialblur.frag new file mode 100644 index 000000000..bc1e884e9 --- /dev/null +++ b/tests/glsl/sascha-willems/radialblur/radialblur.frag @@ -0,0 +1,39 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColor; + +layout (binding = 0) uniform UBO +{ + float radialBlurScale; + float radialBlurStrength; + vec2 radialOrigin; +} ubo; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + ivec2 texDim = textureSize(samplerColor, 0); + vec2 radialSize = vec2(1.0 / texDim.s, 1.0 / texDim.t); + + vec2 UV = inUV; + + vec4 color = vec4(0.0, 0.0, 0.0, 0.0); + UV += radialSize * 0.5 - ubo.radialOrigin; + + #define samples 32 + + for (int i = 0; i < samples; i++) + { + float scale = 1.0 - ubo.radialBlurScale * (float(i) / float(samples-1)); + color += texture(samplerColor, UV * scale + ubo.radialOrigin); + } + + outFragColor = (color / samples) * ubo.radialBlurStrength; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/radialblur/radialblur.vert b/tests/glsl/sascha-willems/radialblur/radialblur.vert new file mode 100644 index 000000000..117eb02ec --- /dev/null +++ b/tests/glsl/sascha-willems/radialblur/radialblur.vert @@ -0,0 +1,18 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); + gl_Position = vec4(outUV * 2.0f - 1.0f, 0.0f, 1.0f); +} diff --git a/tests/glsl/sascha-willems/raytracing/raytracing.comp b/tests/glsl/sascha-willems/raytracing/raytracing.comp new file mode 100644 index 000000000..8ef6c19e8 --- /dev/null +++ b/tests/glsl/sascha-willems/raytracing/raytracing.comp @@ -0,0 +1,258 @@ +//TEST:COMPARE_GLSL: +// Shader is looseley based on the ray tracing coding session by Inigo Quilez (www.iquilezles.org) + +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (local_size_x = 16, local_size_y = 16) in; +layout (binding = 0, rgba8) uniform writeonly image2D resultImage; + +#define EPSILON 0.0001 +#define MAXLEN 1000.0 +#define SHADOW 0.5 +#define RAYBOUNCES 2 +#define REFLECTIONS true +#define REFLECTIONSTRENGTH 0.4 +#define REFLECTIONFALLOFF 0.5 + +struct Camera +{ + vec3 pos; + vec3 lookat; + float fov; +}; + +layout (binding = 1) uniform UBO +{ + vec3 lightPos; + float aspectRatio; + vec4 fogColor; + Camera camera; + mat4 rotMat; +} ubo; + +struct Sphere +{ + vec3 pos; + float radius; + vec3 diffuse; + float specular; + int id; +}; + +struct Plane +{ + vec3 normal; + float distance; + vec3 diffuse; + float specular; + int id; +}; + +layout (std140, binding = 2) buffer Spheres +{ + Sphere spheres[ ]; +}; + +layout (std140, binding = 3) buffer Planes +{ + Plane planes[ ]; +}; + +void reflectRay(inout vec3 rayD, in vec3 mormal) +{ + rayD = rayD + 2.0 * -dot(mormal, rayD) * mormal; +} + +// Lighting ========================================================= + +float lightDiffuse(vec3 normal, vec3 lightDir) +{ + return clamp(dot(normal, lightDir), 0.1, 1.0); +} + +float lightSpecular(vec3 normal, vec3 lightDir, float specularFactor) +{ + vec3 viewVec = normalize(ubo.camera.pos); + vec3 halfVec = normalize(lightDir + viewVec); + return pow(clamp(dot(normal, halfVec), 0.0, 1.0), specularFactor); +} + +// Sphere =========================================================== + +float sphereIntersect(in vec3 rayO, in vec3 rayD, in Sphere sphere) +{ + vec3 oc = rayO - sphere.pos; + float b = 2.0 * dot(oc, rayD); + float c = dot(oc, oc) - sphere.radius*sphere.radius; + float h = b*b - 4.0*c; + if (h < 0.0) + { + return -1.0; + } + float t = (-b - sqrt(h)) / 2.0; + + return t; +} + +vec3 sphereNormal(in vec3 pos, in Sphere sphere) +{ + return (pos - sphere.pos) / sphere.radius; +} + +// Plane =========================================================== + +float planeIntersect(vec3 rayO, vec3 rayD, Plane plane) +{ + float d = dot(rayD, plane.normal); + + if (d == 0.0) + return 0.0; + + float t = -(plane.distance + dot(rayO, plane.normal)) / d; + + if (t < 0.0) + return 0.0; + + return t; +} + + +int intersect(in vec3 rayO, in vec3 rayD, inout float resT) +{ + int id = -1; + + for (int i = 0; i < spheres.length(); i++) + { + float tSphere = sphereIntersect(rayO, rayD, spheres[i]); + if ((tSphere > EPSILON) && (tSphere < resT)) + { + id = spheres[i].id; + resT = tSphere; + } + } + + for (int i = 0; i < planes.length(); i++) + { + float tplane = planeIntersect(rayO, rayD, planes[i]); + if ((tplane > EPSILON) && (tplane < resT)) + { + id = planes[i].id; + resT = tplane; + } + } + + return id; +} + +float calcShadow(in vec3 rayO, in vec3 rayD, in int objectId, inout float t) +{ + for (int i = 0; i < spheres.length(); i++) + { + if (spheres[i].id == objectId) + continue; + float tSphere = sphereIntersect(rayO, rayD, spheres[i]); + if ((tSphere > EPSILON) && (tSphere < t)) + { + t = tSphere; + return SHADOW; + } + } + return 1.0; +} + +vec3 fog(in float t, in vec3 color) +{ + return mix(color, ubo.fogColor.rgb, clamp(sqrt(t*t)/20.0, 0.0, 1.0)); +} + +vec3 renderScene(inout vec3 rayO, inout vec3 rayD, inout int id) +{ + vec3 color = vec3(0.0); + float t = MAXLEN; + + // Get intersected object ID + int objectID = intersect(rayO, rayD, t); + + if (objectID == -1) + { + return color; + } + + vec3 pos = rayO + t * rayD; + vec3 lightVec = normalize(ubo.lightPos - pos); + vec3 normal; + + // Planes + + // Spheres + + for (int i = 0; i < planes.length(); i++) + { + if (objectID == planes[i].id) + { + normal = planes[i].normal; + float diffuse = lightDiffuse(normal, lightVec); + float specular = lightSpecular(normal, lightVec, planes[i].specular); + color = diffuse * planes[i].diffuse + specular; + } + } + + for (int i = 0; i < spheres.length(); i++) + { + if (objectID == spheres[i].id) + { + normal = sphereNormal(pos, spheres[i]); + float diffuse = lightDiffuse(normal, lightVec); + float specular = lightSpecular(normal, lightVec, spheres[i].specular); + color = diffuse * spheres[i].diffuse + specular; + } + } + + if (id == -1) + return color; + + id = objectID; + + // Shadows + t = length(ubo.lightPos - pos); + color *= calcShadow(pos, lightVec, id, t); + + // Fog + color = fog(t, color); + + // Reflect ray for next render pass + reflectRay(rayD, normal); + rayO = pos; + + return color; +} + +void main() +{ + ivec2 dim = imageSize(resultImage); + vec2 uv = vec2(gl_GlobalInvocationID.xy) / dim; + + vec3 rayO = ubo.camera.pos; + vec3 rayD = normalize(vec3((-1.0 + 2.0 * uv) * vec2(ubo.aspectRatio, 1.0), -1.0)); + + // Basic color path + int id = 0; + vec3 finalColor = renderScene(rayO, rayD, id); + + // Reflection + if (REFLECTIONS) + { + float reflectionStrength = REFLECTIONSTRENGTH; + for (int i = 0; i < RAYBOUNCES; i++) + { + vec3 reflectionColor = renderScene(rayO, rayD, id); + finalColor = (1.0 - reflectionStrength) * finalColor + reflectionStrength * mix(reflectionColor, finalColor, 1.0 - reflectionStrength); + reflectionStrength *= REFLECTIONFALLOFF; + } + } + + imageStore(resultImage, ivec2(gl_GlobalInvocationID.xy), vec4(finalColor, 0.0)); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/raytracing/texture.frag b/tests/glsl/sascha-willems/raytracing/texture.frag new file mode 100644 index 000000000..06635bf4b --- /dev/null +++ b/tests/glsl/sascha-willems/raytracing/texture.frag @@ -0,0 +1,16 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 0) uniform sampler2D samplerColor; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + outFragColor = texture(samplerColor, vec2(inUV.s, 1.0 - inUV.t)); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/raytracing/texture.vert b/tests/glsl/sascha-willems/raytracing/texture.vert new file mode 100644 index 000000000..cbf5c0a0d --- /dev/null +++ b/tests/glsl/sascha-willems/raytracing/texture.vert @@ -0,0 +1,18 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); + gl_Position = vec4(outUV * 2.0f + -1.0f, 0.0f, 1.0f); +} diff --git a/tests/glsl/sascha-willems/scenerendering/scene.frag b/tests/glsl/sascha-willems/scenerendering/scene.frag new file mode 100644 index 000000000..032ce45a9 --- /dev/null +++ b/tests/glsl/sascha-willems/scenerendering/scene.frag @@ -0,0 +1,35 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (set = 1, binding = 0) uniform sampler2D samplerColorMap; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; + +layout(push_constant) uniform Material +{ + vec4 ambient; + vec4 diffuse; + vec4 specular; + float opacity; +} material; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec4 color = texture(samplerColorMap, inUV) * vec4(inColor, 1.0); + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 diffuse = max(dot(N, L), 0.0) * material.diffuse.rgb; + vec3 specular = pow(max(dot(R, V), 0.0), 16.0) * material.specular.rgb; + outFragColor = vec4((material.ambient.rgb + diffuse) * color.rgb + specular, 1.0-material.opacity); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/scenerendering/scene.vert b/tests/glsl/sascha-willems/scenerendering/scene.vert new file mode 100644 index 000000000..50852f78c --- /dev/null +++ b/tests/glsl/sascha-willems/scenerendering/scene.vert @@ -0,0 +1,46 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inColor; + +layout (set = 0, binding = 0) uniform UBO +{ + mat4 projection; + mat4 view; + mat4 model; + vec4 lightPos; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec2 outUV; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outNormal = inNormal; + outColor = inColor; + outUV = inUV; + + mat4 modelView = ubo.view * ubo.model; + + gl_Position = ubo.projection * modelView * vec4(inPos.xyz, 1.0); + + vec4 pos = modelView * vec4(inPos, 0.0); + outNormal = mat3(ubo.model) * inNormal; + vec3 lPos = mat3(ubo.model) * ubo.lightPos.xyz; + outLightVec = lPos - (ubo.model * vec4(inPos, 1.0)).xyz; + outViewVec = -(ubo.model * vec4(inPos, 1.0)).xyz; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/screenshot/mesh.frag b/tests/glsl/sascha-willems/screenshot/mesh.frag new file mode 100644 index 000000000..3504b70cf --- /dev/null +++ b/tests/glsl/sascha-willems/screenshot/mesh.frag @@ -0,0 +1,24 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec3 inViewVec; +layout (location = 3) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 ambient = vec3(0.1); + vec3 diffuse = max(dot(N, L), 0.0) * vec3(1.0); + vec3 specular = pow(max(dot(R, V), 0.0), 16.0) * vec3(0.75); + outFragColor = vec4((ambient + diffuse) * inColor.rgb + specular, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/screenshot/mesh.vert b/tests/glsl/sascha-willems/screenshot/mesh.vert new file mode 100644 index 000000000..a0c75ab18 --- /dev/null +++ b/tests/glsl/sascha-willems/screenshot/mesh.vert @@ -0,0 +1,40 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec3 inColor; + +layout (set = 0, binding = 0) uniform UBO +{ + mat4 projection; + mat4 view; + mat4 model; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec3 outViewVec; +layout (location = 3) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outNormal = inNormal; + outColor = inColor; + gl_Position = ubo.projection * ubo.view * ubo.model * inPos; + + vec4 pos = ubo.view * ubo.model * vec4(inPos.xyz, 1.0); + outNormal = mat3(ubo.model) * inNormal; + + vec3 lightPos = vec3(1.0f, -1.0f, 1.0f); + outLightVec = lightPos.xyz - pos.xyz; + outViewVec = -pos.xyz; +} diff --git a/tests/glsl/sascha-willems/shadowmapomni/cubemapdisplay.frag b/tests/glsl/sascha-willems/shadowmapomni/cubemapdisplay.frag new file mode 100644 index 000000000..740cd09e1 --- /dev/null +++ b/tests/glsl/sascha-willems/shadowmapomni/cubemapdisplay.frag @@ -0,0 +1,17 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform samplerCube shadowCubeMap; + +layout (location = 0) in vec3 inUVW; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + float dist = length(texture(shadowCubeMap, inUVW).rgb) * 0.005; + outFragColor = vec4(vec3(dist), 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/shadowmapomni/cubemapdisplay.vert b/tests/glsl/sascha-willems/shadowmapomni/cubemapdisplay.vert new file mode 100644 index 000000000..b5f889174 --- /dev/null +++ b/tests/glsl/sascha-willems/shadowmapomni/cubemapdisplay.vert @@ -0,0 +1,28 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 view; + mat4 model; +} ubo; + +layout (location = 0) out vec3 outUVW; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUVW = inPos; + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); +} + diff --git a/tests/glsl/sascha-willems/shadowmapomni/offscreen.frag b/tests/glsl/sascha-willems/shadowmapomni/offscreen.frag new file mode 100644 index 000000000..6426c4118 --- /dev/null +++ b/tests/glsl/sascha-willems/shadowmapomni/offscreen.frag @@ -0,0 +1,17 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) out float outFragColor; + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec3 inLightPos; + +void main() +{ + // Store distance to light as 32 bit float value + vec3 lightVec = inPos.xyz - inLightPos; + outFragColor = length(lightVec); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/shadowmapomni/offscreen.vert b/tests/glsl/sascha-willems/shadowmapomni/offscreen.vert new file mode 100644 index 000000000..7513070dc --- /dev/null +++ b/tests/glsl/sascha-willems/shadowmapomni/offscreen.vert @@ -0,0 +1,36 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; + +layout (location = 0) out vec4 outPos; +layout (location = 1) out vec3 outLightPos; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 view; + mat4 model; + vec4 lightPos; +} ubo; + +layout(push_constant) uniform PushConsts +{ + mat4 view; +} pushConsts; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + gl_Position = ubo.projection * pushConsts.view * ubo.model * vec4(inPos, 1.0); + + outPos = vec4(inPos, 1.0); + outLightPos = ubo.lightPos.xyz; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/shadowmapomni/scene.frag b/tests/glsl/sascha-willems/shadowmapomni/scene.frag new file mode 100644 index 000000000..1bdc44bdb --- /dev/null +++ b/tests/glsl/sascha-willems/shadowmapomni/scene.frag @@ -0,0 +1,44 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform samplerCube shadowCubeMap; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec3 inEyePos; +layout (location = 3) in vec3 inLightVec; +layout (location = 4) in vec3 inWorldPos; +layout (location = 5) in vec3 inLightPos; + +layout (location = 0) out vec4 outFragColor; + +#define EPSILON 0.15 +#define SHADOW_OPACITY 0.5 + +void main() +{ + // Lighting + vec3 N = normalize(inNormal); + vec3 L = normalize(vec3(1.0)); + + vec3 Eye = normalize(-inEyePos); + vec3 Reflected = normalize(reflect(-inLightVec, inNormal)); + + vec4 IAmbient = vec4(vec3(0.05), 1.0); + vec4 IDiffuse = vec4(1.0) * max(dot(inNormal, inLightVec), 0.0); + + outFragColor = vec4(IAmbient + IDiffuse * vec4(inColor, 1.0)); + + // Shadow + vec3 lightVec = inWorldPos - inLightPos; + float sampledDist = texture(shadowCubeMap, lightVec).r; + float dist = length(lightVec); + + // Check if fragment is in shadow + float shadow = (dist <= sampledDist + EPSILON) ? 1.0 : SHADOW_OPACITY; + + outFragColor.rgb *= shadow; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/shadowmapomni/scene.vert b/tests/glsl/sascha-willems/shadowmapomni/scene.vert new file mode 100644 index 000000000..aed2c97ae --- /dev/null +++ b/tests/glsl/sascha-willems/shadowmapomni/scene.vert @@ -0,0 +1,43 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 2) in vec3 inColor; +layout (location = 3) in vec3 inNormal; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 view; + mat4 model; + vec4 lightPos; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec3 outEyePos; +layout (location = 3) out vec3 outLightVec; +layout (location = 4) out vec3 outWorldPos; +layout (location = 5) out vec3 outLightPos; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outColor = inColor; + outNormal = inNormal; + + gl_Position = ubo.projection * ubo.view * ubo.model * vec4(inPos.xyz, 1.0); + outEyePos = vec3(ubo.model * vec4(inPos, 1.0f)); + outLightVec = normalize(ubo.lightPos.xyz - inPos.xyz); + outWorldPos = inPos; + + outLightPos = ubo.lightPos.xyz; +} + diff --git a/tests/glsl/sascha-willems/shadowmapping/offscreen.frag b/tests/glsl/sascha-willems/shadowmapping/offscreen.frag new file mode 100644 index 000000000..81c8f55a3 --- /dev/null +++ b/tests/glsl/sascha-willems/shadowmapping/offscreen.frag @@ -0,0 +1,14 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout(location = 0) out vec4 color; +//layout(location = 0) out float fragmentdepth; + +void main() +{ +// fragmentdepth = gl_FragCoord.z; + color = vec4(1.0, 0.0, 0.0, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/shadowmapping/offscreen.vert b/tests/glsl/sascha-willems/shadowmapping/offscreen.vert new file mode 100644 index 000000000..e5d18fc88 --- /dev/null +++ b/tests/glsl/sascha-willems/shadowmapping/offscreen.vert @@ -0,0 +1,23 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; + +layout (binding = 0) uniform UBO +{ + mat4 depthMVP; +} ubo; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + + +void main() +{ + gl_Position = ubo.depthMVP * vec4(inPos, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/shadowmapping/quad.frag b/tests/glsl/sascha-willems/shadowmapping/quad.frag new file mode 100644 index 000000000..3074bd5ee --- /dev/null +++ b/tests/glsl/sascha-willems/shadowmapping/quad.frag @@ -0,0 +1,25 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColor; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out vec4 outFragColor; + +float LinearizeDepth(float depth) +{ + float n = 1.0; // camera z near + float f = 128.0; // camera z far + float z = depth; + return (2.0 * n) / (f + n - z * (f - n)); +} + +void main() +{ + float depth = texture(samplerColor, inUV).r; + outFragColor = vec4(vec3(1.0-LinearizeDepth(depth)), 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/shadowmapping/quad.vert b/tests/glsl/sascha-willems/shadowmapping/quad.vert new file mode 100644 index 000000000..7c1286a4c --- /dev/null +++ b/tests/glsl/sascha-willems/shadowmapping/quad.vert @@ -0,0 +1,28 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; +} ubo; + +layout (location = 0) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + + +void main() +{ + outUV = inUV; + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); +} diff --git a/tests/glsl/sascha-willems/shadowmapping/scene.frag b/tests/glsl/sascha-willems/shadowmapping/scene.frag new file mode 100644 index 000000000..58e2986ce --- /dev/null +++ b/tests/glsl/sascha-willems/shadowmapping/scene.frag @@ -0,0 +1,72 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D shadowMap; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec3 inViewVec; +layout (location = 3) in vec3 inLightVec; +layout (location = 4) in vec4 inShadowCoord; + +layout (constant_id = 0) const int enablePCF = 0; + +layout (location = 0) out vec4 outFragColor; + +#define ambient 0.1 + +float textureProj(vec4 P, vec2 off) +{ + float shadow = 1.0; + vec4 shadowCoord = P / P.w; + if ( shadowCoord.z > -1.0 && shadowCoord.z < 1.0 ) + { + float dist = texture( shadowMap, shadowCoord.st + off ).r; + if ( shadowCoord.w > 0.0 && dist < shadowCoord.z ) + { + shadow = ambient; + } + } + return shadow; +} + +float filterPCF(vec4 sc) +{ + ivec2 texDim = textureSize(shadowMap, 0); + float scale = 1.5; + float dx = scale * 1.0 / float(texDim.x); + float dy = scale * 1.0 / float(texDim.y); + + float shadowFactor = 0.0; + int count = 0; + int range = 1; + + for (int x = -range; x <= range; x++) + { + for (int y = -range; y <= range; y++) + { + shadowFactor += textureProj(sc, vec2(dx*x, dy*y)); + count++; + } + + } + return shadowFactor / count; +} + +void main() +{ + float shadow = (enablePCF == 1) ? filterPCF(inShadowCoord / inShadowCoord.w) : textureProj(inShadowCoord / inShadowCoord.w, vec2(0.0)); + + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = normalize(-reflect(L, N)); + vec3 diffuse = max(dot(N, L), ambient) * inColor; +// vec3 specular = pow(max(dot(R, V), 0.0), 50.0) * vec3(0.75); + + outFragColor = vec4(diffuse * shadow, 1.0); + +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/shadowmapping/scene.vert b/tests/glsl/sascha-willems/shadowmapping/scene.vert new file mode 100644 index 000000000..6fda339c3 --- /dev/null +++ b/tests/glsl/sascha-willems/shadowmapping/scene.vert @@ -0,0 +1,52 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inColor; +layout (location = 3) in vec3 inNormal; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 view; + mat4 model; + mat4 lightSpace; + vec3 lightPos; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec3 outViewVec; +layout (location = 3) out vec3 outLightVec; +layout (location = 4) out vec4 outShadowCoord; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +const mat4 biasMat = mat4( + 0.5, 0.0, 0.0, 0.0, + 0.0, 0.5, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.5, 0.5, 0.0, 1.0 ); + +void main() +{ + outColor = inColor; + outNormal = inNormal; + + gl_Position = ubo.projection * ubo.view * ubo.model * vec4(inPos.xyz, 1.0); + + vec4 pos = ubo.model * vec4(inPos, 1.0); + outNormal = mat3(ubo.model) * inNormal; + outLightVec = normalize(ubo.lightPos - inPos); + outViewVec = -pos.xyz; + + outShadowCoord = ( biasMat * ubo.lightSpace * ubo.model ) * vec4(inPos, 1.0); +} + diff --git a/tests/glsl/sascha-willems/skeletalanimation/mesh.frag b/tests/glsl/sascha-willems/skeletalanimation/mesh.frag new file mode 100644 index 000000000..c25560d09 --- /dev/null +++ b/tests/glsl/sascha-willems/skeletalanimation/mesh.frag @@ -0,0 +1,28 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColorMap; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec4 color = texture(samplerColorMap, inUV) * vec4(inColor, 1.0); + + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 diffuse = max(dot(N, L), 0.0) * vec3(1.0);// * inColor; + vec3 specular = pow(max(dot(R, V), 0.0), 32.0) * vec3(0.5); + outFragColor = vec4(diffuse * color.rgb + specular, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/skeletalanimation/mesh.vert b/tests/glsl/sascha-willems/skeletalanimation/mesh.vert new file mode 100644 index 000000000..ca11e0b42 --- /dev/null +++ b/tests/glsl/sascha-willems/skeletalanimation/mesh.vert @@ -0,0 +1,53 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inColor; +layout (location = 4) in vec4 inBoneWeights; +layout (location = 5) in ivec4 inBoneIDs; + +#define MAX_BONES 64 + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 view; + mat4 model; + mat4 bones[MAX_BONES]; + vec4 lightPos; + vec4 viewPos; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec2 outUV; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + mat4 boneTransform = ubo.bones[inBoneIDs[0]] * inBoneWeights[0]; + boneTransform += ubo.bones[inBoneIDs[1]] * inBoneWeights[1]; + boneTransform += ubo.bones[inBoneIDs[2]] * inBoneWeights[2]; + boneTransform += ubo.bones[inBoneIDs[3]] * inBoneWeights[3]; + + outColor = inColor; + outUV = inUV; + + gl_Position = ubo.projection * ubo.view * ubo.model * boneTransform * vec4(inPos.xyz, 1.0); + + vec4 pos = ubo.model * vec4(inPos, 1.0); + outNormal = mat3(inverse(transpose(ubo.model * boneTransform))) * inNormal; + outLightVec = ubo.lightPos.xyz - pos.xyz; + outViewVec = ubo.viewPos.xyz - pos.xyz; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/skeletalanimation/texture.frag b/tests/glsl/sascha-willems/skeletalanimation/texture.frag new file mode 100644 index 000000000..1adb226bb --- /dev/null +++ b/tests/glsl/sascha-willems/skeletalanimation/texture.frag @@ -0,0 +1,32 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColorMap; + +layout (location = 0) in vec2 inUV; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec3 inViewVec; +layout (location = 3) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec4 color = texture(samplerColorMap, inUV); + + float distSqr = dot(inLightVec, inLightVec); + vec3 lVec = inLightVec * inversesqrt(distSqr); + + const float attInvRadius = 1.0/5000.0; + float atten = max(clamp(1.0 - attInvRadius * sqrt(distSqr), 0.0, 1.0), 0.0); + + // Fake drop shadow + const float shadowInvRadius = 1.0/2500.0; + float dropshadow = max(clamp(1.0 - shadowInvRadius * sqrt(distSqr), 0.0, 1.0), 0.0); + + outFragColor = vec4(color.rgba * (1.0 - dropshadow)); + outFragColor.rgb *= atten; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/skeletalanimation/texture.vert b/tests/glsl/sascha-willems/skeletalanimation/texture.vert new file mode 100644 index 000000000..67b3f2334 --- /dev/null +++ b/tests/glsl/sascha-willems/skeletalanimation/texture.vert @@ -0,0 +1,40 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + mat4 view; + vec4 lightPos; + vec4 viewPos; + vec2 uvOffset; +} ubo; + +layout (location = 0) out vec2 outUV; +layout (location = 1) out vec3 outNormal; +layout (location = 2) out vec3 outViewVec; +layout (location = 3) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = inUV + ubo.uvOffset; + vec4 pos = vec4(inPos, 1.0); + gl_Position = ubo.projection * ubo.view * ubo.model * vec4(pos); + + outNormal = mat3(ubo.model) * inNormal; + outLightVec = ubo.lightPos.xyz - pos.xyz; + outViewVec = ubo.viewPos.xyz - pos.xyz; +} diff --git a/tests/glsl/sascha-willems/specializationconstants/uber.frag b/tests/glsl/sascha-willems/specializationconstants/uber.frag new file mode 100644 index 000000000..9661dff03 --- /dev/null +++ b/tests/glsl/sascha-willems/specializationconstants/uber.frag @@ -0,0 +1,75 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColormap; +layout (binding = 2) uniform sampler2D samplerDiscard; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +// We use this constant to control the flow of the shader depending on the +// lighting model selected at pipeline creation time +layout (constant_id = 0) const int LIGHTING_MODEL = 0; +// Parameter for the toon shading part of the shader +layout (constant_id = 1) const float PARAM_TOON_DESATURATION = 0.0f; + +void main() +{ + switch (LIGHTING_MODEL) { + case 0: // Phong + { + vec3 ambient = inColor * vec3(0.25); + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 diffuse = max(dot(N, L), 0.0) * inColor; + vec3 specular = pow(max(dot(R, V), 0.0), 32.0) * vec3(0.75); + outFragColor = vec4(ambient + diffuse * 1.75 + specular, 1.0); + break; + } + case 1: // Toon + { + + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + float intensity = dot(N,L); + vec3 color; + if (intensity > 0.98) + color = inColor * 1.5; + else if (intensity > 0.9) + color = inColor * 1.0; + else if (intensity > 0.5) + color = inColor * 0.6; + else if (intensity > 0.25) + color = inColor * 0.4; + else + color = inColor * 0.2; + // Desaturate a bit + color = vec3(mix(color, vec3(dot(vec3(0.2126,0.7152,0.0722), color)), PARAM_TOON_DESATURATION)); + outFragColor.rgb = color; + break; + } + case 2: // Textured + { + vec4 color = texture(samplerColormap, inUV).rrra; + vec3 ambient = color.rgb * vec3(0.25) * inColor; + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 diffuse = max(dot(N, L), 0.0) * color.rgb; + float specular = pow(max(dot(R, V), 0.0), 32.0) * color.a; + outFragColor = vec4(ambient + diffuse + vec3(specular), 1.0); + break; + } + } +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/specializationconstants/uber.vert b/tests/glsl/sascha-willems/specializationconstants/uber.vert new file mode 100644 index 000000000..44fd2e692 --- /dev/null +++ b/tests/glsl/sascha-willems/specializationconstants/uber.vert @@ -0,0 +1,42 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; +layout (location = 3) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + vec4 lightPos; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec2 outUV; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outNormal = inNormal; + outColor = inColor; + outUV = inUV; + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); + + vec4 pos = ubo.model * vec4(inPos, 1.0); + outNormal = mat3(ubo.model) * inNormal; + vec3 lPos = mat3(ubo.model) * ubo.lightPos.xyz; + outLightVec = lPos - pos.xyz; + outViewVec = -pos.xyz; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/sphericalenvmapping/sem.frag b/tests/glsl/sascha-willems/sphericalenvmapping/sem.frag new file mode 100644 index 000000000..6735ee03c --- /dev/null +++ b/tests/glsl/sascha-willems/sphericalenvmapping/sem.frag @@ -0,0 +1,23 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2DArray matCap; + +layout (location = 0) in vec3 inColor; +layout (location = 1) in vec3 inEyePos; +layout (location = 2) in vec3 inNormal; +layout (location = 3) in flat int inTexIndex; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec3 r = reflect( inEyePos, inNormal ); + vec3 r2 = vec3( r.x, r.y, r.z + 1.0 ); + float m = 2.0 * length( r2 ); + vec2 vN = r.xy / m + .5; + outFragColor = vec4( texture( matCap, vec3(vN, inTexIndex)).rgb * (clamp(inColor.r * 2, 0.0, 1.0)), 1.0 ); +} diff --git a/tests/glsl/sascha-willems/sphericalenvmapping/sem.vert b/tests/glsl/sascha-willems/sphericalenvmapping/sem.vert new file mode 100644 index 000000000..bb94e3f0e --- /dev/null +++ b/tests/glsl/sascha-willems/sphericalenvmapping/sem.vert @@ -0,0 +1,35 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 3) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + mat4 normal; + mat4 view; + int texIndex; +} ubo; + +layout (location = 0) out vec3 outColor; +layout (location = 1) out vec3 outEyePos; +layout (location = 2) out vec3 outNormal; +layout (location = 3) out flat int outTexIndex; + +void main() +{ + outColor = inColor; + mat4 modelView = ubo.view * ubo.model; + outEyePos = normalize( vec3( modelView * inPos ) ); + outTexIndex = ubo.texIndex; + outNormal = normalize( mat3(ubo.normal) * inNormal ); + vec3 r = reflect( outEyePos, outNormal ); + float m = 2.0 * sqrt( pow(r.x, 2.0) + pow(r.y, 2.0) + pow(r.z + 1.0, 2.0)); + gl_Position = ubo.projection * modelView * inPos; +} diff --git a/tests/glsl/sascha-willems/ssao/blur.frag b/tests/glsl/sascha-willems/ssao/blur.frag new file mode 100644 index 000000000..23b808d9b --- /dev/null +++ b/tests/glsl/sascha-willems/ssao/blur.frag @@ -0,0 +1,29 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 0) uniform sampler2D samplerSSAO; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out float outFragColor; + +void main() +{ + const int blurRange = 2; + int n = 0; + vec2 texelSize = 1.0 / vec2(textureSize(samplerSSAO, 0)); + float result = 0.0; + for (int x = -blurRange; x < blurRange; x++) + { + for (int y = -blurRange; y < blurRange; y++) + { + vec2 offset = vec2(float(x), float(y)) * texelSize; + result += texture(samplerSSAO, inUV + offset).r; + n++; + } + } + outFragColor = result / (float(n)); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/ssao/composition.frag b/tests/glsl/sascha-willems/ssao/composition.frag new file mode 100644 index 000000000..edf49b5d3 --- /dev/null +++ b/tests/glsl/sascha-willems/ssao/composition.frag @@ -0,0 +1,56 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 0) uniform sampler2D samplerposition; +layout (binding = 1) uniform sampler2D samplerNormal; +layout (binding = 2) uniform sampler2D samplerAlbedo; +layout (binding = 3) uniform sampler2D samplerSSAO; +layout (binding = 4) uniform sampler2D samplerSSAOBlur; +layout (binding = 5) uniform UBO +{ + mat4 _dummy; + uint ssao; + uint ssaoOnly; + uint ssaoBlur; +} uboParams; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec3 fragPos = texture(samplerposition, inUV).rgb; + vec3 normal = normalize(texture(samplerNormal, inUV).rgb * 2.0 - 1.0); + vec4 albedo = texture(samplerAlbedo, inUV); + + float ssao = (uboParams.ssaoBlur == 1) ? texture(samplerSSAOBlur, inUV).r : texture(samplerSSAO, inUV).r; + + vec3 lightPos = vec3(0.0); + vec3 L = normalize(lightPos - fragPos); + float NdotL = max(0.5, dot(normal, L)); + + if (uboParams.ssaoOnly == 1) + { + outFragColor.rgb = ssao.rrr; + } + else + { + vec3 baseColor = albedo.rgb * NdotL; + + if (uboParams.ssao == 1) + { + outFragColor.rgb = ssao.rrr; + + if (uboParams.ssaoOnly != 1) + outFragColor.rgb *= baseColor; + } + else + { + outFragColor.rgb = baseColor; + } + } +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/ssao/fullscreen.vert b/tests/glsl/sascha-willems/ssao/fullscreen.vert new file mode 100644 index 000000000..117eb02ec --- /dev/null +++ b/tests/glsl/sascha-willems/ssao/fullscreen.vert @@ -0,0 +1,18 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); + gl_Position = vec4(outUV * 2.0f - 1.0f, 0.0f, 1.0f); +} diff --git a/tests/glsl/sascha-willems/ssao/gbuffer.frag b/tests/glsl/sascha-willems/ssao/gbuffer.frag new file mode 100644 index 000000000..9e81b9231 --- /dev/null +++ b/tests/glsl/sascha-willems/ssao/gbuffer.frag @@ -0,0 +1,30 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inColor; +layout (location = 3) in vec3 inPos; + +layout (location = 0) out vec4 outPosition; +layout (location = 1) out vec4 outNormal; +layout (location = 2) out vec4 outAlbedo; + +const float NEAR_PLANE = 0.1f; //todo: specialization const +const float FAR_PLANE = 64.0f; //todo: specialization const + +float linearDepth(float depth) +{ + float z = depth * 2.0f - 1.0f; + return (2.0f * NEAR_PLANE * FAR_PLANE) / (FAR_PLANE + NEAR_PLANE - z * (FAR_PLANE - NEAR_PLANE)); +} + +void main() +{ + outPosition = vec4(inPos, linearDepth(gl_FragCoord.z)); + outNormal = vec4(normalize(inNormal) * 0.5 + 0.5, 1.0); + outAlbedo = vec4(inColor * 2.0, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/ssao/gbuffer.vert b/tests/glsl/sascha-willems/ssao/gbuffer.vert new file mode 100644 index 000000000..3160cf949 --- /dev/null +++ b/tests/glsl/sascha-willems/ssao/gbuffer.vert @@ -0,0 +1,43 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inColor; +layout (location = 3) in vec3 inNormal; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + mat4 view; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec2 outUV; +layout (location = 2) out vec3 outColor; +layout (location = 3) out vec3 outPos; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + gl_Position = ubo.projection * ubo.view * ubo.model * inPos; + + outUV = inUV; + + // Vertex position in view space + outPos = vec3(ubo.view * ubo.model * inPos); + + // Normal in view space + mat3 normalMatrix = transpose(inverse(mat3(ubo.view * ubo.model))); + outNormal = normalMatrix * inNormal; + + outColor = inColor; +} diff --git a/tests/glsl/sascha-willems/ssao/ssao.frag b/tests/glsl/sascha-willems/ssao/ssao.frag new file mode 100644 index 000000000..cdcbfd3ec --- /dev/null +++ b/tests/glsl/sascha-willems/ssao/ssao.frag @@ -0,0 +1,73 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 0) uniform sampler2D samplerPositionDepth; +layout (binding = 1) uniform sampler2D samplerNormal; +layout (binding = 2) uniform sampler2D ssaoNoise; + +layout (constant_id = 0) const int SSAO_KERNEL_SIZE = 64; +layout (constant_id = 1) const float SSAO_RADIUS = 0.5; + +layout (binding = 3) uniform UBOSSAOKernel +{ + vec4 samples[SSAO_KERNEL_SIZE]; +} uboSSAOKernel; + +layout (binding = 4) uniform UBO +{ + mat4 projection; +} ubo; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out float outFragColor; + +void main() +{ + // Get G-Buffer values + vec3 fragPos = texture(samplerPositionDepth, inUV).rgb; + vec3 normal = normalize(texture(samplerNormal, inUV).rgb * 2.0 - 1.0); + + // Get a random vector using a noise lookup + ivec2 texDim = textureSize(samplerPositionDepth, 0); + ivec2 noiseDim = textureSize(ssaoNoise, 0); + const vec2 noiseUV = vec2(float(texDim.x)/float(noiseDim.x), float(texDim.y)/(noiseDim.y)) * inUV; + vec3 randomVec = texture(ssaoNoise, noiseUV).xyz * 2.0 - 1.0; + + // Create TBN matrix + vec3 tangent = normalize(randomVec - normal * dot(randomVec, normal)); + vec3 bitangent = cross(tangent, normal); + mat3 TBN = mat3(tangent, bitangent, normal); + + // Calculate occlusion value + float occlusion = 0.0f; + for(int i = 0; i < SSAO_KERNEL_SIZE; i++) + { + vec3 samplePos = TBN * uboSSAOKernel.samples[i].xyz; + samplePos = fragPos + samplePos * SSAO_RADIUS; + + // project + vec4 offset = vec4(samplePos, 1.0f); + offset = ubo.projection * offset; + offset.xyz /= offset.w; + offset.xyz = offset.xyz * 0.5f + 0.5f; + + float sampleDepth = -texture(samplerPositionDepth, offset.xy).w; + +#define RANGE_CHECK 1 +#ifdef RANGE_CHECK + // Range check + float rangeCheck = smoothstep(0.0f, 1.0f, SSAO_RADIUS / abs(fragPos.z - sampleDepth)); + occlusion += (sampleDepth >= samplePos.z ? 1.0f : 0.0f) * rangeCheck; +#else + occlusion += (sampleDepth >= samplePos.z ? 1.0f : 0.0f); +#endif + } + occlusion = 1.0 - (occlusion / float(SSAO_KERNEL_SIZE)); + + outFragColor = occlusion; +} + diff --git a/tests/glsl/sascha-willems/subpasses/composition.frag b/tests/glsl/sascha-willems/subpasses/composition.frag new file mode 100644 index 000000000..0a538471a --- /dev/null +++ b/tests/glsl/sascha-willems/subpasses/composition.frag @@ -0,0 +1,82 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (input_attachment_index = 0, binding = 0) uniform subpassInput samplerposition; +layout (input_attachment_index = 1, binding = 1) uniform subpassInput samplerNormal; +layout (input_attachment_index = 2, binding = 2) uniform subpassInput samplerAlbedo; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out vec4 outFragcolor; +layout (location = 1) out vec4 outPosition; +layout (location = 2) out vec4 outNormal; +layout (location = 3) out vec4 outAlbedo; + +layout (constant_id = 0) const int NUM_LIGHTS = 64; + +struct Light { + vec4 position; + vec3 color; + float radius; +}; + +layout (binding = 3) uniform UBO +{ + vec4 viewPos; + Light lights[NUM_LIGHTS]; +} ubo; + + +void main() +{ + // Read G-Buffer values from previous sub pass + vec3 fragPos = subpassLoad(samplerposition).rgb; + vec3 normal = subpassLoad(samplerNormal).rgb; + vec4 albedo = subpassLoad(samplerAlbedo); + + #define ambient 0.15 + + // Ambient part + vec3 fragcolor = albedo.rgb * ambient; + + for(int i = 0; i < NUM_LIGHTS; ++i) + { + // Vector to light + vec3 L = ubo.lights[i].position.xyz - fragPos; + // Distance from light to fragment position + float dist = length(L); + + // Viewer to fragment + vec3 V = ubo.viewPos.xyz - fragPos; + V = normalize(V); + + // Light to fragment + L = normalize(L); + + // Attenuation + float atten = ubo.lights[i].radius / (pow(dist, 2.0) + 1.0); + + // Diffuse part + vec3 N = normalize(normal); + float NdotL = max(0.0, dot(N, L)); + vec3 diff = ubo.lights[i].color * albedo.rgb * NdotL * atten; + + // Specular part + // Specular map values are stored in alpha of albedo mrt + vec3 R = reflect(-L, N); + float NdotR = max(0.0, dot(R, V)); + //vec3 spec = ubo.lights[i].color * albedo.a * pow(NdotR, 32.0) * atten; + + fragcolor += diff;// + spec; + } + + outFragcolor = vec4(fragcolor, 1.0); + + // Write G-Buffer attachments to avoid undefined behaviour (validation error) + outPosition = vec4(0.0); + outNormal = vec4(0.0); + outAlbedo = vec4(0.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/subpasses/composition.vert b/tests/glsl/sascha-willems/subpasses/composition.vert new file mode 100644 index 000000000..f463f9182 --- /dev/null +++ b/tests/glsl/sascha-willems/subpasses/composition.vert @@ -0,0 +1,18 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); + gl_Position = vec4(outUV * 2.0f - 1.0f, 0.0f, 1.0f); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/subpasses/gbuffer.frag b/tests/glsl/sascha-willems/subpasses/gbuffer.frag new file mode 100644 index 000000000..389d1aa80 --- /dev/null +++ b/tests/glsl/sascha-willems/subpasses/gbuffer.frag @@ -0,0 +1,43 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColor; +layout (binding = 2) uniform sampler2D samplerNormalMap; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec3 inWorldPos; + +layout (location = 0) out vec4 outColor; +layout (location = 1) out vec4 outPosition; +layout (location = 2) out vec4 outNormal; +layout (location = 3) out vec4 outAlbedo; + +layout (constant_id = 0) const float NEAR_PLANE = 0.1f; +layout (constant_id = 1) const float FAR_PLANE = 256.0f; + +float linearDepth(float depth) +{ + float z = depth * 2.0f - 1.0f; + return (2.0f * NEAR_PLANE * FAR_PLANE) / (FAR_PLANE + NEAR_PLANE - z * (FAR_PLANE - NEAR_PLANE)); +} + +void main() +{ + outPosition = vec4(inWorldPos, 1.0); + + vec3 N = normalize(inNormal); + N.y = -N.y; + outNormal = vec4(N, 1.0); + + outAlbedo.rgb = inColor; + + // Store linearized depth in alpha component + outPosition.a = linearDepth(gl_FragCoord.z); + + // Write color attachments to avoid undefined behaviour (validation error) + outColor = vec4(0.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/subpasses/gbuffer.vert b/tests/glsl/sascha-willems/subpasses/gbuffer.vert new file mode 100644 index 000000000..c57d04e6d --- /dev/null +++ b/tests/glsl/sascha-willems/subpasses/gbuffer.vert @@ -0,0 +1,43 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec3 inNormal; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + mat4 view; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec3 outWorldPos; +layout (location = 3) out vec3 outTangent; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + gl_Position = ubo.projection * ubo.view * ubo.model * inPos; + + // Vertex position in world space + outWorldPos = vec3(ubo.model * inPos); + // GL to Vulkan coord space + outWorldPos.y = -outWorldPos.y; + + // Normal in world space + mat3 mNormal = transpose(inverse(mat3(ubo.model))); + outNormal = mNormal * normalize(inNormal); + + // Currently just vertex color + outColor = inColor; +} diff --git a/tests/glsl/sascha-willems/subpasses/transparent.frag b/tests/glsl/sascha-willems/subpasses/transparent.frag new file mode 100644 index 000000000..f293f2b8c --- /dev/null +++ b/tests/glsl/sascha-willems/subpasses/transparent.frag @@ -0,0 +1,34 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (input_attachment_index = 0, binding = 1) uniform subpassInput samplerPositionDepth; +layout (binding = 2) uniform sampler2D samplerTexture; + +layout (location = 0) in vec3 inColor; +layout (location = 1) in vec2 inUV; + +layout (location = 0) out vec4 outColor; + +layout (constant_id = 0) const float NEAR_PLANE = 0.1f; +layout (constant_id = 1) const float FAR_PLANE = 256.0f; + +float linearDepth(float depth) +{ + float z = depth * 2.0f - 1.0f; + return (2.0f * NEAR_PLANE * FAR_PLANE) / (FAR_PLANE + NEAR_PLANE - z * (FAR_PLANE - NEAR_PLANE)); +} + +void main () +{ + // Sample depth from deferred depth buffer and discard if obscured + float depth = subpassLoad(samplerPositionDepth).a; + if ((depth != 0.0) && (linearDepth(gl_FragCoord.z) > depth)) + { + discard; + }; + + outColor = texture(samplerTexture, inUV); +} diff --git a/tests/glsl/sascha-willems/subpasses/transparent.vert b/tests/glsl/sascha-willems/subpasses/transparent.vert new file mode 100644 index 000000000..8d667b820 --- /dev/null +++ b/tests/glsl/sascha-willems/subpasses/transparent.vert @@ -0,0 +1,28 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec3 inNormal; +layout (location = 3) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + mat4 view; +} ubo; + +layout (location = 0) out vec3 outColor; +layout (location = 1) out vec2 outUV; + +void main () +{ + outColor = inColor; + outUV = inUV; + + gl_Position = ubo.projection * ubo.view * ubo.model * vec4(inPos.xyz, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/terraintessellation/skysphere.frag b/tests/glsl/sascha-willems/terraintessellation/skysphere.frag new file mode 100644 index 000000000..7d87b21cd --- /dev/null +++ b/tests/glsl/sascha-willems/terraintessellation/skysphere.frag @@ -0,0 +1,14 @@ +//TEST:COMPARE_GLSL: +#version 450 core + +layout (location = 0) in vec2 inUV; + +layout (set = 0, binding = 1) uniform sampler2D samplerColorMap; + +layout (location = 0) out vec4 outFragColor; + +void main(void) +{ + vec4 color = texture(samplerColorMap, inUV); + outFragColor = vec4(color.rgb, 1.0); +} diff --git a/tests/glsl/sascha-willems/terraintessellation/skysphere.vert b/tests/glsl/sascha-willems/terraintessellation/skysphere.vert new file mode 100644 index 000000000..74dd7ad3b --- /dev/null +++ b/tests/glsl/sascha-willems/terraintessellation/skysphere.vert @@ -0,0 +1,24 @@ +//TEST:COMPARE_GLSL: +#version 450 core + +layout (location = 0) in vec3 inPos; +layout (location = 2) in vec2 inUV; + +layout (location = 0) out vec2 outUV; + +layout (set = 0, binding = 0) uniform UBO +{ + mat4 mvp; +} ubo; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main(void) +{ + gl_Position = ubo.mvp * vec4(inPos, 1.0); + outUV = inUV; + outUV.t = 1.0 - outUV.t; +} diff --git a/tests/glsl/sascha-willems/terraintessellation/terrain.frag b/tests/glsl/sascha-willems/terraintessellation/terrain.frag new file mode 100644 index 000000000..fcd8612ae --- /dev/null +++ b/tests/glsl/sascha-willems/terraintessellation/terrain.frag @@ -0,0 +1,65 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (set = 0, binding = 1) uniform sampler2D samplerHeight; +layout (set = 0, binding = 2) uniform sampler2DArray samplerLayers; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inViewVec; +layout (location = 3) in vec3 inLightVec; +layout (location = 4) in vec3 inEyePos; +layout (location = 5) in vec3 inWorldPos; + +layout (location = 0) out vec4 outFragColor; + +vec3 sampleTerrainLayer() +{ + // Define some layer ranges for sampling depending on terrain height + vec2 layers[6]; + layers[0] = vec2(-10.0, 10.0); + layers[1] = vec2(5.0, 45.0); + layers[2] = vec2(45.0, 80.0); + layers[3] = vec2(75.0, 100.0); + layers[4] = vec2(95.0, 140.0); + layers[5] = vec2(140.0, 190.0); + + vec3 color = vec3(0.0); + + // Get height from displacement map + float height = textureLod(samplerHeight, inUV, 0.0).r * 255.0; + + for (int i = 0; i < 6; i++) + { + float range = layers[i].y - layers[i].x; + float weight = (range - abs(height - layers[i].y)) / range; + weight = max(0.0, weight); + color += weight * texture(samplerLayers, vec3(inUV * 16.0, i)).rgb; + } + + return color; +} + +float fog(float density) +{ + const float LOG2 = -1.442695; + float dist = gl_FragCoord.z / gl_FragCoord.w * 0.1; + float d = density * dist; + return 1.0 - clamp(exp2(d * d * LOG2), 0.0, 1.0); +} + +void main() +{ + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 ambient = vec3(0.5); + vec3 diffuse = max(dot(N, L), 0.0) * vec3(1.0); + + vec4 color = vec4((ambient + diffuse) * sampleTerrainLayer(), 1.0); + + const vec4 fogColor = vec4(0.47, 0.5, 0.67, 0.0); + outFragColor = mix(color, fogColor, fog(0.25)); +} diff --git a/tests/glsl/sascha-willems/terraintessellation/terrain.tesc b/tests/glsl/sascha-willems/terraintessellation/terrain.tesc new file mode 100644 index 000000000..133e44ea7 --- /dev/null +++ b/tests/glsl/sascha-willems/terraintessellation/terrain.tesc @@ -0,0 +1,120 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout(set = 0, binding = 0) uniform UBO +{ + mat4 projection; + mat4 modelview; + vec4 lightPos; + vec4 frustumPlanes[6]; + float displacementFactor; + float tessellationFactor; + vec2 viewportDim; + float tessellatedEdgeSize; +} ubo; + +layout(set = 0, binding = 1) uniform sampler2D samplerHeight; + +layout (vertices = 4) out; + +layout (location = 0) in vec3 inNormal[]; +layout (location = 1) in vec2 inUV[]; + +layout (location = 0) out vec3 outNormal[4]; +layout (location = 1) out vec2 outUV[4]; + +// Calculate the tessellation factor based on screen space +// dimensions of the edge +float screenSpaceTessFactor(vec4 p0, vec4 p1) +{ + // Calculate edge mid point + vec4 midPoint = 0.5 * (p0 + p1); + // Sphere radius as distance between the control points + float radius = distance(p0, p1) / 2.0; + + // View space + vec4 v0 = ubo.modelview * midPoint; + + // Project into clip space + vec4 clip0 = (ubo.projection * (v0 - vec4(radius, vec3(0.0)))); + vec4 clip1 = (ubo.projection * (v0 + vec4(radius, vec3(0.0)))); + + // Get normalized device coordinates + clip0 /= clip0.w; + clip1 /= clip1.w; + + // Convert to viewport coordinates + clip0.xy *= ubo.viewportDim; + clip1.xy *= ubo.viewportDim; + + // Return the tessellation factor based on the screen size + // given by the distance of the two edge control points in screen space + // and a reference (min.) tessellation size for the edge set by the application + return clamp(distance(clip0, clip1) / ubo.tessellatedEdgeSize * ubo.tessellationFactor, 1.0, 64.0); +} + +// Checks the current's patch visibility against the frustum using a sphere check +// Sphere radius is given by the patch size +bool frustumCheck() +{ + // Fixed radius (increase if patch size is increased in example) + const float radius = 8.0f; + vec4 pos = gl_in[gl_InvocationID].gl_Position; + pos.y -= textureLod(samplerHeight, inUV[0], 0.0).r * ubo.displacementFactor; + + // Check sphere against frustum planes + for (int i = 0; i < 6; i++) { + if (dot(pos, ubo.frustumPlanes[i]) + radius < 0.0) + { + return false; + } + } + return true; +} + +void main() +{ + if (gl_InvocationID == 0) + { + if (!frustumCheck()) + { + gl_TessLevelInner[0] = 0.0; + gl_TessLevelInner[1] = 0.0; + gl_TessLevelOuter[0] = 0.0; + gl_TessLevelOuter[1] = 0.0; + gl_TessLevelOuter[2] = 0.0; + gl_TessLevelOuter[3] = 0.0; + } + else + { + if (ubo.tessellationFactor > 0.0) + { + gl_TessLevelOuter[0] = screenSpaceTessFactor(gl_in[3].gl_Position, gl_in[0].gl_Position); + gl_TessLevelOuter[1] = screenSpaceTessFactor(gl_in[0].gl_Position, gl_in[1].gl_Position); + gl_TessLevelOuter[2] = screenSpaceTessFactor(gl_in[1].gl_Position, gl_in[2].gl_Position); + gl_TessLevelOuter[3] = screenSpaceTessFactor(gl_in[2].gl_Position, gl_in[3].gl_Position); + gl_TessLevelInner[0] = mix(gl_TessLevelOuter[0], gl_TessLevelOuter[3], 0.5); + gl_TessLevelInner[1] = mix(gl_TessLevelOuter[2], gl_TessLevelOuter[1], 0.5); + } + else + { + // Tessellation factor can be set to zero by example + // to demonstrate a simple passthrough + gl_TessLevelInner[0] = 1.0; + gl_TessLevelInner[1] = 1.0; + gl_TessLevelOuter[0] = 1.0; + gl_TessLevelOuter[1] = 1.0; + gl_TessLevelOuter[2] = 1.0; + gl_TessLevelOuter[3] = 1.0; + } + } + + } + + gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position; + outNormal[gl_InvocationID] = inNormal[gl_InvocationID]; + outUV[gl_InvocationID] = inUV[gl_InvocationID]; +} diff --git a/tests/glsl/sascha-willems/terraintessellation/terrain.tese b/tests/glsl/sascha-willems/terraintessellation/terrain.tese new file mode 100644 index 000000000..1a74ac377 --- /dev/null +++ b/tests/glsl/sascha-willems/terraintessellation/terrain.tese @@ -0,0 +1,58 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (set = 0, binding = 0) uniform UBO +{ + mat4 projection; + mat4 modelview; + vec4 lightPos; + vec4 frustumPlanes[6]; + float displacementFactor; + float tessellationFactor; + vec2 viewportDim; + float tessellatedEdgeSize; +} ubo; + +layout (set = 0, binding = 1) uniform sampler2D displacementMap; + +layout(quads, equal_spacing, cw) in; + +layout (location = 0) in vec3 inNormal[]; +layout (location = 1) in vec2 inUV[]; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec2 outUV; +layout (location = 2) out vec3 outViewVec; +layout (location = 3) out vec3 outLightVec; +layout (location = 4) out vec3 outEyePos; +layout (location = 5) out vec3 outWorldPos; + +void main() +{ + // Interpolate UV coordinates + vec2 uv1 = mix(inUV[0], inUV[1], gl_TessCoord.x); + vec2 uv2 = mix(inUV[3], inUV[2], gl_TessCoord.x); + outUV = mix(uv1, uv2, gl_TessCoord.y); + + vec3 n1 = mix(inNormal[0], inNormal[1], gl_TessCoord.x); + vec3 n2 = mix(inNormal[3], inNormal[2], gl_TessCoord.x); + outNormal = mix(n1, n2, gl_TessCoord.y); + + // Interpolate positions + vec4 pos1 = mix(gl_in[0].gl_Position, gl_in[1].gl_Position, gl_TessCoord.x); + vec4 pos2 = mix(gl_in[3].gl_Position, gl_in[2].gl_Position, gl_TessCoord.x); + vec4 pos = mix(pos1, pos2, gl_TessCoord.y); + // Displace + pos.y -= textureLod(displacementMap, outUV, 0.0).r * ubo.displacementFactor; + // Perspective projection + gl_Position = ubo.projection * ubo.modelview * pos; + + // Calculate vectors for lighting based on tessellated position + outViewVec = -pos.xyz; + outLightVec = normalize(ubo.lightPos.xyz + outViewVec); + outWorldPos = pos.xyz; + outEyePos = vec3(ubo.modelview * pos); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/terraintessellation/terrain.vert b/tests/glsl/sascha-willems/terraintessellation/terrain.vert new file mode 100644 index 000000000..4a7c6ec66 --- /dev/null +++ b/tests/glsl/sascha-willems/terraintessellation/terrain.vert @@ -0,0 +1,24 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main(void) +{ + gl_Position = vec4(inPos.xyz, 1.0); + outUV = inUV; + outNormal = inNormal; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/tessellation/base.frag b/tests/glsl/sascha-willems/tessellation/base.frag new file mode 100644 index 000000000..3bdd8b954 --- /dev/null +++ b/tests/glsl/sascha-willems/tessellation/base.frag @@ -0,0 +1,22 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 2) uniform sampler2D samplerColorMap; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec2 inUV; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec3 N = normalize(inNormal); + vec3 L = normalize(vec3(0.0, -4.0, 4.0)); + + vec4 color = texture(samplerColorMap, inUV); + + outFragColor.rgb = vec3(clamp(max(dot(N,L), 0.0), 0.2, 1.0)) * color.rgb * 1.5; +} diff --git a/tests/glsl/sascha-willems/tessellation/base.vert b/tests/glsl/sascha-willems/tessellation/base.vert new file mode 100644 index 000000000..0bce97d99 --- /dev/null +++ b/tests/glsl/sascha-willems/tessellation/base.vert @@ -0,0 +1,24 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main(void) +{ + gl_Position = vec4(inPos.xyz, 1.0); + outNormal = inNormal; + outUV = inUV; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/tessellation/passthrough.tesc b/tests/glsl/sascha-willems/tessellation/passthrough.tesc new file mode 100644 index 000000000..348bb43d7 --- /dev/null +++ b/tests/glsl/sascha-willems/tessellation/passthrough.tesc @@ -0,0 +1,28 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (vertices = 3) out; + +layout (location = 0) in vec3 inNormal[]; +layout (location = 1) in vec2 inUV[]; + +layout (location = 0) out vec3 outNormal[3]; +layout (location = 1) out vec2 outUV[3]; + +void main(void) +{ + if (gl_InvocationID == 0) + { + gl_TessLevelInner[0] = 1.0; + gl_TessLevelOuter[0] = 1.0; + gl_TessLevelOuter[1] = 1.0; + gl_TessLevelOuter[2] = 1.0; + } + + gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position; + outNormal[gl_InvocationID] = inNormal[gl_InvocationID]; + outUV[gl_InvocationID] = inUV[gl_InvocationID]; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/tessellation/passthrough.tese b/tests/glsl/sascha-willems/tessellation/passthrough.tese new file mode 100644 index 000000000..42dc5c562 --- /dev/null +++ b/tests/glsl/sascha-willems/tessellation/passthrough.tese @@ -0,0 +1,31 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (triangles) in; + +layout (binding = 1) uniform UBO +{ + mat4 projection; + mat4 model; + float tessAlpha; +} ubo; + +layout (location = 0) in vec3 inNormal[]; +layout (location = 1) in vec2 inUV[]; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec2 outUV; + +void main(void) +{ + gl_Position = (gl_TessCoord.x * gl_in[0].gl_Position) + + (gl_TessCoord.y * gl_in[1].gl_Position) + + (gl_TessCoord.z * gl_in[2].gl_Position); + gl_Position = ubo.projection * ubo.model * gl_Position; + + outNormal = gl_TessCoord.x*inNormal[0] + gl_TessCoord.y*inNormal[1] + gl_TessCoord.z*inNormal[2]; + outUV = gl_TessCoord.x*inUV[0] + gl_TessCoord.y*inUV[1] + gl_TessCoord.z*inUV[2]; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/tessellation/pntriangles.tesc b/tests/glsl/sascha-willems/tessellation/pntriangles.tesc new file mode 100644 index 000000000..90755153c --- /dev/null +++ b/tests/glsl/sascha-willems/tessellation/pntriangles.tesc @@ -0,0 +1,87 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +// PN patch data +struct PnPatch +{ + float b210; + float b120; + float b021; + float b012; + float b102; + float b201; + float b111; + float n110; + float n011; + float n101; +}; + +// tessellation levels +layout (binding = 0) uniform UBO +{ + float tessLevel; +} ubo; + +layout(vertices=3) out; + +layout(location = 0) in vec3 inNormal[]; +layout(location = 1) in vec2 inUV[]; + +layout(location = 0) out vec3 outNormal[3]; +layout(location = 3) out vec2 outUV[3]; +layout(location = 6) out PnPatch outPatch[3]; + +float wij(int i, int j) +{ + return dot(gl_in[j].gl_Position.xyz - gl_in[i].gl_Position.xyz, inNormal[i]); +} + +float vij(int i, int j) +{ + vec3 Pj_minus_Pi = gl_in[j].gl_Position.xyz + - gl_in[i].gl_Position.xyz; + vec3 Ni_plus_Nj = inNormal[i]+inNormal[j]; + return 2.0*dot(Pj_minus_Pi, Ni_plus_Nj)/dot(Pj_minus_Pi, Pj_minus_Pi); +} + +void main() +{ + // get data + gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position; + outNormal[gl_InvocationID] = inNormal[gl_InvocationID]; + outUV[gl_InvocationID] = inUV[gl_InvocationID]; + + // set base + float P0 = gl_in[0].gl_Position[gl_InvocationID]; + float P1 = gl_in[1].gl_Position[gl_InvocationID]; + float P2 = gl_in[2].gl_Position[gl_InvocationID]; + float N0 = inNormal[0][gl_InvocationID]; + float N1 = inNormal[1][gl_InvocationID]; + float N2 = inNormal[2][gl_InvocationID]; + + // compute control points + outPatch[gl_InvocationID].b210 = (2.0*P0 + P1 - wij(0,1)*N0)/3.0; + outPatch[gl_InvocationID].b120 = (2.0*P1 + P0 - wij(1,0)*N1)/3.0; + outPatch[gl_InvocationID].b021 = (2.0*P1 + P2 - wij(1,2)*N1)/3.0; + outPatch[gl_InvocationID].b012 = (2.0*P2 + P1 - wij(2,1)*N2)/3.0; + outPatch[gl_InvocationID].b102 = (2.0*P2 + P0 - wij(2,0)*N2)/3.0; + outPatch[gl_InvocationID].b201 = (2.0*P0 + P2 - wij(0,2)*N0)/3.0; + float E = ( outPatch[gl_InvocationID].b210 + + outPatch[gl_InvocationID].b120 + + outPatch[gl_InvocationID].b021 + + outPatch[gl_InvocationID].b012 + + outPatch[gl_InvocationID].b102 + + outPatch[gl_InvocationID].b201 ) / 6.0; + float V = (P0 + P1 + P2)/3.0; + outPatch[gl_InvocationID].b111 = E + (E - V)*0.5; + outPatch[gl_InvocationID].n110 = N0+N1-vij(0,1)*(P1-P0); + outPatch[gl_InvocationID].n011 = N1+N2-vij(1,2)*(P2-P1); + outPatch[gl_InvocationID].n101 = N2+N0-vij(2,0)*(P0-P2); + + // set tess levels + gl_TessLevelOuter[gl_InvocationID] = ubo.tessLevel; + gl_TessLevelInner[0] = ubo.tessLevel; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/tessellation/pntriangles.tese b/tests/glsl/sascha-willems/tessellation/pntriangles.tese new file mode 100644 index 000000000..0187ad781 --- /dev/null +++ b/tests/glsl/sascha-willems/tessellation/pntriangles.tese @@ -0,0 +1,92 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +// PN patch data +struct PnPatch +{ + float b210; + float b120; + float b021; + float b012; + float b102; + float b201; + float b111; + float n110; + float n011; + float n101; +}; + +layout (binding = 1) uniform UBO +{ + mat4 projection; + mat4 model; + float tessAlpha; +} ubo; + +layout(triangles, fractional_odd_spacing, ccw) in; + +layout(location = 0) in vec3 iNormal[]; +layout(location = 3) in vec2 iTexCoord[]; +layout(location = 6) in PnPatch iPnPatch[]; + +layout(location = 0) out vec3 oNormal; +layout(location = 1) out vec2 oTexCoord; + +#define uvw gl_TessCoord + +void main() +{ + vec3 uvwSquared = uvw * uvw; + vec3 uvwCubed = uvwSquared * uvw; + + // extract control points + vec3 b210 = vec3(iPnPatch[0].b210, iPnPatch[1].b210, iPnPatch[2].b210); + vec3 b120 = vec3(iPnPatch[0].b120, iPnPatch[1].b120, iPnPatch[2].b120); + vec3 b021 = vec3(iPnPatch[0].b021, iPnPatch[1].b021, iPnPatch[2].b021); + vec3 b012 = vec3(iPnPatch[0].b012, iPnPatch[1].b012, iPnPatch[2].b012); + vec3 b102 = vec3(iPnPatch[0].b102, iPnPatch[1].b102, iPnPatch[2].b102); + vec3 b201 = vec3(iPnPatch[0].b201, iPnPatch[1].b201, iPnPatch[2].b201); + vec3 b111 = vec3(iPnPatch[0].b111, iPnPatch[1].b111, iPnPatch[2].b111); + + // extract control normals + vec3 n110 = normalize(vec3(iPnPatch[0].n110, iPnPatch[1].n110, iPnPatch[2].n110)); + vec3 n011 = normalize(vec3(iPnPatch[0].n011, iPnPatch[1].n011, iPnPatch[2].n011)); + vec3 n101 = normalize(vec3(iPnPatch[0].n101, iPnPatch[1].n101, iPnPatch[2].n101)); + + // compute texcoords + oTexCoord = gl_TessCoord[2]*iTexCoord[0] + gl_TessCoord[0]*iTexCoord[1] + gl_TessCoord[1]*iTexCoord[2]; + + // normal + // Barycentric normal + vec3 barNormal = gl_TessCoord[2]*iNormal[0] + gl_TessCoord[0]*iNormal[1] + gl_TessCoord[1]*iNormal[2]; + vec3 pnNormal = iNormal[0]*uvwSquared[2] + iNormal[1]*uvwSquared[0] + iNormal[2]*uvwSquared[1] + + n110*uvw[2]*uvw[0] + n011*uvw[0]*uvw[1]+ n101*uvw[2]*uvw[1]; + oNormal = ubo.tessAlpha*pnNormal + (1.0-ubo.tessAlpha) * barNormal; + + // compute interpolated pos + vec3 barPos = gl_TessCoord[2]*gl_in[0].gl_Position.xyz + + gl_TessCoord[0]*gl_in[1].gl_Position.xyz + + gl_TessCoord[1]*gl_in[2].gl_Position.xyz; + + // save some computations + uvwSquared *= 3.0; + + // compute PN position + vec3 pnPos = gl_in[0].gl_Position.xyz*uvwCubed[2] + + gl_in[1].gl_Position.xyz*uvwCubed[0] + + gl_in[2].gl_Position.xyz*uvwCubed[1] + + b210*uvwSquared[2]*uvw[0] + + b120*uvwSquared[0]*uvw[2] + + b201*uvwSquared[2]*uvw[1] + + b021*uvwSquared[0]*uvw[1] + + b102*uvwSquared[1]*uvw[2] + + b012*uvwSquared[1]*uvw[0] + + b111*6.0*uvw[0]*uvw[1]*uvw[2]; + + // final position and normal + vec3 finalPos = (1.0-ubo.tessAlpha)*barPos + ubo.tessAlpha*pnPos; + gl_Position = ubo.projection * ubo.model * vec4(finalPos,1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/textoverlay/background.frag b/tests/glsl/sascha-willems/textoverlay/background.frag new file mode 100644 index 000000000..00ac6416b --- /dev/null +++ b/tests/glsl/sascha-willems/textoverlay/background.frag @@ -0,0 +1,16 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColorMap; + +layout (location = 0) in vec2 inUV; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + outFragColor = texture(samplerColorMap, inUV); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/textoverlay/background.vert b/tests/glsl/sascha-willems/textoverlay/background.vert new file mode 100644 index 000000000..476834f38 --- /dev/null +++ b/tests/glsl/sascha-willems/textoverlay/background.vert @@ -0,0 +1,18 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); + gl_Position = vec4(outUV * vec2(2.0f, 2.0f) + vec2(-1.0f, -1.0f), 0.0f, 1.0f); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/textoverlay/mesh.frag b/tests/glsl/sascha-willems/textoverlay/mesh.frag new file mode 100644 index 000000000..696914ded --- /dev/null +++ b/tests/glsl/sascha-willems/textoverlay/mesh.frag @@ -0,0 +1,27 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColorMap; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inViewVec; +layout (location = 3) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec4 color = texture(samplerColorMap, inUV); + + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 diffuse = max(dot(N, L), 0.0) * color.rgb; + vec3 specular = pow(max(dot(R, V), 0.0), 1.0) * vec3(color.a); + outFragColor = vec4(diffuse + specular, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/textoverlay/mesh.vert b/tests/glsl/sascha-willems/textoverlay/mesh.vert new file mode 100644 index 000000000..dde3bf92d --- /dev/null +++ b/tests/glsl/sascha-willems/textoverlay/mesh.vert @@ -0,0 +1,39 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + vec4 lightPos; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec2 outUV; +layout (location = 2) out vec3 outViewVec; +layout (location = 3) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outNormal = inNormal; + outUV = inUV; + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); + + vec4 pos = ubo.model * vec4(inPos, 1.0); + outNormal = mat3(transpose(inverse(ubo.model))) * normalize(inNormal); + vec3 lPos = mat3(ubo.model) * ubo.lightPos.xyz; + outLightVec = lPos - pos.xyz; + outViewVec = -pos.xyz; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/textoverlay/text.frag b/tests/glsl/sascha-willems/textoverlay/text.frag new file mode 100644 index 000000000..42414689f --- /dev/null +++ b/tests/glsl/sascha-willems/textoverlay/text.frag @@ -0,0 +1,14 @@ +//TEST:COMPARE_GLSL: +#version 450 core + +layout (location = 0) in vec2 inUV; + +layout (binding = 0) uniform sampler2D samplerFont; + +layout (location = 0) out vec4 outFragColor; + +void main(void) +{ + float color = texture(samplerFont, inUV).r; + outFragColor = vec4(vec3(color), 1.0); +} diff --git a/tests/glsl/sascha-willems/textoverlay/text.vert b/tests/glsl/sascha-willems/textoverlay/text.vert new file mode 100644 index 000000000..a9877dd0e --- /dev/null +++ b/tests/glsl/sascha-willems/textoverlay/text.vert @@ -0,0 +1,18 @@ +//TEST:COMPARE_GLSL: +#version 450 core + +layout (location = 0) in vec2 inPos; +layout (location = 1) in vec2 inUV; + +layout (location = 0) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main(void) +{ + gl_Position = vec4(inPos, 0.0, 1.0); + outUV = inUV; +} diff --git a/tests/glsl/sascha-willems/texture/texture.frag b/tests/glsl/sascha-willems/texture/texture.frag new file mode 100644 index 000000000..508f7f69c --- /dev/null +++ b/tests/glsl/sascha-willems/texture/texture.frag @@ -0,0 +1,29 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColor; + +layout (location = 0) in vec2 inUV; +layout (location = 1) in float inLodBias; +layout (location = 2) in vec3 inNormal; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec4 color = texture(samplerColor, inUV, inLodBias); + + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 diffuse = max(dot(N, L), 0.0) * vec3(1.0); + float specular = pow(max(dot(R, V), 0.0), 16.0) * color.a; + + outFragColor = vec4(diffuse * color.rgb + specular, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/texture/texture.vert b/tests/glsl/sascha-willems/texture/texture.vert new file mode 100644 index 000000000..9cd64b831 --- /dev/null +++ b/tests/glsl/sascha-willems/texture/texture.vert @@ -0,0 +1,45 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inNormal; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + vec4 viewPos; + float lodBias; +} ubo; + +layout (location = 0) out vec2 outUV; +layout (location = 1) out float outLodBias; +layout (location = 2) out vec3 outNormal; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = inUV; + outLodBias = ubo.lodBias; + + vec3 worldPos = vec3(ubo.model * vec4(inPos, 1.0)); + + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); + + vec4 pos = ubo.model * vec4(inPos, 1.0); + outNormal = mat3(inverse(transpose(ubo.model))) * inNormal; + vec3 lightPos = vec3(0.0); + vec3 lPos = mat3(ubo.model) * lightPos.xyz; + outLightVec = lPos - pos.xyz; + outViewVec = ubo.viewPos.xyz - pos.xyz; +} diff --git a/tests/glsl/sascha-willems/texture3d/texture3d.frag b/tests/glsl/sascha-willems/texture3d/texture3d.frag new file mode 100644 index 000000000..d9464a233 --- /dev/null +++ b/tests/glsl/sascha-willems/texture3d/texture3d.frag @@ -0,0 +1,29 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler3D samplerColor; + +layout (location = 0) in vec3 inUV; +layout (location = 1) in float inLodBias; +layout (location = 2) in vec3 inNormal; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec4 color = texture(samplerColor, inUV); + + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 diffuse = max(dot(N, L), 0.0) * vec3(1.0); + float specular = pow(max(dot(R, V), 0.0), 16.0) * color.r; + + outFragColor = vec4(diffuse * color.r + specular, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/texture3d/texture3d.vert b/tests/glsl/sascha-willems/texture3d/texture3d.vert new file mode 100644 index 000000000..1aca0195b --- /dev/null +++ b/tests/glsl/sascha-willems/texture3d/texture3d.vert @@ -0,0 +1,44 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inNormal; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + vec4 viewPos; + float depth; +} ubo; + +layout (location = 0) out vec3 outUV; +layout (location = 1) out float outLodBias; +layout (location = 2) out vec3 outNormal; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = vec3(inUV, ubo.depth); + + vec3 worldPos = vec3(ubo.model * vec4(inPos, 1.0)); + + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); + + vec4 pos = ubo.model * vec4(inPos, 1.0); + outNormal = mat3(inverse(transpose(ubo.model))) * inNormal; + vec3 lightPos = vec3(0.0); + vec3 lPos = mat3(ubo.model) * lightPos.xyz; + outLightVec = lPos - pos.xyz; + outViewVec = ubo.viewPos.xyz - pos.xyz; +} diff --git a/tests/glsl/sascha-willems/texturearray/instancing.frag b/tests/glsl/sascha-willems/texturearray/instancing.frag new file mode 100644 index 000000000..b0e293e34 --- /dev/null +++ b/tests/glsl/sascha-willems/texturearray/instancing.frag @@ -0,0 +1,16 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2DArray samplerArray; + +layout (location = 0) in vec3 inUV; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + outFragColor = texture(samplerArray, inUV); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/texturearray/instancing.vert b/tests/glsl/sascha-willems/texturearray/instancing.vert new file mode 100644 index 000000000..ad738a59b --- /dev/null +++ b/tests/glsl/sascha-willems/texturearray/instancing.vert @@ -0,0 +1,30 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec2 inUV; + +struct Instance +{ + mat4 model; + vec4 arrayIndex; +}; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 view; + Instance instance[8]; +} ubo; + +layout (location = 0) out vec3 outUV; + +void main() +{ + outUV = vec3(inUV, ubo.instance[gl_InstanceIndex].arrayIndex.x); + mat4 modelView = ubo.view * ubo.instance[gl_InstanceIndex].model; + gl_Position = ubo.projection * modelView * inPos; +} diff --git a/tests/glsl/sascha-willems/texturemipmapgen/texture.frag b/tests/glsl/sascha-willems/texturemipmapgen/texture.frag new file mode 100644 index 000000000..037ed4e30 --- /dev/null +++ b/tests/glsl/sascha-willems/texturemipmapgen/texture.frag @@ -0,0 +1,30 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (set = 0, binding = 1) uniform texture2D textureColor; +layout (set = 0, binding = 2) uniform sampler samplers[3]; + +layout (location = 0) in vec2 inUV; +layout (location = 1) in float inLodBias; +layout (location = 2) flat in int inSamplerIndex; +layout (location = 3) in vec3 inNormal; +layout (location = 4) in vec3 inViewVec; +layout (location = 5) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec4 color = texture(sampler2D(textureColor, samplers[inSamplerIndex]), inUV, inLodBias); + + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(L, N); + vec3 diffuse = max(dot(N, L), 0.65) * vec3(1.0); + float specular = pow(max(dot(R, V), 0.0), 16.0) * color.a; + outFragColor = vec4(diffuse * color.rgb + specular, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/texturemipmapgen/texture.vert b/tests/glsl/sascha-willems/texturemipmapgen/texture.vert new file mode 100644 index 000000000..ed98fc24e --- /dev/null +++ b/tests/glsl/sascha-willems/texturemipmapgen/texture.vert @@ -0,0 +1,47 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inNormal; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 view; + mat4 model; + vec4 viewPos; + float lodBias; + int samplerIndex; +} ubo; + +layout (location = 0) out vec2 outUV; +layout (location = 1) out float outLodBias; +layout (location = 2) flat out int outSamplerIndex; +layout (location = 3) out vec3 outNormal; +layout (location = 4) out vec3 outViewVec; +layout (location = 5) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = inUV * vec2(2.0, 1.0); + outLodBias = ubo.lodBias; + outSamplerIndex = ubo.samplerIndex; + + vec3 worldPos = vec3(ubo.model * vec4(inPos, 1.0)); + + gl_Position = ubo.projection * ubo.view * ubo.model * vec4(inPos.xyz, 1.0); + + outNormal = mat3(inverse(transpose(ubo.model))) * inNormal; + vec3 lightPos = vec3(-30.0, 0.0, 0.0); + outLightVec = worldPos - lightPos; + outViewVec = ubo.viewPos.xyz - worldPos; +} diff --git a/tests/glsl/sascha-willems/texturesparseresidency/sparseresidency.frag b/tests/glsl/sascha-willems/texturesparseresidency/sparseresidency.frag new file mode 100644 index 000000000..c82b621e4 --- /dev/null +++ b/tests/glsl/sascha-willems/texturesparseresidency/sparseresidency.frag @@ -0,0 +1,48 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_sparse_texture2 : enable +#extension GL_ARB_sparse_texture_clamp : enable + +layout (binding = 1) uniform sampler2D samplerColor; + +layout (location = 0) in vec2 inUV; +layout (location = 1) in float inLodBias; +layout (location = 2) in vec3 inNormal; +layout (location = 3) in vec3 inViewVec; +layout (location = 4) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec4 color = vec4(0.0); + + // Get residency code for current texel + int residencyCode = sparseTextureARB(samplerColor, inUV, color, inLodBias); + + // Fetch sparse until we get a valid texel + float minLod = 1.0; + while (!sparseTexelsResidentARB(residencyCode)) + { + residencyCode = sparseTextureClampARB(samplerColor, inUV, minLod, color); + minLod += 1.0f; + } + + // Check if texel is resident + bool texelResident = sparseTexelsResidentARB(residencyCode); + + if (!texelResident) + { + color = vec4(1.0, 0.0, 0.0, 0.0); + } + + vec3 N = normalize(inNormal); + + N = normalize((inNormal - 0.5) * 2.0); + + vec3 L = normalize(inLightVec); + vec3 R = reflect(-L, N); + vec3 diffuse = max(dot(N, L), 0.25) * color.rgb; + outFragColor = vec4(diffuse, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/texturesparseresidency/sparseresidency.vert b/tests/glsl/sascha-willems/texturesparseresidency/sparseresidency.vert new file mode 100644 index 000000000..f29db5b5b --- /dev/null +++ b/tests/glsl/sascha-willems/texturesparseresidency/sparseresidency.vert @@ -0,0 +1,43 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + vec4 viewPos; + float lodBias; +} ubo; + +layout (location = 0) out vec2 outUV; +layout (location = 1) out float outLodBias; +layout (location = 2) out vec3 outNormal; +layout (location = 3) out vec3 outViewVec; +layout (location = 4) out vec3 outLightVec; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = inUV; + outLodBias = ubo.lodBias; + outNormal = inNormal; + + vec3 worldPos = vec3(ubo.model * vec4(inPos, 1.0)); + + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); + + vec3 lightPos = vec3(0.0, 50.0f, 0.0f); + outLightVec = lightPos - inPos.xyz; + outViewVec = ubo.viewPos.xyz - worldPos.xyz; +} diff --git a/tests/glsl/sascha-willems/triangle/triangle.frag b/tests/glsl/sascha-willems/triangle/triangle.frag new file mode 100644 index 000000000..70ee9fc53 --- /dev/null +++ b/tests/glsl/sascha-willems/triangle/triangle.frag @@ -0,0 +1,14 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inColor; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + outFragColor = vec4(inColor, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/triangle/triangle.vert b/tests/glsl/sascha-willems/triangle/triangle.vert new file mode 100644 index 000000000..b14410d80 --- /dev/null +++ b/tests/glsl/sascha-willems/triangle/triangle.vert @@ -0,0 +1,29 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projectionMatrix; + mat4 modelMatrix; + mat4 viewMatrix; +} ubo; + +layout (location = 0) out vec3 outColor; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + + +void main() +{ + outColor = inColor; + gl_Position = ubo.projectionMatrix * ubo.viewMatrix * ubo.modelMatrix * vec4(inPos.xyz, 1.0); +} diff --git a/tests/glsl/sascha-willems/viewportarray/multiview.geom b/tests/glsl/sascha-willems/viewportarray/multiview.geom new file mode 100644 index 000000000..39303fb33 --- /dev/null +++ b/tests/glsl/sascha-willems/viewportarray/multiview.geom @@ -0,0 +1,46 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_viewport_array : enable + +layout (triangles, invocations = 2) in; +layout (triangle_strip, max_vertices = 3) out; + +layout (binding = 0) uniform UBO +{ + mat4 projection[2]; + mat4 modelview[2]; + vec4 lightPos; +} ubo; + +layout (location = 0) in vec3 inNormal[]; +layout (location = 1) in vec3 inColor[]; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; +layout (location = 2) out vec3 outViewVec; +layout (location = 3) out vec3 outLightVec; + +void main(void) +{ + for(int i = 0; i < gl_in.length(); i++) + { + outNormal = mat3(ubo.modelview[gl_InvocationID]) * inNormal[i]; + outColor = inColor[i]; + + vec4 pos = gl_in[i].gl_Position; + vec4 worldPos = (ubo.modelview[gl_InvocationID] * pos); + + vec3 lPos = vec3(ubo.modelview[gl_InvocationID] * ubo.lightPos); + outLightVec = lPos - worldPos.xyz; + outViewVec = -worldPos.xyz; + + gl_Position = ubo.projection[gl_InvocationID] * worldPos; + + // Set the viewport index that the vertex will be emitted to + gl_ViewportIndex = gl_InvocationID; + + EmitVertex(); + } + EndPrimitive(); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/viewportarray/scene.frag b/tests/glsl/sascha-willems/viewportarray/scene.frag new file mode 100644 index 000000000..1ecd7fdb3 --- /dev/null +++ b/tests/glsl/sascha-willems/viewportarray/scene.frag @@ -0,0 +1,21 @@ +//TEST:COMPARE_GLSL: +#version 450 + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec3 inColor; +layout (location = 2) in vec3 inViewVec; +layout (location = 3) in vec3 inLightVec; + +layout (location = 0) out vec4 outColor; + +void main() +{ + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 ambient = vec3(0.1); + vec3 diffuse = max(dot(N, L), 0.0) * vec3(1.0); + vec3 specular = pow(max(dot(R, V), 0.0), 16.0) * vec3(0.75); + outColor = vec4((ambient + diffuse) * inColor.rgb + specular, 1.0); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/viewportarray/scene.vert b/tests/glsl/sascha-willems/viewportarray/scene.vert new file mode 100644 index 000000000..28e1c3d8b --- /dev/null +++ b/tests/glsl/sascha-willems/viewportarray/scene.vert @@ -0,0 +1,21 @@ +//TEST:COMPARE_GLSL: +#version 450 + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec3 inColor; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec3 outColor; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outColor = inColor; + outNormal = inNormal; + gl_Position = vec4(inPos.xyz, 1.0); +} diff --git a/tests/glsl/sascha-willems/vulkanscene/logo.frag b/tests/glsl/sascha-willems/vulkanscene/logo.frag new file mode 100644 index 000000000..aa42773b4 --- /dev/null +++ b/tests/glsl/sascha-willems/vulkanscene/logo.frag @@ -0,0 +1,23 @@ +//TEST:COMPARE_GLSL: +#version 450 + +layout (location = 0) in vec2 inUV; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec3 inColor; +layout (location = 3) in vec3 inEyePos; +layout (location = 4) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec3 Eye = normalize(-inEyePos); + vec3 Reflected = normalize(reflect(-inLightVec, inNormal)); + + vec4 diff = vec4(inColor, 1.0) * max(dot(inNormal, inLightVec), 0.0); + float shininess = 0.0; + vec4 spec = vec4(1.0, 1.0, 1.0, 1.0) * pow(max(dot(Reflected, Eye), 0.0), 2.5) * shininess; + + outFragColor = diff + spec; + outFragColor.a = 1.0; +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/vulkanscene/logo.vert b/tests/glsl/sascha-willems/vulkanscene/logo.vert new file mode 100644 index 000000000..2887245a7 --- /dev/null +++ b/tests/glsl/sascha-willems/vulkanscene/logo.vert @@ -0,0 +1,38 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inTexCoord; +layout (location = 3) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + mat4 normal; + mat4 view; + vec3 lightpos; +} ubo; + +layout (location = 0) out vec2 outUV; +layout (location = 1) out vec3 outNormal; +layout (location = 2) out vec3 outColor; +layout (location = 3) out vec3 outEyePos; +layout (location = 4) out vec3 outLightVec; + +void main() +{ + mat4 modelView = ubo.view * ubo.model; + vec4 pos = modelView * inPos; + outUV = inTexCoord.st; + outNormal = normalize(mat3(ubo.normal) * inNormal); + outColor = inColor; + gl_Position = ubo.projection * pos; + outEyePos = vec3(modelView * pos); + vec4 lightPos = vec4(1.0, 2.0, 0.0, 1.0) * modelView; + outLightVec = normalize(lightPos.xyz - outEyePos); +} diff --git a/tests/glsl/sascha-willems/vulkanscene/mesh.frag b/tests/glsl/sascha-willems/vulkanscene/mesh.frag new file mode 100644 index 000000000..5afa294ed --- /dev/null +++ b/tests/glsl/sascha-willems/vulkanscene/mesh.frag @@ -0,0 +1,45 @@ +//TEST:COMPARE_GLSL: +#version 450 + +layout (binding = 1) uniform sampler2D tex; + +layout (location = 0) in vec2 inUV; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec3 inColor; +layout (location = 3) in vec3 inEyePos; +layout (location = 4) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +float specpart(vec3 L, vec3 N, vec3 H) +{ + if (dot(N, L) > 0.0) + { + return pow(clamp(dot(H, N), 0.0, 1.0), 64.0); + } + return 0.0; +} + +void main() +{ + vec3 Eye = normalize(-inEyePos); + vec3 Reflected = normalize(reflect(-inLightVec, inNormal)); + + vec3 halfVec = normalize(inLightVec + inEyePos); + float diff = clamp(dot(inLightVec, inNormal), 0.0, 1.0); + float spec = specpart(inLightVec, inNormal, halfVec); + float intensity = 0.1 + diff + spec; + + vec4 IAmbient = vec4(0.2, 0.2, 0.2, 1.0); + vec4 IDiffuse = vec4(0.5, 0.5, 0.5, 0.5) * max(dot(inNormal, inLightVec), 0.0); + float shininess = 0.75; + vec4 ISpecular = vec4(0.5, 0.5, 0.5, 1.0) * pow(max(dot(Reflected, Eye), 0.0), 2.0) * shininess; + + outFragColor = vec4((IAmbient + IDiffuse) * vec4(inColor, 1.0) + ISpecular); + + // Some manual saturation + if (intensity > 0.95) + outFragColor *= 2.25; + if (intensity < 0.15) + outFragColor = vec4(0.1); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/vulkanscene/mesh.vert b/tests/glsl/sascha-willems/vulkanscene/mesh.vert new file mode 100644 index 000000000..ca7e5b06d --- /dev/null +++ b/tests/glsl/sascha-willems/vulkanscene/mesh.vert @@ -0,0 +1,38 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inTexCoord; +layout (location = 3) in vec3 inColor; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + mat4 normal; + mat4 view; + vec3 lightpos; +} ubo; + +layout (location = 0) out vec2 outUV; +layout (location = 1) out vec3 outNormal; +layout (location = 2) out vec3 outColor; +layout (location = 3) out vec3 outEyePos; +layout (location = 4) out vec3 outLightVec; + +void main() +{ + outUV = inTexCoord.st; + outNormal = normalize(mat3(ubo.normal) * inNormal); + outColor = inColor; + mat4 modelView = ubo.view * ubo.model; + vec4 pos = modelView * inPos; + gl_Position = ubo.projection * pos; + outEyePos = vec3(modelView * pos); + vec4 lightPos = vec4(ubo.lightpos, 1.0) * modelView; + outLightVec = normalize(lightPos.xyz - outEyePos); +} diff --git a/tests/glsl/sascha-willems/vulkanscene/skybox.frag b/tests/glsl/sascha-willems/vulkanscene/skybox.frag new file mode 100644 index 000000000..8cf1d0b8b --- /dev/null +++ b/tests/glsl/sascha-willems/vulkanscene/skybox.frag @@ -0,0 +1,16 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform samplerCube samplerCubeMap; + +layout (location = 0) in vec3 inUVW; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + outFragColor = texture(samplerCubeMap, inUVW); +} \ No newline at end of file diff --git a/tests/glsl/sascha-willems/vulkanscene/skybox.vert b/tests/glsl/sascha-willems/vulkanscene/skybox.vert new file mode 100644 index 000000000..81c2941dc --- /dev/null +++ b/tests/glsl/sascha-willems/vulkanscene/skybox.vert @@ -0,0 +1,21 @@ +//TEST:COMPARE_GLSL: +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; +} ubo; + +layout (location = 0) out vec3 outUVW; + +void main() +{ + outUVW = inPos; + gl_Position = ubo.projection * ubo.model * vec4(inPos.xyz, 1.0); +} diff --git a/tests/hlsl/dxsdk/AdaptiveTessellationCS40/Render.hlsl b/tests/hlsl/dxsdk/AdaptiveTessellationCS40/Render.hlsl new file mode 100644 index 000000000..b98b870da --- /dev/null +++ b/tests/hlsl/dxsdk/AdaptiveTessellationCS40/Render.hlsl @@ -0,0 +1,58 @@ +//TEST:COMPARE_HLSL: -profile vs_4_0 -entry RenderBaseVS -profile ps_4_0 -entry RenderPS -target dxbc-assembly +//-------------------------------------------------------------------------------------- +// File: Render.hlsl +// +// The shaders for rendering tessellated mesh and base mesh +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- +cbuffer cbPerObject : register( b0 ) +{ + row_major matrix g_mWorldViewProjection : packoffset( c0 ); +} + +// The tessellated vertex structure +struct TessedVertex +{ + uint BaseTriID; // Which triangle of the base mesh this tessellated vertex belongs to? + float2 bc; // Barycentric coordinates with regard to the base triangle +}; +Buffer g_base_vb_buffer : register(t0); // Base mesh vertex buffer +StructuredBuffer g_TessedVertices : register(t1); // Tessellated mesh vertex buffer + +float4 bary_centric(float4 v1, float4 v2, float4 v3, float2 bc) +{ + return (1 - bc.x - bc.y) * v1 + bc.x * v2 + bc.y * v3; +} + +float4 RenderVS( uint vertid : SV_VertexID ) : SV_POSITION +{ + TessedVertex input = g_TessedVertices[vertid]; + + // Get the positions of the three vertices of the base triangle + float4 v[3]; + [unroll] + for (int i = 0; i < 3; ++ i) + { + uint vert_id = input.BaseTriID * 3 + i; + v[i] = g_base_vb_buffer[vert_id]; + } + + // Calculate the position of this tessellated vertex from barycentric coordinates and then project it + return mul(bary_centric(v[0], v[1], v[2], input.bc), g_mWorldViewProjection); +} + +struct BaseVertex +{ + float4 pos : POSITION; +}; + +float4 RenderBaseVS( BaseVertex input ) : SV_POSITION +{ + return mul( input.pos, g_mWorldViewProjection ); +} + +float4 RenderPS() : SV_TARGET +{ + return float4( 1.0f, 1.0f, 0.0f, 1.0f ); +} \ No newline at end of file diff --git a/tests/hlsl/dxsdk/AdaptiveTessellationCS40/ScanCS.hlsl b/tests/hlsl/dxsdk/AdaptiveTessellationCS40/ScanCS.hlsl new file mode 100644 index 000000000..46cdc1ed9 --- /dev/null +++ b/tests/hlsl/dxsdk/AdaptiveTessellationCS40/ScanCS.hlsl @@ -0,0 +1,109 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile cs_4_0 -entry CSScanInBucket -entry CSScanBucketResult -entry CSScanAddBucketResult +//-------------------------------------------------------------------------------------- +// File: ScanCS.hlsl +// +// A simple inclusive prefix sum(scan) implemented in CS4.0, +// using a typical up sweep and down sweep scheme +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- +StructuredBuffer Input : register( t0 ); // Change uint2 here if scan other types, and +RWStructuredBuffer Result : register( u0 ); // also here + +#define groupthreads 128 +groupshared uint4 bucket[groupthreads]; // Change uint4 to the "type x2" if scan other types, e.g. + // if scan uint2, then put uint4 here, + // if scan float, then put float2 here + +void CSScan( uint3 DTid, uint GI, uint2 x ) // Change the type of x here if scan other types +{ + // since CS40 can only support one shared memory for one shader, we use .xy and .zw as ping-ponging buffers + // if scan a single element type like int, search and replace all .xy to .x and .zw to .y below + bucket[GI].xy = x; + bucket[GI].zw = 0; + + // Up sweep + [unroll] + for ( uint stride = 2; stride <= groupthreads; stride <<= 1 ) + { + GroupMemoryBarrierWithGroupSync(); + + if ( (GI & (stride - 1)) == (stride - 1) ) + { + bucket[GI].xy += bucket[GI - stride/2].xy; + } + } + + if ( GI == (groupthreads - 1) ) + { + bucket[GI].xy = 0; + } + + // Down sweep + bool n = true; + [unroll] + for ( stride = groupthreads / 2; stride >= 1; stride >>= 1 ) + { + GroupMemoryBarrierWithGroupSync(); + + uint a = stride - 1; + uint b = stride | a; + + if ( n ) // ping-pong between passes + { + if ( ( GI & b) == b ) + { + bucket[GI].zw = bucket[GI-stride].xy + bucket[GI].xy; + } else + if ( (GI & a) == a ) + { + bucket[GI].zw = bucket[GI+stride].xy; + } else + { + bucket[GI].zw = bucket[GI].xy; + } + } else + { + if ( ( GI & b) == b ) + { + bucket[GI].xy = bucket[GI-stride].zw + bucket[GI].zw; + } else + if ( (GI & a) == a ) + { + bucket[GI].xy = bucket[GI+stride].zw; + } else + { + bucket[GI].xy = bucket[GI].zw; + } + } + + n = !n; + } + + Result[DTid.x] = bucket[GI].zw + x; +} + +// scan in each bucket +[numthreads( groupthreads, 1, 1 )] +void CSScanInBucket( uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI: SV_GroupIndex ) +{ + uint2 x = Input[DTid.x]; // Change the type of x here if scan other types + CSScan( DTid, GI, x ); +} + +// record and scan the sum of each bucket +[numthreads( groupthreads, 1, 1 )] +void CSScanBucketResult( uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI: SV_GroupIndex ) +{ + uint2 x = Input[DTid.x*groupthreads - 1]; // Change the type of x here if scan other types + CSScan( DTid, GI, x ); +} + +StructuredBuffer Input1 : register( t1 ); + +// add the bucket scanned result to each bucket to get the final result +[numthreads( groupthreads, 1, 1 )] +void CSScanAddBucketResult( uint3 Gid : SV_GroupID, uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI: SV_GroupIndex ) +{ + Result[DTid.x] = Input[DTid.x] + Input1[Gid.x]; +} diff --git a/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_EdgeFactorCS.hlsl b/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_EdgeFactorCS.hlsl new file mode 100644 index 000000000..91ebca777 --- /dev/null +++ b/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_EdgeFactorCS.hlsl @@ -0,0 +1,217 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile cs_4_0 -entry CSEdgeFactor +//-------------------------------------------------------------------------------------- +// File: TessellatorCS40_EdgeFactorCS.hlsl +// +// The CS to compute edge tessellation factor acoording to current world, view, projection matrix +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +// http://jgt.akpeters.com/papers/akeninemoller01/tribox.html +bool planeBoxOverlap(float3 normal, float d, float3 maxbox) +{ + float3 vmin = maxbox, vmax = maxbox; + [unroll] + for (int q = 0;q <= 2; ++ q) + { + if (normal[q] > 0.0f) + { + vmin[q] *= -1; + } + else + { + vmax[q] *= -1; + } + } + if (dot(normal, vmin) + d > 0.0f) + { + return false; + } + if (dot(normal, vmax) + d >= 0.0f) + { + return true; + } + + return false; +} + +/*======================== X-tests ========================*/ +bool AXISTEST_X01(float3 v0, float3 v2, float3 boxhalfsize, float2 ab, float2 fab) +{ + float p0 = ab.x * v0.y - ab.y * v0.z; + float p2 = ab.x * v2.y - ab.y * v2.z; + float min_v = min(p0, p2); + float max_v = max(p0, p2); + float rad = dot(fab, boxhalfsize.yz); + return (min_v < rad) && (max_v > -rad); +} + +bool AXISTEST_X2(float3 v0, float3 v1, float3 boxhalfsize, float2 ab, float2 fab) +{ + float p0 = ab.x * v0.y - ab.y * v0.z; + float p1 = ab.x * v1.y - ab.y * v1.z; + float min_v = min(p0, p1); + float max_v = max(p0, p1); + float rad = dot(fab, boxhalfsize.yz); + return (min_v < rad) && (max_v > -rad); +} + +/*======================== Y-tests ========================*/ +bool AXISTEST_Y02(float3 v0, float3 v2, float3 boxhalfsize, float2 ab, float2 fab) +{ + float p0 = -ab.x * v0.x + ab.y * v0.z; + float p2 = -ab.x * v2.x + ab.y * v2.z; + float min_v = min(p0, p2); + float max_v = max(p0, p2); + float rad = dot(fab, boxhalfsize.xz); + return (min_v < rad) && (max_v > -rad); +} + +bool AXISTEST_Y1(float3 v0, float3 v1, float3 boxhalfsize, float2 ab, float2 fab) +{ + float p0 = -ab.x * v0.x + ab.y * v0.z; + float p1 = -ab.x * v1.x + ab.y * v1.z; + float min_v = min(p0, p1); + float max_v = max(p0, p1); + float rad = dot(fab, boxhalfsize.xz); + return (min_v < rad) && (max_v > -rad); +} + +/*======================== Z-tests ========================*/ +bool AXISTEST_Z12(float3 v1, float3 v2, float3 boxhalfsize, float2 ab, float2 fab) +{ + float p1 = ab.x * v1.x - ab.y * v1.y; + float p2 = ab.x * v2.x - ab.y * v2.y; + float min_v = min(p1, p2); + float max_v = max(p1, p2); + float rad = dot(fab, boxhalfsize.xy); + return (min_v < rad) && (max_v > -rad); +} + +bool AXISTEST_Z0(float3 v0, float3 v1, float3 boxhalfsize, float2 ab, float2 fab) +{ + float p0 = ab.x * v0.x - ab.y * v0.y; + float p1 = ab.x * v1.x - ab.y * v1.y; + float min_v = min(p0, p1); + float max_v = max(p0, p1); + float rad = dot(fab, boxhalfsize.xy); + return (min_v < rad) && (max_v > -rad); +} + +bool triBoxOverlap(float3 boxcenter,float3 boxhalfsize,float3 triverts0, float3 triverts1, float3 triverts2) +{ + /* use separating axis theorem to test overlap between triangle and box */ + /* need to test for overlap in these directions: */ + /* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */ + /* we do not even need to test these) */ + /* 2) normal of the triangle */ + /* 3) crossproduct(edge from tri, {x,y,z}-directin) */ + /* this gives 3x3=9 more tests */ + + /* This is the fastest branch on Sun */ + /* move everything so that the boxcenter is in (0,0,0) */ + float3 v0 = triverts0 - boxcenter; + float3 v1 = triverts1 - boxcenter; + float3 v2 = triverts2 - boxcenter; + + /* compute triangle edges */ + float3 e0 = v1 - v0; /* tri edge 0 */ + float3 e1 = v2 - v1; /* tri edge 1 */ + float3 e2 = v0 - v2; /* tri edge 2 */ + + /* Bullet 3: */ + /* test the 9 tests first (this was faster) */ + float3 fe = abs(e0); + if (!AXISTEST_X01(v0, v2, boxhalfsize, e0.zy, fe.zy) + || !AXISTEST_Y02(v0, v2, boxhalfsize, e0.zx, fe.zx) + || !AXISTEST_Z12(v1, v2, boxhalfsize, e0.yx, fe.yx)) + { + return false; + } + + fe = abs(e1); + if (!AXISTEST_X01(v0, v2, boxhalfsize, e1.zy, fe.zy) + || !AXISTEST_Y02(v0, v2, boxhalfsize, e1.zx, fe.zx) + || !AXISTEST_Z0(v0, v1, boxhalfsize, e1.yx, fe.yx)) + { + return false; + } + + fe = abs(e2); + if (!AXISTEST_X2(v0, v1, boxhalfsize, e2.zy, fe.zy) + || !AXISTEST_Y1(v0, v1, boxhalfsize, e2.zx, fe.zx) + || !AXISTEST_Z12(v1, v2, boxhalfsize, e2.yx, fe.yx)) + { + return false; + } + + /* Bullet 1: */ + /* first test overlap in the {x,y,z}-directions */ + /* find min, max of the triangle each direction, and test for overlap in */ + /* that direction -- this is equivalent to testing a minimal AABB around */ + /* the triangle against the AABB */ + + float3 min_v = min(min(v0, v1), v2); + float3 max_v = max(max(v0, v1), v2); + if ((min_v.x > boxhalfsize.x || max_v.x < -boxhalfsize.x) + || (min_v.y > boxhalfsize.y || max_v.y < -boxhalfsize.y) + || (min_v.z > boxhalfsize.z || max_v.z < -boxhalfsize.z)) + { + return false; + } + + /* Bullet 2: */ + /* test if the box intersects the plane of the triangle */ + /* compute plane equation of triangle: normal*x+d=0 */ + float3 normal = cross(e0, e1); + float d = -dot(normal, v0); /* plane eq: normal.x+d=0 */ + if (!planeBoxOverlap(normal, d, boxhalfsize)) + { + return false; + } + + return true; /* box and triangle overlaps */ +} + + +Buffer InputVertices : register(t0); +RWStructuredBuffer EdgeFactorBufOut : register(u0); + +cbuffer cb +{ + row_major matrix g_matWVP; + float2 g_tess_edge_length_scale; + int num_triangles; + float dummy; +} + +[numthreads(128, 1, 1)] +void CSEdgeFactor( uint3 DTid : SV_DispatchThreadID ) +{ + if (DTid.x < num_triangles) + { + float4 p0 = mul(InputVertices[DTid.x*3+0], g_matWVP); + float4 p1 = mul(InputVertices[DTid.x*3+1], g_matWVP); + float4 p2 = mul(InputVertices[DTid.x*3+2], g_matWVP); + p0 = p0 / p0.w; + p1 = p1 / p1.w; + p2 = p2 / p2.w; + + float4 factor; + // Only triangles which are completely inside or intersect with the view frustum are taken into account + if ( triBoxOverlap( float3(0, 0, 0.5), float3(1.02, 1.02, 0.52), p0.xyz, p1.xyz, p2.xyz ) ) + { + factor.x = length((p0.xy - p2.xy) * g_tess_edge_length_scale); + factor.y = length((p1.xy - p0.xy) * g_tess_edge_length_scale); + factor.z = length((p2.xy - p1.xy) * g_tess_edge_length_scale); + factor.w = min(min(factor.x, factor.y), factor.z); + factor = clamp(factor, 0, 9); + } else + { + factor = 0; + } + + EdgeFactorBufOut[DTid.x] = factor; + } +} diff --git a/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_NumVerticesIndicesCS.hlsl b/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_NumVerticesIndicesCS.hlsl new file mode 100644 index 000000000..4f2fb547b --- /dev/null +++ b/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_NumVerticesIndicesCS.hlsl @@ -0,0 +1,56 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile cs_4_0 -entry CSNumVerticesIndices +//-------------------------------------------------------------------------------------- +// File: TessellatorCS40_NumVerticesIndicesCS.hlsl +// +// The CS to compute number of vertices and triangles to be generated from edge tessellation factor +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +#include "TessellatorCS40_common.hlsl" + +StructuredBuffer InputEdgeFactor : register(t0); +RWStructuredBuffer NumVerticesIndicesOut : register(u0); + +cbuffer cbCS : register(b1) +{ + uint4 g_param; +} + +[numthreads(128, 1, 1)] +void CSNumVerticesIndices( uint3 DTid : SV_DispatchThreadID ) +{ + if (DTid.x < g_param.x) + { + float4 edge_factor = InputEdgeFactor[DTid.x]; + + PROCESSED_TESS_FACTORS_TRI processedTessFactors; + int num_points = TriProcessTessFactors(edge_factor, processedTessFactors, g_partitioning); + + int num_index; + if (0 == num_points) + { + num_index = 0; + } + else if (3 == num_points) + { + num_index = 4; + } + else + { + int numRings = ((processedTessFactors.numPointsForOutsideInside.w + 1) / 2); // +1 is so even tess includes the center point, which we want to now + + int4 outsideInsideHalfTessFactor = int4(ceil(processedTessFactors.outsideInsideHalfTessFactor)); + uint3 n = NumStitchTransition(outsideInsideHalfTessFactor, processedTessFactors.outsideInsideTessFactorParity); + num_index = n.x + n.y + n.z; + num_index += TotalNumStitchRegular(true, DIAGONALS_MIRRORED, processedTessFactors.numPointsForOutsideInside.w, numRings - 1) * 3; + if( processedTessFactors.outsideInsideTessFactorParity.w == TESSELLATOR_PARITY_ODD ) + { + num_index += 4; + } + } + + NumVerticesIndicesOut[DTid.x] = uint2(num_points, num_index); + } +} diff --git a/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_ScatterIDCS.hlsl b/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_ScatterIDCS.hlsl new file mode 100644 index 000000000..17f003794 --- /dev/null +++ b/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_ScatterIDCS.hlsl @@ -0,0 +1,45 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile cs_4_0 -entry CSScatterVertexTriIDIndexID -entry CSScatterIndexTriIDIndexID +//-------------------------------------------------------------------------------------- +// File: TessellatorCS40_ScatterIDCS.hlsl +// +// The CS to scatter vertex ID and triangle ID +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- +StructuredBuffer InputScanned : register(t0); +RWStructuredBuffer TriIDIndexIDOut : register(u0); + +cbuffer cbCS : register(b1) +{ + uint4 g_param; +} + +[numthreads(128, 1, 1)] +void CSScatterVertexTriIDIndexID( uint3 DTid : SV_DispatchThreadID ) +{ + if (DTid.x < g_param.x) + { + uint start = InputScanned[DTid.x-1].x; + uint end = InputScanned[DTid.x].x; + + for ( uint i = start; i < end; ++i ) + { + TriIDIndexIDOut[i] = uint2(DTid.x, i - start); + } + } +} + +[numthreads(128, 1, 1)] +void CSScatterIndexTriIDIndexID( uint3 DTid : SV_DispatchThreadID ) +{ + if (DTid.x < g_param.x) + { + uint start = InputScanned[DTid.x-1].y; + uint end = InputScanned[DTid.x].y; + + for ( uint i = start; i < end; ++i ) + { + TriIDIndexIDOut[i] = uint2(DTid.x, i - start); + } + } +} diff --git a/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_TessellateIndicesCS.hlsl b/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_TessellateIndicesCS.hlsl new file mode 100644 index 000000000..756f99e58 --- /dev/null +++ b/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_TessellateIndicesCS.hlsl @@ -0,0 +1,628 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile cs_4_0 -entry CSTessellationIndices +//-------------------------------------------------------------------------------------- +// File: TessellatorCS40_TessellateIndicesCS.hlsl +// +// The CS to tessellate indices +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +#include "TessellatorCS40_common.hlsl" + +StructuredBuffer InputTriIDIndexID : register(t0); +StructuredBuffer InputEdgeFactor : register(t1); +StructuredBuffer InputScanned : register(t2); + +RWByteAddressBuffer TessedIndicesOut : register(u0); + +cbuffer cbCS : register(b1) +{ + uint4 g_param; +} + + +int TransformIndex1(int index, int vertices_base) +{ + return vertices_base + index; +} + +int TransformIndex2(int index, int vertices_base, INDEX_PATCH_CONTEXT IndexPatchContext) +{ + if( index >= IndexPatchContext.outsidePointIndexPatchBase ) // assumed remapped outide indices are > remapped inside vertices + { + if( index == IndexPatchContext.outsidePointIndexBadValue ) + { + index = IndexPatchContext.outsidePointIndexReplacementValue; + } + else + { + index += IndexPatchContext.outsidePointIndexDeltaToRealValue; + } + } + else + { + if( index == IndexPatchContext.insidePointIndexBadValue ) + { + index = IndexPatchContext.insidePointIndexReplacementValue; + } + else + { + index += IndexPatchContext.insidePointIndexDeltaToRealValue; + } + } + + return vertices_base + index; +} + + +int AStitchRegular(bool bTrapezoid, int diagonals, + uint numInsideEdgePoints, + int2 outsideInsideEdgePointBaseOffset, + int i) +{ + if (bTrapezoid) + { + ++ outsideInsideEdgePointBaseOffset.x; + } + + int pt; + + if ((i < 4) && bTrapezoid) + { + if (i < 2) + { + pt = outsideInsideEdgePointBaseOffset.x - 1 + i; + } + else if (i == 2) + { + pt = outsideInsideEdgePointBaseOffset.y; + } + else + { + pt = -1; + } + } + + int index = i; + if (bTrapezoid) + { + index -= 4; + } + + if (index >= 0) + { + uint uindex = (uint)index; + + switch( diagonals ) + { + case DIAGONALS_INSIDE_TO_OUTSIDE: + if (uindex < 5 * numInsideEdgePoints - 5) + { + uint p = uindex / 5; + uint r = uindex - p * 5; + if (r < 2) + { + pt = outsideInsideEdgePointBaseOffset.x + p + r; + } + else if (r < 4) + { + pt = outsideInsideEdgePointBaseOffset.y + p + r; + } + else + { + pt = -1; + } + } + else + { + int r = i - (4 + 5 * numInsideEdgePoints - 5); + if (r < 2) + { + pt = outsideInsideEdgePointBaseOffset.x + numInsideEdgePoints - 1 + r; + } + else if (r == 2) + { + pt = outsideInsideEdgePointBaseOffset.y + numInsideEdgePoints - 1; + } + else + { + pt = -1; + } + } + break; + + case DIAGONALS_INSIDE_TO_OUTSIDE_EXCEPT_MIDDLE: // Assumes ODD tessellation + if (uindex < (numInsideEdgePoints / 2 - 1) * 5) + { + // First half + uint p = uindex / 5; + uint r = uindex - p * 5; + if (r < 2) + { + pt = outsideInsideEdgePointBaseOffset.x + p + r; + } + else if (r < 4) + { + pt = outsideInsideEdgePointBaseOffset.y + p; + } + else + { + pt = -1; + } + } + else if (uindex < (numInsideEdgePoints / 2 - 1) * 5 + 8) + { + // Middle + uint r = uindex - (numInsideEdgePoints / 2 - 1) * 5; + if (0 == r) + { + pt = outsideInsideEdgePointBaseOffset.x + numInsideEdgePoints / 2 - 1; + } + else if (r < 3) + { + pt = outsideInsideEdgePointBaseOffset.y + numInsideEdgePoints / 2 - 1 + (2 - r); + } + else if (r == 3) + { + pt = -1; + } + else if (r < 6) + { + pt = outsideInsideEdgePointBaseOffset.x + numInsideEdgePoints / 2 - 1 + (r - 4); + } + else if (r == 6) + { + pt = outsideInsideEdgePointBaseOffset.y + numInsideEdgePoints / 2 - 1 + 1; + } + else if (r == 7) + { + pt = -1; + } + } + //else if (uindex < (numInsideEdgePoints/2-1) * 5 + 8 + (numInsideEdgePoints - numInsideEdgePoints/2 - 1) * 5) + else if (uindex < numInsideEdgePoints * 5 - 2) + { + // Second half + uint p = (uindex - (numInsideEdgePoints / 2 - 1) * 5 + 8) / 5 + numInsideEdgePoints / 2 + 1; + uint r = uindex - (numInsideEdgePoints / 2 - 1) * 5 + 8 - (p - (numInsideEdgePoints / 2 + 1)) * 5; + if (r < 2) + { + pt = outsideInsideEdgePointBaseOffset.x + p - 1 + r; + } + else if (r < 4) + { + pt = outsideInsideEdgePointBaseOffset.y + p - 1 + r; + } + else + { + pt = -1; + } + } + else + { + //int r = i - (4 + (numInsideEdgePoints/2-1) * 5 + 8 + (numInsideEdgePoints - numInsideEdgePoints/2 - 1) * 5); + int r = i - (numInsideEdgePoints * 5 + 2); + if (r < 2) + { + pt = outsideInsideEdgePointBaseOffset.x + numInsideEdgePoints - 1 + r; + } + else if (r == 2) + { + pt = outsideInsideEdgePointBaseOffset.y + numInsideEdgePoints - 1; + } + else + { + pt = -1; + } + } + break; + + case DIAGONALS_MIRRORED: + if (uindex < (numInsideEdgePoints / 2 + 1) * 2) + { + uint p = uindex / 2; + uint r = uindex - p * 2; + if (0 == r) + { + pt = outsideInsideEdgePointBaseOffset.y + p; + } + else + { + pt = outsideInsideEdgePointBaseOffset.x + p; + } + } + else if (uindex == (numInsideEdgePoints / 2 + 1) * 2) + { + pt = -1; + } + else if (uindex == (numInsideEdgePoints / 2 + 1) * 2 + 1) + { + pt = outsideInsideEdgePointBaseOffset.x + numInsideEdgePoints / 2; + } + //else if (uindex < (numInsideEdgePoints / 2 + 1) * 2 + 2 + (numInsideEdgePoints - numInsideEdgePoints / 2) * 2) + else if (uindex < numInsideEdgePoints * 2 + 4) + { + uint p = (uindex - ((numInsideEdgePoints / 2 + 1) * 2 + 2)) / 2 + numInsideEdgePoints / 2; + uint r = uindex - ((numInsideEdgePoints / 2 + 1) * 2 + 2) - (p - numInsideEdgePoints / 2) * 2; + if (0 == r) + { + pt = outsideInsideEdgePointBaseOffset.x + p; + } + else + { + pt = outsideInsideEdgePointBaseOffset.y + p; + } + } + //else if (uindex == (numInsideEdgePoints / 2 + 1) * 2 + 2 + (numInsideEdgePoints - numInsideEdgePoints / 2) * 2) + else if (uindex == numInsideEdgePoints * 2 + 4) + { + pt = -1; + } + else + { + //int r = i - (4 + (numInsideEdgePoints / 2 + 1) * 2 + 2 + (numInsideEdgePoints - numInsideEdgePoints / 2) * 2 + 1); + uint r = i - (numInsideEdgePoints * 2 + 9); + if (r < 2) + { + pt = outsideInsideEdgePointBaseOffset.x + numInsideEdgePoints - 1 + r; + } + else if (r == 2) + { + pt = outsideInsideEdgePointBaseOffset.y + numInsideEdgePoints - 1; + } + else + { + pt = -1; + } + } + break; + } + } + + return pt; +} + +int AStitchTransition(int2 outsideInsideEdgePointBaseOffset, int2 outsideInsideNumHalfTessFactorPoints, + int2 outsideInsideEdgeTessFactorParity, + uint i) +{ + outsideInsideNumHalfTessFactorPoints -= (TESSELLATOR_PARITY_ODD == outsideInsideEdgeTessFactorParity); + + uint2 out_in_first_half = uint2(outsidePointIndex[outsideInsideNumHalfTessFactorPoints.x][MAX_FACTOR / 2 + 1].y, insidePointIndex[outsideInsideNumHalfTessFactorPoints.y][MAX_FACTOR / 2 + 1].y) * 4; + + uint3 out_in_middle = 0; + if ((outsideInsideEdgeTessFactorParity.y != outsideInsideEdgeTessFactorParity.x) || (outsideInsideEdgeTessFactorParity.y == TESSELLATOR_PARITY_ODD)) + { + if (outsideInsideEdgeTessFactorParity.y == outsideInsideEdgeTessFactorParity.x) + { + // Quad in the middle + out_in_middle.z = 5; + out_in_middle.xy = 1; + } + else if (TESSELLATOR_PARITY_EVEN == outsideInsideEdgeTessFactorParity.y) + { + // Triangle pointing inside + out_in_middle.z = 4; + out_in_middle.x = 1; + } + else + { + // Triangle pointing outside + out_in_middle.z = 4; + out_in_middle.y = 1; + } + } + + + int pt = -1; + + if (i < out_in_first_half.y) + { + // Advance inside + + uint p = i / 4; + uint r = i - p * 4; + p = insidePointIndex[outsideInsideNumHalfTessFactorPoints.y][p].z; + if ((0 == r) || (2 == r)) + { + pt = outsideInsideEdgePointBaseOffset.y + insidePointIndex[outsideInsideNumHalfTessFactorPoints.y][p].y + r / 2; + } + else if (1 == r) + { + pt = outsideInsideEdgePointBaseOffset.x + outsidePointIndex[outsideInsideNumHalfTessFactorPoints.x][p].y; + } + } + else + { + i -= out_in_first_half.y; + + if (i < out_in_first_half.x) + { + // Advance outside + + uint p = i / 4; + uint r = i - p * 4; + p = outsidePointIndex[outsideInsideNumHalfTessFactorPoints.x][p].z; + if (r < 2) + { + pt = outsideInsideEdgePointBaseOffset.x + outsidePointIndex[outsideInsideNumHalfTessFactorPoints.x][p].y + r; + } + else if (r == 2) + { + pt = outsideInsideEdgePointBaseOffset.y + insidePointIndex[outsideInsideNumHalfTessFactorPoints.y][p].y; + if (insidePointIndex[outsideInsideNumHalfTessFactorPoints.y][p].x) + { + ++ pt; + } + } + } + else + { + i -= out_in_first_half.x; + + if (i < out_in_middle.z) + { + uint r = i; + if (outsideInsideEdgeTessFactorParity.y == outsideInsideEdgeTessFactorParity.x) + { + // Quad in the middle + if ((0 == r) || (2 == r)) + { + pt = outsideInsideEdgePointBaseOffset.y + out_in_first_half.y / 4 + (2 == r);//r / 2; + } + else if ((1 == r) || (3 == r)) + { + pt = outsideInsideEdgePointBaseOffset.x + out_in_first_half.x / 4 + (3 == r);//(r - 1) / 2; + } + } + else if (TESSELLATOR_PARITY_EVEN == outsideInsideEdgeTessFactorParity.y) + { + // Triangle pointing inside + if (r == 0) + { + pt = outsideInsideEdgePointBaseOffset.y + out_in_first_half.y / 4; + } + else if (r < 3) + { + pt = outsideInsideEdgePointBaseOffset.x + out_in_first_half.x / 4 + r - 1; + } + } + else + { + // Triangle pointing outside + if ((0 == r) || (2 == r)) + { + pt = outsideInsideEdgePointBaseOffset.y + out_in_first_half.y / 4 + (2 == r);//r / 2; + } + else if (1 == r) + { + pt = outsideInsideEdgePointBaseOffset.x + out_in_first_half.x / 4; + } + } + } + else + { + i -= out_in_middle.z; + + if (i < out_in_first_half.x) + { + // Advance outside + + uint p = i / 4; + uint r = i - p * 4; + p = outsidePointIndex[outsideInsideNumHalfTessFactorPoints.x][p].z; + if (r < 2) + { + pt = outsideInsideEdgePointBaseOffset.x + out_in_first_half.x / 4 + out_in_middle.x + (outsidePointIndex[outsideInsideNumHalfTessFactorPoints.x][MAX_FACTOR / 2 + 1].y - outsidePointIndex[outsideInsideNumHalfTessFactorPoints.x][p + 1].y) + r; + } + else if (r == 2) + { + pt = outsideInsideEdgePointBaseOffset.y + out_in_first_half.y / 4 + out_in_middle.y + (insidePointIndex[outsideInsideNumHalfTessFactorPoints.y][MAX_FACTOR / 2 + 1].y - insidePointIndex[outsideInsideNumHalfTessFactorPoints.y][p + 1].y); + } + } + else + { + // Advance inside + + i -= out_in_first_half.x; + + uint p = i / 4; + uint r = i - p * 4; + p = insidePointIndex[outsideInsideNumHalfTessFactorPoints.y][p].w; + if ((0 == r) || (2 == r)) + { + pt = outsideInsideEdgePointBaseOffset.y + out_in_first_half.y / 4 + out_in_middle.y + + (insidePointIndex[outsideInsideNumHalfTessFactorPoints.y][MAX_FACTOR / 2 + 1].y - insidePointIndex[outsideInsideNumHalfTessFactorPoints.y][p + 1].y) + (2 == r);//r / 2; + } + else if (1 == r) + { + pt = outsideInsideEdgePointBaseOffset.x + out_in_first_half.x / 4 + out_in_middle.x + + (outsidePointIndex[outsideInsideNumHalfTessFactorPoints.x][MAX_FACTOR / 2 + 1].y - outsidePointIndex[outsideInsideNumHalfTessFactorPoints.x][p + 1].y); + if (outsidePointIndex[outsideInsideNumHalfTessFactorPoints.x][p].x) + { + ++ pt; + } + } + } + } + } + } + + return pt; +} + +[numthreads(128, 1, 1)] +void CSTessellationIndices( uint3 DTid : SV_DispatchThreadID, uint3 Gid : SV_GroupID, uint GI : SV_GroupIndex ) +{ + uint id = DTid.x; + //uint id = Gid.x * 128 + GI; // Workaround for some CS4x preview drivers + + if ( id < g_param.x ) + { + uint tri_id = InputTriIDIndexID[id].x; + uint index_id = InputTriIDIndexID[id].y; + uint base_vertex = InputScanned[tri_id-1].x; + + float4 outside_inside_factor = InputEdgeFactor[tri_id]; + + PROCESSED_TESS_FACTORS_TRI processedTessFactors; + int num_points = TriProcessTessFactors(outside_inside_factor, processedTessFactors, g_partitioning); + + uint tessed_indices; + if (3 == num_points) + { + if (index_id < 3) + { + tessed_indices = TransformIndex1(index_id, base_vertex); + } + else + { + tessed_indices = -1; + } + } + else + { + // Generate primitives for all the concentric rings, one side at a time for each ring + static const int startRing = 1; + int numRings = ((processedTessFactors.numPointsForOutsideInside.w + 1) / 2); // +1 is so even tess includes the center point, which we want to now + + int4 outsideInsideHalfTessFactor = int4(ceil(processedTessFactors.outsideInsideHalfTessFactor)); + uint3 num = NumStitchTransition(outsideInsideHalfTessFactor, processedTessFactors.outsideInsideTessFactorParity); + num.y += num.x; + num.z += num.y; + uint num_index = num.z; + num_index += TotalNumStitchRegular(true, DIAGONALS_MIRRORED, processedTessFactors.numPointsForOutsideInside.w, numRings - 1) * 3; + if( processedTessFactors.outsideInsideTessFactorParity.w == TESSELLATOR_PARITY_ODD ) + { + num_index += 4; + } + + int pt; + + if (index_id < num.x) + { + int numPointsForInsideEdge = processedTessFactors.numPointsForOutsideInside.w - 2 * startRing; + + pt = AStitchTransition(int2(0, processedTessFactors.insideEdgePointBaseOffset), + outsideInsideHalfTessFactor.xw, + processedTessFactors.outsideInsideTessFactorParity.xw, + index_id); + if (pt != -1) + { + pt = TransformIndex1(pt, base_vertex); + } + } + else if (index_id < num.y) + { + int numPointsForInsideEdge = processedTessFactors.numPointsForOutsideInside.w - 2 * startRing; + + pt = AStitchTransition( + int2(processedTessFactors.numPointsForOutsideInside.x - 1, processedTessFactors.insideEdgePointBaseOffset + numPointsForInsideEdge - 1), + outsideInsideHalfTessFactor.yw, + processedTessFactors.outsideInsideTessFactorParity.yw, + index_id - num.x); + if (pt != -1) + { + pt = TransformIndex1(pt, base_vertex); + } + } + else if (index_id < num.z) + { + int numPointsForInsideEdge = processedTessFactors.numPointsForOutsideInside.w - 2 * startRing; + + INDEX_PATCH_CONTEXT IndexPatchContext; + IndexPatchContext.insidePointIndexDeltaToRealValue = processedTessFactors.insideEdgePointBaseOffset + 2 * (numPointsForInsideEdge - 1); + IndexPatchContext.insidePointIndexBadValue = numPointsForInsideEdge - 1; + IndexPatchContext.insidePointIndexReplacementValue = processedTessFactors.insideEdgePointBaseOffset; + IndexPatchContext.outsidePointIndexPatchBase = IndexPatchContext.insidePointIndexBadValue+1; // past inside patched index range + IndexPatchContext.outsidePointIndexDeltaToRealValue = processedTessFactors.numPointsForOutsideInside.x + processedTessFactors.numPointsForOutsideInside.y - 2 + - IndexPatchContext.outsidePointIndexPatchBase; + IndexPatchContext.outsidePointIndexBadValue = IndexPatchContext.outsidePointIndexPatchBase + + processedTessFactors.numPointsForOutsideInside.z - 1; + IndexPatchContext.outsidePointIndexReplacementValue = 0; + + pt = AStitchTransition(int2(numPointsForInsideEdge, 0), + outsideInsideHalfTessFactor.zw, + processedTessFactors.outsideInsideTessFactorParity.zw, + index_id - num.y); + if (pt != -1) + { + pt = TransformIndex2(pt, base_vertex, IndexPatchContext); + } + } + else + { + if ((processedTessFactors.outsideInsideTessFactorParity.w == TESSELLATOR_PARITY_ODD) && (index_id >= num_index - 4)) + { + int outsideEdgePointBaseOffset = processedTessFactors.insideEdgePointBaseOffset + + ((processedTessFactors.numPointsForOutsideInside.w + 1) - (numRings + startRing)) * (numRings - startRing - 1) * 3; + + if (index_id - (num_index - 4) != 3) + { + pt = TransformIndex1(outsideEdgePointBaseOffset + index_id - (num_index - 4), base_vertex); + } + else + { + pt = -1; + } + } + else + { + int ring = GetRingFromIndexStitchRegular(true, DIAGONALS_MIRRORED, processedTessFactors.numPointsForOutsideInside.w, index_id - num.z); + + int tn = TotalNumStitchRegular(true, DIAGONALS_MIRRORED, processedTessFactors.numPointsForOutsideInside.w, ring - 1) * 3; + int n = NumStitchRegular(true, DIAGONALS_MIRRORED, processedTessFactors.numPointsForOutsideInside.w - 2 * ring); + + int edge = (index_id - num.z - tn) / n; + int index = (index_id - num.z - tn) - edge * n; + + int2 outsideInsideEdgePointBaseOffset = processedTessFactors.insideEdgePointBaseOffset + + int2(0, 3 * (processedTessFactors.numPointsForOutsideInside.w - 3)) + + ((processedTessFactors.numPointsForOutsideInside.w - (ring + startRing)) + int2(1, -1)) * (ring - startRing - 1) * 3; + + int numPointsForInsideEdge = processedTessFactors.numPointsForOutsideInside.w - 2 * ring; + int numLastPointsForInsideEdge = numPointsForInsideEdge + 2; + + if (edge < 2) + { + pt = AStitchRegular(true, DIAGONALS_MIRRORED, + numPointsForInsideEdge, + outsideInsideEdgePointBaseOffset + (int2(numLastPointsForInsideEdge, numPointsForInsideEdge) - 1) * edge, + index); + if (pt != -1) + { + pt = TransformIndex1(pt, base_vertex); + } + } + else + { + INDEX_PATCH_CONTEXT IndexPatchContext; + IndexPatchContext.insidePointIndexDeltaToRealValue = outsideInsideEdgePointBaseOffset.y + (numPointsForInsideEdge - 1) * 2; + IndexPatchContext.insidePointIndexBadValue = numPointsForInsideEdge - 1; + IndexPatchContext.insidePointIndexReplacementValue = outsideInsideEdgePointBaseOffset.y; + IndexPatchContext.outsidePointIndexPatchBase = IndexPatchContext.insidePointIndexBadValue+1; // past inside patched index range + IndexPatchContext.outsidePointIndexDeltaToRealValue = outsideInsideEdgePointBaseOffset.x + (numLastPointsForInsideEdge - 1) * 2 + - IndexPatchContext.outsidePointIndexPatchBase; + IndexPatchContext.outsidePointIndexBadValue = IndexPatchContext.outsidePointIndexPatchBase + + numLastPointsForInsideEdge - 1; + IndexPatchContext.outsidePointIndexReplacementValue = outsideInsideEdgePointBaseOffset.x; + + pt = AStitchRegular(true, DIAGONALS_MIRRORED, + numPointsForInsideEdge, + int2(numPointsForInsideEdge, 0), + index); + if (pt != -1) + { + pt = TransformIndex2(pt, base_vertex, IndexPatchContext); + } + } + } + } + + tessed_indices = pt; + } + + TessedIndicesOut.Store(id*4, tessed_indices); + } +} diff --git a/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_TessellateVerticesCS.hlsl b/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_TessellateVerticesCS.hlsl new file mode 100644 index 000000000..55bf1be87 --- /dev/null +++ b/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_TessellateVerticesCS.hlsl @@ -0,0 +1,206 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile cs_4_0 -entry CSTessellationVertices +//-------------------------------------------------------------------------------------- +// File: TessellatorCS40_TessellateVerticesCS.hlsl +// +// The CS to tessellate vertices +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +#include "TessellatorCS40_common.hlsl" + +StructuredBuffer InputTriIDIndexID : register(t0); +StructuredBuffer InputEdgeFactor : register(t1); + +struct TessedVertex +{ + uint BaseTriID; + float2 bc; +}; +RWStructuredBuffer TessedVerticesOut : register(u0); + +cbuffer cbCS : register(b1) +{ + uint4 g_param; +} + +void PlacePointIn1D(PROCESSED_TESS_FACTORS_TRI processedTessFactors, int ctx_index, int pt, out float location, int parity) +{ + int numHalfTessFactorPoints = int(ceil(processedTessFactors.outsideInsideHalfTessFactor[ctx_index])); + + bool bFlip; + if( pt >= numHalfTessFactorPoints ) + { + pt = (numHalfTessFactorPoints << 1) - pt; + if( TESSELLATOR_PARITY_ODD == parity ) + { + pt -= 1; + } + bFlip = true; + } + else + { + bFlip = false; + } + + if( pt == numHalfTessFactorPoints ) + { + location = 0.5f; + } + else + { + unsigned int indexOnCeilHalfTessFactor = pt; + unsigned int indexOnFloorHalfTessFactor = indexOnCeilHalfTessFactor; + if( pt > processedTessFactors.outsideInsideSplitPointOnFloorHalfTessFactor[ctx_index] ) + { + indexOnFloorHalfTessFactor -= 1; + } + float locationOnFloorHalfTessFactor = indexOnFloorHalfTessFactor * processedTessFactors.outsideInsideInvNumSegmentsOnFloorTessFactor[ctx_index]; + float locationOnCeilHalfTessFactor = indexOnCeilHalfTessFactor * processedTessFactors.outsideInsideInvNumSegmentsOnCeilTessFactor[ctx_index]; + + location = lerp(locationOnFloorHalfTessFactor, locationOnCeilHalfTessFactor, frac(processedTessFactors.outsideInsideHalfTessFactor[ctx_index])); + + if( bFlip ) + { + location = 1.0f - location; + } + } +} + +[numthreads(128, 1, 1)] +void CSTessellationVertices( uint3 DTid : SV_DispatchThreadID, uint3 Gid : SV_GroupID, uint GI : SV_GroupIndex ) +{ + uint id = DTid.x; + //uint id = Gid.x * 128 + GI; // Workaround for some CS4x preview drivers + + if ( id < g_param.x ) + { + uint tri_id = InputTriIDIndexID[id].x; + uint vert_id = InputTriIDIndexID[id].y; + + float4 outside_inside_factor = InputEdgeFactor[tri_id]; + + PROCESSED_TESS_FACTORS_TRI processedTessFactors; + int num_points = TriProcessTessFactors(outside_inside_factor, processedTessFactors, g_partitioning); + + float2 uv; + if (3 == num_points) + { + if (0 == vert_id) + { + uv = float2(0, 1); + } + else if (1 == vert_id) + { + uv = float2(0, 0); + } + else + { + uv = float2(1, 0); + } + } + else + { + if (vert_id < processedTessFactors.insideEdgePointBaseOffset) + { + // Generate exterior ring edge points, clockwise starting from point V (VW, the U==0 edge) + + int edge; + if (vert_id < processedTessFactors.numPointsForOutsideInside.x - 1) + { + edge = 0; + } + else + { + vert_id -= processedTessFactors.numPointsForOutsideInside.x - 1; + if (vert_id < processedTessFactors.numPointsForOutsideInside.y - 1) + { + edge = 1; + } + else + { + vert_id -= processedTessFactors.numPointsForOutsideInside.y - 1; + edge = 2; + } + } + + int p = vert_id; + int endPoint = processedTessFactors.numPointsForOutsideInside[edge] - 1; + float param; + int q = (edge & 0x1) ? p : endPoint - p; // whether to reverse point order given we are defining V or U (W implicit): + // edge0, VW, has V decreasing, so reverse 1D points below + // edge1, WU, has U increasing, so don't reverse 1D points below + // edge2, UV, has U decreasing, so reverse 1D points below + PlacePointIn1D(processedTessFactors, edge,q,param, processedTessFactors.outsideInsideTessFactorParity[edge]); + if (0 == edge) + { + uv = float2(0, param); + } + else if (1 == edge) + { + uv = float2(param, 0); + } + else + { + uv = float2(param, 1 - param); + } + } + else + { + // Generate interior ring points, clockwise spiralling in + + uint index = vert_id - processedTessFactors.insideEdgePointBaseOffset; + uint ring = 1 + (((3 * processedTessFactors.numPointsForOutsideInside.w - 6) - sqrt(sqr(3 * processedTessFactors.numPointsForOutsideInside.w - 6) - 4 * 3 * index)) + 0.001f) / 6; + index -= 3 * (processedTessFactors.numPointsForOutsideInside.w - ring - 1) * (ring - 1); + + uint startPoint = ring; + uint endPoint = processedTessFactors.numPointsForOutsideInside.w - 1 - startPoint; + if (index < 3 * (endPoint - startPoint)) + { + uint edge = index / (endPoint - startPoint); + uint p = index - edge * (endPoint - startPoint) + startPoint; + + int perpendicularAxisPoint = startPoint; + float perpParam; + PlacePointIn1D(processedTessFactors, 3, perpendicularAxisPoint, perpParam, processedTessFactors.outsideInsideTessFactorParity.w); + perpParam = perpParam * 2 / 3; + + float param; + int q = (edge & 0x1) ? p : endPoint - (p - startPoint); // whether to reverse point given we are defining V or U (W implicit): + // edge0, VW, has V decreasing, so reverse 1D points below + // edge1, WU, has U increasing, so don't reverse 1D points below + // edge2, UV, has U decreasing, so reverse 1D points below + PlacePointIn1D(processedTessFactors, 3, q,param, processedTessFactors.outsideInsideTessFactorParity.w); + // edge0 VW, has perpendicular parameter U constant + // edge1 WU, has perpendicular parameter V constant + // edge2 UV, has perpendicular parameter W constant + const unsigned int deriv = 2; // reciprocal is the rate of change of edge-parallel parameters as they are pushed into the triangle + if (0 == edge) + { + uv = float2(perpParam, param - perpParam / deriv); + } + else if (1 == edge) + { + uv = float2(param - perpParam / deriv, perpParam); + } + else + { + uv = float2(param - perpParam / deriv, 1 - (param - perpParam / deriv + perpParam)); + } + } + else + { + if( processedTessFactors.outsideInsideTessFactorParity.w != TESSELLATOR_PARITY_ODD ) + { + // Last point is the point at the center. + uv = 1 / 3.0f; + } + } + } + } + + TessedVerticesOut[id].BaseTriID = tri_id; + TessedVerticesOut[id].bc = uv; + } +} diff --git a/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_common.hlsl b/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_common.hlsl new file mode 100644 index 000000000..309044cdb --- /dev/null +++ b/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_common.hlsl @@ -0,0 +1,411 @@ +//TEST_IGNORE_FILE: +//-------------------------------------------------------------------------------------- +// File: TessellatorCS40_common.hlsl +// +// The common utils included by other shaders in the sample +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +#include "TessellatorCS40_defines.h" + +cbuffer cbNeverChanges : register(b0) +{ + uint4 insidePointIndex[MAX_FACTOR / 2 + 1][MAX_FACTOR / 2 + 2]; + uint4 outsidePointIndex[MAX_FACTOR / 2 + 1][MAX_FACTOR / 2 + 2]; +} + +#define D3D11_TESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR ( 64 ) +#define D3D11_TESSELLATOR_MAX_ODD_TESSELLATION_FACTOR ( 63 ) +#define D3D11_TESSELLATOR_MIN_EVEN_TESSELLATION_FACTOR ( 2 ) +#define D3D11_TESSELLATOR_MIN_ODD_TESSELLATION_FACTOR ( 1 ) + +#define D3D11_TESSELLATOR_PARTITIONING_INTEGER ( 0 ) +#define D3D11_TESSELLATOR_PARTITIONING_POW2 ( 1 ) +#define D3D11_TESSELLATOR_PARTITIONING_FRACTIONAL_ODD ( 2 ) +#define D3D11_TESSELLATOR_PARTITIONING_FRACTIONAL_EVEN ( 3 ) + +#define TESSELLATOR_PARITY_EVEN ( 0 ) +#define TESSELLATOR_PARITY_ODD ( 1 ) + +#define EPSILON 1e-6f +#define MIN_ODD_TESSFACTOR_PLUS_HALF_EPSILON (D3D11_TESSELLATOR_MIN_ODD_TESSELLATION_FACTOR + EPSILON/2) + +#define DIAGONALS_INSIDE_TO_OUTSIDE ( 0 ) +#define DIAGONALS_INSIDE_TO_OUTSIDE_EXCEPT_MIDDLE ( 1 ) +#define DIAGONALS_MIRRORED ( 2 ) + + +// This is moved to macro defines at shader compile time, so that the partitioning mode can be changed during runtime +//#define g_partitioning (D3D11_TESSELLATOR_PARTITIONING_POW2) + + +struct PROCESSED_TESS_FACTORS_TRI +{ + float4 outsideInsideTessFactor; + int4 outsideInsideTessFactorParity; + + float4 outsideInsideInvNumSegmentsOnFloorTessFactor; + float4 outsideInsideInvNumSegmentsOnCeilTessFactor; + float4 outsideInsideHalfTessFactor; + int4 outsideInsideSplitPointOnFloorHalfTessFactor; + + // Stuff below is specific to the traversal order + uint4 numPointsForOutsideInside; + uint insideEdgePointBaseOffset; +}; + +struct INDEX_PATCH_CONTEXT +{ + int insidePointIndexDeltaToRealValue; + int insidePointIndexBadValue; + int insidePointIndexReplacementValue; + int outsidePointIndexPatchBase; + int outsidePointIndexDeltaToRealValue; + int outsidePointIndexBadValue; + int outsidePointIndexReplacementValue; +}; + +bool4 isEven(float4 input) +{ + return (((uint4)input) & 1) ? false : true; +} + +uint RemoveMSB(uint val) +{ + int check; + if( val <= 0x0000ffff ) + { + check = ( val <= 0x000000ff ) ? 0x00000080 : 0x00008000; + } + else + { + check = ( val <= 0x00ffffff ) ? 0x00800000 : 0x80000000; + } + for (int i = 0; i < 8; i++, check >>= 1) + { + if( val & check ) + { + return (val & ~check); + } + } + return 0; +} + +uint4 NumPointsForTessFactor(float4 tessFactor, int4 parity) +{ + return TESSELLATOR_PARITY_ODD == parity ? uint4(ceil(0.5f + tessFactor / 2)) * 2 : uint4(ceil(tessFactor / 2)) * 2 + 1; +} + +void ComputeTessFactorContext(float4 tessFactor, int4 parity, + out float4 invNumSegmentsOnFloorTessFactor, + out float4 invNumSegmentsOnCeilTessFactor, + out float4 halfTessFactor, + out int4 splitPointOnFloorHalfTessFactor) +{ + halfTessFactor = tessFactor / 2; + + halfTessFactor += 0.5 * ((TESSELLATOR_PARITY_ODD == parity) | (0.5f == halfTessFactor)); + + float4 floorHalfTessFactor = floor(halfTessFactor); + float4 ceilHalfTessFactor = ceil(halfTessFactor); + int4 numHalfTessFactorPoints = int4(ceilHalfTessFactor); + + for (int index = 0; index < 4; ++ index) + { + if( ceilHalfTessFactor[index] == floorHalfTessFactor[index] ) + { + splitPointOnFloorHalfTessFactor[index] = /*pick value to cause this to be ignored*/ numHalfTessFactorPoints[index]+1; + } + else if( TESSELLATOR_PARITY_ODD == parity[index] ) + { + if( floorHalfTessFactor[index] == 1 ) + { + splitPointOnFloorHalfTessFactor[index] = 0; + } + else + { + splitPointOnFloorHalfTessFactor[index] = (RemoveMSB(int(floorHalfTessFactor[index]) - 1) << 1) + 1; + } + } + else + { + splitPointOnFloorHalfTessFactor[index] = (RemoveMSB(int(floorHalfTessFactor[index])) << 1) + 1; + } + } + + int4 numFloorSegments = int4(floorHalfTessFactor * 2); + int4 numCeilSegments = int4(ceilHalfTessFactor * 2); + int4 s = (TESSELLATOR_PARITY_ODD == parity); + numFloorSegments -= s; + numCeilSegments -= s; + invNumSegmentsOnFloorTessFactor = 1.0f / numFloorSegments; + invNumSegmentsOnCeilTessFactor = 1.0f / numCeilSegments; +} + +int TriProcessTessFactors( inout float4 tessFactor, + out PROCESSED_TESS_FACTORS_TRI processedTessFactors, + int partitioning ) +{ + processedTessFactors = (PROCESSED_TESS_FACTORS_TRI)0; + + int parity = TESSELLATOR_PARITY_EVEN; + switch( partitioning ) + { + case D3D11_TESSELLATOR_PARTITIONING_INTEGER: + default: + break; + case D3D11_TESSELLATOR_PARTITIONING_FRACTIONAL_ODD: + parity = TESSELLATOR_PARITY_ODD; + break; + case D3D11_TESSELLATOR_PARTITIONING_FRACTIONAL_EVEN: + parity = TESSELLATOR_PARITY_EVEN; + break; + } + + // Is the patch culled? + if( !(tessFactor.x > 0) || // NaN will pass + !(tessFactor.y > 0) || + !(tessFactor.z > 0) ) + { + return 0; + } + + // Clamp edge TessFactors + float lowerBound, upperBound; + switch(partitioning) + { + case D3D11_TESSELLATOR_PARTITIONING_INTEGER: + case D3D11_TESSELLATOR_PARTITIONING_POW2: // don't care about pow2 distinction for validation, just treat as integer + default: + lowerBound = D3D11_TESSELLATOR_MIN_ODD_TESSELLATION_FACTOR; + upperBound = D3D11_TESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR; + break; + + case D3D11_TESSELLATOR_PARTITIONING_FRACTIONAL_EVEN: + lowerBound = D3D11_TESSELLATOR_MIN_EVEN_TESSELLATION_FACTOR; + upperBound = D3D11_TESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR; + break; + + case D3D11_TESSELLATOR_PARTITIONING_FRACTIONAL_ODD: + lowerBound = D3D11_TESSELLATOR_MIN_ODD_TESSELLATION_FACTOR; + upperBound = D3D11_TESSELLATOR_MAX_ODD_TESSELLATION_FACTOR; + break; + } + + tessFactor.xyz = min( upperBound, max( lowerBound, tessFactor.xyz ) ); + + // Clamp inside TessFactors + if(D3D11_TESSELLATOR_PARTITIONING_FRACTIONAL_ODD == partitioning) + { + if( (tessFactor.x > MIN_ODD_TESSFACTOR_PLUS_HALF_EPSILON) || + (tessFactor.y > MIN_ODD_TESSFACTOR_PLUS_HALF_EPSILON) || + (tessFactor.z > MIN_ODD_TESSFACTOR_PLUS_HALF_EPSILON)) + // Don't need the same check for insideTessFactor for tri patches, + // since there is only one insideTessFactor, as opposed to quad + // patches which have 2 insideTessFactors. + { + // Force picture frame + lowerBound = D3D11_TESSELLATOR_MIN_ODD_TESSELLATION_FACTOR + EPSILON; + } + } + + tessFactor.w = min( upperBound, max( lowerBound, tessFactor.w ) ); + // Note the above clamps map NaN to lowerBound + + if (partitioning == D3D11_TESSELLATOR_PARTITIONING_INTEGER) + { + tessFactor = ceil(tessFactor); + } + else if (partitioning == D3D11_TESSELLATOR_PARTITIONING_POW2) + { + static const int exponentMask = 0x7f800000; + static const int mantissaMask = 0x007fffff; + static const int exponentLSB = 0x00800000; + + int4 bits = asint(tessFactor); + tessFactor = bits & mantissaMask ? asfloat((bits & exponentMask) + exponentLSB) : tessFactor; + } + + // Process tessFactors + if ((partitioning == D3D11_TESSELLATOR_PARTITIONING_INTEGER)|| (partitioning == D3D11_TESSELLATOR_PARTITIONING_POW2)) + { + bool4 e = isEven(tessFactor); + processedTessFactors.outsideInsideTessFactorParity.xyz = e.xyz ? TESSELLATOR_PARITY_EVEN : TESSELLATOR_PARITY_ODD; + processedTessFactors.outsideInsideTessFactorParity.w = (e.w || (1 == tessFactor.w)) ? TESSELLATOR_PARITY_EVEN : TESSELLATOR_PARITY_ODD; + } + else + { + processedTessFactors.outsideInsideTessFactorParity = parity; + } + + processedTessFactors.outsideInsideTessFactor = tessFactor; + + if (((partitioning == D3D11_TESSELLATOR_PARTITIONING_INTEGER)|| (partitioning == D3D11_TESSELLATOR_PARTITIONING_POW2)) || (parity == TESSELLATOR_PARITY_ODD)) + { + // Special case if all TessFactors are 1 + if( (1 == processedTessFactors.outsideInsideTessFactor.x) && + (1 == processedTessFactors.outsideInsideTessFactor.y) && + (1 == processedTessFactors.outsideInsideTessFactor.z) && + (1 == processedTessFactors.outsideInsideTessFactor.w) ) + { + return 3; + } + } + + // Compute per-TessFactor metadata + ComputeTessFactorContext(processedTessFactors.outsideInsideTessFactor, processedTessFactors.outsideInsideTessFactorParity, + processedTessFactors.outsideInsideInvNumSegmentsOnFloorTessFactor, + processedTessFactors.outsideInsideInvNumSegmentsOnCeilTessFactor, + processedTessFactors.outsideInsideHalfTessFactor, + processedTessFactors.outsideInsideSplitPointOnFloorHalfTessFactor); + + // Compute some initial data. + + // outside edge offsets and storage + processedTessFactors.numPointsForOutsideInside = NumPointsForTessFactor(processedTessFactors.outsideInsideTessFactor, processedTessFactors.outsideInsideTessFactorParity); + int NumPoints = processedTessFactors.numPointsForOutsideInside.x + processedTessFactors.numPointsForOutsideInside.y + processedTessFactors.numPointsForOutsideInside.z - 3; + + // inside edge offsets + { + uint pointCountMin = (processedTessFactors.outsideInsideTessFactorParity.w == TESSELLATOR_PARITY_ODD) ? 4 : 3; + // max() allows degenerate transition regions when inside TessFactor == 1 + processedTessFactors.numPointsForOutsideInside.w = max(pointCountMin, processedTessFactors.numPointsForOutsideInside.w); + } + + processedTessFactors.insideEdgePointBaseOffset = NumPoints; + + // inside storage, including interior edges above + { + int numInteriorRings = (processedTessFactors.numPointsForOutsideInside.w >> 1) - 1; + int numInteriorPoints; + if( processedTessFactors.outsideInsideTessFactorParity.w == TESSELLATOR_PARITY_ODD ) + { + numInteriorPoints = 3*(numInteriorRings*(numInteriorRings+1) - numInteriorRings); + } + else + { + numInteriorPoints = 3*(numInteriorRings*(numInteriorRings+1)) + 1; + } + NumPoints += numInteriorPoints; + } + + return NumPoints; +} + +int NumStitchRegular(bool bTrapezoid, int diagonals, int numInsideEdgePoints) +{ + int num_index = 0; + + if( bTrapezoid ) + { + num_index += 8; + } + switch( diagonals ) + { + case DIAGONALS_INSIDE_TO_OUTSIDE: + // Diagonals pointing from inside edge forward towards outside edge + num_index += 5 * numInsideEdgePoints - 5; + break; + + case DIAGONALS_INSIDE_TO_OUTSIDE_EXCEPT_MIDDLE: // Assumes ODD tessellation + // Diagonals pointing from outside edge forward towards inside edge + num_index += 5 * numInsideEdgePoints - 2; + break; + + case DIAGONALS_MIRRORED: + num_index += 2 * numInsideEdgePoints + 5; + break; + } + + return num_index; +} + +uint TotalNumStitchRegular(bool bTrapezoid, int diagonals, + int numPointsForInsideTessFactor, int ring) +{ + uint num_index = 0; + + if( bTrapezoid ) + { + num_index += 8 * (ring - 1); + } + switch( diagonals ) + { + case DIAGONALS_INSIDE_TO_OUTSIDE: + // Diagonals pointing from inside edge forward towards outside edge + num_index += (5 * numPointsForInsideTessFactor - 35 - 5 * ring) * (ring - 1); + break; + + case DIAGONALS_INSIDE_TO_OUTSIDE_EXCEPT_MIDDLE: // Assumes ODD tessellation + // Diagonals pointing from outside edge forward towards inside edge + num_index += (5 * numPointsForInsideTessFactor - 12 - 5 * ring) * (ring - 1); + break; + + case DIAGONALS_MIRRORED: + num_index += (2 * numPointsForInsideTessFactor + 1 - 2 * ring) * (ring - 1); + break; + } + + return num_index; +} + +int sqr(int x) +{ + return x * x; +} + +int GetRingFromIndexStitchRegular(bool bTrapezoid, int diagonals, int numPointsForInsideTessFactor, int index) +{ + int t = 0; + if (bTrapezoid) + { + t = 8; + } + + switch( diagonals ) + { + case DIAGONALS_INSIDE_TO_OUTSIDE: + t = (5 * numPointsForInsideTessFactor - (35 - t)) * 3; + return 1 + uint((t + 15) - sqrt(sqr(t + 15) - 4 * 15 * (t + index)) + 0.001f) / 30; + + case DIAGONALS_INSIDE_TO_OUTSIDE_EXCEPT_MIDDLE: + t = (5 * numPointsForInsideTessFactor - (12 - t)) * 3; + return 1 + uint((t + 15) - sqrt(sqr(t + 15) - 4 * 15 * (t + index)) + 0.001f) / 30; + + case DIAGONALS_MIRRORED: + t = ((t + 1) + 2 * numPointsForInsideTessFactor) * 3; + return 1 + uint((t + 6) - sqrt(sqr(t + 6) - 4 * 6 * (t + index)) + 0.001f) / 12; + + default: + return -1; + } +} + +uint3 NumStitchTransition(int4 outsideInsideNumHalfTessFactorPoints, + int4 outsideInsideEdgeTessFactorParity) +{ + outsideInsideNumHalfTessFactorPoints -= (TESSELLATOR_PARITY_ODD == outsideInsideEdgeTessFactorParity); + + uint3 num_index = insidePointIndex[outsideInsideNumHalfTessFactorPoints.w][MAX_FACTOR / 2 + 1].y * 8; + + [unroll] + for (int edge = 0; edge < 3; ++ edge) + { + num_index[edge] += outsidePointIndex[outsideInsideNumHalfTessFactorPoints[edge]][MAX_FACTOR / 2 + 1].y * 8; + + if( (outsideInsideEdgeTessFactorParity.w != outsideInsideEdgeTessFactorParity[edge]) || (outsideInsideEdgeTessFactorParity.w == TESSELLATOR_PARITY_ODD)) + { + if( outsideInsideEdgeTessFactorParity.w == outsideInsideEdgeTessFactorParity[edge] ) + { + num_index[edge] += 5; + } + else + { + num_index[edge] += 4; + } + } + } + + return num_index; +} diff --git a/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_defines.h b/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_defines.h new file mode 100644 index 000000000..6b4382393 --- /dev/null +++ b/tests/hlsl/dxsdk/AdaptiveTessellationCS40/TessellatorCS40_defines.h @@ -0,0 +1,9 @@ +//-------------------------------------------------------------------------------------- +// File: TessellatorCS40_defines.h +// +// This file defines common constants which are included by both CPU code and shader code +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +#define MAX_FACTOR 16 diff --git a/tests/hlsl/dxsdk/BC6HBC7EncoderCS/Shaders/BC6HEncode.hlsl b/tests/hlsl/dxsdk/BC6HBC7EncoderCS/Shaders/BC6HEncode.hlsl new file mode 100644 index 000000000..1e40c80ef --- /dev/null +++ b/tests/hlsl/dxsdk/BC6HBC7EncoderCS/Shaders/BC6HEncode.hlsl @@ -0,0 +1,2567 @@ +//TEST_IGNORE_FILE: +//-------------------------------------------------------------------------------------- +// File: BC6HEncode.hlsl +// +// The Compute Shader for BC6H Encoder +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//#define REF_DEVICE + +#define UINTLENGTH 32 +#define NCHANNELS 3 +#define SIGNED_F16 96 +#define UNSIGNED_F16 95 +#define MAX_FLOAT asfloat(0x7F7FFFFF) +#define MIN_FLOAT asfloat(0xFF7FFFFF) +#define MAX_INT asint(0x7FFFFFFF) +#define MIN_INT asint(0x80000000) + +cbuffer cbCS : register( b0 ) +{ + uint g_tex_width; + uint g_num_block_x; + uint g_format; //either SIGNED_F16 for DXGI_FORMAT_BC6H_SF16 or UNSIGNED_F16 for DXGI_FORMAT_BC6H_UF16 + uint g_mode_id; + uint g_start_block_id; + uint g_num_total_blocks; +}; + +static const uint candidateModeMemory[14] = { 0x00, 0x01, 0x02, 0x06, 0x0A, 0x0E, 0x12, 0x16, 0x1A, 0x1E, 0x03, 0x07, 0x0B, 0x0F }; +static const uint candidateModeFlag[14] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }; +static const bool candidateModeTransformed[14] = { true, true, true, true, true, true, true, true, true, false, false, true, true, true }; +static const uint4 candidateModePrec[14] = { uint4(10,5,5,5), uint4(7,6,6,6), + uint4(11,5,4,4), uint4(11,4,5,4), uint4(11,4,4,5), uint4(9,5,5,5), + uint4(8,6,5,5), uint4(8,5,6,5), uint4(8,5,5,6), uint4(6,6,6,6), + uint4(10,10,10,10), uint4(11,9,9,9), uint4(12,8,8,8), uint4(16,4,4,4) }; + +/*static const uint4x4 candidateSection[32] = +{ + {0,0,1,1, 0,0,1,1, 0,0,1,1, 0,0,1,1}, {0,0,0,1, 0,0,0,1, 0,0,0,1, 0,0,0,1}, {0,1,1,1, 0,1,1,1, 0,1,1,1, 0,1,1,1}, {0,0,0,1, 0,0,1,1, 0,0,1,1, 0,1,1,1}, + {0,0,0,0, 0,0,0,1, 0,0,0,1, 0,0,1,1}, {0,0,1,1, 0,1,1,1, 0,1,1,1, 1,1,1,1}, {0,0,0,1, 0,0,1,1, 0,1,1,1, 1,1,1,1}, {0,0,0,0, 0,0,0,1, 0,0,1,1, 0,1,1,1}, + {0,0,0,0, 0,0,0,0, 0,0,0,1, 0,0,1,1}, {0,0,1,1, 0,1,1,1, 1,1,1,1, 1,1,1,1}, {0,0,0,0, 0,0,0,1, 0,1,1,1, 1,1,1,1}, {0,0,0,0, 0,0,0,0, 0,0,0,1, 0,1,1,1}, + {0,0,0,1, 0,1,1,1, 1,1,1,1, 1,1,1,1}, {0,0,0,0, 0,0,0,0, 1,1,1,1, 1,1,1,1}, {0,0,0,0, 1,1,1,1, 1,1,1,1, 1,1,1,1}, {0,0,0,0, 0,0,0,0, 0,0,0,0, 1,1,1,1}, + {0,0,0,0, 1,0,0,0, 1,1,1,0, 1,1,1,1}, {0,1,1,1, 0,0,0,1, 0,0,0,0, 0,0,0,0}, {0,0,0,0, 0,0,0,0, 1,0,0,0, 1,1,1,0}, {0,1,1,1, 0,0,1,1, 0,0,0,1, 0,0,0,0}, + {0,0,1,1, 0,0,0,1, 0,0,0,0, 0,0,0,0}, {0,0,0,0, 1,0,0,0, 1,1,0,0, 1,1,1,0}, {0,0,0,0, 0,0,0,0, 1,0,0,0, 1,1,0,0}, {0,1,1,1, 0,0,1,1, 0,0,1,1, 0,0,0,1}, + {0,0,1,1, 0,0,0,1, 0,0,0,1, 0,0,0,0}, {0,0,0,0, 1,0,0,0, 1,0,0,0, 1,1,0,0}, {0,1,1,0, 0,1,1,0, 0,1,1,0, 0,1,1,0}, {0,0,1,1, 0,1,1,0, 0,1,1,0, 1,1,0,0}, + {0,0,0,1, 0,1,1,1, 1,1,1,0, 1,0,0,0}, {0,0,0,0, 1,1,1,1, 1,1,1,1, 0,0,0,0}, {0,1,1,1, 0,0,0,1, 1,0,0,0, 1,1,1,0}, {0,0,1,1, 1,0,0,1, 1,0,0,1, 1,1,0,0} +};*/ + +static const uint candidateSectionBit[32] = +{ + 0xCCCC, 0x8888, 0xEEEE, 0xECC8, + 0xC880, 0xFEEC, 0xFEC8, 0xEC80, + 0xC800, 0xFFEC, 0xFE80, 0xE800, + 0xFFE8, 0xFF00, 0xFFF0, 0xF000, + 0xF710, 0x008E, 0x7100, 0x08CE, + 0x008C, 0x7310, 0x3100, 0x8CCE, + 0x088C, 0x3110, 0x6666, 0x366C, + 0x17E8, 0x0FF0, 0x718E, 0x399C +}; + +static const uint candidateFixUpIndex1D[32] = +{ + 15,15,15,15, + 15,15,15,15, + 15,15,15,15, + 15,15,15,15, + 15, 2, 8, 2, + 2, 8, 8,15, + 2, 8, 2, 2, + 8, 8, 2, 2 +}; + +//0, 9, 18, 27, 37, 46, 55, 64 +static const uint aStep1[64] = {0,0,0,0,0,1,1,1, + 1,1,1,1,1,1,2,2, + 2,2,2,2,2,2,2,3, + 3,3,3,3,3,3,3,3, + 3,4,4,4,4,4,4,4, + 4,4,5,5,5,5,5,5, + 5,5,5,6,6,6,6,6, + 6,6,6,6,7,7,7,7}; + +//0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64 +static const uint aStep2[64] = { 0, 0, 0, 1, 1, 1, 1, 2, + 2, 2, 2, 2, 3, 3, 3, 3, + 4, 4, 4, 4, 5, 5, 5, 5, + 6, 6, 6, 6, 6, 7, 7, 7, + 7, 8, 8, 8, 8, 9, 9, 9, + 9,10,10,10,10,10,11,11, + 11,11,12,12,12,12,13,13, + 13,13,14,14,14,14,15,15}; + +static const float3 RGB2LUM = float3(0.2126f, 0.7152f, 0.0722f); + +#define THREAD_GROUP_SIZE 64 +#define BLOCK_SIZE_Y 4 +#define BLOCK_SIZE_X 4 +#define BLOCK_SIZE (BLOCK_SIZE_Y * BLOCK_SIZE_X) + + +//Forward declaration +uint3 float2half( float3 pixel_f ); +int3 start_quantize( uint3 pixel_h ); +void quantize( inout int2x3 endPoint, uint prec ); +void finish_quantize_0( inout int bBadQuantize, inout int2x3 endPoint, uint4 prec, bool transformed ); +void finish_quantize_1( inout int bBadQuantize, inout int2x3 endPoint, uint4 prec, bool transformed ); +void finish_quantize( out bool bBadQuantize, inout int2x3 endPoint, uint4 prec, bool transformed ); + +void start_unquantize( inout int2x3 endPoint[2], uint4 prec, bool transformed ); +void start_unquantize( inout int2x3 endPoint, uint4 prec, bool transformed ); +void unquantize( inout int2x3 color, uint prec ); +uint3 finish_unquantize( int3 color ); +void generate_palette_unquantized8( out uint3 palette, int3 low, int3 high, int i ); +void generate_palette_unquantized16( out uint3 palette, int3 low, int3 high, int i ); +float3 half2float(uint3 color_h ); + +void block_package( inout uint4 block, int2x3 endPoint[2], uint mode_type, uint partition_index ); +void block_package( inout uint4 block, int2x3 endPoint, uint mode_type ); + +void swap(inout int3 lhs, inout int3 rhs) +{ + int3 tmp = lhs; + lhs = rhs; + rhs = tmp; +} + +Texture2D g_Input : register( t0 ); +StructuredBuffer g_InBuff : register( t1 ); + +RWStructuredBuffer g_OutBuff : register( u0 ); + +struct SharedData +{ + float3 pixel; + int3 pixel_ph; + float3 pixel_hr; + float pixel_lum; + float error; + uint best_mode; + uint best_partition; + int3 endPoint_low; + int3 endPoint_high; + float endPoint_lum_low; + float endPoint_lum_high; +}; + +groupshared SharedData shared_temp[THREAD_GROUP_SIZE]; + +[numthreads( THREAD_GROUP_SIZE, 1, 1 )] +void TryModeG10CS( uint GI : SV_GroupIndex, uint3 groupID : SV_GroupID ) +{ + const uint MAX_USED_THREAD = 16; + uint BLOCK_IN_GROUP = THREAD_GROUP_SIZE / MAX_USED_THREAD; + uint blockInGroup = GI / MAX_USED_THREAD; + uint blockID = g_start_block_id + groupID.x * BLOCK_IN_GROUP + blockInGroup; + uint threadBase = blockInGroup * MAX_USED_THREAD; + uint threadInBlock = GI - threadBase; + +#ifndef REF_DEVICE + if (blockID >= g_num_total_blocks) + { + return; + } +#endif + + uint block_y = blockID / g_num_block_x; + uint block_x = blockID - block_y * g_num_block_x; + uint base_x = block_x * BLOCK_SIZE_X; + uint base_y = block_y * BLOCK_SIZE_Y; + + if (threadInBlock < 16) + { + shared_temp[GI].pixel = g_Input.Load( uint3( base_x + threadInBlock % 4, base_y + threadInBlock / 4, 0 ) ).rgb; + uint3 pixel_h = float2half( shared_temp[GI].pixel ); + shared_temp[GI].pixel_hr = half2float(pixel_h); + shared_temp[GI].pixel_lum = dot(shared_temp[GI].pixel_hr, RGB2LUM); + shared_temp[GI].pixel_ph = start_quantize( pixel_h ); + + shared_temp[GI].endPoint_low = shared_temp[GI].pixel_ph; + shared_temp[GI].endPoint_high = shared_temp[GI].pixel_ph; + shared_temp[GI].endPoint_lum_low = shared_temp[GI].pixel_lum; + shared_temp[GI].endPoint_lum_high = shared_temp[GI].pixel_lum; + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + if (threadInBlock < 8) + { + if (shared_temp[GI].endPoint_lum_low > shared_temp[GI + 8].endPoint_lum_low) + { + shared_temp[GI].endPoint_low = shared_temp[GI + 8].endPoint_low; + shared_temp[GI].endPoint_lum_low = shared_temp[GI + 8].endPoint_lum_low; + } + if (shared_temp[GI].endPoint_lum_high < shared_temp[GI + 8].endPoint_lum_high) + { + shared_temp[GI].endPoint_high = shared_temp[GI + 8].endPoint_high; + shared_temp[GI].endPoint_lum_high = shared_temp[GI + 8].endPoint_lum_high; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 4) + { + if (shared_temp[GI].endPoint_lum_low > shared_temp[GI + 4].endPoint_lum_low) + { + shared_temp[GI].endPoint_low = shared_temp[GI + 4].endPoint_low; + shared_temp[GI].endPoint_lum_low = shared_temp[GI + 4].endPoint_lum_low; + } + if (shared_temp[GI].endPoint_lum_high < shared_temp[GI + 4].endPoint_lum_high) + { + shared_temp[GI].endPoint_high = shared_temp[GI + 4].endPoint_high; + shared_temp[GI].endPoint_lum_high = shared_temp[GI + 4].endPoint_lum_high; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 2) + { + if (shared_temp[GI].endPoint_lum_low > shared_temp[GI + 2].endPoint_lum_low) + { + shared_temp[GI].endPoint_low = shared_temp[GI + 2].endPoint_low; + shared_temp[GI].endPoint_lum_low = shared_temp[GI + 2].endPoint_lum_low; + } + if (shared_temp[GI].endPoint_lum_high < shared_temp[GI + 2].endPoint_lum_high) + { + shared_temp[GI].endPoint_high = shared_temp[GI + 2].endPoint_high; + shared_temp[GI].endPoint_lum_high = shared_temp[GI + 2].endPoint_lum_high; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 1) + { + if (shared_temp[GI].endPoint_lum_low > shared_temp[GI + 1].endPoint_lum_low) + { + shared_temp[GI].endPoint_low = shared_temp[GI + 1].endPoint_low; + shared_temp[GI].endPoint_lum_low = shared_temp[GI + 1].endPoint_lum_low; + } + if (shared_temp[GI].endPoint_lum_high < shared_temp[GI + 1].endPoint_lum_high) + { + shared_temp[GI].endPoint_high = shared_temp[GI + 1].endPoint_high; + shared_temp[GI].endPoint_lum_high = shared_temp[GI + 1].endPoint_lum_high; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + //ergod mode_type 11:14 + if ( threadInBlock == 0 ) + { + int2x3 endPoint; + // find_axis + endPoint[0] = shared_temp[threadBase + 0].endPoint_low; + endPoint[1] = shared_temp[threadBase + 0].endPoint_high; + + //compute_index + float3 span = endPoint[1] - endPoint[0];// fixed a bug in v0.2 + float span_norm_sqr = dot( span, span );// fixed a bug in v0.2 + float dotProduct = dot( span, shared_temp[threadBase + 0].pixel_ph - endPoint[0] );// fixed a bug in v0.2 + if ( span_norm_sqr > 0 && dotProduct >= 0 && uint( dotProduct * 63.49999 / span_norm_sqr ) > 32 ) + { + swap(endPoint[0], endPoint[1]); + + shared_temp[GI].endPoint_low = endPoint[0]; + shared_temp[GI].endPoint_high = endPoint[1]; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + if (threadInBlock < 4) + { + int2x3 endPoint; + endPoint[0] = shared_temp[threadBase + 0].endPoint_low; + endPoint[1] = shared_temp[threadBase + 0].endPoint_high; + + float3 span = endPoint[1] - endPoint[0]; + float span_norm_sqr = dot( span, span ); + + uint4 prec = candidateModePrec[threadInBlock + 10]; + int2x3 endPoint_q = endPoint; + quantize( endPoint_q, prec.x ); + + bool transformed = candidateModeTransformed[threadInBlock + 10]; + if (transformed) + { + endPoint_q[1] -= endPoint_q[0]; + } + + bool bBadQuantize; + finish_quantize( bBadQuantize, endPoint_q, prec, transformed ); + + start_unquantize( endPoint_q, prec, transformed ); + + unquantize( endPoint_q, prec.x ); + + float error = 0; + [loop]for ( uint j = 0; j < 16; j ++ ) + { + float dotProduct = dot( span, shared_temp[threadBase + j].pixel_ph - endPoint[0] );// fixed a bug in v0.2 + uint index = ( span_norm_sqr <= 0 || dotProduct <= 0 ) ? 0 + : ( ( dotProduct < span_norm_sqr ) ? aStep2[ uint( dotProduct * 63.49999 / span_norm_sqr ) ] : aStep2[63] ); + + uint3 pixel_rh; + generate_palette_unquantized16( pixel_rh, endPoint_q[0], endPoint_q[1], index ); + float3 pixel_r = half2float( pixel_rh ); + pixel_r -= shared_temp[threadBase + j].pixel_hr; + error += dot(pixel_r, pixel_r); + } + if ( bBadQuantize ) + error = 1e20f; + + shared_temp[GI].error = error; + shared_temp[GI].best_mode = candidateModeFlag[threadInBlock + 10]; + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + if (threadInBlock < 2) + { + if ( shared_temp[GI].error > shared_temp[GI + 2].error ) + { + shared_temp[GI].error = shared_temp[GI + 2].error; + shared_temp[GI].best_mode = shared_temp[GI + 2].best_mode; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 1) + { + if ( shared_temp[GI].error > shared_temp[GI + 1].error ) + { + shared_temp[GI].error = shared_temp[GI + 1].error; + shared_temp[GI].best_mode = shared_temp[GI + 1].best_mode; + } + + g_OutBuff[blockID] = uint4(asuint(shared_temp[GI].error), shared_temp[GI].best_mode, 0, 0); + } +} + +[numthreads( THREAD_GROUP_SIZE, 1, 1 )] +void TryModeLE10CS( uint GI : SV_GroupIndex, uint3 groupID : SV_GroupID ) +{ + const uint MAX_USED_THREAD = 32; + uint BLOCK_IN_GROUP = THREAD_GROUP_SIZE / MAX_USED_THREAD; + uint blockInGroup = GI / MAX_USED_THREAD; + uint blockID = g_start_block_id + groupID.x * BLOCK_IN_GROUP + blockInGroup; + uint threadBase = blockInGroup * MAX_USED_THREAD; + uint threadInBlock = GI - threadBase; + +#ifndef REF_DEVICE + if (blockID >= g_num_total_blocks) + { + return; + } + + if (asfloat(g_InBuff[blockID].x) < 1e-6f) + { + g_OutBuff[blockID] = g_InBuff[blockID]; + return; + } +#endif + + uint block_y = blockID / g_num_block_x; + uint block_x = blockID - block_y * g_num_block_x; + uint base_x = block_x * BLOCK_SIZE_X; + uint base_y = block_y * BLOCK_SIZE_Y; + + if (threadInBlock < 16) + { + shared_temp[GI].pixel = g_Input.Load( uint3( base_x + threadInBlock % 4, base_y + threadInBlock / 4, 0 ) ).rgb; + uint3 pixel_h = float2half( shared_temp[GI].pixel ); + shared_temp[GI].pixel_hr = half2float(pixel_h); + shared_temp[GI].pixel_lum = dot(shared_temp[GI].pixel_hr, RGB2LUM); + shared_temp[GI].pixel_ph = start_quantize( pixel_h ); + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + //ergod mode_type 1:10 + if (threadInBlock < 32) + { + // find_axis + int2x3 endPoint[2]; + endPoint[0][0] = MAX_INT; + endPoint[0][1] = MIN_INT; + endPoint[1][0] = MAX_INT; + endPoint[1][1] = MIN_INT; + + float2 endPoint_lum[2]; + endPoint_lum[0][0] = MAX_FLOAT; + endPoint_lum[0][1] = MIN_FLOAT; + endPoint_lum[1][0] = MAX_FLOAT; + endPoint_lum[1][1] = MIN_FLOAT; + + uint bit = candidateSectionBit[threadInBlock]; + for ( uint i = 0; i < 16; i ++ ) + { + int3 pixel_ph = shared_temp[threadBase + i].pixel_ph; + float pixel_lum = shared_temp[threadBase + i].pixel_lum; + if ( (bit >> i) & 1 ) //It gets error when using "candidateSection" as "endPoint_ph" index + { + if (endPoint_lum[1][0] > pixel_lum) + { + endPoint[1][0] = pixel_ph; + endPoint_lum[1][0] = pixel_lum; + } + if (endPoint_lum[1][1] < pixel_lum) + { + endPoint[1][1] = pixel_ph; + endPoint_lum[1][1] = pixel_lum; + } + } + else + { + if (endPoint_lum[0][0] > pixel_lum) + { + endPoint[0][0] = pixel_ph; + endPoint_lum[0][0] = pixel_lum; + } + if (endPoint_lum[0][1] < pixel_lum) + { + endPoint[0][1] = pixel_ph; + endPoint_lum[0][1] = pixel_lum; + } + } + } + + //compute_index + float3 span[2];// fixed a bug in v0.2 + float span_norm_sqr[2];// fixed a bug in v0.2 + [unroll] + for (uint p = 0; p < 2; ++ p) + { + span[p] = endPoint[p][1] - endPoint[p][0]; + span_norm_sqr[p] = dot( span[p], span[p] ); + + float dotProduct = dot( span[p], shared_temp[threadBase + (0 == p ? 0 : candidateFixUpIndex1D[threadInBlock])].pixel_ph - endPoint[p][0] );// fixed a bug in v0.2 + if ( span_norm_sqr[p] > 0 && dotProduct >= 0 && uint( dotProduct * 63.49999 / span_norm_sqr[p] ) > 32 ) + { + span[p] = -span[p]; + swap(endPoint[p][0], endPoint[p][1]); + } + } + + uint4 prec = candidateModePrec[g_mode_id]; + int2x3 endPoint_q[2] = endPoint; + quantize( endPoint_q[0], prec.x ); + quantize( endPoint_q[1], prec.x ); + + bool transformed = candidateModeTransformed[g_mode_id]; + if (transformed) + { + endPoint_q[0][1] -= endPoint_q[0][0]; + endPoint_q[1][0] -= endPoint_q[0][0]; + endPoint_q[1][1] -= endPoint_q[0][0]; + } + + int bBadQuantize = 0; + finish_quantize_0( bBadQuantize, endPoint_q[0], prec, transformed ); + finish_quantize_1( bBadQuantize, endPoint_q[1], prec, transformed ); + + start_unquantize( endPoint_q, prec, transformed ); + + unquantize( endPoint_q[0], prec.x ); + unquantize( endPoint_q[1], prec.x ); + + float error = 0; + for ( uint j = 0; j < 16; j ++ ) + { + uint3 pixel_rh; + if ((bit >> j) & 1) + { + float dotProduct = dot( span[1], shared_temp[threadBase + j].pixel_ph - endPoint[1][0] );// fixed a bug in v0.2 + uint index = ( span_norm_sqr[1] <= 0 || dotProduct <= 0 ) ? 0 + : ( ( dotProduct < span_norm_sqr[1] ) ? aStep1[ uint( dotProduct * 63.49999 / span_norm_sqr[1] ) ] : aStep1[63] ); + generate_palette_unquantized8( pixel_rh, endPoint_q[1][0], endPoint_q[1][1], index ); + } + else + { + float dotProduct = dot( span[0], shared_temp[threadBase + j].pixel_ph - endPoint[0][0] );// fixed a bug in v0.2 + uint index = ( span_norm_sqr[0] <= 0 || dotProduct <= 0 ) ? 0 + : ( ( dotProduct < span_norm_sqr[0] ) ? aStep1[ uint( dotProduct * 63.49999 / span_norm_sqr[0] ) ] : aStep1[63] ); + generate_palette_unquantized8( pixel_rh, endPoint_q[0][0], endPoint_q[0][1], index ); + } + + float3 pixel_r = half2float( pixel_rh ); + pixel_r -= shared_temp[threadBase + j].pixel_hr; + error += dot(pixel_r, pixel_r); + } + if ( bBadQuantize ) + error = 1e20f; + + shared_temp[GI].error = error; + shared_temp[GI].best_mode = candidateModeFlag[g_mode_id]; + shared_temp[GI].best_partition = threadInBlock; + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + if (threadInBlock < 16) + { + if ( shared_temp[GI].error > shared_temp[GI + 16].error ) + { + shared_temp[GI].error = shared_temp[GI + 16].error; + shared_temp[GI].best_mode = shared_temp[GI + 16].best_mode; + shared_temp[GI].best_partition = shared_temp[GI + 16].best_partition; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 8) + { + if ( shared_temp[GI].error > shared_temp[GI + 8].error ) + { + shared_temp[GI].error = shared_temp[GI + 8].error; + shared_temp[GI].best_mode = shared_temp[GI + 8].best_mode; + shared_temp[GI].best_partition = shared_temp[GI + 8].best_partition; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 4) + { + if ( shared_temp[GI].error > shared_temp[GI + 4].error ) + { + shared_temp[GI].error = shared_temp[GI + 4].error; + shared_temp[GI].best_mode = shared_temp[GI + 4].best_mode; + shared_temp[GI].best_partition = shared_temp[GI + 4].best_partition; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 2) + { + if ( shared_temp[GI].error > shared_temp[GI + 2].error ) + { + shared_temp[GI].error = shared_temp[GI + 2].error; + shared_temp[GI].best_mode = shared_temp[GI + 2].best_mode; + shared_temp[GI].best_partition = shared_temp[GI + 2].best_partition; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 1) + { + if ( shared_temp[GI].error > shared_temp[GI + 1].error ) + { + shared_temp[GI].error = shared_temp[GI + 1].error; + shared_temp[GI].best_mode = shared_temp[GI + 1].best_mode; + shared_temp[GI].best_partition = shared_temp[GI + 1].best_partition; + } + + if (asfloat(g_InBuff[blockID].x) > shared_temp[GI].error) + { + g_OutBuff[blockID] = uint4(asuint(shared_temp[GI].error), shared_temp[GI].best_mode, shared_temp[GI].best_partition, 0); + } + else + { + g_OutBuff[blockID] = g_InBuff[blockID]; + } + } +} + +[numthreads( THREAD_GROUP_SIZE, 1, 1 )] +void EncodeBlockCS(uint GI : SV_GroupIndex, uint3 groupID : SV_GroupID) +{ + const uint MAX_USED_THREAD = 32; + uint BLOCK_IN_GROUP = THREAD_GROUP_SIZE / MAX_USED_THREAD; + uint blockInGroup = GI / MAX_USED_THREAD; + uint blockID = g_start_block_id + groupID.x * BLOCK_IN_GROUP + blockInGroup; + uint threadBase = blockInGroup * MAX_USED_THREAD; + uint threadInBlock = GI - threadBase; + +#ifndef REF_DEVICE + if (blockID >= g_num_total_blocks) + { + return; + } +#endif + + uint block_y = blockID / g_num_block_x; + uint block_x = blockID - block_y * g_num_block_x; + uint base_x = block_x * BLOCK_SIZE_X; + uint base_y = block_y * BLOCK_SIZE_Y; + + if (threadInBlock < 16) + { + shared_temp[GI].pixel = g_Input.Load( uint3( base_x + threadInBlock % 4, base_y + threadInBlock / 4, 0 ) ).rgb; + shared_temp[GI].pixel_lum = dot(shared_temp[GI].pixel, RGB2LUM); + uint3 pixel_h = float2half( shared_temp[GI].pixel ); + shared_temp[GI].pixel_ph = start_quantize( pixel_h ); + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + uint best_mode = g_InBuff[blockID].y; + uint best_partition = g_InBuff[blockID].z; + + uint4 block = 0; + + if (threadInBlock < 32) + { + int2x3 endPoint; + endPoint[0] = MAX_INT; + endPoint[1] = MIN_INT; + + float2 endPoint_lum; + endPoint_lum[0] = MAX_FLOAT; + endPoint_lum[1] = MIN_FLOAT; + + int2 endPoint_lum_index; + endPoint_lum_index[0] = -1; + endPoint_lum_index[1] = -1; + + int3 pixel_ph = shared_temp[threadBase + (threadInBlock & 0xF)].pixel_ph; + float pixel_lum = shared_temp[threadBase + (threadInBlock & 0xF)].pixel_lum; + if (threadInBlock < 16) + { + if (best_mode > 10) + { + endPoint[0] = endPoint[1] = pixel_ph; + endPoint_lum[0] = endPoint_lum[1] = pixel_lum; + } + else + { + uint bits = candidateSectionBit[best_partition]; + if (0 == ((bits >> threadInBlock) & 1)) + { + endPoint[0] = endPoint[1] = pixel_ph; + endPoint_lum[0] = endPoint_lum[1] = pixel_lum; + } + } + } + else + { + if (best_mode <= 10) + { + uint bits = candidateSectionBit[best_partition]; + if (1 == ((bits >> (threadInBlock & 0xF)) & 1)) + { + endPoint[0] = endPoint[1] = pixel_ph; + endPoint_lum[0] = endPoint_lum[1] = pixel_lum; + } + } + } + + shared_temp[GI].endPoint_low = endPoint[0]; + shared_temp[GI].endPoint_high = endPoint[1]; + + shared_temp[GI].endPoint_lum_low = endPoint_lum[0]; + shared_temp[GI].endPoint_lum_high = endPoint_lum[1]; + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if ((threadInBlock & 0xF) < 8) + { + if (shared_temp[GI].endPoint_lum_low > shared_temp[GI + 8].endPoint_lum_low) + { + shared_temp[GI].endPoint_low = shared_temp[GI + 8].endPoint_low; + shared_temp[GI].endPoint_lum_low = shared_temp[GI + 8].endPoint_lum_low; + } + if (shared_temp[GI].endPoint_lum_high < shared_temp[GI + 8].endPoint_lum_high) + { + shared_temp[GI].endPoint_high = shared_temp[GI + 8].endPoint_high; + shared_temp[GI].endPoint_lum_high = shared_temp[GI + 8].endPoint_lum_high; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if ((threadInBlock & 0xF) < 4) + { + if (shared_temp[GI].endPoint_lum_low > shared_temp[GI + 4].endPoint_lum_low) + { + shared_temp[GI].endPoint_low = shared_temp[GI + 4].endPoint_low; + shared_temp[GI].endPoint_lum_low = shared_temp[GI + 4].endPoint_lum_low; + } + if (shared_temp[GI].endPoint_lum_high < shared_temp[GI + 4].endPoint_lum_high) + { + shared_temp[GI].endPoint_high = shared_temp[GI + 4].endPoint_high; + shared_temp[GI].endPoint_lum_high = shared_temp[GI + 4].endPoint_lum_high; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if ((threadInBlock & 0xF) < 2) + { + if (shared_temp[GI].endPoint_lum_low > shared_temp[GI + 2].endPoint_lum_low) + { + shared_temp[GI].endPoint_low = shared_temp[GI + 2].endPoint_low; + shared_temp[GI].endPoint_lum_low = shared_temp[GI + 2].endPoint_lum_low; + } + if (shared_temp[GI].endPoint_lum_high < shared_temp[GI + 2].endPoint_lum_high) + { + shared_temp[GI].endPoint_high = shared_temp[GI + 2].endPoint_high; + shared_temp[GI].endPoint_lum_high = shared_temp[GI + 2].endPoint_lum_high; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if ((threadInBlock & 0xF) < 1) + { + if (shared_temp[GI].endPoint_lum_low > shared_temp[GI + 1].endPoint_lum_low) + { + shared_temp[GI].endPoint_low = shared_temp[GI + 1].endPoint_low; + shared_temp[GI].endPoint_lum_low = shared_temp[GI + 1].endPoint_lum_low; + } + if (shared_temp[GI].endPoint_lum_high < shared_temp[GI + 1].endPoint_lum_high) + { + shared_temp[GI].endPoint_high = shared_temp[GI + 1].endPoint_high; + shared_temp[GI].endPoint_lum_high = shared_temp[GI + 1].endPoint_lum_high; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + if (threadInBlock < 2) + { + // find_axis + int2x3 endPoint; + endPoint[0] = shared_temp[threadBase + threadInBlock * 16].endPoint_low; + endPoint[1] = shared_temp[threadBase + threadInBlock * 16].endPoint_high; + + uint fixup = 0; + if ((1 == threadInBlock) && (best_mode <= 10)) + { + fixup = candidateFixUpIndex1D[best_partition]; + } + + float3 span = endPoint[1] - endPoint[0]; + float span_norm_sqr = dot( span, span ); + float dotProduct = dot( span, shared_temp[threadBase + fixup].pixel_ph - endPoint[0] ); + if ( span_norm_sqr > 0 && dotProduct >= 0 && uint( dotProduct * 63.49999 / span_norm_sqr ) > 32 ) + { + swap(endPoint[0], endPoint[1]); + } + + shared_temp[GI].endPoint_low = endPoint[0]; + shared_temp[GI].endPoint_high = endPoint[1]; + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + if (threadInBlock < 16) + { + uint bits; + if (best_mode > 10) + { + bits = 0; + } + else + { + bits = candidateSectionBit[best_partition]; + } + + float3 span; + float dotProduct; + if ((bits >> threadInBlock) & 1) + { + span = shared_temp[threadBase + 1].endPoint_high - shared_temp[threadBase + 1].endPoint_low; + dotProduct = dot( span, shared_temp[threadBase + threadInBlock].pixel_ph - shared_temp[threadBase + 1].endPoint_low ); + } + else + { + span = shared_temp[threadBase + 0].endPoint_high - shared_temp[threadBase + 0].endPoint_low; + dotProduct = dot( span, shared_temp[threadBase + threadInBlock].pixel_ph - shared_temp[threadBase + 0].endPoint_low ); + } + float span_norm_sqr = dot( span, span ); + + if (best_mode > 10) + { + uint index = ( span_norm_sqr <= 0 || dotProduct <= 0 ) ? 0 + : ( ( dotProduct < span_norm_sqr ) ? aStep2[ uint( dotProduct * 63.49999 / span_norm_sqr ) ] : aStep2[63] ); + if (threadInBlock == 0) + { + block.z |= index << 1; + } + else if (threadInBlock < 8) + { + block.z |= index << (threadInBlock * 4); + } + else + { + block.w |= index << ((threadInBlock - 8) * 4); + } + } + else + { + uint index = ( span_norm_sqr <= 0 || dotProduct <= 0 ) ? 0 + : ( ( dotProduct < span_norm_sqr ) ? aStep1[ uint( dotProduct * 63.49999 / span_norm_sqr ) ] : aStep1[63] ); + + uint fixup = candidateFixUpIndex1D[best_partition]; + int2 offset = int2((fixup != 2), (fixup == 15)); + + if (threadInBlock == 0) + { + block.z |= index << 18; + } + else if (threadInBlock < 3) + { + block.z |= index << (20 + (threadInBlock - 1) * 3); + } + else if (threadInBlock < 5) + { + block.z |= index << (25 + (threadInBlock - 3) * 3 + offset.x); + } + else if (threadInBlock == 5) + { + block.w |= index >> !offset.x; + if (!offset.x) + { + block.z |= index << 31; + } + } + else if (threadInBlock < 9) + { + block.w |= index << (2 + (threadInBlock - 6) * 3 + offset.x); + } + else + { + block.w |= index << (11 + (threadInBlock - 9) * 3 + offset.y); + } + } + + shared_temp[GI].pixel_hr.xy = asfloat(block.zw); + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 8) + { + shared_temp[GI].pixel_hr.xy = asfloat(asuint(shared_temp[GI].pixel_hr.xy) | asuint(shared_temp[GI + 8].pixel_hr.xy)); + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 4) + { + shared_temp[GI].pixel_hr.xy = asfloat(asuint(shared_temp[GI].pixel_hr.xy) | asuint(shared_temp[GI + 4].pixel_hr.xy)); + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 2) + { + shared_temp[GI].pixel_hr.xy = asfloat(asuint(shared_temp[GI].pixel_hr.xy) | asuint(shared_temp[GI + 2].pixel_hr.xy)); + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 1) + { + shared_temp[GI].pixel_hr.xy = asfloat(asuint(shared_temp[GI].pixel_hr.xy) | asuint(shared_temp[GI + 1].pixel_hr.xy)); + + block.zw = asuint(shared_temp[GI].pixel_hr.xy); + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + bool transformed = candidateModeTransformed[best_mode - 1]; + uint4 prec = candidateModePrec[best_mode - 1]; + if (threadInBlock == 2) + { + int2x3 endPoint_q; + endPoint_q[0] = shared_temp[threadBase + 0].endPoint_low; + endPoint_q[1] = shared_temp[threadBase + 0].endPoint_high; + + quantize( endPoint_q, prec.x ); + if (transformed) + { + endPoint_q[1] -= endPoint_q[0]; + } + + shared_temp[GI].endPoint_low = endPoint_q[0]; + shared_temp[GI].endPoint_high = endPoint_q[1]; + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock == 3) + { + int3 ep0 = shared_temp[threadBase + 2].endPoint_low; + int2x3 endPoint_q; + endPoint_q[0] = shared_temp[threadBase + 1].endPoint_low; + endPoint_q[1] = shared_temp[threadBase + 1].endPoint_high; + + if (best_mode <= 10) + { + quantize( endPoint_q, prec.x ); + if (transformed) + { + endPoint_q[0] -= ep0; + endPoint_q[1] -= ep0; + } + + shared_temp[GI].endPoint_low = endPoint_q[0]; + shared_temp[GI].endPoint_high = endPoint_q[1]; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + if (threadInBlock < 2) + { + int2x3 endPoint_q; + endPoint_q[0] = shared_temp[threadBase + threadInBlock + 2].endPoint_low; + endPoint_q[1] = shared_temp[threadBase + threadInBlock + 2].endPoint_high; + + int bBadQuantize = 0; + if (threadInBlock == 0) + { + if (best_mode > 10) + { + finish_quantize( bBadQuantize, endPoint_q, prec, transformed ); + } + else + { + finish_quantize_0( bBadQuantize, endPoint_q, prec, transformed ); + } + } + else // if (threadInBlock == 1) + { + if (best_mode <= 10) + { + finish_quantize_1( bBadQuantize, endPoint_q, prec, transformed ); + } + } + + shared_temp[GI].endPoint_low = endPoint_q[0]; + shared_temp[GI].endPoint_high = endPoint_q[1]; + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + if ( threadInBlock == 0 ) + { + int2x3 endPoint_q[2]; + endPoint_q[0][0] = shared_temp[threadBase + 0].endPoint_low; + endPoint_q[0][1] = shared_temp[threadBase + 0].endPoint_high; + endPoint_q[1][0] = shared_temp[threadBase + 1].endPoint_low; + endPoint_q[1][1] = shared_temp[threadBase + 1].endPoint_high; + + if ( best_mode > 10 ) + { + block_package( block, endPoint_q[0], best_mode ); + } + else + { + block_package( block, endPoint_q, best_mode, best_partition ); + } + + g_OutBuff[blockID] = block; + } +} + +uint float2half1( float f ) +{ + uint Result; + + uint IValue = asuint(f); + uint Sign = (IValue & 0x80000000U) >> 16U; + IValue = IValue & 0x7FFFFFFFU; + + if (IValue > 0x47FFEFFFU) + { + // The number is too large to be represented as a half. Saturate to infinity. + Result = 0x7FFFU; + } + else + { + if (IValue < 0x38800000U) + { + // The number is too small to be represented as a normalized half. + // Convert it to a denormalized value. + uint Shift = 113U - (IValue >> 23U); + IValue = (0x800000U | (IValue & 0x7FFFFFU)) >> Shift; + } + else + { + // Rebias the exponent to represent the value as a normalized half. + IValue += 0xC8000000U; + } + + Result = ((IValue + 0x0FFFU + ((IValue >> 13U) & 1U)) >> 13U)&0x7FFFU; + } + return (Result|Sign); +} + +uint3 float2half( float3 endPoint_f ) +{ + //uint3 sign = asuint(endPoint_f) & 0x80000000; + //uint3 expo = asuint(endPoint_f) & 0x7F800000; + //uint3 base = asuint(endPoint_f) & 0x007FFFFF; + //return ( expo < 0x33800000 ) ? 0 + // //0x33800000 indicating 2^-24, which is minimal denormalized number that half can present + // : ( ( expo < 0x38800000 ) ? ( sign >> 16 ) | ( ( base + 0x00800000 ) >> ( 23 - ( ( expo - 0x33800000 ) >> 23 ) ) )//fixed a bug in v0.2 + // //0x38800000 indicating 2^-14, which is minimal normalized number that half can present, so need to use denormalized half presentation + // : ( ( expo == 0x7F800000 || expo > 0x47000000 ) ? ( ( sign >> 16 ) | 0x7bff ) + // // treat NaN as INF, treat INF (including NaN) as the maximum/minimum number that half can present + // // 0x47000000 indicating 2^15, which is maximum exponent that half can present, so cut to 0x7bff which is the maximum half number + // : ( ( sign >> 16 ) | ( ( ( expo - 0x38000000 ) | base ) >> 13 ) ) ) ); + + + return uint3( float2half1( endPoint_f.x ), float2half1( endPoint_f.y ), float2half1( endPoint_f.z ) ); +} +int3 start_quantize( uint3 pixel_h ) +{ + if ( g_format == UNSIGNED_F16 ) + { + return asint( ( pixel_h << 6 ) / 31 ); + } + else + { + return ( pixel_h < 0x8000 ) ? ( ( pixel_h == 0x7bff ) ? 0x7fff : asint( ( pixel_h << 5 ) / 31 ) )// fixed a bug in v0.2 + : ( ( pixel_h == 0x7bff ) ? 0xffff8001 : -asint( ( ( 0x00007fff & pixel_h ) << 5 ) / 31 ) );// fixed a bug in v0.2 + } +} +void quantize( inout int2x3 endPoint, uint prec ) +{ + int iprec = asint( prec ); + if ( g_format == UNSIGNED_F16 ) + { + endPoint = ( ( iprec >= 15 ) | ( endPoint == 0 ) ) ? endPoint + : ( ( endPoint == asint(0xFFFF) ) ? ( ( 1 << iprec ) - 1 ) + : ( ( ( endPoint << iprec ) + asint(0x0000) ) >> 16 ) ); + } + else + { + endPoint = ( ( iprec >= 16 ) | ( endPoint == 0 ) ) ? endPoint + : ( ( endPoint >= 0 ) ? ( ( endPoint == asint(0x7FFF) ) ? ( ( 1 << ( iprec - 1 ) ) - 1 ) : ( ( ( endPoint << ( iprec - 1 ) ) + asint(0x0000) ) >> 15 ) ) + : ( ( -endPoint == asint(0x7FFF) ) ? -( ( 1 << ( iprec - 1 ) ) - 1 ) : -( ( ( -endPoint << ( iprec - 1 ) ) + asint(0x0000) ) >> 15 ) ) ); + } +} +void finish_quantize_0( inout int bBadQuantize, inout int2x3 endPoint, uint4 prec, bool transformed ) +{ + if ( transformed ) + { + bool3 bBadComponent = ( endPoint[1] >= 0 ) ? ( endPoint[1] >= ( 1 << ( prec.yzw - 1 ) ) ) + : ( -endPoint[1] > ( 1 << ( prec.yzw - 1 ) ) ); + bBadQuantize |= any(bBadComponent); + + endPoint[0] = endPoint[0] & ( ( 1 << prec.x ) - 1 ); + endPoint[1] = ( endPoint[1] >= 0 ) ? ( ( endPoint[1] >= ( 1 << ( prec.yzw - 1 ) ) ) ? ( ( 1 << ( prec.yzw - 1 ) ) - 1 ) : endPoint[1] ) + : ( ( -endPoint[1] > ( 1 << ( prec.yzw - 1 ) ) ) ? ( 1 << ( prec.yzw - 1 ) ) : ( endPoint[1] & ( ( 1 << prec.yzw ) - 1 ) ) ); + } + else + { + endPoint &= ( ( 1 << prec.x ) - 1 ); + } +} +void finish_quantize_1( inout int bBadQuantize, inout int2x3 endPoint, uint4 prec, bool transformed ) +{ + if ( transformed ) + { + bool2x3 bBadComponent; + bBadComponent[0] = ( endPoint[0] >= 0 ) ? ( endPoint[0] >= ( 1 << ( prec.yzw - 1 ) ) ) + : ( -endPoint[0] > ( 1 << ( prec.yzw - 1 ) ) ); + bBadComponent[1] = ( endPoint[1] >= 0 ) ? ( endPoint[1] >= ( 1 << ( prec.yzw - 1 ) ) ) + : ( -endPoint[1] > ( 1 << ( prec.yzw - 1 ) ) ); + bBadQuantize |= any(bBadComponent); + + endPoint[0] = ( endPoint[0] >= 0 ) ? ( ( endPoint[0] >= ( 1 << ( prec.yzw - 1 ) ) ) ? ( ( 1 << ( prec.yzw - 1 ) ) - 1 ) : endPoint[0] ) + : ( ( -endPoint[0] > ( 1 << ( prec.yzw - 1 ) ) ) ? ( 1 << ( prec.yzw - 1 ) ) : ( endPoint[0] & ( ( 1 << prec.yzw ) - 1 ) ) ); + endPoint[1] = ( endPoint[1] >= 0 ) ? ( ( endPoint[1] >= ( 1 << ( prec.yzw - 1 ) ) ) ? ( ( 1 << ( prec.yzw - 1 ) ) - 1 ) : endPoint[1] ) + : ( ( -endPoint[1] > ( 1 << ( prec.yzw - 1 ) ) ) ? ( 1 << ( prec.yzw - 1 ) ) : ( endPoint[1] & ( ( 1 << prec.yzw ) - 1 ) ) ); + } + else + { + endPoint &= ( ( 1 << prec.x ) - 1 ); + } +} +void finish_quantize( out bool bBadQuantize, inout int2x3 endPoint, uint4 prec, bool transformed ) +{ + if ( transformed ) + { + bool3 bBadComponent; + bBadComponent = ( endPoint[1] >= 0 ) ? ( endPoint[1] >= ( 1 << ( prec.yzw - 1 ) ) ) + : ( -endPoint[1] > ( 1 << ( prec.yzw - 1 ) ) ); + bBadQuantize = any( bBadComponent ); + + endPoint[0] = endPoint[0] & ( ( 1 << prec.x ) - 1 ); + endPoint[1] = ( endPoint[1] >= 0 ) ? ( ( endPoint[1] >= ( 1 << ( prec.yzw - 1 ) ) ) ? ( ( 1 << ( prec.yzw - 1 ) ) - 1 ) : endPoint[1] ) + : ( ( -endPoint[1] > ( 1 << ( prec.yzw - 1 ) ) ) ? ( 1 << ( prec.yzw - 1 ) ) : ( endPoint[1] & ( ( 1 << prec.yzw ) - 1 ) ) ); + } + else + { + endPoint &= ( ( 1 << prec.x ) - 1 ); + + bBadQuantize = 0; + } +} + +void SIGN_EXTEND( uint3 prec, inout int3 color ) +{ + uint3 p = 1 << (prec - 1); + color = (color & p) ? (color & (p - 1)) - p : color; +} + +void sign_extend( bool transformed, uint4 prec, inout int2x3 endPoint ) +{ + if ( g_format == SIGNED_F16 ) + SIGN_EXTEND( prec.x, endPoint[0] ); + if ( g_format == SIGNED_F16 || transformed ) + SIGN_EXTEND( prec.yzw, endPoint[1] ); +} + +void sign_extend( bool transformed, uint4 prec, inout int2x3 endPoint[2] ) +{ + if ( g_format == SIGNED_F16 ) + SIGN_EXTEND( prec.x, endPoint[0][0] ); + if ( g_format == SIGNED_F16 || transformed ) + { + SIGN_EXTEND( prec.yzw, endPoint[0][1] ); + SIGN_EXTEND( prec.yzw, endPoint[1][0] ); + SIGN_EXTEND( prec.yzw, endPoint[1][1] ); + } +} +void start_unquantize( inout int2x3 endPoint[2], uint4 prec, bool transformed ) +{ + sign_extend( transformed, prec, endPoint ); + if ( transformed ) + { + endPoint[0][1] += endPoint[0][0]; + endPoint[1][0] += endPoint[0][0]; + endPoint[1][1] += endPoint[0][0]; + } +} +void start_unquantize( inout int2x3 endPoint, uint4 prec, bool transformed ) +{ + sign_extend( transformed, prec, endPoint ); + if ( transformed ) + endPoint[1] += endPoint[0]; +} +void unquantize( inout int2x3 color, uint prec ) +{ + int iprec = asint( prec ); + if (g_format == UNSIGNED_F16 ) + { + if (prec < 15) + { + color = (color != 0) ? (color == ((1 << iprec) - 1) ? 0xFFFF : (((color << 16) + 0x8000) >> iprec)) : color; + } + } + else + { + if (prec < 16) + { + uint2x3 s = color >= 0 ? 0 : 1; + color = abs(color); + color = (color != 0) ? (color >= ((1 << (iprec - 1)) - 1) ? 0x7FFF : (((color << 15) + 0x4000) >> (iprec - 1))) : color; + color = s > 0 ? -color : color; + } + } +} +uint3 finish_unquantize( int3 color ) +{ + if ( g_format == UNSIGNED_F16 ) + color = ( color * 31 ) >> 6; + else + { + color = ( color < 0 ) ? -( ( -color * 31 ) >> 5 ) : ( color * 31 ) >> 5; + color = ( color < 0 ) ? ( ( -color ) | 0x8000 ) : color; + } + return asuint(color); +} +void generate_palette_unquantized8( out uint3 palette, int3 low, int3 high, int i ) +{ + static const int aWeight3[] = {0, 9, 18, 27, 37, 46, 55, 64}; + + int3 tmp = ( low * ( 64 - aWeight3[i] ) + high * aWeight3[i] + 32 ) >> 6; + palette = finish_unquantize( tmp ); +} +void generate_palette_unquantized16( out uint3 palette, int3 low, int3 high, int i ) +{ + static const int aWeight4[] = {0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64}; + + int3 tmp = ( low * ( 64 - aWeight4[i] ) + high * aWeight4[i] + 32 ) >> 6; + palette = finish_unquantize( tmp ); +} + +float half2float1( uint Value ) +{ + uint Mantissa = (uint)(Value & 0x03FF); + + uint Exponent; + if ((Value & 0x7C00) != 0) // The value is normalized + { + Exponent = (uint)((Value >> 10) & 0x1F); + } + else if (Mantissa != 0) // The value is denormalized + { + // Normalize the value in the resulting float + Exponent = 1; + + do + { + Exponent--; + Mantissa <<= 1; + } while ((Mantissa & 0x0400) == 0); + + Mantissa &= 0x03FF; + } + else // The value is zero + { + Exponent = (uint)(-112); + } + + uint Result = ((Value & 0x8000) << 16) | // Sign + ((Exponent + 112) << 23) | // Exponent + (Mantissa << 13); // Mantissa + + return asfloat(Result); +} + +float3 half2float(uint3 color_h ) +{ + //uint3 sign = color_h & 0x8000; + //uint3 expo = color_h & 0x7C00; + //uint3 base = color_h & 0x03FF; + //return ( expo == 0 ) ? asfloat( ( sign << 16 ) | asuint( float3(base) / 16777216 ) ) //16777216 = 2^24 + // : asfloat( ( sign << 16 ) | ( ( ( expo + 0x1C000 ) | base ) << 13 ) ); //0x1C000 = 0x1FC00 - 0x3C00 + + return float3( half2float1( color_h.x ), half2float1( color_h.y ), half2float1( color_h.z ) ); +} + +void block_package( inout uint4 block, int2x3 endPoint[2], uint mode_type, uint partition_index ) // for mode 1 - 10 +{ + block.xy = 0; + block.z &= 0xFFFC0000; + + //block.z |= (partition_index & 0x1f) << 13; + + if ( mode_type == candidateModeFlag[0]) + { + /*block.x = candidateModeMemory[0]; + block.x |= ( ( endPoint[0][0].r << 5 ) & 0x00007FE0 ) | ( ( endPoint[0][0].g << 15 ) & 0x01FF8000 ) | ( ( endPoint[0][0].b << 25 ) & 0xFE000000 ); + block.x |= ( endPoint[1][0].g >> 2 ) & 0x00000004; + block.x |= ( endPoint[1][0].b >> 1 ) & 0x00000008; + block.x |= endPoint[1][1].b & 0x00000010; + block.y |= ( ( endPoint[0][0].b >> 7 ) & 0x00000007 ); + block.y |= ( ( endPoint[0][1].r << 3 ) & 0x000000F8 ) | ( ( endPoint[0][1].g << 13 ) & 0x0003E000 ) | ( ( endPoint[0][1].b << 23 ) & 0x0F800000 ); + block.yz |= ( endPoint[1][0].gr << uint2(9, 1) ) & uint2(0x00001E00, 0x0000003E); + block.y |= ( endPoint[1][0].b << 29 ) & 0xE0000000; + block.y |= ( ( endPoint[1][1].g << 4 ) & 0x00000100 ); + block.yz |= ( endPoint[1][1].gr << uint2(19, 7) ) & uint2(0x00780000, 0x00000F80); + block.yz |= ( ( endPoint[1][1].b << uint2(27, 9) ) & uint2(0x10000000, 0x00001000) ) | ( ( endPoint[1][1].b << uint2(18, 4) ) & uint2(0x00040000, 0x00000040) ); + block.z |= ( endPoint[1][0].b >> 3 ) & 0x00000001;*/ + + block.x |= ((candidateModeMemory[0] >> 0) & 1) << 0; + block.x |= ((candidateModeMemory[0] >> 1) & 1) << 1; + block.x |= ((endPoint[1][0].g >> 4) & 1) << 2; + block.x |= ((endPoint[1][0].b >> 4) & 1) << 3; + block.x |= ((endPoint[1][1].b >> 4) & 1) << 4; + block.x |= ((endPoint[0][0].r >> 0) & 1) << 5; + block.x |= ((endPoint[0][0].r >> 1) & 1) << 6; + block.x |= ((endPoint[0][0].r >> 2) & 1) << 7; + block.x |= ((endPoint[0][0].r >> 3) & 1) << 8; + block.x |= ((endPoint[0][0].r >> 4) & 1) << 9; + block.x |= ((endPoint[0][0].r >> 5) & 1) << 10; + block.x |= ((endPoint[0][0].r >> 6) & 1) << 11; + block.x |= ((endPoint[0][0].r >> 7) & 1) << 12; + block.x |= ((endPoint[0][0].r >> 8) & 1) << 13; + block.x |= ((endPoint[0][0].r >> 9) & 1) << 14; + block.x |= ((endPoint[0][0].g >> 0) & 1) << 15; + block.x |= ((endPoint[0][0].g >> 1) & 1) << 16; + block.x |= ((endPoint[0][0].g >> 2) & 1) << 17; + block.x |= ((endPoint[0][0].g >> 3) & 1) << 18; + block.x |= ((endPoint[0][0].g >> 4) & 1) << 19; + block.x |= ((endPoint[0][0].g >> 5) & 1) << 20; + block.x |= ((endPoint[0][0].g >> 6) & 1) << 21; + block.x |= ((endPoint[0][0].g >> 7) & 1) << 22; + block.x |= ((endPoint[0][0].g >> 8) & 1) << 23; + block.x |= ((endPoint[0][0].g >> 9) & 1) << 24; + block.x |= ((endPoint[0][0].b >> 0) & 1) << 25; + block.x |= ((endPoint[0][0].b >> 1) & 1) << 26; + block.x |= ((endPoint[0][0].b >> 2) & 1) << 27; + block.x |= ((endPoint[0][0].b >> 3) & 1) << 28; + block.x |= ((endPoint[0][0].b >> 4) & 1) << 29; + block.x |= ((endPoint[0][0].b >> 5) & 1) << 30; + block.x |= ((endPoint[0][0].b >> 6) & 1) << 31; + block.y |= ((endPoint[0][0].b >> 7) & 1) << 0; + block.y |= ((endPoint[0][0].b >> 8) & 1) << 1; + block.y |= ((endPoint[0][0].b >> 9) & 1) << 2; + block.y |= ((endPoint[0][1].r >> 0) & 1) << 3; + block.y |= ((endPoint[0][1].r >> 1) & 1) << 4; + block.y |= ((endPoint[0][1].r >> 2) & 1) << 5; + block.y |= ((endPoint[0][1].r >> 3) & 1) << 6; + block.y |= ((endPoint[0][1].r >> 4) & 1) << 7; + block.y |= ((endPoint[1][1].g >> 4) & 1) << 8; + block.y |= ((endPoint[1][0].g >> 0) & 1) << 9; + block.y |= ((endPoint[1][0].g >> 1) & 1) << 10; + block.y |= ((endPoint[1][0].g >> 2) & 1) << 11; + block.y |= ((endPoint[1][0].g >> 3) & 1) << 12; + block.y |= ((endPoint[0][1].g >> 0) & 1) << 13; + block.y |= ((endPoint[0][1].g >> 1) & 1) << 14; + block.y |= ((endPoint[0][1].g >> 2) & 1) << 15; + block.y |= ((endPoint[0][1].g >> 3) & 1) << 16; + block.y |= ((endPoint[0][1].g >> 4) & 1) << 17; + block.y |= ((endPoint[1][1].b >> 0) & 1) << 18; + block.y |= ((endPoint[1][1].g >> 0) & 1) << 19; + block.y |= ((endPoint[1][1].g >> 1) & 1) << 20; + block.y |= ((endPoint[1][1].g >> 2) & 1) << 21; + block.y |= ((endPoint[1][1].g >> 3) & 1) << 22; + block.y |= ((endPoint[0][1].b >> 0) & 1) << 23; + block.y |= ((endPoint[0][1].b >> 1) & 1) << 24; + block.y |= ((endPoint[0][1].b >> 2) & 1) << 25; + block.y |= ((endPoint[0][1].b >> 3) & 1) << 26; + block.y |= ((endPoint[0][1].b >> 4) & 1) << 27; + block.y |= ((endPoint[1][1].b >> 1) & 1) << 28; + block.y |= ((endPoint[1][0].b >> 0) & 1) << 29; + block.y |= ((endPoint[1][0].b >> 1) & 1) << 30; + block.y |= ((endPoint[1][0].b >> 2) & 1) << 31; + block.z |= ((endPoint[1][0].b >> 3) & 1) << 0; + block.z |= ((endPoint[1][0].r >> 0) & 1) << 1; + block.z |= ((endPoint[1][0].r >> 1) & 1) << 2; + block.z |= ((endPoint[1][0].r >> 2) & 1) << 3; + block.z |= ((endPoint[1][0].r >> 3) & 1) << 4; + block.z |= ((endPoint[1][0].r >> 4) & 1) << 5; + block.z |= ((endPoint[1][1].b >> 2) & 1) << 6; + block.z |= ((endPoint[1][1].r >> 0) & 1) << 7; + block.z |= ((endPoint[1][1].r >> 1) & 1) << 8; + block.z |= ((endPoint[1][1].r >> 2) & 1) << 9; + block.z |= ((endPoint[1][1].r >> 3) & 1) << 10; + block.z |= ((endPoint[1][1].r >> 4) & 1) << 11; + block.z |= ((endPoint[1][1].b >> 3) & 1) << 12; + block.z |= ((partition_index >> 0) & 1) << 13; + block.z |= ((partition_index >> 1) & 1) << 14; + block.z |= ((partition_index >> 2) & 1) << 15; + block.z |= ((partition_index >> 3) & 1) << 16; + block.z |= ((partition_index >> 4) & 1) << 17; + } + else if ( mode_type == candidateModeFlag[1]) + { + /*block.x = candidateModeMemory[1]; + block.x |= ( ( endPoint[0][0].r << 5 ) & 0x00000FE0 ) | ( ( endPoint[0][0].g << 15 ) & 0x003F8000 ) | ( ( endPoint[0][0].b << 25 ) & 0xFE000000 ); + block.y |= ( ( endPoint[0][1].r << 3 ) & 0x000001F8 ) | ( ( endPoint[0][1].g << 13 ) & 0x0007E000 ) | ( ( endPoint[0][1].b << 23 ) & 0x1F800000 ); + block.x |= ( ( endPoint[1][0].g >> 3 ) & 0x00000004 ) | ( ( endPoint[1][0].g << 20 ) & 0x01000000 ); + block.x |= ( endPoint[1][1].g >> 1 ) & 0x00000018; + block.x |= ( ( endPoint[1][1].b << 21 ) & 0x00800000 ) | ( ( endPoint[1][1].b << 12 ) & 0x00003000 ); + block.x |= ( ( endPoint[1][0].b << 17 ) & 0x00400000 ) | ( ( endPoint[1][0].b << 10 ) & 0x00004000 ); + block.yz |= ( endPoint[1][0].gr << uint2(9, 1) ) & uint2(0x00001E00, 0x0000007E); + block.y |= ( endPoint[1][0].b << 29 ) & 0xE0000000; + block.yz |= ( endPoint[1][1].gr << uint2(19, 7) ) & uint2(0x00780000, 0x00001F80); + block.y |= ( ( endPoint[1][1].b >> 4 ) & 0x00000002 ) | ( ( endPoint[1][1].b >> 2 ) & 0x00000004 ) | ( ( endPoint[1][1].b >> 3 ) & 0x00000001 ); + block.z |= ( endPoint[1][0].b >> 3 ) & 0x00000001;*/ + + block.x |= ((candidateModeMemory[1] >> 0) & 1) << 0; + block.x |= ((candidateModeMemory[1] >> 1) & 1) << 1; + block.x |= ((endPoint[1][0].g >> 5) & 1) << 2; + block.x |= ((endPoint[1][1].g >> 4) & 1) << 3; + block.x |= ((endPoint[1][1].g >> 5) & 1) << 4; + block.x |= ((endPoint[0][0].r >> 0) & 1) << 5; + block.x |= ((endPoint[0][0].r >> 1) & 1) << 6; + block.x |= ((endPoint[0][0].r >> 2) & 1) << 7; + block.x |= ((endPoint[0][0].r >> 3) & 1) << 8; + block.x |= ((endPoint[0][0].r >> 4) & 1) << 9; + block.x |= ((endPoint[0][0].r >> 5) & 1) << 10; + block.x |= ((endPoint[0][0].r >> 6) & 1) << 11; + block.x |= ((endPoint[1][1].b >> 0) & 1) << 12; + block.x |= ((endPoint[1][1].b >> 1) & 1) << 13; + block.x |= ((endPoint[1][0].b >> 4) & 1) << 14; + block.x |= ((endPoint[0][0].g >> 0) & 1) << 15; + block.x |= ((endPoint[0][0].g >> 1) & 1) << 16; + block.x |= ((endPoint[0][0].g >> 2) & 1) << 17; + block.x |= ((endPoint[0][0].g >> 3) & 1) << 18; + block.x |= ((endPoint[0][0].g >> 4) & 1) << 19; + block.x |= ((endPoint[0][0].g >> 5) & 1) << 20; + block.x |= ((endPoint[0][0].g >> 6) & 1) << 21; + block.x |= ((endPoint[1][0].b >> 5) & 1) << 22; + block.x |= ((endPoint[1][1].b >> 2) & 1) << 23; + block.x |= ((endPoint[1][0].g >> 4) & 1) << 24; + block.x |= ((endPoint[0][0].b >> 0) & 1) << 25; + block.x |= ((endPoint[0][0].b >> 1) & 1) << 26; + block.x |= ((endPoint[0][0].b >> 2) & 1) << 27; + block.x |= ((endPoint[0][0].b >> 3) & 1) << 28; + block.x |= ((endPoint[0][0].b >> 4) & 1) << 29; + block.x |= ((endPoint[0][0].b >> 5) & 1) << 30; + block.x |= ((endPoint[0][0].b >> 6) & 1) << 31; + block.y |= ((endPoint[1][1].b >> 3) & 1) << 0; + block.y |= ((endPoint[1][1].b >> 5) & 1) << 1; + block.y |= ((endPoint[1][1].b >> 4) & 1) << 2; + block.y |= ((endPoint[0][1].r >> 0) & 1) << 3; + block.y |= ((endPoint[0][1].r >> 1) & 1) << 4; + block.y |= ((endPoint[0][1].r >> 2) & 1) << 5; + block.y |= ((endPoint[0][1].r >> 3) & 1) << 6; + block.y |= ((endPoint[0][1].r >> 4) & 1) << 7; + block.y |= ((endPoint[0][1].r >> 5) & 1) << 8; + block.y |= ((endPoint[1][0].g >> 0) & 1) << 9; + block.y |= ((endPoint[1][0].g >> 1) & 1) << 10; + block.y |= ((endPoint[1][0].g >> 2) & 1) << 11; + block.y |= ((endPoint[1][0].g >> 3) & 1) << 12; + block.y |= ((endPoint[0][1].g >> 0) & 1) << 13; + block.y |= ((endPoint[0][1].g >> 1) & 1) << 14; + block.y |= ((endPoint[0][1].g >> 2) & 1) << 15; + block.y |= ((endPoint[0][1].g >> 3) & 1) << 16; + block.y |= ((endPoint[0][1].g >> 4) & 1) << 17; + block.y |= ((endPoint[0][1].g >> 5) & 1) << 18; + block.y |= ((endPoint[1][1].g >> 0) & 1) << 19; + block.y |= ((endPoint[1][1].g >> 1) & 1) << 20; + block.y |= ((endPoint[1][1].g >> 2) & 1) << 21; + block.y |= ((endPoint[1][1].g >> 3) & 1) << 22; + block.y |= ((endPoint[0][1].b >> 0) & 1) << 23; + block.y |= ((endPoint[0][1].b >> 1) & 1) << 24; + block.y |= ((endPoint[0][1].b >> 2) & 1) << 25; + block.y |= ((endPoint[0][1].b >> 3) & 1) << 26; + block.y |= ((endPoint[0][1].b >> 4) & 1) << 27; + block.y |= ((endPoint[0][1].b >> 5) & 1) << 28; + block.y |= ((endPoint[1][0].b >> 0) & 1) << 29; + block.y |= ((endPoint[1][0].b >> 1) & 1) << 30; + block.y |= ((endPoint[1][0].b >> 2) & 1) << 31; + block.z |= ((endPoint[1][0].b >> 3) & 1) << 0; + block.z |= ((endPoint[1][0].r >> 0) & 1) << 1; + block.z |= ((endPoint[1][0].r >> 1) & 1) << 2; + block.z |= ((endPoint[1][0].r >> 2) & 1) << 3; + block.z |= ((endPoint[1][0].r >> 3) & 1) << 4; + block.z |= ((endPoint[1][0].r >> 4) & 1) << 5; + block.z |= ((endPoint[1][0].r >> 5) & 1) << 6; + block.z |= ((endPoint[1][1].r >> 0) & 1) << 7; + block.z |= ((endPoint[1][1].r >> 1) & 1) << 8; + block.z |= ((endPoint[1][1].r >> 2) & 1) << 9; + block.z |= ((endPoint[1][1].r >> 3) & 1) << 10; + block.z |= ((endPoint[1][1].r >> 4) & 1) << 11; + block.z |= ((endPoint[1][1].r >> 5) & 1) << 12; + block.z |= ((partition_index >> 0) & 1) << 13; + block.z |= ((partition_index >> 1) & 1) << 14; + block.z |= ((partition_index >> 2) & 1) << 15; + block.z |= ((partition_index >> 3) & 1) << 16; + block.z |= ((partition_index >> 4) & 1) << 17; + } + else if ( mode_type == candidateModeFlag[2]) + { + /*block.x = candidateModeMemory[2]; + block.x |= ( ( endPoint[0][0].r << 5 ) & 0x00007FE0 ) | ( ( endPoint[0][0].g << 15 ) & 0x01FF8000 ) | ( ( endPoint[0][0].b << 25 ) & 0xFE000000 ); + block.y |= ( endPoint[0][0].r >> 2 ) & 0x00000100; + block.y |= ( endPoint[0][0].g << 7 ) & 0x00020000; + block.y |= ( ( endPoint[0][0].b << 17 ) & 0x08000000 ) | ( ( endPoint[0][0].b >> 7 ) & 0x00000007 ); + block.y |= ( ( endPoint[0][1].r << 3 ) & 0x000000F8 ) | ( ( endPoint[0][1].g << 13 ) & 0x0001E000 ) | ( ( endPoint[0][1].b << 23 ) & 0x07800000 ); + block.yz |= ( endPoint[1][0].gr << uint2(9, 1) ) & uint2(0x00001E00, 0x0000003E); + block.y |= ( endPoint[1][0].b << 29 ) & 0xE0000000; + block.yz |= ( endPoint[1][1].gr << uint2(19, 7) ) & uint2(0x00780000, 0x00000F80); + block.yz |= ( ( endPoint[1][1].b << uint2(27, 9) ) & uint2(0x10000000, 0x00001000) ) | ( ( endPoint[1][1].b << uint2(18, 4) ) & uint2(0x00040000, 0x00000040) ); + block.z |= ( endPoint[1][0].b >> 3 ) & 0x00000001;*/ + + block.x |= ((candidateModeMemory[2] >> 0) & 1) << 0; + block.x |= ((candidateModeMemory[2] >> 1) & 1) << 1; + block.x |= ((candidateModeMemory[2] >> 2) & 1) << 2; + block.x |= ((candidateModeMemory[2] >> 3) & 1) << 3; + block.x |= ((candidateModeMemory[2] >> 4) & 1) << 4; + block.x |= ((endPoint[0][0].r >> 0) & 1) << 5; + block.x |= ((endPoint[0][0].r >> 1) & 1) << 6; + block.x |= ((endPoint[0][0].r >> 2) & 1) << 7; + block.x |= ((endPoint[0][0].r >> 3) & 1) << 8; + block.x |= ((endPoint[0][0].r >> 4) & 1) << 9; + block.x |= ((endPoint[0][0].r >> 5) & 1) << 10; + block.x |= ((endPoint[0][0].r >> 6) & 1) << 11; + block.x |= ((endPoint[0][0].r >> 7) & 1) << 12; + block.x |= ((endPoint[0][0].r >> 8) & 1) << 13; + block.x |= ((endPoint[0][0].r >> 9) & 1) << 14; + block.x |= ((endPoint[0][0].g >> 0) & 1) << 15; + block.x |= ((endPoint[0][0].g >> 1) & 1) << 16; + block.x |= ((endPoint[0][0].g >> 2) & 1) << 17; + block.x |= ((endPoint[0][0].g >> 3) & 1) << 18; + block.x |= ((endPoint[0][0].g >> 4) & 1) << 19; + block.x |= ((endPoint[0][0].g >> 5) & 1) << 20; + block.x |= ((endPoint[0][0].g >> 6) & 1) << 21; + block.x |= ((endPoint[0][0].g >> 7) & 1) << 22; + block.x |= ((endPoint[0][0].g >> 8) & 1) << 23; + block.x |= ((endPoint[0][0].g >> 9) & 1) << 24; + block.x |= ((endPoint[0][0].b >> 0) & 1) << 25; + block.x |= ((endPoint[0][0].b >> 1) & 1) << 26; + block.x |= ((endPoint[0][0].b >> 2) & 1) << 27; + block.x |= ((endPoint[0][0].b >> 3) & 1) << 28; + block.x |= ((endPoint[0][0].b >> 4) & 1) << 29; + block.x |= ((endPoint[0][0].b >> 5) & 1) << 30; + block.x |= ((endPoint[0][0].b >> 6) & 1) << 31; + block.y |= ((endPoint[0][0].b >> 7) & 1) << 0; + block.y |= ((endPoint[0][0].b >> 8) & 1) << 1; + block.y |= ((endPoint[0][0].b >> 9) & 1) << 2; + block.y |= ((endPoint[0][1].r >> 0) & 1) << 3; + block.y |= ((endPoint[0][1].r >> 1) & 1) << 4; + block.y |= ((endPoint[0][1].r >> 2) & 1) << 5; + block.y |= ((endPoint[0][1].r >> 3) & 1) << 6; + block.y |= ((endPoint[0][1].r >> 4) & 1) << 7; + block.y |= ((endPoint[0][0].r >> 10) & 1) << 8; + block.y |= ((endPoint[1][0].g >> 0) & 1) << 9; + block.y |= ((endPoint[1][0].g >> 1) & 1) << 10; + block.y |= ((endPoint[1][0].g >> 2) & 1) << 11; + block.y |= ((endPoint[1][0].g >> 3) & 1) << 12; + block.y |= ((endPoint[0][1].g >> 0) & 1) << 13; + block.y |= ((endPoint[0][1].g >> 1) & 1) << 14; + block.y |= ((endPoint[0][1].g >> 2) & 1) << 15; + block.y |= ((endPoint[0][1].g >> 3) & 1) << 16; + block.y |= ((endPoint[0][0].g >> 10) & 1) << 17; + block.y |= ((endPoint[1][1].b >> 0) & 1) << 18; + block.y |= ((endPoint[1][1].g >> 0) & 1) << 19; + block.y |= ((endPoint[1][1].g >> 1) & 1) << 20; + block.y |= ((endPoint[1][1].g >> 2) & 1) << 21; + block.y |= ((endPoint[1][1].g >> 3) & 1) << 22; + block.y |= ((endPoint[0][1].b >> 0) & 1) << 23; + block.y |= ((endPoint[0][1].b >> 1) & 1) << 24; + block.y |= ((endPoint[0][1].b >> 2) & 1) << 25; + block.y |= ((endPoint[0][1].b >> 3) & 1) << 26; + block.y |= ((endPoint[0][0].b >> 10) & 1) << 27; + block.y |= ((endPoint[1][1].b >> 1) & 1) << 28; + block.y |= ((endPoint[1][0].b >> 0) & 1) << 29; + block.y |= ((endPoint[1][0].b >> 1) & 1) << 30; + block.y |= ((endPoint[1][0].b >> 2) & 1) << 31; + block.z |= ((endPoint[1][0].b >> 3) & 1) << 0; + block.z |= ((endPoint[1][0].r >> 0) & 1) << 1; + block.z |= ((endPoint[1][0].r >> 1) & 1) << 2; + block.z |= ((endPoint[1][0].r >> 2) & 1) << 3; + block.z |= ((endPoint[1][0].r >> 3) & 1) << 4; + block.z |= ((endPoint[1][0].r >> 4) & 1) << 5; + block.z |= ((endPoint[1][1].b >> 2) & 1) << 6; + block.z |= ((endPoint[1][1].r >> 0) & 1) << 7; + block.z |= ((endPoint[1][1].r >> 1) & 1) << 8; + block.z |= ((endPoint[1][1].r >> 2) & 1) << 9; + block.z |= ((endPoint[1][1].r >> 3) & 1) << 10; + block.z |= ((endPoint[1][1].r >> 4) & 1) << 11; + block.z |= ((endPoint[1][1].b >> 3) & 1) << 12; + block.z |= ((partition_index >> 0) & 1) << 13; + block.z |= ((partition_index >> 1) & 1) << 14; + block.z |= ((partition_index >> 2) & 1) << 15; + block.z |= ((partition_index >> 3) & 1) << 16; + block.z |= ((partition_index >> 4) & 1) << 17; + } + else if ( mode_type == candidateModeFlag[3]) + { + /*block.x = candidateModeMemory[3]; + block.x |= ( ( endPoint[0][0].r << 5 ) & 0x00007FE0 ) | ( ( endPoint[0][0].g << 15 ) & 0x01FF8000 ) | ( ( endPoint[0][0].b << 25 ) & 0xFE000000 ); + block.y |= ( endPoint[0][0].r >> 3 ) & 0x00000080; + block.y |= ( endPoint[0][0].g << 8 ) & 0x00040000; + block.y |= ( ( endPoint[0][0].b << 17 ) & 0x08000000 ) | ( ( endPoint[0][0].b >> 7 ) & 0x00000007 ); + block.y |= ( ( endPoint[0][1].r << 3 ) & 0x00000078 ) | ( ( endPoint[0][1].g << 13 ) & 0x0003E000 ) | ( ( endPoint[0][1].b << 23 ) & 0x07800000 ); + block.yz |= ( endPoint[1][0].gr << uint2(9, 1) ) & uint2(0x00001E00, 0x0000001E); + block.y |= ( endPoint[1][0].b << 29 ) & 0xE0000000; + block.y |= ( ( endPoint[1][1].g << 4 ) & 0x00000100 ); + block.yz |= ( endPoint[1][1].gr << uint2(19, 7) ) & uint2(0x00780000, 0x00000780); + block.yz |= ( endPoint[1][1].b << uint2(27, 9) ) & uint2(0x10000000, 0x00001000); + block.z |= ( ( endPoint[1][0].g << 7 ) & 0x00000800 ); + block.z |= ( endPoint[1][0].b >> 3 ) & 0x00000001; + block.z |= ( endPoint[1][1].b << 4 ) & 0x00000040; + block.z |= ( endPoint[1][1].b << 5 ) & 0x00000020;*/ + + block.x |= ((candidateModeMemory[3] >> 0) & 1) << 0; + block.x |= ((candidateModeMemory[3] >> 1) & 1) << 1; + block.x |= ((candidateModeMemory[3] >> 2) & 1) << 2; + block.x |= ((candidateModeMemory[3] >> 3) & 1) << 3; + block.x |= ((candidateModeMemory[3] >> 4) & 1) << 4; + block.x |= ((endPoint[0][0].r >> 0) & 1) << 5; + block.x |= ((endPoint[0][0].r >> 1) & 1) << 6; + block.x |= ((endPoint[0][0].r >> 2) & 1) << 7; + block.x |= ((endPoint[0][0].r >> 3) & 1) << 8; + block.x |= ((endPoint[0][0].r >> 4) & 1) << 9; + block.x |= ((endPoint[0][0].r >> 5) & 1) << 10; + block.x |= ((endPoint[0][0].r >> 6) & 1) << 11; + block.x |= ((endPoint[0][0].r >> 7) & 1) << 12; + block.x |= ((endPoint[0][0].r >> 8) & 1) << 13; + block.x |= ((endPoint[0][0].r >> 9) & 1) << 14; + block.x |= ((endPoint[0][0].g >> 0) & 1) << 15; + block.x |= ((endPoint[0][0].g >> 1) & 1) << 16; + block.x |= ((endPoint[0][0].g >> 2) & 1) << 17; + block.x |= ((endPoint[0][0].g >> 3) & 1) << 18; + block.x |= ((endPoint[0][0].g >> 4) & 1) << 19; + block.x |= ((endPoint[0][0].g >> 5) & 1) << 20; + block.x |= ((endPoint[0][0].g >> 6) & 1) << 21; + block.x |= ((endPoint[0][0].g >> 7) & 1) << 22; + block.x |= ((endPoint[0][0].g >> 8) & 1) << 23; + block.x |= ((endPoint[0][0].g >> 9) & 1) << 24; + block.x |= ((endPoint[0][0].b >> 0) & 1) << 25; + block.x |= ((endPoint[0][0].b >> 1) & 1) << 26; + block.x |= ((endPoint[0][0].b >> 2) & 1) << 27; + block.x |= ((endPoint[0][0].b >> 3) & 1) << 28; + block.x |= ((endPoint[0][0].b >> 4) & 1) << 29; + block.x |= ((endPoint[0][0].b >> 5) & 1) << 30; + block.x |= ((endPoint[0][0].b >> 6) & 1) << 31; + block.y |= ((endPoint[0][0].b >> 7) & 1) << 0; + block.y |= ((endPoint[0][0].b >> 8) & 1) << 1; + block.y |= ((endPoint[0][0].b >> 9) & 1) << 2; + block.y |= ((endPoint[0][1].r >> 0) & 1) << 3; + block.y |= ((endPoint[0][1].r >> 1) & 1) << 4; + block.y |= ((endPoint[0][1].r >> 2) & 1) << 5; + block.y |= ((endPoint[0][1].r >> 3) & 1) << 6; + block.y |= ((endPoint[0][0].r >> 10) & 1) << 7; + block.y |= ((endPoint[1][1].g >> 4) & 1) << 8; + block.y |= ((endPoint[1][0].g >> 0) & 1) << 9; + block.y |= ((endPoint[1][0].g >> 1) & 1) << 10; + block.y |= ((endPoint[1][0].g >> 2) & 1) << 11; + block.y |= ((endPoint[1][0].g >> 3) & 1) << 12; + block.y |= ((endPoint[0][1].g >> 0) & 1) << 13; + block.y |= ((endPoint[0][1].g >> 1) & 1) << 14; + block.y |= ((endPoint[0][1].g >> 2) & 1) << 15; + block.y |= ((endPoint[0][1].g >> 3) & 1) << 16; + block.y |= ((endPoint[0][1].g >> 4) & 1) << 17; + block.y |= ((endPoint[0][0].g >> 10) & 1) << 18; + block.y |= ((endPoint[1][1].g >> 0) & 1) << 19; + block.y |= ((endPoint[1][1].g >> 1) & 1) << 20; + block.y |= ((endPoint[1][1].g >> 2) & 1) << 21; + block.y |= ((endPoint[1][1].g >> 3) & 1) << 22; + block.y |= ((endPoint[0][1].b >> 0) & 1) << 23; + block.y |= ((endPoint[0][1].b >> 1) & 1) << 24; + block.y |= ((endPoint[0][1].b >> 2) & 1) << 25; + block.y |= ((endPoint[0][1].b >> 3) & 1) << 26; + block.y |= ((endPoint[0][0].b >> 10) & 1) << 27; + block.y |= ((endPoint[1][1].b >> 1) & 1) << 28; + block.y |= ((endPoint[1][0].b >> 0) & 1) << 29; + block.y |= ((endPoint[1][0].b >> 1) & 1) << 30; + block.y |= ((endPoint[1][0].b >> 2) & 1) << 31; + block.z |= ((endPoint[1][0].b >> 3) & 1) << 0; + block.z |= ((endPoint[1][0].r >> 0) & 1) << 1; + block.z |= ((endPoint[1][0].r >> 1) & 1) << 2; + block.z |= ((endPoint[1][0].r >> 2) & 1) << 3; + block.z |= ((endPoint[1][0].r >> 3) & 1) << 4; + block.z |= ((endPoint[1][1].b >> 0) & 1) << 5; + block.z |= ((endPoint[1][1].b >> 2) & 1) << 6; + block.z |= ((endPoint[1][1].r >> 0) & 1) << 7; + block.z |= ((endPoint[1][1].r >> 1) & 1) << 8; + block.z |= ((endPoint[1][1].r >> 2) & 1) << 9; + block.z |= ((endPoint[1][1].r >> 3) & 1) << 10; + block.z |= ((endPoint[1][0].g >> 4) & 1) << 11; + block.z |= ((endPoint[1][1].b >> 3) & 1) << 12; + block.z |= ((partition_index >> 0) & 1) << 13; + block.z |= ((partition_index >> 1) & 1) << 14; + block.z |= ((partition_index >> 2) & 1) << 15; + block.z |= ((partition_index >> 3) & 1) << 16; + block.z |= ((partition_index >> 4) & 1) << 17; + } + else if ( mode_type == candidateModeFlag[4]) + { + /*block.x = candidateModeMemory[4]; + block.x |= ( ( endPoint[0][0].r << 5 ) & 0x00007FE0 ) | ( ( endPoint[0][0].g << 15 ) & 0x01FF8000 ) | ( ( endPoint[0][0].b << 25 ) & 0xFE000000 ); + block.y |= ( endPoint[0][0].r >> 3 ) & 0x00000080; + block.y |= ( endPoint[0][0].g << 7 ) & 0x00020000; + block.y |= ( ( endPoint[0][0].b << 18 ) & 0x10000000 ) | ( ( endPoint[0][0].b >> 7 ) & 0x00000007 ); + block.y |= ( ( endPoint[0][1].r << 3 ) & 0x00000078 ) | ( ( endPoint[0][1].g << 13 ) & 0x0001E000 ) | ( ( endPoint[0][1].b << 23 ) & 0x0F800000 ); + block.y |= ( ( endPoint[1][0].g << 9 ) & 0x00001E00 ) | ( ( endPoint[1][0].b << 4 ) & 0x00000100 ); + block.y |= ( endPoint[1][0].b << 29 ) & 0xE0000000; + block.yz |= ( endPoint[1][1].gr << uint2(19, 7) ) & uint2(0x00780000, 0x00000780); + block.yz |= ( endPoint[1][1].b << uint2(18, 4) ) & uint2(0x00040000, 0x00000060); + block.z |= ( endPoint[1][0].r << 1 ) & 0x0000001E; + block.z |= ( endPoint[1][0].b >> 3 ) & 0x00000001; + block.z |= ( ( endPoint[1][1].b << 7 ) & 0x00000800 ) | ( ( endPoint[1][1].b << 9 ) & 0x00001000 );*/ + + block.x |= ((candidateModeMemory[4] >> 0) & 1) << 0; + block.x |= ((candidateModeMemory[4] >> 1) & 1) << 1; + block.x |= ((candidateModeMemory[4] >> 2) & 1) << 2; + block.x |= ((candidateModeMemory[4] >> 3) & 1) << 3; + block.x |= ((candidateModeMemory[4] >> 4) & 1) << 4; + block.x |= ((endPoint[0][0].r >> 0) & 1) << 5; + block.x |= ((endPoint[0][0].r >> 1) & 1) << 6; + block.x |= ((endPoint[0][0].r >> 2) & 1) << 7; + block.x |= ((endPoint[0][0].r >> 3) & 1) << 8; + block.x |= ((endPoint[0][0].r >> 4) & 1) << 9; + block.x |= ((endPoint[0][0].r >> 5) & 1) << 10; + block.x |= ((endPoint[0][0].r >> 6) & 1) << 11; + block.x |= ((endPoint[0][0].r >> 7) & 1) << 12; + block.x |= ((endPoint[0][0].r >> 8) & 1) << 13; + block.x |= ((endPoint[0][0].r >> 9) & 1) << 14; + block.x |= ((endPoint[0][0].g >> 0) & 1) << 15; + block.x |= ((endPoint[0][0].g >> 1) & 1) << 16; + block.x |= ((endPoint[0][0].g >> 2) & 1) << 17; + block.x |= ((endPoint[0][0].g >> 3) & 1) << 18; + block.x |= ((endPoint[0][0].g >> 4) & 1) << 19; + block.x |= ((endPoint[0][0].g >> 5) & 1) << 20; + block.x |= ((endPoint[0][0].g >> 6) & 1) << 21; + block.x |= ((endPoint[0][0].g >> 7) & 1) << 22; + block.x |= ((endPoint[0][0].g >> 8) & 1) << 23; + block.x |= ((endPoint[0][0].g >> 9) & 1) << 24; + block.x |= ((endPoint[0][0].b >> 0) & 1) << 25; + block.x |= ((endPoint[0][0].b >> 1) & 1) << 26; + block.x |= ((endPoint[0][0].b >> 2) & 1) << 27; + block.x |= ((endPoint[0][0].b >> 3) & 1) << 28; + block.x |= ((endPoint[0][0].b >> 4) & 1) << 29; + block.x |= ((endPoint[0][0].b >> 5) & 1) << 30; + block.x |= ((endPoint[0][0].b >> 6) & 1) << 31; + block.y |= ((endPoint[0][0].b >> 7) & 1) << 0; + block.y |= ((endPoint[0][0].b >> 8) & 1) << 1; + block.y |= ((endPoint[0][0].b >> 9) & 1) << 2; + block.y |= ((endPoint[0][1].r >> 0) & 1) << 3; + block.y |= ((endPoint[0][1].r >> 1) & 1) << 4; + block.y |= ((endPoint[0][1].r >> 2) & 1) << 5; + block.y |= ((endPoint[0][1].r >> 3) & 1) << 6; + block.y |= ((endPoint[0][0].r >> 10) & 1) << 7; + block.y |= ((endPoint[1][0].b >> 4) & 1) << 8; + block.y |= ((endPoint[1][0].g >> 0) & 1) << 9; + block.y |= ((endPoint[1][0].g >> 1) & 1) << 10; + block.y |= ((endPoint[1][0].g >> 2) & 1) << 11; + block.y |= ((endPoint[1][0].g >> 3) & 1) << 12; + block.y |= ((endPoint[0][1].g >> 0) & 1) << 13; + block.y |= ((endPoint[0][1].g >> 1) & 1) << 14; + block.y |= ((endPoint[0][1].g >> 2) & 1) << 15; + block.y |= ((endPoint[0][1].g >> 3) & 1) << 16; + block.y |= ((endPoint[0][0].g >> 10) & 1) << 17; + block.y |= ((endPoint[1][1].b >> 0) & 1) << 18; + block.y |= ((endPoint[1][1].g >> 0) & 1) << 19; + block.y |= ((endPoint[1][1].g >> 1) & 1) << 20; + block.y |= ((endPoint[1][1].g >> 2) & 1) << 21; + block.y |= ((endPoint[1][1].g >> 3) & 1) << 22; + block.y |= ((endPoint[0][1].b >> 0) & 1) << 23; + block.y |= ((endPoint[0][1].b >> 1) & 1) << 24; + block.y |= ((endPoint[0][1].b >> 2) & 1) << 25; + block.y |= ((endPoint[0][1].b >> 3) & 1) << 26; + block.y |= ((endPoint[0][1].b >> 4) & 1) << 27; + block.y |= ((endPoint[0][0].b >> 10) & 1) << 28; + block.y |= ((endPoint[1][0].b >> 0) & 1) << 29; + block.y |= ((endPoint[1][0].b >> 1) & 1) << 30; + block.y |= ((endPoint[1][0].b >> 2) & 1) << 31; + block.z |= ((endPoint[1][0].b >> 3) & 1) << 0; + block.z |= ((endPoint[1][0].r >> 0) & 1) << 1; + block.z |= ((endPoint[1][0].r >> 1) & 1) << 2; + block.z |= ((endPoint[1][0].r >> 2) & 1) << 3; + block.z |= ((endPoint[1][0].r >> 3) & 1) << 4; + block.z |= ((endPoint[1][1].b >> 1) & 1) << 5; + block.z |= ((endPoint[1][1].b >> 2) & 1) << 6; + block.z |= ((endPoint[1][1].r >> 0) & 1) << 7; + block.z |= ((endPoint[1][1].r >> 1) & 1) << 8; + block.z |= ((endPoint[1][1].r >> 2) & 1) << 9; + block.z |= ((endPoint[1][1].r >> 3) & 1) << 10; + block.z |= ((endPoint[1][1].b >> 4) & 1) << 11; + block.z |= ((endPoint[1][1].b >> 3) & 1) << 12; + block.z |= ((partition_index >> 0) & 1) << 13; + block.z |= ((partition_index >> 1) & 1) << 14; + block.z |= ((partition_index >> 2) & 1) << 15; + block.z |= ((partition_index >> 3) & 1) << 16; + block.z |= ((partition_index >> 4) & 1) << 17; + } + else if ( mode_type == candidateModeFlag[5]) + { + /*block.x = candidateModeMemory[5]; + block.x |= ( ( endPoint[0][0].r << 5 ) & 0x00003FE0 ) | ( ( endPoint[0][0].g << 15 ) & 0x00FF8000 ) | ( ( endPoint[0][0].b << 25 ) & 0xFE000000); + block.y |= ( endPoint[0][0].b >> 7 ) & 0x00000003; + block.y |= ( ( endPoint[0][1].r << 3 ) & 0x000000F8 ) | ( ( endPoint[0][1].g << 13 ) & 0x0003E000 ) | ( ( endPoint[0][1].b << 23 ) & 0x0F800000 ); + block.x |= ( ( endPoint[1][0].g << 20 ) & 0x01000000 ) | ( ( endPoint[1][0].b << 10 ) & 0x00004000 ); + block.yz |= ( endPoint[1][0].gr << uint2(9, 1) ) & uint2(0x00001E00, 0x0000003E); + block.y |= ( endPoint[1][0].b << 29 ) & 0xE0000000; + block.y |= ( ( endPoint[1][1].g << 4 ) & 0x00000100 ) | ( ( endPoint[1][1].b >> 2 ) & 0x00000004 ); + block.y |= ( ( endPoint[1][1].b << 27 ) & 0x10000000 ); + block.yz |= ( endPoint[1][1].gr << uint2(19, 7) ) & uint2(0x00780000, 0x00000F80); + block.yz |= ( endPoint[1][1].b << uint2(18, 4) ) & uint2(0x00040000, 0x00000040); + block.z |= ( endPoint[1][0].b >> 3 ) & 0x00000001; + block.z |= ( ( endPoint[1][1].b << 9 ) & 0x00001000 );*/ + + block.x |= ((candidateModeMemory[5] >> 0) & 1) << 0; + block.x |= ((candidateModeMemory[5] >> 1) & 1) << 1; + block.x |= ((candidateModeMemory[5] >> 2) & 1) << 2; + block.x |= ((candidateModeMemory[5] >> 3) & 1) << 3; + block.x |= ((candidateModeMemory[5] >> 4) & 1) << 4; + block.x |= ((endPoint[0][0].r >> 0) & 1) << 5; + block.x |= ((endPoint[0][0].r >> 1) & 1) << 6; + block.x |= ((endPoint[0][0].r >> 2) & 1) << 7; + block.x |= ((endPoint[0][0].r >> 3) & 1) << 8; + block.x |= ((endPoint[0][0].r >> 4) & 1) << 9; + block.x |= ((endPoint[0][0].r >> 5) & 1) << 10; + block.x |= ((endPoint[0][0].r >> 6) & 1) << 11; + block.x |= ((endPoint[0][0].r >> 7) & 1) << 12; + block.x |= ((endPoint[0][0].r >> 8) & 1) << 13; + block.x |= ((endPoint[1][0].b >> 4) & 1) << 14; + block.x |= ((endPoint[0][0].g >> 0) & 1) << 15; + block.x |= ((endPoint[0][0].g >> 1) & 1) << 16; + block.x |= ((endPoint[0][0].g >> 2) & 1) << 17; + block.x |= ((endPoint[0][0].g >> 3) & 1) << 18; + block.x |= ((endPoint[0][0].g >> 4) & 1) << 19; + block.x |= ((endPoint[0][0].g >> 5) & 1) << 20; + block.x |= ((endPoint[0][0].g >> 6) & 1) << 21; + block.x |= ((endPoint[0][0].g >> 7) & 1) << 22; + block.x |= ((endPoint[0][0].g >> 8) & 1) << 23; + block.x |= ((endPoint[1][0].g >> 4) & 1) << 24; + block.x |= ((endPoint[0][0].b >> 0) & 1) << 25; + block.x |= ((endPoint[0][0].b >> 1) & 1) << 26; + block.x |= ((endPoint[0][0].b >> 2) & 1) << 27; + block.x |= ((endPoint[0][0].b >> 3) & 1) << 28; + block.x |= ((endPoint[0][0].b >> 4) & 1) << 29; + block.x |= ((endPoint[0][0].b >> 5) & 1) << 30; + block.x |= ((endPoint[0][0].b >> 6) & 1) << 31; + block.y |= ((endPoint[0][0].b >> 7) & 1) << 0; + block.y |= ((endPoint[0][0].b >> 8) & 1) << 1; + block.y |= ((endPoint[1][1].b >> 4) & 1) << 2; + block.y |= ((endPoint[0][1].r >> 0) & 1) << 3; + block.y |= ((endPoint[0][1].r >> 1) & 1) << 4; + block.y |= ((endPoint[0][1].r >> 2) & 1) << 5; + block.y |= ((endPoint[0][1].r >> 3) & 1) << 6; + block.y |= ((endPoint[0][1].r >> 4) & 1) << 7; + block.y |= ((endPoint[1][1].g >> 4) & 1) << 8; + block.y |= ((endPoint[1][0].g >> 0) & 1) << 9; + block.y |= ((endPoint[1][0].g >> 1) & 1) << 10; + block.y |= ((endPoint[1][0].g >> 2) & 1) << 11; + block.y |= ((endPoint[1][0].g >> 3) & 1) << 12; + block.y |= ((endPoint[0][1].g >> 0) & 1) << 13; + block.y |= ((endPoint[0][1].g >> 1) & 1) << 14; + block.y |= ((endPoint[0][1].g >> 2) & 1) << 15; + block.y |= ((endPoint[0][1].g >> 3) & 1) << 16; + block.y |= ((endPoint[0][1].g >> 4) & 1) << 17; + block.y |= ((endPoint[1][1].b >> 0) & 1) << 18; + block.y |= ((endPoint[1][1].g >> 0) & 1) << 19; + block.y |= ((endPoint[1][1].g >> 1) & 1) << 20; + block.y |= ((endPoint[1][1].g >> 2) & 1) << 21; + block.y |= ((endPoint[1][1].g >> 3) & 1) << 22; + block.y |= ((endPoint[0][1].b >> 0) & 1) << 23; + block.y |= ((endPoint[0][1].b >> 1) & 1) << 24; + block.y |= ((endPoint[0][1].b >> 2) & 1) << 25; + block.y |= ((endPoint[0][1].b >> 3) & 1) << 26; + block.y |= ((endPoint[0][1].b >> 4) & 1) << 27; + block.y |= ((endPoint[1][1].b >> 1) & 1) << 28; + block.y |= ((endPoint[1][0].b >> 0) & 1) << 29; + block.y |= ((endPoint[1][0].b >> 1) & 1) << 30; + block.y |= ((endPoint[1][0].b >> 2) & 1) << 31; + block.z |= ((endPoint[1][0].b >> 3) & 1) << 0; + block.z |= ((endPoint[1][0].r >> 0) & 1) << 1; + block.z |= ((endPoint[1][0].r >> 1) & 1) << 2; + block.z |= ((endPoint[1][0].r >> 2) & 1) << 3; + block.z |= ((endPoint[1][0].r >> 3) & 1) << 4; + block.z |= ((endPoint[1][0].r >> 4) & 1) << 5; + block.z |= ((endPoint[1][1].b >> 2) & 1) << 6; + block.z |= ((endPoint[1][1].r >> 0) & 1) << 7; + block.z |= ((endPoint[1][1].r >> 1) & 1) << 8; + block.z |= ((endPoint[1][1].r >> 2) & 1) << 9; + block.z |= ((endPoint[1][1].r >> 3) & 1) << 10; + block.z |= ((endPoint[1][1].r >> 4) & 1) << 11; + block.z |= ((endPoint[1][1].b >> 3) & 1) << 12; + block.z |= ((partition_index >> 0) & 1) << 13; + block.z |= ((partition_index >> 1) & 1) << 14; + block.z |= ((partition_index >> 2) & 1) << 15; + block.z |= ((partition_index >> 3) & 1) << 16; + block.z |= ((partition_index >> 4) & 1) << 17; + } + else if ( mode_type == candidateModeFlag[6]) + { + /*block.x = candidateModeMemory[6]; + block.x |= ( ( endPoint[0][0].r << 5 ) & 0x00001FE0 ) | ( ( endPoint[0][0].g << 15 ) & 0x007F8000 ) | ( ( endPoint[0][0].b << 25 ) & 0xFE000000 ); + block.y |= ( endPoint[0][0].b >> 7 ) & 0x00000001; + block.y |= ( ( endPoint[0][1].r << 3 ) & 0x000001F8 ) | ( ( endPoint[0][1].g << 13 ) & 0x0003E000 ) | ( ( endPoint[0][1].b << 23 ) & 0x0F800000 ); + block.x |= ( ( endPoint[1][0].g << 20 ) & 0x01000000 ) | ( ( endPoint[1][0].b << 10 ) & 0x00004000); + block.x |= ( ( endPoint[1][1].g << 9 ) & 0x00002000 ) | ( ( endPoint[1][1].b << 21 ) & 0x00800000); + block.yz |= ( endPoint[1][0].gr << uint2(9, 1) ) & uint2(0x00001E00, 0x0000007E); + block.y |= ( endPoint[1][0].b << 29 ) & 0xE0000000; + block.yz |= ( endPoint[1][1].gr << uint2(19, 7) ) & uint2(0x00780000, 0x00001F80); + block.y |= ( ( endPoint[1][1].b >> 2 ) & 0x00000006 ); + block.y |= ( ( endPoint[1][1].b << 27 ) & 0x10000000 ) | ( ( endPoint[1][1].b << 18 ) & 0x00040000 ); + block.z |= ( endPoint[1][0].b >> 3 ) & 0x00000001;*/ + + block.x |= ((candidateModeMemory[6] >> 0) & 1) << 0; + block.x |= ((candidateModeMemory[6] >> 1) & 1) << 1; + block.x |= ((candidateModeMemory[6] >> 2) & 1) << 2; + block.x |= ((candidateModeMemory[6] >> 3) & 1) << 3; + block.x |= ((candidateModeMemory[6] >> 4) & 1) << 4; + block.x |= ((endPoint[0][0].r >> 0) & 1) << 5; + block.x |= ((endPoint[0][0].r >> 1) & 1) << 6; + block.x |= ((endPoint[0][0].r >> 2) & 1) << 7; + block.x |= ((endPoint[0][0].r >> 3) & 1) << 8; + block.x |= ((endPoint[0][0].r >> 4) & 1) << 9; + block.x |= ((endPoint[0][0].r >> 5) & 1) << 10; + block.x |= ((endPoint[0][0].r >> 6) & 1) << 11; + block.x |= ((endPoint[0][0].r >> 7) & 1) << 12; + block.x |= ((endPoint[1][1].g >> 4) & 1) << 13; + block.x |= ((endPoint[1][0].b >> 4) & 1) << 14; + block.x |= ((endPoint[0][0].g >> 0) & 1) << 15; + block.x |= ((endPoint[0][0].g >> 1) & 1) << 16; + block.x |= ((endPoint[0][0].g >> 2) & 1) << 17; + block.x |= ((endPoint[0][0].g >> 3) & 1) << 18; + block.x |= ((endPoint[0][0].g >> 4) & 1) << 19; + block.x |= ((endPoint[0][0].g >> 5) & 1) << 20; + block.x |= ((endPoint[0][0].g >> 6) & 1) << 21; + block.x |= ((endPoint[0][0].g >> 7) & 1) << 22; + block.x |= ((endPoint[1][1].b >> 2) & 1) << 23; + block.x |= ((endPoint[1][0].g >> 4) & 1) << 24; + block.x |= ((endPoint[0][0].b >> 0) & 1) << 25; + block.x |= ((endPoint[0][0].b >> 1) & 1) << 26; + block.x |= ((endPoint[0][0].b >> 2) & 1) << 27; + block.x |= ((endPoint[0][0].b >> 3) & 1) << 28; + block.x |= ((endPoint[0][0].b >> 4) & 1) << 29; + block.x |= ((endPoint[0][0].b >> 5) & 1) << 30; + block.x |= ((endPoint[0][0].b >> 6) & 1) << 31; + block.y |= ((endPoint[0][0].b >> 7) & 1) << 0; + block.y |= ((endPoint[1][1].b >> 3) & 1) << 1; + block.y |= ((endPoint[1][1].b >> 4) & 1) << 2; + block.y |= ((endPoint[0][1].r >> 0) & 1) << 3; + block.y |= ((endPoint[0][1].r >> 1) & 1) << 4; + block.y |= ((endPoint[0][1].r >> 2) & 1) << 5; + block.y |= ((endPoint[0][1].r >> 3) & 1) << 6; + block.y |= ((endPoint[0][1].r >> 4) & 1) << 7; + block.y |= ((endPoint[0][1].r >> 5) & 1) << 8; + block.y |= ((endPoint[1][0].g >> 0) & 1) << 9; + block.y |= ((endPoint[1][0].g >> 1) & 1) << 10; + block.y |= ((endPoint[1][0].g >> 2) & 1) << 11; + block.y |= ((endPoint[1][0].g >> 3) & 1) << 12; + block.y |= ((endPoint[0][1].g >> 0) & 1) << 13; + block.y |= ((endPoint[0][1].g >> 1) & 1) << 14; + block.y |= ((endPoint[0][1].g >> 2) & 1) << 15; + block.y |= ((endPoint[0][1].g >> 3) & 1) << 16; + block.y |= ((endPoint[0][1].g >> 4) & 1) << 17; + block.y |= ((endPoint[1][1].b >> 0) & 1) << 18; + block.y |= ((endPoint[1][1].g >> 0) & 1) << 19; + block.y |= ((endPoint[1][1].g >> 1) & 1) << 20; + block.y |= ((endPoint[1][1].g >> 2) & 1) << 21; + block.y |= ((endPoint[1][1].g >> 3) & 1) << 22; + block.y |= ((endPoint[0][1].b >> 0) & 1) << 23; + block.y |= ((endPoint[0][1].b >> 1) & 1) << 24; + block.y |= ((endPoint[0][1].b >> 2) & 1) << 25; + block.y |= ((endPoint[0][1].b >> 3) & 1) << 26; + block.y |= ((endPoint[0][1].b >> 4) & 1) << 27; + block.y |= ((endPoint[1][1].b >> 1) & 1) << 28; + block.y |= ((endPoint[1][0].b >> 0) & 1) << 29; + block.y |= ((endPoint[1][0].b >> 1) & 1) << 30; + block.y |= ((endPoint[1][0].b >> 2) & 1) << 31; + block.z |= ((endPoint[1][0].b >> 3) & 1) << 0; + block.z |= ((endPoint[1][0].r >> 0) & 1) << 1; + block.z |= ((endPoint[1][0].r >> 1) & 1) << 2; + block.z |= ((endPoint[1][0].r >> 2) & 1) << 3; + block.z |= ((endPoint[1][0].r >> 3) & 1) << 4; + block.z |= ((endPoint[1][0].r >> 4) & 1) << 5; + block.z |= ((endPoint[1][0].r >> 5) & 1) << 6; + block.z |= ((endPoint[1][1].r >> 0) & 1) << 7; + block.z |= ((endPoint[1][1].r >> 1) & 1) << 8; + block.z |= ((endPoint[1][1].r >> 2) & 1) << 9; + block.z |= ((endPoint[1][1].r >> 3) & 1) << 10; + block.z |= ((endPoint[1][1].r >> 4) & 1) << 11; + block.z |= ((endPoint[1][1].r >> 5) & 1) << 12; + block.z |= ((partition_index >> 0) & 1) << 13; + block.z |= ((partition_index >> 1) & 1) << 14; + block.z |= ((partition_index >> 2) & 1) << 15; + block.z |= ((partition_index >> 3) & 1) << 16; + block.z |= ((partition_index >> 4) & 1) << 17; + } + else if ( mode_type == candidateModeFlag[7]) + { + /*block.x = candidateModeMemory[7]; + block.x |= ( ( endPoint[0][0].r << 5 ) & 0x00001FE0 ) | ( ( endPoint[0][0].g << 15 ) & 0x007F8000 ) | ( ( endPoint[0][0].b << 25 ) & 0xFE000000 ); + block.y |= ( endPoint[0][0].b >> 7 ) & 0x00000001; + block.y |= ( ( endPoint[0][1].r << 3 ) & 0x000000F8 ) | ( ( endPoint[0][1].g << 13 ) & 0x0007E000 ) | ( ( endPoint[0][1].b << 23 ) & 0x0F800000 ); + block.x |= ( ( endPoint[1][0].g << 20 ) & 0x01000000 ) | ( ( endPoint[1][0].b << 10 ) & 0x00004000 ); + block.x |= ( ( endPoint[1][0].g << 18 ) & 0x00800000 ); + block.x |= ( ( endPoint[1][1].b << 13 ) & 0x00002000 ); + block.yz |= ( endPoint[1][0].gr << uint2(9, 1) ) & uint2(0x00001E00, 0x0000003E); + block.yz |= ( endPoint[1][1].gr << uint2(19, 7) ) & uint2(0x00780000, 0x00000F80); + block.y |= ( endPoint[1][0].b << 29 ) & 0xE0000000; + block.y |= ( ( endPoint[1][1].g >> 4 ) & 0x00000002 ) | ( ( endPoint[1][1].g << 4 ) & 0x00000100 ) | ( ( endPoint[1][1].b >> 2 ) & 0x00000004 ); + block.y |= ( endPoint[1][1].b << 27 ) & 0x10000000; + block.z |= ( endPoint[1][0].b >> 3 ) & 0x00000001; + block.z |= ( ( endPoint[1][1].b << 9 ) & 0x00001000 ) | ( ( endPoint[1][1].b << 4 ) & 0x00000040 );*/ + + block.x |= ((candidateModeMemory[7] >> 0) & 1) << 0; + block.x |= ((candidateModeMemory[7] >> 1) & 1) << 1; + block.x |= ((candidateModeMemory[7] >> 2) & 1) << 2; + block.x |= ((candidateModeMemory[7] >> 3) & 1) << 3; + block.x |= ((candidateModeMemory[7] >> 4) & 1) << 4; + block.x |= ((endPoint[0][0].r >> 0) & 1) << 5; + block.x |= ((endPoint[0][0].r >> 1) & 1) << 6; + block.x |= ((endPoint[0][0].r >> 2) & 1) << 7; + block.x |= ((endPoint[0][0].r >> 3) & 1) << 8; + block.x |= ((endPoint[0][0].r >> 4) & 1) << 9; + block.x |= ((endPoint[0][0].r >> 5) & 1) << 10; + block.x |= ((endPoint[0][0].r >> 6) & 1) << 11; + block.x |= ((endPoint[0][0].r >> 7) & 1) << 12; + block.x |= ((endPoint[1][1].b >> 0) & 1) << 13; + block.x |= ((endPoint[1][0].b >> 4) & 1) << 14; + block.x |= ((endPoint[0][0].g >> 0) & 1) << 15; + block.x |= ((endPoint[0][0].g >> 1) & 1) << 16; + block.x |= ((endPoint[0][0].g >> 2) & 1) << 17; + block.x |= ((endPoint[0][0].g >> 3) & 1) << 18; + block.x |= ((endPoint[0][0].g >> 4) & 1) << 19; + block.x |= ((endPoint[0][0].g >> 5) & 1) << 20; + block.x |= ((endPoint[0][0].g >> 6) & 1) << 21; + block.x |= ((endPoint[0][0].g >> 7) & 1) << 22; + block.x |= ((endPoint[1][0].g >> 5) & 1) << 23; + block.x |= ((endPoint[1][0].g >> 4) & 1) << 24; + block.x |= ((endPoint[0][0].b >> 0) & 1) << 25; + block.x |= ((endPoint[0][0].b >> 1) & 1) << 26; + block.x |= ((endPoint[0][0].b >> 2) & 1) << 27; + block.x |= ((endPoint[0][0].b >> 3) & 1) << 28; + block.x |= ((endPoint[0][0].b >> 4) & 1) << 29; + block.x |= ((endPoint[0][0].b >> 5) & 1) << 30; + block.x |= ((endPoint[0][0].b >> 6) & 1) << 31; + block.y |= ((endPoint[0][0].b >> 7) & 1) << 0; + block.y |= ((endPoint[1][1].g >> 5) & 1) << 1; + block.y |= ((endPoint[1][1].b >> 4) & 1) << 2; + block.y |= ((endPoint[0][1].r >> 0) & 1) << 3; + block.y |= ((endPoint[0][1].r >> 1) & 1) << 4; + block.y |= ((endPoint[0][1].r >> 2) & 1) << 5; + block.y |= ((endPoint[0][1].r >> 3) & 1) << 6; + block.y |= ((endPoint[0][1].r >> 4) & 1) << 7; + block.y |= ((endPoint[1][1].g >> 4) & 1) << 8; + block.y |= ((endPoint[1][0].g >> 0) & 1) << 9; + block.y |= ((endPoint[1][0].g >> 1) & 1) << 10; + block.y |= ((endPoint[1][0].g >> 2) & 1) << 11; + block.y |= ((endPoint[1][0].g >> 3) & 1) << 12; + block.y |= ((endPoint[0][1].g >> 0) & 1) << 13; + block.y |= ((endPoint[0][1].g >> 1) & 1) << 14; + block.y |= ((endPoint[0][1].g >> 2) & 1) << 15; + block.y |= ((endPoint[0][1].g >> 3) & 1) << 16; + block.y |= ((endPoint[0][1].g >> 4) & 1) << 17; + block.y |= ((endPoint[0][1].g >> 5) & 1) << 18; + block.y |= ((endPoint[1][1].g >> 0) & 1) << 19; + block.y |= ((endPoint[1][1].g >> 1) & 1) << 20; + block.y |= ((endPoint[1][1].g >> 2) & 1) << 21; + block.y |= ((endPoint[1][1].g >> 3) & 1) << 22; + block.y |= ((endPoint[0][1].b >> 0) & 1) << 23; + block.y |= ((endPoint[0][1].b >> 1) & 1) << 24; + block.y |= ((endPoint[0][1].b >> 2) & 1) << 25; + block.y |= ((endPoint[0][1].b >> 3) & 1) << 26; + block.y |= ((endPoint[0][1].b >> 4) & 1) << 27; + block.y |= ((endPoint[1][1].b >> 1) & 1) << 28; + block.y |= ((endPoint[1][0].b >> 0) & 1) << 29; + block.y |= ((endPoint[1][0].b >> 1) & 1) << 30; + block.y |= ((endPoint[1][0].b >> 2) & 1) << 31; + block.z |= ((endPoint[1][0].b >> 3) & 1) << 0; + block.z |= ((endPoint[1][0].r >> 0) & 1) << 1; + block.z |= ((endPoint[1][0].r >> 1) & 1) << 2; + block.z |= ((endPoint[1][0].r >> 2) & 1) << 3; + block.z |= ((endPoint[1][0].r >> 3) & 1) << 4; + block.z |= ((endPoint[1][0].r >> 4) & 1) << 5; + block.z |= ((endPoint[1][1].b >> 2) & 1) << 6; + block.z |= ((endPoint[1][1].r >> 0) & 1) << 7; + block.z |= ((endPoint[1][1].r >> 1) & 1) << 8; + block.z |= ((endPoint[1][1].r >> 2) & 1) << 9; + block.z |= ((endPoint[1][1].r >> 3) & 1) << 10; + block.z |= ((endPoint[1][1].r >> 4) & 1) << 11; + block.z |= ((endPoint[1][1].b >> 3) & 1) << 12; + block.z |= ((partition_index >> 0) & 1) << 13; + block.z |= ((partition_index >> 1) & 1) << 14; + block.z |= ((partition_index >> 2) & 1) << 15; + block.z |= ((partition_index >> 3) & 1) << 16; + block.z |= ((partition_index >> 4) & 1) << 17; + } + else if ( mode_type == candidateModeFlag[8]) + { + /*block.x = candidateModeMemory[8]; + block.x |= ( ( endPoint[0][0].r << 5 ) & 0x00001FE0 ) | ( ( endPoint[0][0].g << 15 ) & 0x007F8000 ) | ( ( endPoint[0][0].b << 25 ) & 0xFE000000 ); + block.y |= ( endPoint[0][0].b >> 7 ) & 0x00000001; + block.y |= ( ( endPoint[0][1].r << 3 ) & 0x000000F8 ) | ( ( endPoint[0][1].g << 13 ) & 0x0003E000 ) | ( ( endPoint[0][1].b << 23 ) & 0x1F800000 ); + block.x |= ( ( endPoint[1][0].g << 20 ) & 0x01000000 ) | ( ( endPoint[1][0].b << 10 ) & 0x00004000 ); + block.x |= ( ( endPoint[1][0].b << 18 ) & 0x00800000 ); + block.x |= ( endPoint[1][1].b << 12 ) & 0x00002000; + block.y |= ( endPoint[1][0].b << 29 ) & 0xE0000000; + block.y |= ( ( endPoint[1][1].g << 4 ) & 0x00000100 ) | ( ( endPoint[1][1].b >> 4 ) & 0x00000002 ) | ( ( endPoint[1][1].b >> 2 ) & 0x00000004 ); + block.yz |= ( endPoint[1][0].gr << uint2(9, 1) ) & uint2(0x00001E00, 0x0000003E); + block.yz |= ( endPoint[1][1].gr << uint2(19, 7) ) & uint2(0x00780000, 0x00000F80); + block.y |= ( endPoint[1][1].b << 18 ) & 0x00040000; + block.z |= ( endPoint[1][0].b >> 3 ) & 0x00000001; + block.z |= ( ( endPoint[1][1].b << 9 ) & 0x00001000 ) | ( ( endPoint[1][1].b << 4 ) & 0x00000040 );*/ + + block.x |= ((candidateModeMemory[8] >> 0) & 1) << 0; + block.x |= ((candidateModeMemory[8] >> 1) & 1) << 1; + block.x |= ((candidateModeMemory[8] >> 2) & 1) << 2; + block.x |= ((candidateModeMemory[8] >> 3) & 1) << 3; + block.x |= ((candidateModeMemory[8] >> 4) & 1) << 4; + block.x |= ((endPoint[0][0].r >> 0) & 1) << 5; + block.x |= ((endPoint[0][0].r >> 1) & 1) << 6; + block.x |= ((endPoint[0][0].r >> 2) & 1) << 7; + block.x |= ((endPoint[0][0].r >> 3) & 1) << 8; + block.x |= ((endPoint[0][0].r >> 4) & 1) << 9; + block.x |= ((endPoint[0][0].r >> 5) & 1) << 10; + block.x |= ((endPoint[0][0].r >> 6) & 1) << 11; + block.x |= ((endPoint[0][0].r >> 7) & 1) << 12; + block.x |= ((endPoint[1][1].b >> 1) & 1) << 13; + block.x |= ((endPoint[1][0].b >> 4) & 1) << 14; + block.x |= ((endPoint[0][0].g >> 0) & 1) << 15; + block.x |= ((endPoint[0][0].g >> 1) & 1) << 16; + block.x |= ((endPoint[0][0].g >> 2) & 1) << 17; + block.x |= ((endPoint[0][0].g >> 3) & 1) << 18; + block.x |= ((endPoint[0][0].g >> 4) & 1) << 19; + block.x |= ((endPoint[0][0].g >> 5) & 1) << 20; + block.x |= ((endPoint[0][0].g >> 6) & 1) << 21; + block.x |= ((endPoint[0][0].g >> 7) & 1) << 22; + block.x |= ((endPoint[1][0].b >> 5) & 1) << 23; + block.x |= ((endPoint[1][0].g >> 4) & 1) << 24; + block.x |= ((endPoint[0][0].b >> 0) & 1) << 25; + block.x |= ((endPoint[0][0].b >> 1) & 1) << 26; + block.x |= ((endPoint[0][0].b >> 2) & 1) << 27; + block.x |= ((endPoint[0][0].b >> 3) & 1) << 28; + block.x |= ((endPoint[0][0].b >> 4) & 1) << 29; + block.x |= ((endPoint[0][0].b >> 5) & 1) << 30; + block.x |= ((endPoint[0][0].b >> 6) & 1) << 31; + block.y |= ((endPoint[0][0].b >> 7) & 1) << 0; + block.y |= ((endPoint[1][1].b >> 5) & 1) << 1; + block.y |= ((endPoint[1][1].b >> 4) & 1) << 2; + block.y |= ((endPoint[0][1].r >> 0) & 1) << 3; + block.y |= ((endPoint[0][1].r >> 1) & 1) << 4; + block.y |= ((endPoint[0][1].r >> 2) & 1) << 5; + block.y |= ((endPoint[0][1].r >> 3) & 1) << 6; + block.y |= ((endPoint[0][1].r >> 4) & 1) << 7; + block.y |= ((endPoint[1][1].g >> 4) & 1) << 8; + block.y |= ((endPoint[1][0].g >> 0) & 1) << 9; + block.y |= ((endPoint[1][0].g >> 1) & 1) << 10; + block.y |= ((endPoint[1][0].g >> 2) & 1) << 11; + block.y |= ((endPoint[1][0].g >> 3) & 1) << 12; + block.y |= ((endPoint[0][1].g >> 0) & 1) << 13; + block.y |= ((endPoint[0][1].g >> 1) & 1) << 14; + block.y |= ((endPoint[0][1].g >> 2) & 1) << 15; + block.y |= ((endPoint[0][1].g >> 3) & 1) << 16; + block.y |= ((endPoint[0][1].g >> 4) & 1) << 17; + block.y |= ((endPoint[1][1].b >> 0) & 1) << 18; + block.y |= ((endPoint[1][1].g >> 0) & 1) << 19; + block.y |= ((endPoint[1][1].g >> 1) & 1) << 20; + block.y |= ((endPoint[1][1].g >> 2) & 1) << 21; + block.y |= ((endPoint[1][1].g >> 3) & 1) << 22; + block.y |= ((endPoint[0][1].b >> 0) & 1) << 23; + block.y |= ((endPoint[0][1].b >> 1) & 1) << 24; + block.y |= ((endPoint[0][1].b >> 2) & 1) << 25; + block.y |= ((endPoint[0][1].b >> 3) & 1) << 26; + block.y |= ((endPoint[0][1].b >> 4) & 1) << 27; + block.y |= ((endPoint[0][1].b >> 5) & 1) << 28; + block.y |= ((endPoint[1][0].b >> 0) & 1) << 29; + block.y |= ((endPoint[1][0].b >> 1) & 1) << 30; + block.y |= ((endPoint[1][0].b >> 2) & 1) << 31; + block.z |= ((endPoint[1][0].b >> 3) & 1) << 0; + block.z |= ((endPoint[1][0].r >> 0) & 1) << 1; + block.z |= ((endPoint[1][0].r >> 1) & 1) << 2; + block.z |= ((endPoint[1][0].r >> 2) & 1) << 3; + block.z |= ((endPoint[1][0].r >> 3) & 1) << 4; + block.z |= ((endPoint[1][0].r >> 4) & 1) << 5; + block.z |= ((endPoint[1][1].b >> 2) & 1) << 6; + block.z |= ((endPoint[1][1].r >> 0) & 1) << 7; + block.z |= ((endPoint[1][1].r >> 1) & 1) << 8; + block.z |= ((endPoint[1][1].r >> 2) & 1) << 9; + block.z |= ((endPoint[1][1].r >> 3) & 1) << 10; + block.z |= ((endPoint[1][1].r >> 4) & 1) << 11; + block.z |= ((endPoint[1][1].b >> 3) & 1) << 12; + block.z |= ((partition_index >> 0) & 1) << 13; + block.z |= ((partition_index >> 1) & 1) << 14; + block.z |= ((partition_index >> 2) & 1) << 15; + block.z |= ((partition_index >> 3) & 1) << 16; + block.z |= ((partition_index >> 4) & 1) << 17; + } + else if ( mode_type == candidateModeFlag[9]) + { + /*block.x = candidateModeMemory[9]; + block.x |= ( ( endPoint[0][0].r << 5 ) & 0x000007E0 ) | ( ( endPoint[0][0].g << 15 ) & 0x001F8000 ) | ( ( endPoint[0][0].b << 25 ) & 0x7E000000 ); + block.y |= ( ( endPoint[0][1].r << 3 ) & 0x000001F8 ) | ( ( endPoint[0][1].g << 13 ) & 0x0007E000 ) | ( ( endPoint[0][1].b << 23 ) & 0x1F800000 ); + block.x |= ( ( endPoint[1][0].g << 16 ) & 0x00200000 ) | ( ( endPoint[1][0].g << 20 ) & 0x01000000 ); + block.x |= ( ( endPoint[1][0].b << 17 ) & 0x00400000 ) | ( ( endPoint[1][0].b << 10 ) & 0x00004000 ); + block.x |= ( ( endPoint[1][1].b << 21 ) & 0x00800000 ) | ( ( endPoint[1][1].b << 12 ) & 0x00003000 ); + block.x |= ( ( endPoint[1][1].g << 26 ) & 0x80000000 ) | ( ( endPoint[1][1].g << 7 ) & 0x00000800 ); + block.yz |= ( endPoint[1][0].gr << uint2(9, 1) ) & uint2(0x00001E00, 0x0000007E); + block.yz |= ( endPoint[1][1].gr << uint2(19, 7) ) & uint2(0x00780000, 0x00001F80); + block.y |= ( endPoint[1][0].b << 29 ) & 0xE0000000; + block.y |= ( ( endPoint[1][1].b >> 4 ) & 0x00000002 ) | ( ( endPoint[1][1].b >> 2 ) & 0x00000004 ) | ( ( endPoint[1][1].b >> 3 ) & 0x00000001 ); + block.z |= ( endPoint[1][0].b >> 3 ) & 0x00000001;*/ + + block.x |= ((candidateModeMemory[9] >> 0) & 1) << 0; + block.x |= ((candidateModeMemory[9] >> 1) & 1) << 1; + block.x |= ((candidateModeMemory[9] >> 2) & 1) << 2; + block.x |= ((candidateModeMemory[9] >> 3) & 1) << 3; + block.x |= ((candidateModeMemory[9] >> 4) & 1) << 4; + block.x |= ((endPoint[0][0].r >> 0) & 1) << 5; + block.x |= ((endPoint[0][0].r >> 1) & 1) << 6; + block.x |= ((endPoint[0][0].r >> 2) & 1) << 7; + block.x |= ((endPoint[0][0].r >> 3) & 1) << 8; + block.x |= ((endPoint[0][0].r >> 4) & 1) << 9; + block.x |= ((endPoint[0][0].r >> 5) & 1) << 10; + block.x |= ((endPoint[1][1].g >> 4) & 1) << 11; + block.x |= ((endPoint[1][1].b >> 0) & 1) << 12; + block.x |= ((endPoint[1][1].b >> 1) & 1) << 13; + block.x |= ((endPoint[1][0].b >> 4) & 1) << 14; + block.x |= ((endPoint[0][0].g >> 0) & 1) << 15; + block.x |= ((endPoint[0][0].g >> 1) & 1) << 16; + block.x |= ((endPoint[0][0].g >> 2) & 1) << 17; + block.x |= ((endPoint[0][0].g >> 3) & 1) << 18; + block.x |= ((endPoint[0][0].g >> 4) & 1) << 19; + block.x |= ((endPoint[0][0].g >> 5) & 1) << 20; + block.x |= ((endPoint[1][0].g >> 5) & 1) << 21; + block.x |= ((endPoint[1][0].b >> 5) & 1) << 22; + block.x |= ((endPoint[1][1].b >> 2) & 1) << 23; + block.x |= ((endPoint[1][0].g >> 4) & 1) << 24; + block.x |= ((endPoint[0][0].b >> 0) & 1) << 25; + block.x |= ((endPoint[0][0].b >> 1) & 1) << 26; + block.x |= ((endPoint[0][0].b >> 2) & 1) << 27; + block.x |= ((endPoint[0][0].b >> 3) & 1) << 28; + block.x |= ((endPoint[0][0].b >> 4) & 1) << 29; + block.x |= ((endPoint[0][0].b >> 5) & 1) << 30; + block.x |= ((endPoint[1][1].g >> 5) & 1) << 31; + block.y |= ((endPoint[1][1].b >> 3) & 1) << 0; + block.y |= ((endPoint[1][1].b >> 5) & 1) << 1; + block.y |= ((endPoint[1][1].b >> 4) & 1) << 2; + block.y |= ((endPoint[0][1].r >> 0) & 1) << 3; + block.y |= ((endPoint[0][1].r >> 1) & 1) << 4; + block.y |= ((endPoint[0][1].r >> 2) & 1) << 5; + block.y |= ((endPoint[0][1].r >> 3) & 1) << 6; + block.y |= ((endPoint[0][1].r >> 4) & 1) << 7; + block.y |= ((endPoint[0][1].r >> 5) & 1) << 8; + block.y |= ((endPoint[1][0].g >> 0) & 1) << 9; + block.y |= ((endPoint[1][0].g >> 1) & 1) << 10; + block.y |= ((endPoint[1][0].g >> 2) & 1) << 11; + block.y |= ((endPoint[1][0].g >> 3) & 1) << 12; + block.y |= ((endPoint[0][1].g >> 0) & 1) << 13; + block.y |= ((endPoint[0][1].g >> 1) & 1) << 14; + block.y |= ((endPoint[0][1].g >> 2) & 1) << 15; + block.y |= ((endPoint[0][1].g >> 3) & 1) << 16; + block.y |= ((endPoint[0][1].g >> 4) & 1) << 17; + block.y |= ((endPoint[0][1].g >> 5) & 1) << 18; + block.y |= ((endPoint[1][1].g >> 0) & 1) << 19; + block.y |= ((endPoint[1][1].g >> 1) & 1) << 20; + block.y |= ((endPoint[1][1].g >> 2) & 1) << 21; + block.y |= ((endPoint[1][1].g >> 3) & 1) << 22; + block.y |= ((endPoint[0][1].b >> 0) & 1) << 23; + block.y |= ((endPoint[0][1].b >> 1) & 1) << 24; + block.y |= ((endPoint[0][1].b >> 2) & 1) << 25; + block.y |= ((endPoint[0][1].b >> 3) & 1) << 26; + block.y |= ((endPoint[0][1].b >> 4) & 1) << 27; + block.y |= ((endPoint[0][1].b >> 5) & 1) << 28; + block.y |= ((endPoint[1][0].b >> 0) & 1) << 29; + block.y |= ((endPoint[1][0].b >> 1) & 1) << 30; + block.y |= ((endPoint[1][0].b >> 2) & 1) << 31; + block.z |= ((endPoint[1][0].b >> 3) & 1) << 0; + block.z |= ((endPoint[1][0].r >> 0) & 1) << 1; + block.z |= ((endPoint[1][0].r >> 1) & 1) << 2; + block.z |= ((endPoint[1][0].r >> 2) & 1) << 3; + block.z |= ((endPoint[1][0].r >> 3) & 1) << 4; + block.z |= ((endPoint[1][0].r >> 4) & 1) << 5; + block.z |= ((endPoint[1][0].r >> 5) & 1) << 6; + block.z |= ((endPoint[1][1].r >> 0) & 1) << 7; + block.z |= ((endPoint[1][1].r >> 1) & 1) << 8; + block.z |= ((endPoint[1][1].r >> 2) & 1) << 9; + block.z |= ((endPoint[1][1].r >> 3) & 1) << 10; + block.z |= ((endPoint[1][1].r >> 4) & 1) << 11; + block.z |= ((endPoint[1][1].r >> 5) & 1) << 12; + block.z |= ((partition_index >> 0) & 1) << 13; + block.z |= ((partition_index >> 1) & 1) << 14; + block.z |= ((partition_index >> 2) & 1) << 15; + block.z |= ((partition_index >> 3) & 1) << 16; + block.z |= ((partition_index >> 4) & 1) << 17; + } +} +void block_package( inout uint4 block, int2x3 endPoint, uint mode_type ) // for mode 11 - 14 +{ + /*block.x = ( ( endPoint[0].r << 5 ) & 0x00007FE0 ) | ( ( endPoint[0].g << 15 ) & 0x01FF8000 ) | ( ( endPoint[0].b << 25 ) & 0xFE000000 ); + block.y |= ( endPoint[0].b >> 7 ) & 0x00000007;*/ + + block.xy = 0; + block.z &= 0xFFFFFFFE; + + + if ( mode_type == candidateModeFlag[10]) + { + /* block.x |= candidateModeMemory[10]; + block.y |= ( ( endPoint[1].r << 3 ) & 0x00001FF8 ) | ( ( endPoint[1].g << 13 ) & 0x007FE000 ) | ( ( endPoint[1].b << 23 ) & 0xFF800000 ); + block.z |= ( endPoint[1].b >> 9 ) & 0x00000001;*/ + + block.x |= ((candidateModeMemory[10] >> 0) & 1) << 0; + block.x |= ((candidateModeMemory[10] >> 1) & 1) << 1; + block.x |= ((candidateModeMemory[10] >> 2) & 1) << 2; + block.x |= ((candidateModeMemory[10] >> 3) & 1) << 3; + block.x |= ((candidateModeMemory[10] >> 4) & 1) << 4; + block.x |= ((endPoint[0].r >> 0) & 1) << 5; + block.x |= ((endPoint[0].r >> 1) & 1) << 6; + block.x |= ((endPoint[0].r >> 2) & 1) << 7; + block.x |= ((endPoint[0].r >> 3) & 1) << 8; + block.x |= ((endPoint[0].r >> 4) & 1) << 9; + block.x |= ((endPoint[0].r >> 5) & 1) << 10; + block.x |= ((endPoint[0].r >> 6) & 1) << 11; + block.x |= ((endPoint[0].r >> 7) & 1) << 12; + block.x |= ((endPoint[0].r >> 8) & 1) << 13; + block.x |= ((endPoint[0].r >> 9) & 1) << 14; + block.x |= ((endPoint[0].g >> 0) & 1) << 15; + block.x |= ((endPoint[0].g >> 1) & 1) << 16; + block.x |= ((endPoint[0].g >> 2) & 1) << 17; + block.x |= ((endPoint[0].g >> 3) & 1) << 18; + block.x |= ((endPoint[0].g >> 4) & 1) << 19; + block.x |= ((endPoint[0].g >> 5) & 1) << 20; + block.x |= ((endPoint[0].g >> 6) & 1) << 21; + block.x |= ((endPoint[0].g >> 7) & 1) << 22; + block.x |= ((endPoint[0].g >> 8) & 1) << 23; + block.x |= ((endPoint[0].g >> 9) & 1) << 24; + block.x |= ((endPoint[0].b >> 0) & 1) << 25; + block.x |= ((endPoint[0].b >> 1) & 1) << 26; + block.x |= ((endPoint[0].b >> 2) & 1) << 27; + block.x |= ((endPoint[0].b >> 3) & 1) << 28; + block.x |= ((endPoint[0].b >> 4) & 1) << 29; + block.x |= ((endPoint[0].b >> 5) & 1) << 30; + block.x |= ((endPoint[0].b >> 6) & 1) << 31; + block.y |= ((endPoint[0].b >> 7) & 1) << 0; + block.y |= ((endPoint[0].b >> 8) & 1) << 1; + block.y |= ((endPoint[0].b >> 9) & 1) << 2; + block.y |= ((endPoint[1].r >> 0) & 1) << 3; + block.y |= ((endPoint[1].r >> 1) & 1) << 4; + block.y |= ((endPoint[1].r >> 2) & 1) << 5; + block.y |= ((endPoint[1].r >> 3) & 1) << 6; + block.y |= ((endPoint[1].r >> 4) & 1) << 7; + block.y |= ((endPoint[1].r >> 5) & 1) << 8; + block.y |= ((endPoint[1].r >> 6) & 1) << 9; + block.y |= ((endPoint[1].r >> 7) & 1) << 10; + block.y |= ((endPoint[1].r >> 8) & 1) << 11; + block.y |= ((endPoint[1].r >> 9) & 1) << 12; + block.y |= ((endPoint[1].g >> 0) & 1) << 13; + block.y |= ((endPoint[1].g >> 1) & 1) << 14; + block.y |= ((endPoint[1].g >> 2) & 1) << 15; + block.y |= ((endPoint[1].g >> 3) & 1) << 16; + block.y |= ((endPoint[1].g >> 4) & 1) << 17; + block.y |= ((endPoint[1].g >> 5) & 1) << 18; + block.y |= ((endPoint[1].g >> 6) & 1) << 19; + block.y |= ((endPoint[1].g >> 7) & 1) << 20; + block.y |= ((endPoint[1].g >> 8) & 1) << 21; + block.y |= ((endPoint[1].g >> 9) & 1) << 22; + block.y |= ((endPoint[1].b >> 0) & 1) << 23; + block.y |= ((endPoint[1].b >> 1) & 1) << 24; + block.y |= ((endPoint[1].b >> 2) & 1) << 25; + block.y |= ((endPoint[1].b >> 3) & 1) << 26; + block.y |= ((endPoint[1].b >> 4) & 1) << 27; + block.y |= ((endPoint[1].b >> 5) & 1) << 28; + block.y |= ((endPoint[1].b >> 6) & 1) << 29; + block.y |= ((endPoint[1].b >> 7) & 1) << 30; + block.y |= ((endPoint[1].b >> 8) & 1) << 31; + block.z |= ((endPoint[1].b >> 9) & 1) << 0; + } + else if (mode_type == candidateModeFlag[11]) + { + /*block.x |= candidateModeMemory[11]; + block.y |= ( ( endPoint[0].r << 2 ) & 0x00001000 ) | ( ( endPoint[0].g << 12 ) & 0x00400000 ); + block.y |= ( ( endPoint[1].r << 3 ) & 0x00000FF8 ) | ( ( endPoint[1].g << 13 ) & 0x003FE000 ) | ( ( endPoint[1].b << 23 ) & 0xFF800000 ); + block.z |= ( endPoint[0].b >> 10 ) & 0x00000001;*/ + + block.x |= ((candidateModeMemory[11] >> 0) & 1) << 0; + block.x |= ((candidateModeMemory[11] >> 1) & 1) << 1; + block.x |= ((candidateModeMemory[11] >> 2) & 1) << 2; + block.x |= ((candidateModeMemory[11] >> 3) & 1) << 3; + block.x |= ((candidateModeMemory[11] >> 4) & 1) << 4; + block.x |= ((endPoint[0].r >> 0) & 1) << 5; + block.x |= ((endPoint[0].r >> 1) & 1) << 6; + block.x |= ((endPoint[0].r >> 2) & 1) << 7; + block.x |= ((endPoint[0].r >> 3) & 1) << 8; + block.x |= ((endPoint[0].r >> 4) & 1) << 9; + block.x |= ((endPoint[0].r >> 5) & 1) << 10; + block.x |= ((endPoint[0].r >> 6) & 1) << 11; + block.x |= ((endPoint[0].r >> 7) & 1) << 12; + block.x |= ((endPoint[0].r >> 8) & 1) << 13; + block.x |= ((endPoint[0].r >> 9) & 1) << 14; + block.x |= ((endPoint[0].g >> 0) & 1) << 15; + block.x |= ((endPoint[0].g >> 1) & 1) << 16; + block.x |= ((endPoint[0].g >> 2) & 1) << 17; + block.x |= ((endPoint[0].g >> 3) & 1) << 18; + block.x |= ((endPoint[0].g >> 4) & 1) << 19; + block.x |= ((endPoint[0].g >> 5) & 1) << 20; + block.x |= ((endPoint[0].g >> 6) & 1) << 21; + block.x |= ((endPoint[0].g >> 7) & 1) << 22; + block.x |= ((endPoint[0].g >> 8) & 1) << 23; + block.x |= ((endPoint[0].g >> 9) & 1) << 24; + block.x |= ((endPoint[0].b >> 0) & 1) << 25; + block.x |= ((endPoint[0].b >> 1) & 1) << 26; + block.x |= ((endPoint[0].b >> 2) & 1) << 27; + block.x |= ((endPoint[0].b >> 3) & 1) << 28; + block.x |= ((endPoint[0].b >> 4) & 1) << 29; + block.x |= ((endPoint[0].b >> 5) & 1) << 30; + block.x |= ((endPoint[0].b >> 6) & 1) << 31; + block.y |= ((endPoint[0].b >> 7) & 1) << 0; + block.y |= ((endPoint[0].b >> 8) & 1) << 1; + block.y |= ((endPoint[0].b >> 9) & 1) << 2; + block.y |= ((endPoint[1].r >> 0) & 1) << 3; + block.y |= ((endPoint[1].r >> 1) & 1) << 4; + block.y |= ((endPoint[1].r >> 2) & 1) << 5; + block.y |= ((endPoint[1].r >> 3) & 1) << 6; + block.y |= ((endPoint[1].r >> 4) & 1) << 7; + block.y |= ((endPoint[1].r >> 5) & 1) << 8; + block.y |= ((endPoint[1].r >> 6) & 1) << 9; + block.y |= ((endPoint[1].r >> 7) & 1) << 10; + block.y |= ((endPoint[1].r >> 8) & 1) << 11; + block.y |= ((endPoint[0].r >> 10) & 1) << 12; + block.y |= ((endPoint[1].g >> 0) & 1) << 13; + block.y |= ((endPoint[1].g >> 1) & 1) << 14; + block.y |= ((endPoint[1].g >> 2) & 1) << 15; + block.y |= ((endPoint[1].g >> 3) & 1) << 16; + block.y |= ((endPoint[1].g >> 4) & 1) << 17; + block.y |= ((endPoint[1].g >> 5) & 1) << 18; + block.y |= ((endPoint[1].g >> 6) & 1) << 19; + block.y |= ((endPoint[1].g >> 7) & 1) << 20; + block.y |= ((endPoint[1].g >> 8) & 1) << 21; + block.y |= ((endPoint[0].g >> 10) & 1) << 22; + block.y |= ((endPoint[1].b >> 0) & 1) << 23; + block.y |= ((endPoint[1].b >> 1) & 1) << 24; + block.y |= ((endPoint[1].b >> 2) & 1) << 25; + block.y |= ((endPoint[1].b >> 3) & 1) << 26; + block.y |= ((endPoint[1].b >> 4) & 1) << 27; + block.y |= ((endPoint[1].b >> 5) & 1) << 28; + block.y |= ((endPoint[1].b >> 6) & 1) << 29; + block.y |= ((endPoint[1].b >> 7) & 1) << 30; + block.y |= ((endPoint[1].b >> 8) & 1) << 31; + block.z |= ((endPoint[0].b >> 10) & 1) << 0; + } + else if (mode_type == candidateModeFlag[12])// violate the spec in [0].low + { + /*block.x |= candidateModeMemory[12]; + block.y |= ( ( endPoint[0].r << 2 ) & 0x00001000 ) | ( ( endPoint[0].g << 12 ) & 0x00400000 ); + block.y |= ( ( endPoint[0].r << 0 ) & 0x00000800 ) | ( ( endPoint[0].g << 10 ) & 0x00200000 ); + block.y |= ( endPoint[0].b << 20 ) & 0x80000000; + block.y |= ( ( endPoint[1].r << 3 ) & 0x000007F8 ) | ( ( endPoint[1].g << 13 ) & 0x001FE000 ) | ( ( endPoint[1].b << 23 ) & 0x7F800000 ); + block.z |= ( endPoint[0].b >> 10 ) & 0x00000001;*/ + + block.x |= ((candidateModeMemory[12] >> 0) & 1) << 0; + block.x |= ((candidateModeMemory[12] >> 1) & 1) << 1; + block.x |= ((candidateModeMemory[12] >> 2) & 1) << 2; + block.x |= ((candidateModeMemory[12] >> 3) & 1) << 3; + block.x |= ((candidateModeMemory[12] >> 4) & 1) << 4; + block.x |= ((endPoint[0].r >> 0) & 1) << 5; + block.x |= ((endPoint[0].r >> 1) & 1) << 6; + block.x |= ((endPoint[0].r >> 2) & 1) << 7; + block.x |= ((endPoint[0].r >> 3) & 1) << 8; + block.x |= ((endPoint[0].r >> 4) & 1) << 9; + block.x |= ((endPoint[0].r >> 5) & 1) << 10; + block.x |= ((endPoint[0].r >> 6) & 1) << 11; + block.x |= ((endPoint[0].r >> 7) & 1) << 12; + block.x |= ((endPoint[0].r >> 8) & 1) << 13; + block.x |= ((endPoint[0].r >> 9) & 1) << 14; + block.x |= ((endPoint[0].g >> 0) & 1) << 15; + block.x |= ((endPoint[0].g >> 1) & 1) << 16; + block.x |= ((endPoint[0].g >> 2) & 1) << 17; + block.x |= ((endPoint[0].g >> 3) & 1) << 18; + block.x |= ((endPoint[0].g >> 4) & 1) << 19; + block.x |= ((endPoint[0].g >> 5) & 1) << 20; + block.x |= ((endPoint[0].g >> 6) & 1) << 21; + block.x |= ((endPoint[0].g >> 7) & 1) << 22; + block.x |= ((endPoint[0].g >> 8) & 1) << 23; + block.x |= ((endPoint[0].g >> 9) & 1) << 24; + block.x |= ((endPoint[0].b >> 0) & 1) << 25; + block.x |= ((endPoint[0].b >> 1) & 1) << 26; + block.x |= ((endPoint[0].b >> 2) & 1) << 27; + block.x |= ((endPoint[0].b >> 3) & 1) << 28; + block.x |= ((endPoint[0].b >> 4) & 1) << 29; + block.x |= ((endPoint[0].b >> 5) & 1) << 30; + block.x |= ((endPoint[0].b >> 6) & 1) << 31; + block.y |= ((endPoint[0].b >> 7) & 1) << 0; + block.y |= ((endPoint[0].b >> 8) & 1) << 1; + block.y |= ((endPoint[0].b >> 9) & 1) << 2; + block.y |= ((endPoint[1].r >> 0) & 1) << 3; + block.y |= ((endPoint[1].r >> 1) & 1) << 4; + block.y |= ((endPoint[1].r >> 2) & 1) << 5; + block.y |= ((endPoint[1].r >> 3) & 1) << 6; + block.y |= ((endPoint[1].r >> 4) & 1) << 7; + block.y |= ((endPoint[1].r >> 5) & 1) << 8; + block.y |= ((endPoint[1].r >> 6) & 1) << 9; + block.y |= ((endPoint[1].r >> 7) & 1) << 10; + block.y |= ((endPoint[0].r >> 11) & 1) << 11; + block.y |= ((endPoint[0].r >> 10) & 1) << 12; + block.y |= ((endPoint[1].g >> 0) & 1) << 13; + block.y |= ((endPoint[1].g >> 1) & 1) << 14; + block.y |= ((endPoint[1].g >> 2) & 1) << 15; + block.y |= ((endPoint[1].g >> 3) & 1) << 16; + block.y |= ((endPoint[1].g >> 4) & 1) << 17; + block.y |= ((endPoint[1].g >> 5) & 1) << 18; + block.y |= ((endPoint[1].g >> 6) & 1) << 19; + block.y |= ((endPoint[1].g >> 7) & 1) << 20; + block.y |= ((endPoint[0].g >> 11) & 1) << 21; + block.y |= ((endPoint[0].g >> 10) & 1) << 22; + block.y |= ((endPoint[1].b >> 0) & 1) << 23; + block.y |= ((endPoint[1].b >> 1) & 1) << 24; + block.y |= ((endPoint[1].b >> 2) & 1) << 25; + block.y |= ((endPoint[1].b >> 3) & 1) << 26; + block.y |= ((endPoint[1].b >> 4) & 1) << 27; + block.y |= ((endPoint[1].b >> 5) & 1) << 28; + block.y |= ((endPoint[1].b >> 6) & 1) << 29; + block.y |= ((endPoint[1].b >> 7) & 1) << 30; + block.y |= ((endPoint[0].b >> 11) & 1) << 31; + block.z |= ((endPoint[0].b >> 10) & 1) << 0; + } + else if (mode_type == candidateModeFlag[13]) + { + /*block.x |= candidateModeMemory[13]; + block.y |= ( ( endPoint[0].r >> 8 ) & 0x00000080 ); + block.y |= ( ( endPoint[0].r >> 6 ) & 0x00000100 ); + block.y |= ( ( endPoint[0].r >> 4 ) & 0x00000200 ); + block.y |= ( ( endPoint[0].r >> 2 ) & 0x00000400 ); + block.y |= ( ( endPoint[0].r >> 0 ) & 0x00000800 ); + block.y |= ( ( endPoint[0].r << 2 ) & 0x00001000 ); + block.y |= ( ( endPoint[0].g << 2 ) & 0x00020000 ); + block.y |= ( ( endPoint[0].g << 4 ) & 0x00040000 ); + block.y |= ( ( endPoint[0].g << 6 ) & 0x00080000 ); + block.y |= ( ( endPoint[0].g << 8 ) & 0x00100000 ); + block.y |= ( ( endPoint[0].g << 10 ) & 0x00200000 ); + block.y |= ( ( endPoint[0].g << 12 ) & 0x00400000 ); + block.y |= ( ( endPoint[0].b << 12 ) & 0x08000000 ); + block.y |= ( ( endPoint[0].b << 14 ) & 0x10000000 ); + block.y |= ( ( endPoint[0].b << 16 ) & 0x20000000 ); + block.y |= ( ( endPoint[0].b << 18 ) & 0x40000000 ); + block.y |= ( ( endPoint[0].b << 20 ) & 0x80000000 ); + block.y |= ( ( endPoint[1].r << 3 ) & 0x00000078 ) | ( ( endPoint[1].g << 13 ) & 0x0001E000 ) | ( ( endPoint[1].b << 23 ) & 0x07800000 ); + block.z |= ( endPoint[0].b >> 10 ) & 0x00000001;*/ + + block.x |= ((candidateModeMemory[13] >> 0) & 1) << 0; + block.x |= ((candidateModeMemory[13] >> 1) & 1) << 1; + block.x |= ((candidateModeMemory[13] >> 2) & 1) << 2; + block.x |= ((candidateModeMemory[13] >> 3) & 1) << 3; + block.x |= ((candidateModeMemory[13] >> 4) & 1) << 4; + block.x |= ((endPoint[0].r >> 0) & 1) << 5; + block.x |= ((endPoint[0].r >> 1) & 1) << 6; + block.x |= ((endPoint[0].r >> 2) & 1) << 7; + block.x |= ((endPoint[0].r >> 3) & 1) << 8; + block.x |= ((endPoint[0].r >> 4) & 1) << 9; + block.x |= ((endPoint[0].r >> 5) & 1) << 10; + block.x |= ((endPoint[0].r >> 6) & 1) << 11; + block.x |= ((endPoint[0].r >> 7) & 1) << 12; + block.x |= ((endPoint[0].r >> 8) & 1) << 13; + block.x |= ((endPoint[0].r >> 9) & 1) << 14; + block.x |= ((endPoint[0].g >> 0) & 1) << 15; + block.x |= ((endPoint[0].g >> 1) & 1) << 16; + block.x |= ((endPoint[0].g >> 2) & 1) << 17; + block.x |= ((endPoint[0].g >> 3) & 1) << 18; + block.x |= ((endPoint[0].g >> 4) & 1) << 19; + block.x |= ((endPoint[0].g >> 5) & 1) << 20; + block.x |= ((endPoint[0].g >> 6) & 1) << 21; + block.x |= ((endPoint[0].g >> 7) & 1) << 22; + block.x |= ((endPoint[0].g >> 8) & 1) << 23; + block.x |= ((endPoint[0].g >> 9) & 1) << 24; + block.x |= ((endPoint[0].b >> 0) & 1) << 25; + block.x |= ((endPoint[0].b >> 1) & 1) << 26; + block.x |= ((endPoint[0].b >> 2) & 1) << 27; + block.x |= ((endPoint[0].b >> 3) & 1) << 28; + block.x |= ((endPoint[0].b >> 4) & 1) << 29; + block.x |= ((endPoint[0].b >> 5) & 1) << 30; + block.x |= ((endPoint[0].b >> 6) & 1) << 31; + block.y |= ((endPoint[0].b >> 7) & 1) << 0; + block.y |= ((endPoint[0].b >> 8) & 1) << 1; + block.y |= ((endPoint[0].b >> 9) & 1) << 2; + block.y |= ((endPoint[1].r >> 0) & 1) << 3; + block.y |= ((endPoint[1].r >> 1) & 1) << 4; + block.y |= ((endPoint[1].r >> 2) & 1) << 5; + block.y |= ((endPoint[1].r >> 3) & 1) << 6; + block.y |= ((endPoint[0].r >> 15) & 1) << 7; + block.y |= ((endPoint[0].r >> 14) & 1) << 8; + block.y |= ((endPoint[0].r >> 13) & 1) << 9; + block.y |= ((endPoint[0].r >> 12) & 1) << 10; + block.y |= ((endPoint[0].r >> 11) & 1) << 11; + block.y |= ((endPoint[0].r >> 10) & 1) << 12; + block.y |= ((endPoint[1].g >> 0) & 1) << 13; + block.y |= ((endPoint[1].g >> 1) & 1) << 14; + block.y |= ((endPoint[1].g >> 2) & 1) << 15; + block.y |= ((endPoint[1].g >> 3) & 1) << 16; + block.y |= ((endPoint[0].g >> 15) & 1) << 17; + block.y |= ((endPoint[0].g >> 14) & 1) << 18; + block.y |= ((endPoint[0].g >> 13) & 1) << 19; + block.y |= ((endPoint[0].g >> 12) & 1) << 20; + block.y |= ((endPoint[0].g >> 11) & 1) << 21; + block.y |= ((endPoint[0].g >> 10) & 1) << 22; + block.y |= ((endPoint[1].b >> 0) & 1) << 23; + block.y |= ((endPoint[1].b >> 1) & 1) << 24; + block.y |= ((endPoint[1].b >> 2) & 1) << 25; + block.y |= ((endPoint[1].b >> 3) & 1) << 26; + block.y |= ((endPoint[0].b >> 15) & 1) << 27; + block.y |= ((endPoint[0].b >> 14) & 1) << 28; + block.y |= ((endPoint[0].b >> 13) & 1) << 29; + block.y |= ((endPoint[0].b >> 12) & 1) << 30; + block.y |= ((endPoint[0].b >> 11) & 1) << 31; + block.z |= ((endPoint[0].b >> 10) & 1) << 0; + } +} diff --git a/tests/hlsl/dxsdk/BC6HBC7EncoderCS/Shaders/BC7Encode.hlsl b/tests/hlsl/dxsdk/BC6HBC7EncoderCS/Shaders/BC7Encode.hlsl new file mode 100644 index 000000000..6a57c3862 --- /dev/null +++ b/tests/hlsl/dxsdk/BC6HBC7EncoderCS/Shaders/BC7Encode.hlsl @@ -0,0 +1,1908 @@ +//TEST_IGNORE_FILE: +//-------------------------------------------------------------------------------------- +// File: BC7Encode.hlsl +// +// The Compute Shader for BC7 Encoder +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//#define REF_DEVICE + +#define CHAR_LENGTH 8 +#define NCHANNELS 4 +#define BC7_UNORM 98 +#define MAX_UINT 0xFFFFFFFF +#define MIN_UINT 0 + +static const uint candidateSectionBit[64] = //Associated to partition 0-63 +{ + 0xCCCC, 0x8888, 0xEEEE, 0xECC8, + 0xC880, 0xFEEC, 0xFEC8, 0xEC80, + 0xC800, 0xFFEC, 0xFE80, 0xE800, + 0xFFE8, 0xFF00, 0xFFF0, 0xF000, + 0xF710, 0x008E, 0x7100, 0x08CE, + 0x008C, 0x7310, 0x3100, 0x8CCE, + 0x088C, 0x3110, 0x6666, 0x366C, + 0x17E8, 0x0FF0, 0x718E, 0x399C, + 0xaaaa, 0xf0f0, 0x5a5a, 0x33cc, + 0x3c3c, 0x55aa, 0x9696, 0xa55a, + 0x73ce, 0x13c8, 0x324c, 0x3bdc, + 0x6996, 0xc33c, 0x9966, 0x660, + 0x272, 0x4e4, 0x4e40, 0x2720, + 0xc936, 0x936c, 0x39c6, 0x639c, + 0x9336, 0x9cc6, 0x817e, 0xe718, + 0xccf0, 0xfcc, 0x7744, 0xee22, +}; +static const uint candidateSectionBit2[64] = //Associated to partition 64-127 +{ + 0xaa685050, 0x6a5a5040, 0x5a5a4200, 0x5450a0a8, + 0xa5a50000, 0xa0a05050, 0x5555a0a0, 0x5a5a5050, + 0xaa550000, 0xaa555500, 0xaaaa5500, 0x90909090, + 0x94949494, 0xa4a4a4a4, 0xa9a59450, 0x2a0a4250, + 0xa5945040, 0x0a425054, 0xa5a5a500, 0x55a0a0a0, + 0xa8a85454, 0x6a6a4040, 0xa4a45000, 0x1a1a0500, + 0x0050a4a4, 0xaaa59090, 0x14696914, 0x69691400, + 0xa08585a0, 0xaa821414, 0x50a4a450, 0x6a5a0200, + 0xa9a58000, 0x5090a0a8, 0xa8a09050, 0x24242424, + 0x00aa5500, 0x24924924, 0x24499224, 0x50a50a50, + 0x500aa550, 0xaaaa4444, 0x66660000, 0xa5a0a5a0, + 0x50a050a0, 0x69286928, 0x44aaaa44, 0x66666600, + 0xaa444444, 0x54a854a8, 0x95809580, 0x96969600, + 0xa85454a8, 0x80959580, 0xaa141414, 0x96960000, + 0xaaaa1414, 0xa05050a0, 0xa0a5a5a0, 0x96000000, + 0x40804080, 0xa9a8a9a8, 0xaaaaaa44, 0x2a4a5254, +}; +static const uint2 candidateFixUpIndex1D[128] = +{ + {15, 0},{15, 0},{15, 0},{15, 0}, + {15, 0},{15, 0},{15, 0},{15, 0}, + {15, 0},{15, 0},{15, 0},{15, 0}, + {15, 0},{15, 0},{15, 0},{15, 0}, + {15, 0},{ 2, 0},{ 8, 0},{ 2, 0}, + { 2, 0},{ 8, 0},{ 8, 0},{15, 0}, + { 2, 0},{ 8, 0},{ 2, 0},{ 2, 0}, + { 8, 0},{ 8, 0},{ 2, 0},{ 2, 0}, + + {15, 0},{15, 0},{ 6, 0},{ 8, 0}, + { 2, 0},{ 8, 0},{15, 0},{15, 0}, + { 2, 0},{ 8, 0},{ 2, 0},{ 2, 0}, + { 2, 0},{15, 0},{15, 0},{ 6, 0}, + { 6, 0},{ 2, 0},{ 6, 0},{ 8, 0}, + {15, 0},{15, 0},{ 2, 0},{ 2, 0}, + {15, 0},{15, 0},{15, 0},{15, 0}, + {15, 0},{ 2, 0},{ 2, 0},{15, 0}, + //candidateFixUpIndex1D[i][1], i < 64 should not be used + + { 3,15},{ 3, 8},{15, 8},{15, 3}, + { 8,15},{ 3,15},{15, 3},{15, 8}, + { 8,15},{ 8,15},{ 6,15},{ 6,15}, + { 6,15},{ 5,15},{ 3,15},{ 3, 8}, + { 3,15},{ 3, 8},{ 8,15},{15, 3}, + { 3,15},{ 3, 8},{ 6,15},{10, 8}, + { 5, 3},{ 8,15},{ 8, 6},{ 6,10}, + { 8,15},{ 5,15},{15,10},{15, 8}, + + { 8,15},{15, 3},{ 3,15},{ 5,10}, + { 6,10},{10, 8},{ 8, 9},{15,10}, + {15, 6},{ 3,15},{15, 8},{ 5,15}, + {15, 3},{15, 6},{15, 6},{15, 8}, //The Spec doesn't mark the first fixed up index in this row, so I apply 15 for them, and seems correct + { 3,15},{15, 3},{ 5,15},{ 5,15}, + { 5,15},{ 8,15},{ 5,15},{10,15}, + { 5,15},{10,15},{ 8,15},{13,15}, + {15, 3},{12,15},{ 3,15},{ 3, 8}, +}; +static const uint2 candidateFixUpIndex1DOrdered[128] = //Same with candidateFixUpIndex1D but order the result when i >= 64 +{ + {15, 0},{15, 0},{15, 0},{15, 0}, + {15, 0},{15, 0},{15, 0},{15, 0}, + {15, 0},{15, 0},{15, 0},{15, 0}, + {15, 0},{15, 0},{15, 0},{15, 0}, + {15, 0},{ 2, 0},{ 8, 0},{ 2, 0}, + { 2, 0},{ 8, 0},{ 8, 0},{15, 0}, + { 2, 0},{ 8, 0},{ 2, 0},{ 2, 0}, + { 8, 0},{ 8, 0},{ 2, 0},{ 2, 0}, + + {15, 0},{15, 0},{ 6, 0},{ 8, 0}, + { 2, 0},{ 8, 0},{15, 0},{15, 0}, + { 2, 0},{ 8, 0},{ 2, 0},{ 2, 0}, + { 2, 0},{15, 0},{15, 0},{ 6, 0}, + { 6, 0},{ 2, 0},{ 6, 0},{ 8, 0}, + {15, 0},{15, 0},{ 2, 0},{ 2, 0}, + {15, 0},{15, 0},{15, 0},{15, 0}, + {15, 0},{ 2, 0},{ 2, 0},{15, 0}, + //candidateFixUpIndex1DOrdered[i][1], i < 64 should not be used + + { 3,15},{ 3, 8},{ 8,15},{ 3,15}, + { 8,15},{ 3,15},{ 3,15},{ 8,15}, + { 8,15},{ 8,15},{ 6,15},{ 6,15}, + { 6,15},{ 5,15},{ 3,15},{ 3, 8}, + { 3,15},{ 3, 8},{ 8,15},{ 3,15}, + { 3,15},{ 3, 8},{ 6,15},{ 8,10}, + { 3, 5},{ 8,15},{ 6, 8},{ 6,10}, + { 8,15},{ 5,15},{10,15},{ 8,15}, + + { 8,15},{ 3,15},{ 3,15},{ 5,10}, + { 6,10},{ 8,10},{ 8, 9},{10,15}, + { 6,15},{ 3,15},{ 8,15},{ 5,15}, + { 3,15},{ 6,15},{ 6,15},{ 8,15}, //The Spec doesn't mark the first fixed up index in this row, so I apply 15 for them, and seems correct + { 3,15},{ 3,15},{ 5,15},{ 5,15}, + { 5,15},{ 8,15},{ 5,15},{10,15}, + { 5,15},{10,15},{ 8,15},{13,15}, + { 3,15},{12,15},{ 3,15},{ 3, 8}, +}; +//static const uint4x4 candidateRotation[4] = +//{ +// {1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}, +// {0,0,0,1},{0,1,0,0},{0,0,1,0},{1,0,0,0}, +// {1,0,0,0},{0,0,0,1},{0,0,1,0},{0,1,0,0}, +// {1,0,0,0},{0,1,0,0},{0,0,0,1},{0,0,1,0} +//}; +//static const uint2 candidateIndexPrec[8] = {{3,0},{3,0},{2,0},{2,0}, +// {2,3}, //color index and alpha index can exchange +// {2,2},{4,4},{2,2}}; + +static const uint aWeight[3][16] = { {0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64}, + {0, 9, 18, 27, 37, 46, 55, 64, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 21, 43, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} }; + + //4 bit index: 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64 +static const uint aStep[3][64] = { { 0, 0, 0, 1, 1, 1, 1, 2, + 2, 2, 2, 2, 3, 3, 3, 3, + 4, 4, 4, 4, 5, 5, 5, 5, + 6, 6, 6, 6, 6, 7, 7, 7, + 7, 8, 8, 8, 8, 9, 9, 9, + 9,10,10,10,10,10,11,11, + 11,11,12,12,12,12,13,13, + 13,13,14,14,14,14,15,15 }, + //3 bit index: 0, 9, 18, 27, 37, 46, 55, 64 + { 0,0,0,0,0,1,1,1, + 1,1,1,1,1,1,2,2, + 2,2,2,2,2,2,2,3, + 3,3,3,3,3,3,3,3, + 3,4,4,4,4,4,4,4, + 4,4,5,5,5,5,5,5, + 5,5,5,6,6,6,6,6, + 6,6,6,6,7,7,7,7 }, + //2 bit index: 0, 21, 43, 64 + { 0,0,0,0,0,0,0,0, + 0,0,0,1,1,1,1,1, + 1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1, + 1,2,2,2,2,2,2,2, + 2,2,2,2,2,2,2,2, + 2,2,2,2,2,2,3,3, + 3,3,3,3,3,3,3,3 } }; + +cbuffer cbCS : register( b0 ) +{ + uint g_tex_width; + uint g_num_block_x; + uint g_format; + uint g_mode_id; + uint g_start_block_id; + uint g_num_total_blocks; + float g_alpha_weight; +}; + +//Forward declaration +uint2x4 compress_endpoints0( inout uint2x4 endPoint, uint2 P ); //Mode = 0 +uint2x4 compress_endpoints1( inout uint2x4 endPoint, uint2 P ); //Mode = 1 +uint2x4 compress_endpoints2( inout uint2x4 endPoint ); //Mode = 2 +uint2x4 compress_endpoints3( inout uint2x4 endPoint, uint2 P ); //Mode = 3 +uint2x4 compress_endpoints7( inout uint2x4 endPoint, uint2 P ); //Mode = 7 +uint2x4 compress_endpoints6( inout uint2x4 endPoint, uint2 P ); //Mode = 6 +uint2x4 compress_endpoints4( inout uint2x4 endPoint ); //Mode = 4 +uint2x4 compress_endpoints5( inout uint2x4 endPoint ); //Mode = 5 + +void block_package0( out uint4 block, uint partition, uint threadBase ); //Mode0 +void block_package1( out uint4 block, uint partition, uint threadBase ); //Mode1 +void block_package2( out uint4 block, uint partition, uint threadBase ); //Mode2 +void block_package3( out uint4 block, uint partition, uint threadBase ); //Mode3 +void block_package4( out uint4 block, uint rotation, uint index_selector, uint threadBase ); //Mode4 +void block_package5( out uint4 block, uint rotation, uint threadBase ); //Mode5 +void block_package6( out uint4 block, uint threadBase ); //Mode6 +void block_package7( out uint4 block, uint partition, uint threadBase ); //Mode7 + + +void swap(inout uint4 lhs, inout uint4 rhs) +{ + uint4 tmp = lhs; + lhs = rhs; + rhs = tmp; +} +void swap(inout uint3 lhs, inout uint3 rhs) +{ + uint3 tmp = lhs; + lhs = rhs; + rhs = tmp; +} +void swap(inout uint lhs, inout uint rhs) +{ + uint tmp = lhs; + lhs = rhs; + rhs = tmp; +} + +uint ComputeError(in uint4 a, in uint4 b) +{ + return dot(a.rgb, b.rgb) + g_alpha_weight * a.a*b.a; +} + +void Ensure_A_Is_Larger( inout uint4 a, inout uint4 b ) +{ + if ( a.x < b.x ) + swap( a.x, b.x ); + if ( a.y < b.y ) + swap( a.y, b.y ); + if ( a.z < b.z ) + swap( a.z, b.z ); + if ( a.w < b.w ) + swap( a.w, b.w ); +} + + +Texture2D g_Input : register( t0 ); +StructuredBuffer g_InBuff : register( t1 ); + +RWStructuredBuffer g_OutBuff : register( u0 ); + +#define THREAD_GROUP_SIZE 64 +#define BLOCK_SIZE_Y 4 +#define BLOCK_SIZE_X 4 +#define BLOCK_SIZE (BLOCK_SIZE_Y * BLOCK_SIZE_X) + +struct BufferShared +{ + uint4 pixel; + uint error; + uint mode; + uint partition; + uint index_selector; + uint rotation; + uint4 endPoint_low; + uint4 endPoint_high; + uint4 endPoint_low_quantized; + uint4 endPoint_high_quantized; +}; +groupshared BufferShared shared_temp[THREAD_GROUP_SIZE]; + +[numthreads( THREAD_GROUP_SIZE, 1, 1 )] +void TryMode456CS( uint GI : SV_GroupIndex, uint3 groupID : SV_GroupID ) // mode 4 5 6 all have 1 subset per block, and fix-up index is always index 0 +{ + // we process 4 BC blocks per thread group + const uint MAX_USED_THREAD = 16; // pixels in a BC (block compressed) block + uint BLOCK_IN_GROUP = THREAD_GROUP_SIZE / MAX_USED_THREAD; // the number of BC blocks a thread group processes = 64 / 16 = 4 + uint blockInGroup = GI / MAX_USED_THREAD; // what BC block this thread is on within this thread group + uint blockID = g_start_block_id + groupID.x * BLOCK_IN_GROUP + blockInGroup; // what global BC block this thread is on + uint threadBase = blockInGroup * MAX_USED_THREAD; // the first id of the pixel in this BC block in this thread group + uint threadInBlock = GI - threadBase; // id of the pixel in this BC block + +#ifndef REF_DEVICE + if (blockID >= g_num_total_blocks) + { + return; + } +#endif + + uint block_y = blockID / g_num_block_x; + uint block_x = blockID - block_y * g_num_block_x; + uint base_x = block_x * BLOCK_SIZE_X; + uint base_y = block_y * BLOCK_SIZE_Y; + + if (threadInBlock < 16) + { + shared_temp[GI].pixel = clamp(uint4(g_Input.Load( uint3( base_x + threadInBlock % 4, base_y + threadInBlock / 4, 0 ) ) * 255), 0, 255); + + shared_temp[GI].endPoint_low = shared_temp[GI].pixel; + shared_temp[GI].endPoint_high = shared_temp[GI].pixel; + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + if (threadInBlock < 8) + { + shared_temp[GI].endPoint_low = min(shared_temp[GI].endPoint_low, shared_temp[GI + 8].endPoint_low); + shared_temp[GI].endPoint_high = max(shared_temp[GI].endPoint_high, shared_temp[GI + 8].endPoint_high); + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 4) + { + shared_temp[GI].endPoint_low = min(shared_temp[GI].endPoint_low, shared_temp[GI + 4].endPoint_low); + shared_temp[GI].endPoint_high = max(shared_temp[GI].endPoint_high, shared_temp[GI + 4].endPoint_high); + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 2) + { + shared_temp[GI].endPoint_low = min(shared_temp[GI].endPoint_low, shared_temp[GI + 2].endPoint_low); + shared_temp[GI].endPoint_high = max(shared_temp[GI].endPoint_high, shared_temp[GI + 2].endPoint_high); + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 1) + { + shared_temp[GI].endPoint_low = min(shared_temp[GI].endPoint_low, shared_temp[GI + 1].endPoint_low); + shared_temp[GI].endPoint_high = max(shared_temp[GI].endPoint_high, shared_temp[GI + 1].endPoint_high); + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + uint2x4 endPoint; + endPoint[0] = shared_temp[threadBase].endPoint_low; + endPoint[1] = shared_temp[threadBase].endPoint_high; + + uint error = 0xFFFFFFFF; + uint mode = 0; + uint index_selector = 0; + uint rotation = 0; + + uint2 indexPrec; + if (threadInBlock < 8) // all threads of threadInBlock < 8 will be working on trying out mode 4, since only mode 4 has index selector bit + { + if (0 == (threadInBlock & 1)) // thread 0, 2, 4, 6 + { + //2 represents 2bit index precision; 1 represents 3bit index precision + index_selector = 0; + indexPrec = uint2( 2, 1 ); + } + else // thread 1, 3, 5, 7 + { + //2 represents 2bit index precision; 1 represents 3bit index precision + index_selector = 1; + indexPrec = uint2( 1, 2 ); + } + } + else + { + //2 represents 2bit index precision + indexPrec = uint2( 2, 2 ); + } + + uint4 pixel_r; + uint color_index; + uint alpha_index; + int4 span; + int2 span_norm_sqr; + int2 dotProduct; + if (threadInBlock < 12) // Try mode 4 5 in threads 0..11 + { + // mode 4 5 have component rotation + if ((threadInBlock < 2) || (8 == threadInBlock)) // rotation = 0 in thread 0, 1 + { + rotation = 0; + } + else if ((threadInBlock < 4) || (9 == threadInBlock)) // rotation = 1 in thread 2, 3 + { + endPoint[0].ra = endPoint[0].ar; + endPoint[1].ra = endPoint[1].ar; + + rotation = 1; + } + else if ((threadInBlock < 6) || (10 == threadInBlock)) // rotation = 2 in thread 4, 5 + { + endPoint[0].ga = endPoint[0].ag; + endPoint[1].ga = endPoint[1].ag; + + rotation = 2; + } + else if ((threadInBlock < 8) || (11 == threadInBlock)) // rotation = 3 in thread 6, 7 + { + endPoint[0].ba = endPoint[0].ab; + endPoint[1].ba = endPoint[1].ab; + + rotation = 3; + } + + if (threadInBlock < 8) // try mode 4 in threads 0..7 + { + // mode 4 thread distribution + // Thread 0 1 2 3 4 5 6 7 + // Rotation 0 0 1 1 2 2 3 3 + // Index selector 0 1 0 1 0 1 0 1 + + mode = 4; + compress_endpoints4( endPoint ); + } + else // try mode 5 in threads 8..11 + { + // mode 5 thread distribution + // Thread 8 9 10 11 + // Rotation 0 1 2 3 + + mode = 5; + compress_endpoints5( endPoint ); + } + + uint4 pixel = shared_temp[threadBase + 0].pixel; + if (1 == rotation) + { + pixel.ra = pixel.ar; + } + else if (2 == rotation) + { + pixel.ga = pixel.ag; + } + else if (3 == rotation) + { + pixel.ba = pixel.ab; + } + + span = endPoint[1] - endPoint[0]; + span_norm_sqr = uint2( dot( span.rgb, span.rgb ), span.a * span.a ); + + // in mode 4 5 6, end point 0 must be closer to pixel 0 than end point 1, because of the fix-up index is always index 0 + // TODO: this shouldn't be necessary here in error calculation + /* + dotProduct = int2( dot( span.rgb, pixel.rgb - endPoint[0].rgb ), span.a * ( pixel.a - endPoint[0].a ) ); + if ( span_norm_sqr.x > 0 && dotProduct.x > 0 && uint( dotProduct.x * 63.49999 ) > uint( 32 * span_norm_sqr.x ) ) + { + span.rgb = -span.rgb; + swap(endPoint[0].rgb, endPoint[1].rgb); + } + if ( span_norm_sqr.y > 0 && dotProduct.y > 0 && uint( dotProduct.y * 63.49999 ) > uint( 32 * span_norm_sqr.y ) ) + { + span.a = -span.a; + swap(endPoint[0].a, endPoint[1].a); + } + */ + + // should be the same as above + dotProduct = int2( dot( pixel.rgb - endPoint[0].rgb, pixel.rgb - endPoint[0].rgb ), dot( pixel.rgb - endPoint[1].rgb, pixel.rgb - endPoint[1].rgb ) ); + if ( dotProduct.x > dotProduct.y ) + { + span.rgb = -span.rgb; + swap(endPoint[0].rgb, endPoint[1].rgb); + } + dotProduct = int2( dot( pixel.a - endPoint[0].a, pixel.a - endPoint[0].a ), dot( pixel.a - endPoint[1].a, pixel.a - endPoint[1].a ) ); + if ( dotProduct.x > dotProduct.y ) + { + span.a = -span.a; + swap(endPoint[0].a, endPoint[1].a); + } + + error = 0; + for ( uint i = 0; i < 16; i ++ ) + { + pixel = shared_temp[threadBase + i].pixel; + if (1 == rotation) + { + pixel.ra = pixel.ar; + } + else if (2 == rotation) + { + pixel.ga = pixel.ag; + } + else if (3 == rotation) + { + pixel.ba = pixel.ab; + } + + dotProduct.x = dot( span.rgb, pixel.rgb - endPoint[0].rgb ); + color_index = ( span_norm_sqr.x <= 0 /*endPoint[0] == endPoint[1]*/ || dotProduct.x <= 0 /*pixel == endPoint[0]*/ ) ? 0 + : ( ( dotProduct.x < span_norm_sqr.x ) ? aStep[indexPrec.x][ uint( dotProduct.x * 63.49999 / span_norm_sqr.x ) ] : aStep[indexPrec.x][63] ); + dotProduct.y = dot( span.a, pixel.a - endPoint[0].a ); + alpha_index = ( span_norm_sqr.y <= 0 || dotProduct.y <= 0 ) ? 0 + : ( ( dotProduct.y < span_norm_sqr.y ) ? aStep[indexPrec.y][ uint( dotProduct.y * 63.49999 / span_norm_sqr.y ) ] : aStep[indexPrec.y][63] ); + + // the same color_index and alpha_index should be used for reconstruction, so this should be left commented out + /*if (index_selector) + { + swap(color_index, alpha_index); + }*/ + + pixel_r.rgb = ( ( 64 - aWeight[indexPrec.x][color_index] ) * endPoint[0].rgb + + aWeight[indexPrec.x][color_index] * endPoint[1].rgb + + 32 ) >> 6; + pixel_r.a = ( ( 64 - aWeight[indexPrec.y][alpha_index] ) * endPoint[0].a + + aWeight[indexPrec.y][alpha_index] * endPoint[1].a + + 32 ) >> 6; + + Ensure_A_Is_Larger( pixel_r, pixel ); + pixel_r -= pixel; + if (1 == rotation) + { + pixel_r.ra = pixel_r.ar; + } + else if (2 == rotation) + { + pixel_r.ga = pixel_r.ag; + } + else if (3 == rotation) + { + pixel_r.ba = pixel_r.ab; + } + error += ComputeError(pixel_r, pixel_r); + } + } + else if (threadInBlock < 16) // Try mode 6 in threads 12..15, since in mode 4 5 6, only mode 6 has p bit + { + uint p = threadInBlock - 12; + + compress_endpoints6( endPoint, uint2(p >> 0, p >> 1) & 1 ); + + uint4 pixel = shared_temp[threadBase + 0].pixel; + + span = endPoint[1] - endPoint[0]; + span_norm_sqr = dot( span, span ); + dotProduct = dot( span, pixel - endPoint[0] ); + if ( span_norm_sqr.x > 0 && dotProduct.x >= 0 && uint( dotProduct.x * 63.49999 ) > uint( 32 * span_norm_sqr.x ) ) + { + span = -span; + swap(endPoint[0], endPoint[1]); + } + + error = 0; + for ( uint i = 0; i < 16; i ++ ) + { + pixel = shared_temp[threadBase + i].pixel; + + dotProduct.x = dot( span, pixel - endPoint[0] ); + color_index = ( span_norm_sqr.x <= 0 || dotProduct.x <= 0 ) ? 0 + : ( ( dotProduct.x < span_norm_sqr.x ) ? aStep[0][ uint( dotProduct.x * 63.49999 / span_norm_sqr.x ) ] : aStep[0][63] ); + + pixel_r = ( ( 64 - aWeight[0][color_index] ) * endPoint[0] + + aWeight[0][color_index] * endPoint[1] + 32 ) >> 6; + + Ensure_A_Is_Larger( pixel_r, pixel ); + pixel_r -= pixel; + error += ComputeError(pixel_r, pixel_r); + } + + mode = 6; + rotation = p; // Borrow rotation for p + } + + shared_temp[GI].error = error; + shared_temp[GI].mode = mode; + shared_temp[GI].index_selector = index_selector; + shared_temp[GI].rotation = rotation; + +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + if (threadInBlock < 8) + { + if ( shared_temp[GI].error > shared_temp[GI + 8].error ) + { + shared_temp[GI].error = shared_temp[GI + 8].error; + shared_temp[GI].mode = shared_temp[GI + 8].mode; + shared_temp[GI].index_selector = shared_temp[GI + 8].index_selector; + shared_temp[GI].rotation = shared_temp[GI + 8].rotation; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 4) + { + if ( shared_temp[GI].error > shared_temp[GI + 4].error ) + { + shared_temp[GI].error = shared_temp[GI + 4].error; + shared_temp[GI].mode = shared_temp[GI + 4].mode; + shared_temp[GI].index_selector = shared_temp[GI + 4].index_selector; + shared_temp[GI].rotation = shared_temp[GI + 4].rotation; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 2) + { + if ( shared_temp[GI].error > shared_temp[GI + 2].error ) + { + shared_temp[GI].error = shared_temp[GI + 2].error; + shared_temp[GI].mode = shared_temp[GI + 2].mode; + shared_temp[GI].index_selector = shared_temp[GI + 2].index_selector; + shared_temp[GI].rotation = shared_temp[GI + 2].rotation; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 1) + { + if ( shared_temp[GI].error > shared_temp[GI + 1].error ) + { + shared_temp[GI].error = shared_temp[GI + 1].error; + shared_temp[GI].mode = shared_temp[GI + 1].mode; + shared_temp[GI].index_selector = shared_temp[GI + 1].index_selector; + shared_temp[GI].rotation = shared_temp[GI + 1].rotation; + } + + g_OutBuff[blockID] = uint4(shared_temp[GI].error, (shared_temp[GI].index_selector << 31) | shared_temp[GI].mode, + 0, shared_temp[GI].rotation); // rotation is indeed rotation for mode 4 5. for mode 6, rotation is p bit + } +} + +[numthreads( THREAD_GROUP_SIZE, 1, 1 )] +void TryMode137CS( uint GI : SV_GroupIndex, uint3 groupID : SV_GroupID ) // mode 1 3 7 all have 2 subsets per block +{ + const uint MAX_USED_THREAD = 64; + uint BLOCK_IN_GROUP = THREAD_GROUP_SIZE / MAX_USED_THREAD; + uint blockInGroup = GI / MAX_USED_THREAD; + uint blockID = g_start_block_id + groupID.x * BLOCK_IN_GROUP + blockInGroup; + uint threadBase = blockInGroup * MAX_USED_THREAD; + uint threadInBlock = GI - threadBase; + + uint block_y = blockID / g_num_block_x; + uint block_x = blockID - block_y * g_num_block_x; + uint base_x = block_x * BLOCK_SIZE_X; + uint base_y = block_y * BLOCK_SIZE_Y; + + if (threadInBlock < 16) + { + shared_temp[GI].pixel = clamp(uint4(g_Input.Load( uint3( base_x + threadInBlock % 4, base_y + threadInBlock / 4, 0 ) ) * 255), 0, 255); + } + GroupMemoryBarrierWithGroupSync(); + + shared_temp[GI].error = 0xFFFFFFFF; + + uint4 pixel_r; + uint2x4 endPoint[2]; // endPoint[0..1 for subset id][0..1 for low and high in the subset] + uint2x4 endPointBackup[2]; + uint color_index; + if (threadInBlock < 64) + { + uint partition = threadInBlock; + + endPoint[0][0] = MAX_UINT; + endPoint[0][1] = MIN_UINT; + endPoint[1][0] = MAX_UINT; + endPoint[1][1] = MIN_UINT; + uint bits = candidateSectionBit[partition]; + for ( uint i = 0; i < 16; i ++ ) + { + uint4 pixel = shared_temp[threadBase + i].pixel; + if ( (( bits >> i ) & 0x01) == 1 ) + { + endPoint[1][0] = min( endPoint[1][0], pixel ); + endPoint[1][1] = max( endPoint[1][1], pixel ); + } + else + { + endPoint[0][0] = min( endPoint[0][0], pixel ); + endPoint[0][1] = max( endPoint[0][1], pixel ); + } + } + + endPointBackup[0] = endPoint[0]; + endPointBackup[1] = endPoint[1]; + + uint max_p; + if (1 == g_mode_id) + { + // in mode 1, there is only one p bit per subset + max_p = 4; + } + else + { + // in mode 3 7, there are two p bits per subset, one for each end point + max_p = 16; + } + + uint rotation = 0; + uint error = MAX_UINT; + for ( uint p = 0; p < max_p; p ++ ) + { + endPoint[0] = endPointBackup[0]; + endPoint[1] = endPointBackup[1]; + + for ( i = 0; i < 2; i ++ ) // loop through 2 subsets + { + if (g_mode_id == 1) + { + compress_endpoints1( endPoint[i], (p >> i) & 1 ); + } + else if (g_mode_id == 3) + { + compress_endpoints3( endPoint[i], uint2(p >> (i * 2 + 0), p >> (i * 2 + 1)) & 1 ); + } + else if (g_mode_id == 7) + { + compress_endpoints7( endPoint[i], uint2(p >> (i * 2 + 0), p >> (i * 2 + 1)) & 1 ); + } + } + + int4 span[2]; + span[0] = endPoint[0][1] - endPoint[0][0]; + span[1] = endPoint[1][1] - endPoint[1][0]; + + if (g_mode_id != 7) + { + span[0].w = span[1].w = 0; + } + + int span_norm_sqr[2]; + span_norm_sqr[0] = dot( span[0], span[0] ); + span_norm_sqr[1] = dot( span[1], span[1] ); + + // TODO: again, this shouldn't be necessary here in error calculation + int dotProduct = dot( span[0], shared_temp[threadBase + 0].pixel - endPoint[0][0] ); + if ( span_norm_sqr[0] > 0 && dotProduct > 0 && uint( dotProduct * 63.49999 ) > uint( 32 * span_norm_sqr[0] ) ) + { + span[0] = -span[0]; + swap(endPoint[0][0], endPoint[0][1]); + } + dotProduct = dot( span[1], shared_temp[threadBase + candidateFixUpIndex1D[partition].x].pixel - endPoint[1][0] ); + if ( span_norm_sqr[1] > 0 && dotProduct > 0 && uint( dotProduct * 63.49999 ) > uint( 32 * span_norm_sqr[1] ) ) + { + span[1] = -span[1]; + swap(endPoint[1][0], endPoint[1][1]); + } + + uint step_selector; + if (g_mode_id != 1) + { + step_selector = 2; // mode 3 7 have 2 bit index + } + else + { + step_selector = 1; // mode 1 has 3 bit index + } + + uint p_error = 0; + for ( i = 0; i < 16; i ++ ) + { + if (((bits >> i) & 0x01) == 1) + { + dotProduct = dot( span[1], shared_temp[threadBase + i].pixel - endPoint[1][0] ); + color_index = (span_norm_sqr[1] <= 0 || dotProduct <= 0) ? 0 + : ((dotProduct < span_norm_sqr[1]) ? aStep[step_selector][uint(dotProduct * 63.49999 / span_norm_sqr[1])] : aStep[step_selector][63]); + } + else + { + dotProduct = dot( span[0], shared_temp[threadBase + i].pixel - endPoint[0][0] ); + color_index = (span_norm_sqr[0] <= 0 || dotProduct <= 0) ? 0 + : ((dotProduct < span_norm_sqr[0]) ? aStep[step_selector][uint(dotProduct * 63.49999 / span_norm_sqr[0])] : aStep[step_selector][63]); + } + + uint subset_index = (bits >> i) & 0x01; + + pixel_r = ((64 - aWeight[step_selector][color_index]) * endPoint[subset_index][0] + + aWeight[step_selector][color_index] * endPoint[subset_index][1] + 32) >> 6; + if (g_mode_id != 7) + { + pixel_r.a = 255; + } + + uint4 pixel = shared_temp[threadBase + i].pixel; + Ensure_A_Is_Larger( pixel_r, pixel ); + pixel_r -= pixel; + p_error += ComputeError(pixel_r, pixel_r); + } + + if (p_error < error) + { + error = p_error; + rotation = p; + } + } + + shared_temp[GI].error = error; + shared_temp[GI].mode = g_mode_id; + shared_temp[GI].partition = partition; + shared_temp[GI].rotation = rotation; // mode 1 3 7 don't have rotation, we use rotation for p bits + } + GroupMemoryBarrierWithGroupSync(); + + if (threadInBlock < 32) + { + if ( shared_temp[GI].error > shared_temp[GI + 32].error ) + { + shared_temp[GI].error = shared_temp[GI + 32].error; + shared_temp[GI].mode = shared_temp[GI + 32].mode; + shared_temp[GI].partition = shared_temp[GI + 32].partition; + shared_temp[GI].rotation = shared_temp[GI + 32].rotation; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif +if (threadInBlock < 16) + { + if ( shared_temp[GI].error > shared_temp[GI + 16].error ) + { + shared_temp[GI].error = shared_temp[GI + 16].error; + shared_temp[GI].mode = shared_temp[GI + 16].mode; + shared_temp[GI].partition = shared_temp[GI + 16].partition; + shared_temp[GI].rotation = shared_temp[GI + 16].rotation; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 8) + { + if ( shared_temp[GI].error > shared_temp[GI + 8].error ) + { + shared_temp[GI].error = shared_temp[GI + 8].error; + shared_temp[GI].mode = shared_temp[GI + 8].mode; + shared_temp[GI].partition = shared_temp[GI + 8].partition; + shared_temp[GI].rotation = shared_temp[GI + 8].rotation; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 4) + { + if ( shared_temp[GI].error > shared_temp[GI + 4].error ) + { + shared_temp[GI].error = shared_temp[GI + 4].error; + shared_temp[GI].mode = shared_temp[GI + 4].mode; + shared_temp[GI].partition = shared_temp[GI + 4].partition; + shared_temp[GI].rotation = shared_temp[GI + 4].rotation; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 2) + { + if ( shared_temp[GI].error > shared_temp[GI + 2].error ) + { + shared_temp[GI].error = shared_temp[GI + 2].error; + shared_temp[GI].mode = shared_temp[GI + 2].mode; + shared_temp[GI].partition = shared_temp[GI + 2].partition; + shared_temp[GI].rotation = shared_temp[GI + 2].rotation; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 1) + { + if ( shared_temp[GI].error > shared_temp[GI + 1].error ) + { + shared_temp[GI].error = shared_temp[GI + 1].error; + shared_temp[GI].mode = shared_temp[GI + 1].mode; + shared_temp[GI].partition = shared_temp[GI + 1].partition; + shared_temp[GI].rotation = shared_temp[GI + 1].rotation; + } + + if (g_InBuff[blockID].x > shared_temp[GI].error) + { + g_OutBuff[blockID] = uint4(shared_temp[GI].error, shared_temp[GI].mode, shared_temp[GI].partition, shared_temp[GI].rotation); // mode 1 3 7 don't have rotation, we use rotation for p bits + } + else + { + g_OutBuff[blockID] = g_InBuff[blockID]; + } + } +} + +[numthreads( THREAD_GROUP_SIZE, 1, 1 )] +void TryMode02CS( uint GI : SV_GroupIndex, uint3 groupID : SV_GroupID ) // mode 0 2 have 3 subsets per block +{ + const uint MAX_USED_THREAD = 64; + uint BLOCK_IN_GROUP = THREAD_GROUP_SIZE / MAX_USED_THREAD; + uint blockInGroup = GI / MAX_USED_THREAD; + uint blockID = g_start_block_id + groupID.x * BLOCK_IN_GROUP + blockInGroup; + uint threadBase = blockInGroup * MAX_USED_THREAD; + uint threadInBlock = GI - threadBase; + + uint block_y = blockID / g_num_block_x; + uint block_x = blockID - block_y * g_num_block_x; + uint base_x = block_x * BLOCK_SIZE_X; + uint base_y = block_y * BLOCK_SIZE_Y; + + if (threadInBlock < 16) + { + shared_temp[GI].pixel = clamp(uint4(g_Input.Load( uint3( base_x + threadInBlock % 4, base_y + threadInBlock / 4, 0 ) ) * 255), 0, 255); + } + GroupMemoryBarrierWithGroupSync(); + + shared_temp[GI].error = 0xFFFFFFFF; + + uint num_partitions; + if (0 == g_mode_id) + { + num_partitions = 16; + } + else + { + num_partitions = 64; + } + + uint4 pixel_r; + uint2x4 endPoint[3]; // endPoint[0..1 for subset id][0..1 for low and high in the subset] + uint2x4 endPointBackup[3]; + uint color_index[16]; + if (threadInBlock < num_partitions) + { + uint partition = threadInBlock + 64; + + endPoint[0][0] = MAX_UINT; + endPoint[0][1] = MIN_UINT; + endPoint[1][0] = MAX_UINT; + endPoint[1][1] = MIN_UINT; + endPoint[2][0] = MAX_UINT; + endPoint[2][1] = MIN_UINT; + uint bits2 = candidateSectionBit2[partition - 64]; + for ( uint i = 0; i < 16; i ++ ) + { + uint4 pixel = shared_temp[threadBase + i].pixel; + uint subset_index = ( bits2 >> ( i * 2 ) ) & 0x03; + if ( subset_index == 2 ) + { + endPoint[2][0] = min( endPoint[2][0], pixel ); + endPoint[2][1] = max( endPoint[2][1], pixel ); + } + else if ( subset_index == 1 ) + { + endPoint[1][0] = min( endPoint[1][0], pixel ); + endPoint[1][1] = max( endPoint[1][1], pixel ); + } + else + { + endPoint[0][0] = min( endPoint[0][0], pixel ); + endPoint[0][1] = max( endPoint[0][1], pixel ); + } + } + + endPointBackup[0] = endPoint[0]; + endPointBackup[1] = endPoint[1]; + endPointBackup[2] = endPoint[2]; + + uint max_p; + if (0 == g_mode_id) + { + max_p = 64; // changed from 32 to 64 + } + else + { + max_p = 1; + } + + uint rotation = 0; + uint error = MAX_UINT; + for ( uint p = 0; p < max_p; p ++ ) + { + endPoint[0] = endPointBackup[0]; + endPoint[1] = endPointBackup[1]; + endPoint[2] = endPointBackup[2]; + + for ( i = 0; i < 3; i ++ ) + { + if (0 == g_mode_id) + { + compress_endpoints0( endPoint[i], uint2(p >> (i * 2 + 0), p >> (i * 2 + 1)) & 1 ); + } + else + { + compress_endpoints2( endPoint[i] ); + } + } + + uint step_selector = 1 + (2 == g_mode_id); + + int4 span[3]; + span[0] = endPoint[0][1] - endPoint[0][0]; + span[1] = endPoint[1][1] - endPoint[1][0]; + span[2] = endPoint[2][1] - endPoint[2][0]; + span[0].w = span[1].w = span[2].w = 0; + int span_norm_sqr[3]; + span_norm_sqr[0] = dot( span[0], span[0] ); + span_norm_sqr[1] = dot( span[1], span[1] ); + span_norm_sqr[2] = dot( span[2], span[2] ); + + // TODO: again, this shouldn't be necessary here in error calculation + uint ci[3] = { 0, candidateFixUpIndex1D[partition].x, candidateFixUpIndex1D[partition].y }; + for (i = 0; i < 3; i ++) + { + int dotProduct = dot( span[i], shared_temp[threadBase + ci[i]].pixel - endPoint[i][0] ); + if ( span_norm_sqr[i] > 0 && dotProduct > 0 && uint( dotProduct * 63.49999 ) > uint( 32 * span_norm_sqr[i] ) ) + { + span[i] = -span[i]; + swap(endPoint[i][0], endPoint[i][1]); + } + } + + uint p_error = 0; + for ( i = 0; i < 16; i ++ ) + { + uint subset_index = ( bits2 >> ( i * 2 ) ) & 0x03; + if ( subset_index == 2 ) + { + int dotProduct = dot( span[2], shared_temp[threadBase + i].pixel - endPoint[2][0] ); + color_index[i] = ( span_norm_sqr[2] <= 0 || dotProduct <= 0 ) ? 0 + : ( ( dotProduct < span_norm_sqr[2] ) ? aStep[step_selector][ uint( dotProduct * 63.49999 / span_norm_sqr[2] ) ] : aStep[step_selector][63] ); + } + else if ( subset_index == 1 ) + { + int dotProduct = dot( span[1], shared_temp[threadBase + i].pixel - endPoint[1][0] ); + color_index[i] = ( span_norm_sqr[1] <= 0 || dotProduct <= 0 ) ? 0 + : ( ( dotProduct < span_norm_sqr[1] ) ? aStep[step_selector][ uint( dotProduct * 63.49999 / span_norm_sqr[1] ) ] : aStep[step_selector][63] ); + } + else + { + int dotProduct = dot( span[0], shared_temp[threadBase + i].pixel - endPoint[0][0] ); + color_index[i] = ( span_norm_sqr[0] <= 0 || dotProduct <= 0 ) ? 0 + : ( ( dotProduct < span_norm_sqr[0] ) ? aStep[step_selector][ uint( dotProduct * 63.49999 / span_norm_sqr[0] ) ] : aStep[step_selector][63] ); + } + + pixel_r = ( ( 64 - aWeight[step_selector][color_index[i]] ) * endPoint[subset_index][0] + + aWeight[step_selector][color_index[i]] * endPoint[subset_index][1] + 32 ) >> 6; + pixel_r.a = 255; + + uint4 pixel = shared_temp[threadBase + i].pixel; + Ensure_A_Is_Larger( pixel_r, pixel ); + pixel_r -= pixel; + p_error += ComputeError(pixel_r, pixel_r); + } + + if (p_error < error) + { + error = p_error; + rotation = p; // Borrow rotation for p + } + } + + shared_temp[GI].error = error; + shared_temp[GI].partition = partition; + shared_temp[GI].rotation = rotation; + } + GroupMemoryBarrierWithGroupSync(); + + if (threadInBlock < 32) + { + if ( shared_temp[GI].error > shared_temp[GI + 32].error ) + { + shared_temp[GI].error = shared_temp[GI + 32].error; + shared_temp[GI].partition = shared_temp[GI + 32].partition; + shared_temp[GI].rotation = shared_temp[GI + 32].rotation; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 16) + { + if ( shared_temp[GI].error > shared_temp[GI + 16].error ) + { + shared_temp[GI].error = shared_temp[GI + 16].error; + shared_temp[GI].partition = shared_temp[GI + 16].partition; + shared_temp[GI].rotation = shared_temp[GI + 16].rotation; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 8) + { + if ( shared_temp[GI].error > shared_temp[GI + 8].error ) + { + shared_temp[GI].error = shared_temp[GI + 8].error; + shared_temp[GI].partition = shared_temp[GI + 8].partition; + shared_temp[GI].rotation = shared_temp[GI + 8].rotation; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 4) + { + if ( shared_temp[GI].error > shared_temp[GI + 4].error ) + { + shared_temp[GI].error = shared_temp[GI + 4].error; + shared_temp[GI].partition = shared_temp[GI + 4].partition; + shared_temp[GI].rotation = shared_temp[GI + 4].rotation; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 2) + { + if ( shared_temp[GI].error > shared_temp[GI + 2].error ) + { + shared_temp[GI].error = shared_temp[GI + 2].error; + shared_temp[GI].partition = shared_temp[GI + 2].partition; + shared_temp[GI].rotation = shared_temp[GI + 2].rotation; + } + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 1) + { + if ( shared_temp[GI].error > shared_temp[GI + 1].error ) + { + shared_temp[GI].error = shared_temp[GI + 1].error; + shared_temp[GI].partition = shared_temp[GI + 1].partition; + shared_temp[GI].rotation = shared_temp[GI + 1].rotation; + } + + if (g_InBuff[blockID].x > shared_temp[GI].error) + { + g_OutBuff[blockID] = uint4(shared_temp[GI].error, g_mode_id, shared_temp[GI].partition, shared_temp[GI].rotation); // rotation is actually p bit for mode 0. for mode 2, rotation is always 0 + } + else + { + g_OutBuff[blockID] = g_InBuff[blockID]; + } + } +} + +[numthreads( THREAD_GROUP_SIZE, 1, 1 )] +void EncodeBlockCS(uint GI : SV_GroupIndex, uint3 groupID : SV_GroupID) +{ + const uint MAX_USED_THREAD = 16; + uint BLOCK_IN_GROUP = THREAD_GROUP_SIZE / MAX_USED_THREAD; + uint blockInGroup = GI / MAX_USED_THREAD; + uint blockID = g_start_block_id + groupID.x * BLOCK_IN_GROUP + blockInGroup; + uint threadBase = blockInGroup * MAX_USED_THREAD; + uint threadInBlock = GI - threadBase; + +#ifndef REF_DEVICE + if (blockID >= g_num_total_blocks) + { + return; + } +#endif + + uint block_y = blockID / g_num_block_x; + uint block_x = blockID - block_y * g_num_block_x; + uint base_x = block_x * BLOCK_SIZE_X; + uint base_y = block_y * BLOCK_SIZE_Y; + + uint mode = g_InBuff[blockID].y & 0x7FFFFFFF; + uint partition = g_InBuff[blockID].z; + uint index_selector = (g_InBuff[blockID].y >> 31) & 1; + uint rotation = g_InBuff[blockID].w; + + if (threadInBlock < 16) + { + uint4 pixel = clamp(uint4(g_Input.Load( uint3( base_x + threadInBlock % 4, base_y + threadInBlock / 4, 0 ) ) * 255), 0, 255); + + if ((4 == mode) || (5 == mode)) + { + if (1 == rotation) + { + pixel.ra = pixel.ar; + } + else if (2 == rotation) + { + pixel.ga = pixel.ag; + } + else if (3 == rotation) + { + pixel.ba = pixel.ab; + } + } + + shared_temp[GI].pixel = pixel; + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + uint bits = candidateSectionBit[partition]; + uint bits2 = candidateSectionBit2[partition - 64]; + + uint2x4 ep; + uint2x4 ep_quantized; + [unroll] + for (int ii = 2; ii >= 0; -- ii) + { + if (threadInBlock < 16) + { + uint2x4 ep; + ep[0] = MAX_UINT; + ep[1] = MIN_UINT; + + uint4 pixel = shared_temp[GI].pixel; + + uint subset_index = ( bits >> threadInBlock ) & 0x01; + uint subset_index2 = ( bits2 >> ( threadInBlock * 2 ) ) & 0x03; + if (0 == ii) + { + if ((0 == mode) || (2 == mode)) + { + if (0 == subset_index2) + { + ep[0] = ep[1] = pixel; + } + } + else if ((1 == mode) || (3 == mode) || (7 == mode)) + { + if (0 == subset_index) + { + ep[0] = ep[1] = pixel; + } + } + else if ((4 == mode) || (5 == mode) || (6 == mode)) + { + ep[0] = ep[1] = pixel; + } + } + else if (1 == ii) + { + if ((0 == mode) || (2 == mode)) + { + if (1 == subset_index2) + { + ep[0] = ep[1] = pixel; + } + } + else if ((1 == mode) || (3 == mode) || (7 == mode)) + { + if (1 == subset_index) + { + ep[0] = ep[1] = pixel; + } + } + } + else + { + if ((0 == mode) || (2 == mode)) + { + if (2 == subset_index2) + { + ep[0] = ep[1] = pixel; + } + } + } + + shared_temp[GI].endPoint_low = ep[0]; + shared_temp[GI].endPoint_high = ep[1]; + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + if (threadInBlock < 8) + { + shared_temp[GI].endPoint_low = min(shared_temp[GI].endPoint_low, shared_temp[GI + 8].endPoint_low); + shared_temp[GI].endPoint_high = max(shared_temp[GI].endPoint_high, shared_temp[GI + 8].endPoint_high); + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 4) + { + shared_temp[GI].endPoint_low = min(shared_temp[GI].endPoint_low, shared_temp[GI + 4].endPoint_low); + shared_temp[GI].endPoint_high = max(shared_temp[GI].endPoint_high, shared_temp[GI + 4].endPoint_high); + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 2) + { + shared_temp[GI].endPoint_low = min(shared_temp[GI].endPoint_low, shared_temp[GI + 2].endPoint_low); + shared_temp[GI].endPoint_high = max(shared_temp[GI].endPoint_high, shared_temp[GI + 2].endPoint_high); + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + if (threadInBlock < 1) + { + shared_temp[GI].endPoint_low = min(shared_temp[GI].endPoint_low, shared_temp[GI + 1].endPoint_low); + shared_temp[GI].endPoint_high = max(shared_temp[GI].endPoint_high, shared_temp[GI + 1].endPoint_high); + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + if (ii == (int)threadInBlock) + { + ep[0] = shared_temp[threadBase].endPoint_low; + ep[1] = shared_temp[threadBase].endPoint_high; + } + } + + if (threadInBlock < 3) + { + uint2 P; + if (1 == mode) + { + P = (rotation >> threadInBlock) & 1; + } + else + { + P = uint2(rotation >> (threadInBlock * 2 + 0), rotation >> (threadInBlock * 2 + 1)) & 1; + } + + if (0 == mode) + { + ep_quantized = compress_endpoints0( ep, P ); + } + else if (1 == mode) + { + ep_quantized = compress_endpoints1( ep, P ); + } + else if (2 == mode) + { + ep_quantized = compress_endpoints2( ep ); + } + else if (3 == mode) + { + ep_quantized = compress_endpoints3( ep, P ); + } + else if (4 == mode) + { + ep_quantized = compress_endpoints4( ep ); + } + else if (5 == mode) + { + ep_quantized = compress_endpoints5( ep ); + } + else if (6 == mode) + { + ep_quantized = compress_endpoints6( ep, P ); + } + else //if (7 == mode) + { + ep_quantized = compress_endpoints7( ep, P ); + } + + int4 span = ep[1] - ep[0]; + if (mode < 4) + { + span.w = 0; + } + + if ((4 == mode) || (5 == mode)) + { + if (0 == threadInBlock) + { + int2 span_norm_sqr = uint2( dot( span.rgb, span.rgb ), span.a * span.a ); + int2 dotProduct = int2( dot( span.rgb, shared_temp[threadBase + 0].pixel.rgb - ep[0].rgb ), span.a * ( shared_temp[threadBase + 0].pixel.a - ep[0].a ) ); + if ( span_norm_sqr.x > 0 && dotProduct.x > 0 && uint( dotProduct.x * 63.49999 ) > uint( 32 * span_norm_sqr.x ) ) + { + swap(ep[0].rgb, ep[1].rgb); + swap(ep_quantized[0].rgb, ep_quantized[1].rgb); + } + if ( span_norm_sqr.y > 0 && dotProduct.y > 0 && uint( dotProduct.y * 63.49999 ) > uint( 32 * span_norm_sqr.y ) ) + { + swap(ep[0].a, ep[1].a); + swap(ep_quantized[0].a, ep_quantized[1].a); + } + } + } + else //if ((0 == mode) || (2 == mode) || (1 == mode) || (3 == mode) || (7 == mode) || (6 == mode)) + { + int p; + if (0 == threadInBlock) + { + p = 0; + } + else if (1 == threadInBlock) + { + p = candidateFixUpIndex1D[partition].x; + } + else //if (2 == threadInBlock) + { + p = candidateFixUpIndex1D[partition].y; + } + + int span_norm_sqr = dot( span, span ); + int dotProduct = dot( span, shared_temp[threadBase + p].pixel - ep[0] ); + if ( span_norm_sqr > 0 && dotProduct > 0 && uint( dotProduct * 63.49999 ) > uint( 32 * span_norm_sqr ) ) + { + swap(ep[0], ep[1]); + swap(ep_quantized[0], ep_quantized[1]); + } + } + + shared_temp[GI].endPoint_low = ep[0]; + shared_temp[GI].endPoint_high = ep[1]; + shared_temp[GI].endPoint_low_quantized = ep_quantized[0]; + shared_temp[GI].endPoint_high_quantized = ep_quantized[1]; + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + if (threadInBlock < 16) + { + uint color_index = 0; + uint alpha_index = 0; + + uint2x4 ep; + + uint2 indexPrec; + if ((0 == mode) || (1 == mode)) + { + indexPrec = 1; + } + else if (6 == mode) + { + indexPrec = 0; + } + else if (4 == mode) + { + if (0 == index_selector) + { + indexPrec = uint2(2, 1); + } + else + { + indexPrec = uint2(1, 2); + } + } + else + { + indexPrec = 2; + } + + int subset_index; + if ((0 == mode) || (2 == mode)) + { + subset_index = (bits2 >> (threadInBlock * 2)) & 0x03; + } + else if ((1 == mode) || (3 == mode) || (7 == mode)) + { + subset_index = (bits >> threadInBlock) & 0x01; + } + else + { + subset_index = 0; + } + + ep[0] = shared_temp[threadBase + subset_index].endPoint_low; + ep[1] = shared_temp[threadBase + subset_index].endPoint_high; + + int4 span = ep[1] - ep[0]; + if (mode < 4) + { + span.w = 0; + } + + if ((4 == mode) || (5 == mode)) + { + int2 span_norm_sqr; + span_norm_sqr.x = dot( span.rgb, span.rgb ); + span_norm_sqr.y = span.a * span.a; + + int dotProduct = dot( span.rgb, shared_temp[threadBase + threadInBlock].pixel.rgb - ep[0].rgb ); + color_index = ( span_norm_sqr.x <= 0 || dotProduct <= 0 ) ? 0 + : ( ( dotProduct < span_norm_sqr.x ) ? aStep[indexPrec.x][ uint( dotProduct * 63.49999 / span_norm_sqr.x ) ] : aStep[indexPrec.x][63] ); + dotProduct = dot( span.a, shared_temp[threadBase + threadInBlock].pixel.a - ep[0].a ); + alpha_index = ( span_norm_sqr.y <= 0 || dotProduct <= 0 ) ? 0 + : ( ( dotProduct < span_norm_sqr.y ) ? aStep[indexPrec.y][ uint( dotProduct * 63.49999 / span_norm_sqr.y ) ] : aStep[indexPrec.y][63] ); + + if (index_selector) + { + swap(color_index, alpha_index); + } + } + else + { + int span_norm_sqr = dot( span, span ); + + int dotProduct = dot( span, shared_temp[threadBase + threadInBlock].pixel - ep[0] ); + color_index = ( span_norm_sqr <= 0 || dotProduct <= 0 ) ? 0 + : ( ( dotProduct < span_norm_sqr ) ? aStep[indexPrec.x][ uint( dotProduct * 63.49999 / span_norm_sqr ) ] : aStep[indexPrec.x][63] ); + } + + shared_temp[GI].error = color_index; + shared_temp[GI].mode = alpha_index; + } +#ifdef REF_DEVICE + GroupMemoryBarrierWithGroupSync(); +#endif + + if (0 == threadInBlock) + { + uint4 block; + if (0 == mode) + { + block_package0( block, partition, threadBase ); + } + else if (1 == mode) + { + block_package1( block, partition, threadBase ); + } + else if (2 == mode) + { + block_package2( block, partition, threadBase ); + } + else if (3 == mode) + { + block_package3( block, partition, threadBase ); + } + else if (4 == mode) + { + block_package4( block, rotation, index_selector, threadBase ); + } + else if (5 == mode) + { + block_package5( block, rotation, threadBase ); + } + else if (6 == mode) + { + block_package6( block, threadBase ); + } + else //if (7 == mode) + { + block_package7( block, partition, threadBase ); + } + + g_OutBuff[blockID] = block; + } +} + +//uint4 truncate_and_round( uint4 color, uint bits) +//{ +// uint precisionMask = ((1 << bits) - 1) << (8 - bits); +// uint precisionHalf = (1 << (7-bits)); +// +// uint4 truncated = color & precisionMask; +// uint4 rounded = min(255, color + precisionHalf) & precisionMask; +// +// uint4 truncated_bak = truncated = truncated | (truncated >> bits); +// uint4 rounded_bak = rounded = rounded | (rounded >> bits); +// +// uint4 color_bak = color; +// +// Ensure_A_Is_Larger( rounded, color ); +// Ensure_A_Is_Larger( truncated, color_bak ); +// +// if (dot(rounded - color, rounded - color) < +// dot(truncated - color_bak, truncated - color_bak)) +// { +// return rounded_bak; +// } +// else +// { +// return truncated_bak; +// } +//} + +uint4 quantize( uint4 color, uint uPrec ) +{ + uint4 rnd = min(255, color + (1 << (7 - uPrec))); + return rnd >> (8 - uPrec); +} + +uint4 unquantize( uint4 color, uint uPrec ) +{ + color = color << (8 - uPrec); + return color | (color >> uPrec); +} + +uint2x4 compress_endpoints0( inout uint2x4 endPoint, uint2 P ) +{ + uint2x4 quantized; + for ( uint j = 0; j < 2; j ++ ) + { + quantized[j].rgb = quantize(endPoint[j].rgbb, 5).rgb & 0xFFFFFFFE; + quantized[j].rgb |= P[j]; + quantized[j].a = 0xFF; + + endPoint[j].rgb = unquantize(quantized[j].rgbb, 5).rgb; + endPoint[j].a = 0xFF; + + quantized[j] <<= 3; + } + return quantized; +} +uint2x4 compress_endpoints1( inout uint2x4 endPoint, uint2 P ) +{ + uint2x4 quantized; + for ( uint j = 0; j < 2; j ++ ) + { + quantized[j].rgb = quantize(endPoint[j].rgbb, 7).rgb & 0xFFFFFFFE; + quantized[j].rgb |= P[j]; + quantized[j].a = 0xFF; + + endPoint[j].rgb = unquantize(quantized[j].rgbb, 7).rgb; + endPoint[j].a = 0xFF; + + quantized[j] <<= 1; + } + return quantized; +} +uint2x4 compress_endpoints2( inout uint2x4 endPoint ) +{ + uint2x4 quantized; + for ( uint j = 0; j < 2; j ++ ) + { + quantized[j].rgb = quantize(endPoint[j].rgbb, 5).rgb; + quantized[j].a = 0xFF; + + endPoint[j].rgb = unquantize(quantized[j].rgbb, 5).rgb; + endPoint[j].a = 0xFF; + + quantized[j] <<= 3; + } + return quantized; +} +uint2x4 compress_endpoints3( inout uint2x4 endPoint, uint2 P ) +{ + uint2x4 quantized; + for ( uint j = 0; j < 2; j ++ ) + { + quantized[j].rgb = endPoint[j].rgb & 0xFFFFFFFE; + quantized[j].rgb |= P[j]; + quantized[j].a = 0xFF; + + endPoint[j].rgb = quantized[j].rgb; + endPoint[j].a = 0xFF; + } + return quantized; +} +uint2x4 compress_endpoints4( inout uint2x4 endPoint ) +{ + uint2x4 quantized; + for ( uint j = 0; j < 2; j ++ ) + { + quantized[j].rgb = quantize(endPoint[j].rgbb, 5).rgb; + quantized[j].a = quantize(endPoint[j].a, 6).r; + + endPoint[j].rgb = unquantize(quantized[j].rgbb, 5).rgb; + endPoint[j].a = unquantize(quantized[j].a, 6).r; + + quantized[j].rgb <<= 3; + quantized[j].a <<= 2; + } + return quantized; +} +uint2x4 compress_endpoints5( inout uint2x4 endPoint ) +{ + uint2x4 quantized; + for ( uint j = 0; j < 2; j ++ ) + { + quantized[j].rgb = quantize(endPoint[j].rgbb, 7).rgb; + quantized[j].a = endPoint[j].a; + + endPoint[j].rgb = unquantize(quantized[j].rgbb, 7).rgb; + // endPoint[j].a Alpha is full precision + + quantized[j].rgb <<= 1; + } + return quantized; +} +uint2x4 compress_endpoints6( inout uint2x4 endPoint, uint2 P ) +{ + uint2x4 quantized; + for ( uint j = 0; j < 2; j ++ ) + { + quantized[j] = endPoint[j] & 0xFFFFFFFE; + quantized[j] |= P[j]; + + endPoint[j] = quantized[j]; + } + return quantized; +} +uint2x4 compress_endpoints7( inout uint2x4 endPoint, uint2 P ) +{ + uint2x4 quantized; + for ( uint j = 0; j < 2; j ++ ) + { + quantized[j] = quantize(endPoint[j], 6) & 0xFFFFFFFE; + quantized[j] |= P[j]; + + endPoint[j] = unquantize(quantized[j], 6); + } + return quantized << 2; +} + +#define get_end_point_l(subset) shared_temp[threadBase + subset].endPoint_low_quantized +#define get_end_point_h(subset) shared_temp[threadBase + subset].endPoint_high_quantized +#define get_color_index(index) shared_temp[threadBase + index].error +#define get_alpha_index(index) shared_temp[threadBase + index].mode + +void block_package0( out uint4 block, uint partition, uint threadBase ) +{ + block.x = 0x01 | ( (partition - 64) << 1 ) + | ( ( get_end_point_l(0).r & 0xF0 ) << 1 ) | ( ( get_end_point_h(0).r & 0xF0 ) << 5 ) + | ( ( get_end_point_l(1).r & 0xF0 ) << 9 ) | ( ( get_end_point_h(1).r & 0xF0 ) << 13 ) + | ( ( get_end_point_l(2).r & 0xF0 ) << 17 ) | ( ( get_end_point_h(2).r & 0xF0 ) << 21 ) + | ( ( get_end_point_l(0).g & 0xF0 ) << 25 ); + block.y = ( ( get_end_point_l(0).g & 0xF0 ) >> 7 ) | ( ( get_end_point_h(0).g & 0xF0 ) >> 3 ) + | ( ( get_end_point_l(1).g & 0xF0 ) << 1 ) | ( ( get_end_point_h(1).g & 0xF0 ) << 5 ) + | ( ( get_end_point_l(2).g & 0xF0 ) << 9 ) | ( ( get_end_point_h(2).g & 0xF0 ) << 13 ) + | ( ( get_end_point_l(0).b & 0xF0 ) << 17 ) | ( ( get_end_point_h(0).b & 0xF0 ) << 21 ) + | ( ( get_end_point_l(1).b & 0xF0 ) << 25 ); + block.z = ( ( get_end_point_l(1).b & 0xF0 ) >> 7 ) | ( ( get_end_point_h(1).b & 0xF0 ) >> 3 ) + | ( ( get_end_point_l(2).b & 0xF0 ) << 1 ) | ( ( get_end_point_h(2).b & 0xF0 ) << 5 ) + | ( ( get_end_point_l(0).r & 0x08 ) << 10 ) | ( ( get_end_point_h(0).r & 0x08 ) << 11 ) + | ( ( get_end_point_l(1).r & 0x08 ) << 12 ) | ( ( get_end_point_h(1).r & 0x08 ) << 13 ) + | ( ( get_end_point_l(2).r & 0x08 ) << 14 ) | ( ( get_end_point_h(2).r & 0x08 ) << 15 ) + | ( get_color_index(0) << 19 ); + block.w = 0; + uint i = 1; + for ( ; i <= min( candidateFixUpIndex1DOrdered[partition][0], 4 ); i ++ ) + { + block.z |= get_color_index(i) << ( i * 3 + 18 ); + } + if ( candidateFixUpIndex1DOrdered[partition][0] < 4 ) //i = 4 + { + block.z |= get_color_index(4) << 29; + i += 1; + } + else //i = 5 + { + block.w |= ( get_color_index(4) & 0x04 ) >> 2; + for ( ; i <= candidateFixUpIndex1DOrdered[partition][0]; i ++ ) + block.w |= get_color_index(i) << ( i * 3 - 14 ); + } + for ( ; i <= candidateFixUpIndex1DOrdered[partition][1]; i ++ ) + { + block.w |= get_color_index(i) << ( i * 3 - 15 ); + } + for ( ; i < 16; i ++ ) + { + block.w |= get_color_index(i) << ( i * 3 - 16 ); + } +} +void block_package1( out uint4 block, uint partition, uint threadBase ) +{ + block.x = 0x02 | ( partition << 2 ) + | ( ( get_end_point_l(0).r & 0xFC ) << 6 ) | ( ( get_end_point_h(0).r & 0xFC ) << 12 ) + | ( ( get_end_point_l(1).r & 0xFC ) << 18 ) | ( ( get_end_point_h(1).r & 0xFC ) << 24 ); + block.y = ( ( get_end_point_l(0).g & 0xFC ) >> 2 ) | ( ( get_end_point_h(0).g & 0xFC ) << 4 ) + | ( ( get_end_point_l(1).g & 0xFC ) << 10 ) | ( ( get_end_point_h(1).g & 0xFC ) << 16 ) + | ( ( get_end_point_l(0).b & 0xFC ) << 22 ) | ( ( get_end_point_h(0).b & 0xFC ) << 28 ); + block.z = ( ( get_end_point_h(0).b & 0xFC ) >> 4 ) | ( ( get_end_point_l(1).b & 0xFC ) << 2 ) + | ( ( get_end_point_h(1).b & 0xFC ) << 8 ) + | ( ( get_end_point_l(0).r & 0x02 ) << 15 ) | ( ( get_end_point_l(1).r & 0x02 ) << 16 ) + | ( get_color_index(0) << 18 ); + if ( candidateFixUpIndex1DOrdered[partition][0] == 15 ) + { + block.w = (get_color_index(15) << 30) | (get_color_index(14) << 27) | (get_color_index(13) << 24) | (get_color_index(12) << 21) | (get_color_index(11) << 18) | (get_color_index(10) << 15) + | (get_color_index(9) << 12) | (get_color_index(8) << 9) | (get_color_index(7) << 6) | (get_color_index(6) << 3) | get_color_index(5); + block.z |= (get_color_index(4) << 29) | (get_color_index(3) << 26) | (get_color_index(2) << 23) | (get_color_index(1) << 20) | (get_color_index(0) << 18); + } + else if ( candidateFixUpIndex1DOrdered[partition][0] == 2 ) + { + block.w = (get_color_index(15) << 29) | (get_color_index(14) << 26) | (get_color_index(13) << 23) | (get_color_index(12) << 20) | (get_color_index(11) << 17) | (get_color_index(10) << 14) + | (get_color_index(9) << 11) | (get_color_index(8) << 8) | (get_color_index(7) << 5) | (get_color_index(6) << 2) | (get_color_index(5) >> 1); + block.z |= (get_color_index(5) << 31) | (get_color_index(4) << 28) | (get_color_index(3) << 25) | (get_color_index(2) << 23) | (get_color_index(1) << 20) | (get_color_index(0) << 18); + } + else if ( candidateFixUpIndex1DOrdered[partition][0] == 8 ) + { + block.w = (get_color_index(15) << 29) | (get_color_index(14) << 26) | (get_color_index(13) << 23) | (get_color_index(12) << 20) | (get_color_index(11) << 17) | (get_color_index(10) << 14) + | (get_color_index(9) << 11) | (get_color_index(8) << 9) | (get_color_index(7) << 6) | (get_color_index(6) << 3) | get_color_index(5); + block.z |= (get_color_index(4) << 29) | (get_color_index(3) << 26) | (get_color_index(2) << 23) | (get_color_index(1) << 20) | (get_color_index(0) << 18); + } + else //candidateFixUpIndex1DOrdered[partition] == 6 + { + block.w = (get_color_index(15) << 29) | (get_color_index(14) << 26) | (get_color_index(13) << 23) | (get_color_index(12) << 20) | (get_color_index(11) << 17) | (get_color_index(10) << 14) + | (get_color_index(9) << 11) | (get_color_index(8) << 8) | (get_color_index(7) << 6) | (get_color_index(6) << 4) | get_color_index(5); + block.z |= (get_color_index(4) << 29) | (get_color_index(3) << 26) | (get_color_index(2) << 23) | (get_color_index(1) << 20) | (get_color_index(0) << 18); + } +} +void block_package2( out uint4 block, uint partition, uint threadBase ) +{ + block.x = 0x04 | ( (partition - 64) << 3 ) + | ( ( get_end_point_l(0).r & 0xF8 ) << 6 ) | ( ( get_end_point_h(0).r & 0xF8 ) << 11 ) + | ( ( get_end_point_l(1).r & 0xF8 ) << 16 ) | ( ( get_end_point_h(1).r & 0xF8 ) << 21 ) + | ( ( get_end_point_l(2).r & 0xF8 ) << 26 ); + block.y = ( ( get_end_point_l(2).r & 0xF8 ) >> 6 ) | ( ( get_end_point_h(2).r & 0xF8 ) >> 1 ) + | ( ( get_end_point_l(0).g & 0xF8 ) << 4 ) | ( ( get_end_point_h(0).g & 0xF8 ) << 9 ) + | ( ( get_end_point_l(1).g & 0xF8 ) << 14 ) | ( ( get_end_point_h(1).g & 0xF8 ) << 19 ) + | ( ( get_end_point_l(2).g & 0xF8 ) << 24 ); + block.z = ( ( get_end_point_h(2).g & 0xF8 ) >> 3 ) | ( ( get_end_point_l(0).b & 0xF8 ) << 2 ) + | ( ( get_end_point_h(0).b & 0xF8 ) << 7 ) | ( ( get_end_point_l(1).b & 0xF8 ) << 12 ) + | ( ( get_end_point_h(1).b & 0xF8 ) << 17 ) | ( ( get_end_point_l(2).b & 0xF8 ) << 22 ) + | ( ( get_end_point_h(2).b & 0xF8 ) << 27 ); + block.w = ( ( get_end_point_h(2).b & 0xF8 ) >> 5 ) + | ( get_color_index(0) << 3 ); + uint i = 1; + for ( ; i <= candidateFixUpIndex1DOrdered[partition][0]; i ++ ) + { + block.w |= get_color_index(i) << ( i * 2 + 2 ); + } + for ( ; i <= candidateFixUpIndex1DOrdered[partition][1]; i ++ ) + { + block.w |= get_color_index(i) << ( i * 2 + 1 ); + } + for ( ; i < 16; i ++ ) + { + block.w |= get_color_index(i) << ( i * 2 ); + } +} +void block_package3( out uint4 block, uint partition, uint threadBase ) +{ + block.x = 0x08 | ( partition << 4 ) + | ( ( get_end_point_l(0).r & 0xFE ) << 9 ) | ( ( get_end_point_h(0).r & 0xFE ) << 16 ) + | ( ( get_end_point_l(1).r & 0xFE ) << 23 ) | ( ( get_end_point_h(1).r & 0xFE ) << 30 ); + block.y = ( ( get_end_point_h(1).r & 0xFE ) >> 2 ) | ( ( get_end_point_l(0).g & 0xFE ) << 5 ) + | ( ( get_end_point_h(0).g & 0xFE ) << 12 ) | ( ( get_end_point_l(1).g & 0xFE ) << 19 ) + | ( ( get_end_point_h(1).g & 0xFE ) << 26 ); + block.z = ( ( get_end_point_h(1).g & 0xFE ) >> 6 ) | ( ( get_end_point_l(0).b & 0xFE ) << 1 ) + | ( ( get_end_point_h(0).b & 0xFE ) << 8 ) | ( ( get_end_point_l(1).b & 0xFE ) << 15 ) + | ( ( get_end_point_h(1).b & 0xFE ) << 22 ) + | ( ( get_end_point_l(0).r & 0x01 ) << 30 ) | ( ( get_end_point_h(0).r & 0x01 ) << 31 ); + block.w = ( ( get_end_point_l(1).r & 0x01 ) << 0 ) | ( ( get_end_point_h(1).r & 0x01 ) << 1 ) + | ( get_color_index(0) << 2 ); + uint i = 1; + for ( ; i <= candidateFixUpIndex1DOrdered[partition][0]; i ++ ) + { + block.w |= get_color_index(i) << ( i * 2 + 1 ); + } + for ( ; i < 16; i ++ ) + { + block.w |= get_color_index(i) << ( i * 2 ); + } +} +void block_package4( out uint4 block, uint rotation, uint index_selector, uint threadBase ) +{ + block.x = 0x10 | ( (rotation & 3) << 5 ) | ( (index_selector & 1) << 7 ) + | ( ( get_end_point_l(0).r & 0xF8 ) << 5 ) | ( ( get_end_point_h(0).r & 0xF8 ) << 10 ) + | ( ( get_end_point_l(0).g & 0xF8 ) << 15 ) | ( ( get_end_point_h(0).g & 0xF8 ) << 20 ) + | ( ( get_end_point_l(0).b & 0xF8 ) << 25 ); + + block.y = ( ( get_end_point_l(0).b & 0xF8 ) >> 7 ) | ( ( get_end_point_h(0).b & 0xF8 ) >> 2 ) + | ( ( get_end_point_l(0).a & 0xFC ) << 4 ) | ( ( get_end_point_h(0).a & 0xFC ) << 10 ) + | ( (get_color_index(0) & 1) << 18 ) | ( get_color_index(1) << 19 ) | ( get_color_index(2) << 21 ) | ( get_color_index(3) << 23 ) + | ( get_color_index(4) << 25 ) | ( get_color_index(5) << 27 ) | ( get_color_index(6) << 29 ) | ( get_color_index(7) << 31 ); + + block.z = ( get_color_index(7) >> 1 ) | ( get_color_index(8) << 1 ) | ( get_color_index(9) << 3 ) | ( get_color_index(10)<< 5 ) + | ( get_color_index(11)<< 7 ) | ( get_color_index(12)<< 9 ) | ( get_color_index(13)<< 11 ) | ( get_color_index(14)<< 13 ) + | ( get_color_index(15)<< 15 ) | ( (get_alpha_index(0) & 3) << 17 ) | ( get_alpha_index(1) << 19 ) | ( get_alpha_index(2) << 22 ) + | ( get_alpha_index(3) << 25 ) | ( get_alpha_index(4) << 28 ) | ( get_alpha_index(5) << 31 ); + + block.w = ( get_alpha_index(5) >> 1 ) | ( get_alpha_index(6) << 2 ) | ( get_alpha_index(7) << 5 ) | ( get_alpha_index(8) << 8 ) + | ( get_alpha_index(9) << 11 ) | ( get_alpha_index(10)<< 14 ) | ( get_alpha_index(11)<< 17 ) | ( get_alpha_index(12)<< 20 ) + | ( get_alpha_index(13)<< 23 ) | ( get_alpha_index(14)<< 26 ) | ( get_alpha_index(15)<< 29 ); +} +void block_package5( out uint4 block, uint rotation, uint threadBase ) +{ + block.x = 0x20 | ( rotation << 6 ) + | ( ( get_end_point_l(0).r & 0xFE ) << 7 ) | ( ( get_end_point_h(0).r & 0xFE ) << 14 ) + | ( ( get_end_point_l(0).g & 0xFE ) << 21 ) | ( ( get_end_point_h(0).g & 0xFE ) << 28 ); + block.y = ( ( get_end_point_h(0).g & 0xFE ) >> 4 ) | ( ( get_end_point_l(0).b & 0xFE ) << 3 ) + | ( ( get_end_point_h(0).b & 0xFE ) << 10 ) | ( get_end_point_l(0).a << 18 ) | ( get_end_point_h(0).a << 26 ); + block.z = ( get_end_point_h(0).a >> 6 ) + | ( get_color_index(0) << 2 ) | ( get_color_index(1) << 3 ) | ( get_color_index(2) << 5 ) | ( get_color_index(3) << 7 ) + | ( get_color_index(4) << 9 ) | ( get_color_index(5) << 11 ) | ( get_color_index(6) << 13 ) | ( get_color_index(7) << 15 ) + | ( get_color_index(8) << 17 ) | ( get_color_index(9) << 19 ) | ( get_color_index(10)<< 21 ) | ( get_color_index(11)<< 23 ) + | ( get_color_index(12)<< 25 ) | ( get_color_index(13)<< 27 ) | ( get_color_index(14)<< 29 ) | ( get_color_index(15)<< 31 ); + block.w = ( get_color_index(15)>> 1 ) | ( get_alpha_index(0) << 1 ) | ( get_alpha_index(1) << 2 ) | ( get_alpha_index(2) << 4 ) + | ( get_alpha_index(3) << 6 ) | ( get_alpha_index(4) << 8 ) | ( get_alpha_index(5) << 10 ) | ( get_alpha_index(6) << 12 ) + | ( get_alpha_index(7) << 14 ) | ( get_alpha_index(8) << 16 ) | ( get_alpha_index(9) << 18 ) | ( get_alpha_index(10)<< 20 ) + | ( get_alpha_index(11)<< 22 ) | ( get_alpha_index(12)<< 24 ) | ( get_alpha_index(13)<< 26 ) | ( get_alpha_index(14)<< 28 ) + | ( get_alpha_index(15)<< 30 ); +} +void block_package6( out uint4 block, uint threadBase ) +{ + block.x = 0x40 + | ( ( get_end_point_l(0).r & 0xFE ) << 6 ) | ( ( get_end_point_h(0).r & 0xFE ) << 13 ) + | ( ( get_end_point_l(0).g & 0xFE ) << 20 ) | ( ( get_end_point_h(0).g & 0xFE ) << 27 ); + block.y = ( ( get_end_point_h(0).g & 0xFE ) >> 5 ) | ( ( get_end_point_l(0).b & 0xFE ) << 2 ) + | ( ( get_end_point_h(0).b & 0xFE ) << 9 ) | ( ( get_end_point_l(0).a & 0xFE ) << 16 ) + | ( ( get_end_point_h(0).a & 0xFE ) << 23 ) + | ( get_end_point_l(0).r & 0x01 ) << 31; + block.z = ( get_end_point_h(0).r & 0x01 ) + | ( get_color_index(0) << 1 ) | ( get_color_index(1) << 4 ) | ( get_color_index(2) << 8 ) | ( get_color_index(3) << 12 ) + | ( get_color_index(4) << 16 ) | ( get_color_index(5) << 20 ) | ( get_color_index(6) << 24 ) | ( get_color_index(7) << 28 ); + block.w = ( get_color_index(8) << 0 ) | ( get_color_index(9) << 4 ) | ( get_color_index(10)<< 8 ) | ( get_color_index(11)<< 12 ) + | ( get_color_index(12)<< 16 ) | ( get_color_index(13)<< 20 ) | ( get_color_index(14)<< 24 ) | ( get_color_index(15)<< 28 ); +} +void block_package7( out uint4 block, uint partition, uint threadBase ) +{ + block.x = 0x80 | ( partition << 8 ) + | ( ( get_end_point_l(0).r & 0xF8 ) << 11 ) | ( ( get_end_point_h(0).r & 0xF8 ) << 16 ) + | ( ( get_end_point_l(1).r & 0xF8 ) << 21 ) | ( ( get_end_point_h(1).r & 0xF8 ) << 26 ); + block.y = ( ( get_end_point_h(1).r & 0xF8 ) >> 6 ) | ( ( get_end_point_l(0).g & 0xF8 ) >> 1 ) + | ( ( get_end_point_h(0).g & 0xF8 ) << 4 ) | ( ( get_end_point_l(1).g & 0xF8 ) << 9 ) + | ( ( get_end_point_h(1).g & 0xF8 ) << 14 ) | ( ( get_end_point_l(0).b & 0xF8 ) << 19 ) + | ( ( get_end_point_h(0).b & 0xF8 ) << 24 ); + block.z = ( ( get_end_point_l(1).b & 0xF8 ) >> 3 ) | ( ( get_end_point_h(1).b & 0xF8 ) << 2 ) + | ( ( get_end_point_l(0).a & 0xF8 ) << 7 ) | ( ( get_end_point_h(0).a & 0xF8 ) << 12 ) + | ( ( get_end_point_l(1).a & 0xF8 ) << 17 ) | ( ( get_end_point_h(1).a & 0xF8 ) << 22 ) + | ( ( get_end_point_l(0).r & 0x04 ) << 28 ) | ( ( get_end_point_h(0).r & 0x04 ) << 29 ); + block.w = ( ( get_end_point_l(1).r & 0x04 ) >> 2 ) | ( ( get_end_point_h(1).r & 0x04 ) >> 1 ) + | ( get_color_index(0) << 2 ); + uint i = 1; + for ( ; i <= candidateFixUpIndex1DOrdered[partition][0]; i ++ ) + { + block.w |= get_color_index(i) << ( i * 2 + 1 ); + } + for ( ; i < 16; i ++ ) + { + block.w |= get_color_index(i) << ( i * 2 ); + } +} \ No newline at end of file diff --git a/tests/hlsl/dxsdk/BasicCompute11/BasicCompute11.hlsl b/tests/hlsl/dxsdk/BasicCompute11/BasicCompute11.hlsl new file mode 100644 index 000000000..798eea2ff --- /dev/null +++ b/tests/hlsl/dxsdk/BasicCompute11/BasicCompute11.hlsl @@ -0,0 +1,72 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile cs_4_0 -entry CSMain +//-------------------------------------------------------------------------------------- +// File: BasicCompute11.hlsl +// +// This file contains the Compute Shader to perform array A + array B +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +#ifdef USE_STRUCTURED_BUFFERS + +struct BufType +{ + int i; + float f; +#ifdef TEST_DOUBLE + double d; +#endif +}; + +StructuredBuffer Buffer0 : register(t0); +StructuredBuffer Buffer1 : register(t1); +RWStructuredBuffer BufferOut : register(u0); + +[numthreads(1, 1, 1)] +void CSMain( uint3 DTid : SV_DispatchThreadID ) +{ + BufferOut[DTid.x].i = Buffer0[DTid.x].i + Buffer1[DTid.x].i; + BufferOut[DTid.x].f = Buffer0[DTid.x].f + Buffer1[DTid.x].f; +#ifdef TEST_DOUBLE + BufferOut[DTid.x].d = Buffer0[DTid.x].d + Buffer1[DTid.x].d; +#endif +} + +#else // The following code is for raw buffers + +ByteAddressBuffer Buffer0 : register(t0); +ByteAddressBuffer Buffer1 : register(t1); +RWByteAddressBuffer BufferOut : register(u0); + +[numthreads(1, 1, 1)] +void CSMain( uint3 DTid : SV_DispatchThreadID ) +{ +#ifdef TEST_DOUBLE + int i0 = asint( Buffer0.Load( DTid.x*16 ) ); + float f0 = asfloat( Buffer0.Load( DTid.x*16+4 ) ); + double d0 = asdouble( Buffer0.Load( DTid.x*16+8 ), Buffer0.Load( DTid.x*16+12 ) ); + int i1 = asint( Buffer1.Load( DTid.x*16 ) ); + float f1 = asfloat( Buffer1.Load( DTid.x*16+4 ) ); + double d1 = asdouble( Buffer1.Load( DTid.x*16+8 ), Buffer1.Load( DTid.x*16+12 ) ); + + BufferOut.Store( DTid.x*16, asuint(i0 + i1) ); + BufferOut.Store( DTid.x*16+4, asuint(f0 + f1) ); + + uint dl, dh; + asuint( d0 + d1, dl, dh ); + + BufferOut.Store( DTid.x*16+8, dl ); + BufferOut.Store( DTid.x*16+12, dh ); +#else + int i0 = asint( Buffer0.Load( DTid.x*8 ) ); + float f0 = asfloat( Buffer0.Load( DTid.x*8+4 ) ); + int i1 = asint( Buffer1.Load( DTid.x*8 ) ); + float f1 = asfloat( Buffer1.Load( DTid.x*8+4 ) ); + + BufferOut.Store( DTid.x*8, asuint(i0 + i1) ); + BufferOut.Store( DTid.x*8+4, asuint(f0 + f1) ); +#endif // TEST_DOUBLE +} + +#endif // USE_STRUCTURED_BUFFERS diff --git a/tests/hlsl/dxsdk/BasicHLSL11/BasicHLSL.fx b/tests/hlsl/dxsdk/BasicHLSL11/BasicHLSL.fx new file mode 100644 index 000000000..bd28f862b --- /dev/null +++ b/tests/hlsl/dxsdk/BasicHLSL11/BasicHLSL.fx @@ -0,0 +1,158 @@ +//TEST_IGNORE_FILE: +//-------------------------------------------------------------------------------------- +// File: BasicHLSL.fx +// +// The effect file for the BasicHLSL sample. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + + +//-------------------------------------------------------------------------------------- +// Global variables +//-------------------------------------------------------------------------------------- +float4 g_MaterialAmbientColor; // Material's ambient color +float4 g_MaterialDiffuseColor; // Material's diffuse color +int g_nNumLights; + +float3 g_LightDir; // Light's direction in world space +float4 g_LightDiffuse; // Light's diffuse color +float4 g_LightAmbient; // Light's ambient color + +texture g_MeshTexture; // Color texture for mesh + +float g_fTime; // App's time in seconds +float4x4 g_mWorld; // World matrix for object +float4x4 g_mWorldViewProjection; // World * View * Projection matrix + + + +//-------------------------------------------------------------------------------------- +// Texture samplers +//-------------------------------------------------------------------------------------- +sampler MeshTextureSampler = +sampler_state +{ + Texture = ; + MipFilter = LINEAR; + MinFilter = LINEAR; + MagFilter = LINEAR; +}; + + +//-------------------------------------------------------------------------------------- +// Vertex shader output structure +//-------------------------------------------------------------------------------------- +struct VS_OUTPUT +{ + float4 Position : POSITION; // vertex position + float4 Diffuse : COLOR0; // vertex diffuse color (note that COLOR0 is clamped from 0..1) + float2 TextureUV : TEXCOORD0; // vertex texture coords +}; + + +//-------------------------------------------------------------------------------------- +// This shader computes standard transform and lighting +//-------------------------------------------------------------------------------------- +VS_OUTPUT RenderSceneVS( float4 vPos : POSITION, + float3 vNormal : NORMAL, + float2 vTexCoord0 : TEXCOORD0, + uniform int nNumLights, + uniform bool bTexture, + uniform bool bAnimate ) +{ + + VS_OUTPUT Output; + float3 vNormalWorldSpace; + + // Transform the position from object space to homogeneous projection space + Output.Position = mul(vPos, g_mWorldViewProjection); + + // Transform the normal from object space to world space + vNormalWorldSpace = normalize(mul(vNormal, (float3x3)g_mWorld)); // normal (world space) + + // Compute simple directional lighting equation + float3 vTotalLightDiffuse = float3(0,0,0); + for(int i=0; i 1 ) + int fBlendIntervalbelowIndex = min(0, iCurrentCascadeIndex-1); + fPixelDepth -= m_fCascadeFrustumsEyeSpaceDepthsFloat4[ fBlendIntervalbelowIndex ].x; + fBlendInterval -= m_fCascadeFrustumsEyeSpaceDepthsFloat4[ fBlendIntervalbelowIndex ].x; + + // The current pixel's blend band location will be used to determine when we need to blend and by how much. + fCurrentPixelsBlendBandLocation = fPixelDepth / fBlendInterval; + fCurrentPixelsBlendBandLocation = 1.0f - fCurrentPixelsBlendBandLocation; + // The fBlendBetweenCascadesAmount is our location in the blend band. + fBlendBetweenCascadesAmount = fCurrentPixelsBlendBandLocation / m_fCascadeBlendArea; +} + + + +//-------------------------------------------------------------------------------------- +// Calculate amount to blend between two cascades and the band where blending will occure. +//-------------------------------------------------------------------------------------- +void CalculateBlendAmountForMap ( in float4 vShadowMapTextureCoord, + in out float fCurrentPixelsBlendBandLocation, + out float fBlendBetweenCascadesAmount ) +{ + // Calcaulte the blend band for the map based selection. + float2 distanceToOne = float2 ( 1.0f - vShadowMapTextureCoord.x, 1.0f - vShadowMapTextureCoord.y ); + fCurrentPixelsBlendBandLocation = min( vShadowMapTextureCoord.x, vShadowMapTextureCoord.y ); + float fCurrentPixelsBlendBandLocation2 = min( distanceToOne.x, distanceToOne.y ); + fCurrentPixelsBlendBandLocation = + min( fCurrentPixelsBlendBandLocation, fCurrentPixelsBlendBandLocation2 ); + fBlendBetweenCascadesAmount = fCurrentPixelsBlendBandLocation / m_fCascadeBlendArea; +} + +//-------------------------------------------------------------------------------------- +// Calculate the shadow based on several options and rende the scene. +//-------------------------------------------------------------------------------------- +float4 PSMain( VS_OUTPUT Input ) : SV_TARGET +{ + float4 vDiffuse = g_txDiffuse.Sample( g_samLinear, Input.vTexcoord ); + + float4 vShadowMapTextureCoord = 0.0f; + float4 vShadowMapTextureCoord_blend = 0.0f; + + float4 vVisualizeCascadeColor = float4(0.0f,0.0f,0.0f,1.0f); + + float fPercentLit = 0.0f; + float fPercentLit_blend = 0.0f; + + + float fUpTextDepthWeight=0; + float fRightTextDepthWeight=0; + float fUpTextDepthWeight_blend=0; + float fRightTextDepthWeight_blend=0; + + int iBlurRowSize = m_iPCFBlurForLoopEnd - m_iPCFBlurForLoopStart; + iBlurRowSize *= iBlurRowSize; + float fBlurRowSize = (float)iBlurRowSize; + + int iCascadeFound = 0; + int iNextCascadeIndex = 1; + + float fCurrentPixelDepth; + + // The interval based selection technique compares the pixel's depth against the frustum's cascade divisions. + fCurrentPixelDepth = Input.vDepth; + + // This for loop is not necessary when the frustum is uniformaly divided and interval based selection is used. + // In this case fCurrentPixelDepth could be used as an array lookup into the correct frustum. + int iCurrentCascadeIndex; + + float4 vShadowMapTextureCoordViewSpace = Input.vTexShadow; + if( SELECT_CASCADE_BY_INTERVAL_FLAG ) + { + iCurrentCascadeIndex = 0; + if ( CASCADE_COUNT_FLAG > 1 ) + { + float4 vCurrentPixelDepth = Input.vDepth; + float4 fComparison = ( vCurrentPixelDepth > m_fCascadeFrustumsEyeSpaceDepthsFloat[0]); + float4 fComparison2 = ( vCurrentPixelDepth > m_fCascadeFrustumsEyeSpaceDepthsFloat[1]); + float fIndex = dot( + float4( CASCADE_COUNT_FLAG > 0, + CASCADE_COUNT_FLAG > 1, + CASCADE_COUNT_FLAG > 2, + CASCADE_COUNT_FLAG > 3) + , fComparison ) + + dot( + float4( + CASCADE_COUNT_FLAG > 4, + CASCADE_COUNT_FLAG > 5, + CASCADE_COUNT_FLAG > 6, + CASCADE_COUNT_FLAG > 7) + , fComparison2 ) ; + + fIndex = min( fIndex, CASCADE_COUNT_FLAG - 1 ); + iCurrentCascadeIndex = (int)fIndex; + } + } + + if ( !SELECT_CASCADE_BY_INTERVAL_FLAG ) + { + iCurrentCascadeIndex = 0; + if ( CASCADE_COUNT_FLAG == 1 ) + { + vShadowMapTextureCoord = vShadowMapTextureCoordViewSpace * m_vCascadeScale[0]; + vShadowMapTextureCoord += m_vCascadeOffset[0]; + } + if ( CASCADE_COUNT_FLAG > 1 ) { + for( int iCascadeIndex = 0; iCascadeIndex < CASCADE_COUNT_FLAG && iCascadeFound == 0; ++iCascadeIndex ) + { + vShadowMapTextureCoord = vShadowMapTextureCoordViewSpace * m_vCascadeScale[iCascadeIndex]; + vShadowMapTextureCoord += m_vCascadeOffset[iCascadeIndex]; + + if ( min( vShadowMapTextureCoord.x, vShadowMapTextureCoord.y ) > m_fMinBorderPadding + && max( vShadowMapTextureCoord.x, vShadowMapTextureCoord.y ) < m_fMaxBorderPadding ) + { + iCurrentCascadeIndex = iCascadeIndex; + iCascadeFound = 1; + } + } + } + } + + float4 color = 0; + + if( BLEND_BETWEEN_CASCADE_LAYERS_FLAG ) + { + // Repeat text coord calculations for the next cascade. + // The next cascade index is used for blurring between maps. + iNextCascadeIndex = min ( CASCADE_COUNT_FLAG - 1, iCurrentCascadeIndex + 1 ); + } + + float fBlendBetweenCascadesAmount = 1.0f; + float fCurrentPixelsBlendBandLocation = 1.0f; + + if( SELECT_CASCADE_BY_INTERVAL_FLAG ) + { + if( BLEND_BETWEEN_CASCADE_LAYERS_FLAG && CASCADE_COUNT_FLAG > 1 ) + { + CalculateBlendAmountForInterval ( iCurrentCascadeIndex, fCurrentPixelDepth, + fCurrentPixelsBlendBandLocation, fBlendBetweenCascadesAmount ); + } + } + else + { + + if( BLEND_BETWEEN_CASCADE_LAYERS_FLAG ) + { + CalculateBlendAmountForMap ( vShadowMapTextureCoord, + fCurrentPixelsBlendBandLocation, fBlendBetweenCascadesAmount ); + } + } + + float3 vShadowMapTextureCoordDDX; + float3 vShadowMapTextureCoordDDY; + // The derivatives are used to find the slope of the current plane. + // The derivative calculation has to be inside of the loop in order to prevent divergent flow control artifacts. + if( USE_DERIVATIVES_FOR_DEPTH_OFFSET_FLAG ) + { + vShadowMapTextureCoordDDX = ddx( vShadowMapTextureCoordViewSpace ); + vShadowMapTextureCoordDDY = ddy( vShadowMapTextureCoordViewSpace ); + + vShadowMapTextureCoordDDX *= m_vCascadeScale[iCurrentCascadeIndex]; + vShadowMapTextureCoordDDY *= m_vCascadeScale[iCurrentCascadeIndex]; + } + + ComputeCoordinatesTransform( iCurrentCascadeIndex, + Input.vInterpPos, + vShadowMapTextureCoord, + vShadowMapTextureCoordViewSpace ); + + + vVisualizeCascadeColor = vCascadeColorsMultiplier[iCurrentCascadeIndex]; + + if( USE_DERIVATIVES_FOR_DEPTH_OFFSET_FLAG ) + { + CalculateRightAndUpTexelDepthDeltas ( vShadowMapTextureCoordDDX, vShadowMapTextureCoordDDY, + fUpTextDepthWeight, fRightTextDepthWeight ); + } + + CalculatePCFPercentLit ( vShadowMapTextureCoord, fRightTextDepthWeight, + fUpTextDepthWeight, fBlurRowSize, fPercentLit ); + + if( BLEND_BETWEEN_CASCADE_LAYERS_FLAG && CASCADE_COUNT_FLAG > 1 ) + { + if( fCurrentPixelsBlendBandLocation < m_fCascadeBlendArea) + { // the current pixel is within the blend band. + + // Repeat text coord calculations for the next cascade. + // The next cascade index is used for blurring between maps. + if( !SELECT_CASCADE_BY_INTERVAL_FLAG ) + { + vShadowMapTextureCoord_blend = vShadowMapTextureCoordViewSpace * m_vCascadeScale[iNextCascadeIndex]; + vShadowMapTextureCoord_blend += m_vCascadeOffset[iNextCascadeIndex]; + } + + ComputeCoordinatesTransform( iNextCascadeIndex, Input.vInterpPos, + vShadowMapTextureCoord_blend, + vShadowMapTextureCoordViewSpace ); + + // We repeat the calcuation for the next cascade layer, when blending between maps. + if( fCurrentPixelsBlendBandLocation < m_fCascadeBlendArea) + { // the current pixel is within the blend band. + if( USE_DERIVATIVES_FOR_DEPTH_OFFSET_FLAG ) + { + + CalculateRightAndUpTexelDepthDeltas ( vShadowMapTextureCoordDDX, + vShadowMapTextureCoordDDY, + fUpTextDepthWeight_blend, + fRightTextDepthWeight_blend ); + } + CalculatePCFPercentLit ( vShadowMapTextureCoord_blend, fRightTextDepthWeight_blend, + fUpTextDepthWeight_blend, fBlurRowSize, fPercentLit_blend ); + fPercentLit = lerp( fPercentLit_blend, fPercentLit, fBlendBetweenCascadesAmount ); + // Blend the two calculated shadows by the blend amount. + } + } + } + + + if( !m_iVisualizeCascades ) vVisualizeCascadeColor = float4(1.0f,1.0f,1.0f,1.0f); + + float3 vLightDir1 = float3( -1.0f, 1.0f, -1.0f ); + float3 vLightDir2 = float3( 1.0f, 1.0f, -1.0f ); + float3 vLightDir3 = float3( 0.0f, -1.0f, 0.0f ); + float3 vLightDir4 = float3( 1.0f, 1.0f, 1.0f ); + // Some ambient-like lighting. + float fLighting = + saturate( dot( vLightDir1 , Input.vNormal ) )*0.05f + + saturate( dot( vLightDir2 , Input.vNormal ) )*0.05f + + saturate( dot( vLightDir3 , Input.vNormal ) )*0.05f + + saturate( dot( vLightDir4 , Input.vNormal ) )*0.05f ; + + float4 vShadowLighting = fLighting * 0.5f; + fLighting += saturate( dot( m_vLightDir , Input.vNormal ) ); + fLighting = lerp( vShadowLighting, fLighting, fPercentLit ); + + return fLighting * vVisualizeCascadeColor * vDiffuse; + +} + diff --git a/tests/hlsl/dxsdk/CascadedShadowMaps11/RenderCascadeShadow.hlsl b/tests/hlsl/dxsdk/CascadedShadowMaps11/RenderCascadeShadow.hlsl new file mode 100644 index 000000000..3b4d32a0d --- /dev/null +++ b/tests/hlsl/dxsdk/CascadedShadowMaps11/RenderCascadeShadow.hlsl @@ -0,0 +1,53 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VSMain -entry VSMainPancake +//-------------------------------------------------------------------------------------- +// File: RenderCascadeShadow.hlsl +// +// The shader file for the RenderCascadeScene sample. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + + +//-------------------------------------------------------------------------------------- +// Globals +//-------------------------------------------------------------------------------------- +cbuffer cbPerObject : register( b0 ) +{ + matrix g_mWorldViewProjection : packoffset( c0 ); +}; + +//-------------------------------------------------------------------------------------- +// Input / Output structures +//-------------------------------------------------------------------------------------- +struct VS_INPUT +{ + float4 vPosition : POSITION; +}; + +struct VS_OUTPUT +{ + float4 vPosition : SV_POSITION; +}; + +//-------------------------------------------------------------------------------------- +// Vertex Shader +//-------------------------------------------------------------------------------------- +VS_OUTPUT VSMain( VS_INPUT Input ) +{ + VS_OUTPUT Output; + + // There is nothing special here, just transform and write out the depth. + Output.vPosition = mul( Input.vPosition, g_mWorldViewProjection ); + + return Output; +} + + +VS_OUTPUT VSMainPancake( VS_INPUT Input ) +{ + VS_OUTPUT Output; + // after transform move clipped geometry to near plane + Output.vPosition = mul( Input.vPosition, g_mWorldViewProjection ); + //Output.vPosition.z = max( Output.vPosition.z, 0.0f ); + return Output; +} \ No newline at end of file diff --git a/tests/hlsl/dxsdk/ComputeShaderSort11/ComputeShaderSort11.hlsl b/tests/hlsl/dxsdk/ComputeShaderSort11/ComputeShaderSort11.hlsl new file mode 100644 index 000000000..db7bd5136 --- /dev/null +++ b/tests/hlsl/dxsdk/ComputeShaderSort11/ComputeShaderSort11.hlsl @@ -0,0 +1,75 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile cs_4_0 -entry BitonicSort -entry MatrixTranspose +//-------------------------------------------------------------------------------------- +// File: ComputeShaderSort11.hlsl +// +// This file contains the compute shaders to perform GPU sorting using DirectX 11. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +#define BITONIC_BLOCK_SIZE 512 + +#define TRANSPOSE_BLOCK_SIZE 16 + +//-------------------------------------------------------------------------------------- +// Constant Buffers +//-------------------------------------------------------------------------------------- +cbuffer CB : register( b0 ) +{ + unsigned int g_iLevel; + unsigned int g_iLevelMask; + unsigned int g_iWidth; + unsigned int g_iHeight; +}; + +//-------------------------------------------------------------------------------------- +// Structured Buffers +//-------------------------------------------------------------------------------------- +StructuredBuffer Input : register( t0 ); +RWStructuredBuffer Data : register( u0 ); + +//-------------------------------------------------------------------------------------- +// Bitonic Sort Compute Shader +//-------------------------------------------------------------------------------------- +groupshared unsigned int shared_data[BITONIC_BLOCK_SIZE]; + +[numthreads(BITONIC_BLOCK_SIZE, 1, 1)] +void BitonicSort( uint3 Gid : SV_GroupID, + uint3 DTid : SV_DispatchThreadID, + uint3 GTid : SV_GroupThreadID, + uint GI : SV_GroupIndex ) +{ + // Load shared data + shared_data[GI] = Data[DTid.x]; + GroupMemoryBarrierWithGroupSync(); + + // Sort the shared data + for (unsigned int j = g_iLevel >> 1 ; j > 0 ; j >>= 1) + { + unsigned int result = ((shared_data[GI & ~j] <= shared_data[GI | j]) == (bool)(g_iLevelMask & DTid.x))? shared_data[GI ^ j] : shared_data[GI]; + GroupMemoryBarrierWithGroupSync(); + shared_data[GI] = result; + GroupMemoryBarrierWithGroupSync(); + } + + // Store shared data + Data[DTid.x] = shared_data[GI]; +} + +//-------------------------------------------------------------------------------------- +// Matrix Transpose Compute Shader +//-------------------------------------------------------------------------------------- +groupshared unsigned int transpose_shared_data[TRANSPOSE_BLOCK_SIZE * TRANSPOSE_BLOCK_SIZE]; + +[numthreads(TRANSPOSE_BLOCK_SIZE, TRANSPOSE_BLOCK_SIZE, 1)] +void MatrixTranspose( uint3 Gid : SV_GroupID, + uint3 DTid : SV_DispatchThreadID, + uint3 GTid : SV_GroupThreadID, + uint GI : SV_GroupIndex ) +{ + transpose_shared_data[GI] = Input[DTid.y * g_iWidth + DTid.x]; + GroupMemoryBarrierWithGroupSync(); + uint2 XY = DTid.yx - GTid.yx + GTid.xy; + Data[XY.y * g_iHeight + XY.x] = transpose_shared_data[GTid.x * TRANSPOSE_BLOCK_SIZE + GTid.y]; +} diff --git a/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial02/Tutorial02.fx b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial02/Tutorial02.fx new file mode 100644 index 000000000..941e001b3 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial02/Tutorial02.fx @@ -0,0 +1,23 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VS -profile ps_4_0 -entry PS +//-------------------------------------------------------------------------------------- +// File: Tutorial02.fx +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Vertex Shader +//-------------------------------------------------------------------------------------- +float4 VS( float4 Pos : POSITION ) : SV_POSITION +{ + return Pos; +} + + +//-------------------------------------------------------------------------------------- +// Pixel Shader +//-------------------------------------------------------------------------------------- +float4 PS( float4 Pos : SV_POSITION ) : SV_Target +{ + return float4( 1.0f, 1.0f, 0.0f, 1.0f ); // Yellow, with Alpha = 1 +} diff --git a/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial02/Tutorial02_PS.hlsl b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial02/Tutorial02_PS.hlsl new file mode 100644 index 000000000..5a59aadc6 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial02/Tutorial02_PS.hlsl @@ -0,0 +1,3 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile ps_4_0 -entry PS +#include "Tutorial02.fx" diff --git a/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial02/Tutorial02_VS.hlsl b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial02/Tutorial02_VS.hlsl new file mode 100644 index 000000000..d58459b78 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial02/Tutorial02_VS.hlsl @@ -0,0 +1,3 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VS +#include "Tutorial02.fx" diff --git a/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial03/Tutorial03.fx b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial03/Tutorial03.fx new file mode 100644 index 000000000..941e001b3 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial03/Tutorial03.fx @@ -0,0 +1,23 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VS -profile ps_4_0 -entry PS +//-------------------------------------------------------------------------------------- +// File: Tutorial02.fx +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Vertex Shader +//-------------------------------------------------------------------------------------- +float4 VS( float4 Pos : POSITION ) : SV_POSITION +{ + return Pos; +} + + +//-------------------------------------------------------------------------------------- +// Pixel Shader +//-------------------------------------------------------------------------------------- +float4 PS( float4 Pos : SV_POSITION ) : SV_Target +{ + return float4( 1.0f, 1.0f, 0.0f, 1.0f ); // Yellow, with Alpha = 1 +} diff --git a/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial03/Tutorial03_PS.hlsl b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial03/Tutorial03_PS.hlsl new file mode 100644 index 000000000..29b6e8b2c --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial03/Tutorial03_PS.hlsl @@ -0,0 +1,3 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile ps_4_0 -entry PS +#include "Tutorial03.fx" diff --git a/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial03/Tutorial03_VS.hlsl b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial03/Tutorial03_VS.hlsl new file mode 100644 index 000000000..db47ead28 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial03/Tutorial03_VS.hlsl @@ -0,0 +1,3 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VS +#include "Tutorial03.fx" diff --git a/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial04/Tutorial04.fx b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial04/Tutorial04.fx new file mode 100644 index 000000000..deb7b585f --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial04/Tutorial04.fx @@ -0,0 +1,46 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VS -profile ps_4_0 -entry PS +//-------------------------------------------------------------------------------------- +// File: Tutorial04.fx +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Constant Buffer Variables +//-------------------------------------------------------------------------------------- +cbuffer ConstantBuffer : register( b0 ) +{ + matrix World; + matrix View; + matrix Projection; +} + +//-------------------------------------------------------------------------------------- +struct VS_OUTPUT +{ + float4 Pos : SV_POSITION; + float4 Color : COLOR0; +}; + +//-------------------------------------------------------------------------------------- +// Vertex Shader +//-------------------------------------------------------------------------------------- +VS_OUTPUT VS( float4 Pos : POSITION, float4 Color : COLOR ) +{ + VS_OUTPUT output = (VS_OUTPUT)0; + output.Pos = mul( Pos, World ); + output.Pos = mul( output.Pos, View ); + output.Pos = mul( output.Pos, Projection ); + output.Color = Color; + return output; +} + + +//-------------------------------------------------------------------------------------- +// Pixel Shader +//-------------------------------------------------------------------------------------- +float4 PS( VS_OUTPUT input ) : SV_Target +{ + return input.Color; +} diff --git a/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial04/Tutorial04_PS.hlsl b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial04/Tutorial04_PS.hlsl new file mode 100644 index 000000000..dc627637c --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial04/Tutorial04_PS.hlsl @@ -0,0 +1,3 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile ps_4_0 -entry PS +#include "Tutorial04.fx" diff --git a/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial04/Tutorial04_VS.hlsl b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial04/Tutorial04_VS.hlsl new file mode 100644 index 000000000..96d0a642c --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial04/Tutorial04_VS.hlsl @@ -0,0 +1,3 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VS +#include "Tutorial04.fx" diff --git a/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial05/Tutorial05.fx b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial05/Tutorial05.fx new file mode 100644 index 000000000..b15c99e49 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial05/Tutorial05.fx @@ -0,0 +1,54 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VS -profile ps_4_0 -entry PS +//-------------------------------------------------------------------------------------- +// File: Tutorial05.fx +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Constant Buffer Variables +//-------------------------------------------------------------------------------------- +cbuffer ConstantBuffer : register( b0 ) +{ + matrix World; + matrix View; + matrix Projection; +} + +//-------------------------------------------------------------------------------------- +struct VS_INPUT +{ + float4 Pos : POSITION; + float4 Color : COLOR; +}; + +struct PS_INPUT +{ + float4 Pos : SV_POSITION; + float4 Color : COLOR; +}; + + +//-------------------------------------------------------------------------------------- +// Vertex Shader +//-------------------------------------------------------------------------------------- +PS_INPUT VS( VS_INPUT input ) +{ + PS_INPUT output = (PS_INPUT)0; + output.Pos = mul( input.Pos, World ); + output.Pos = mul( output.Pos, View ); + output.Pos = mul( output.Pos, Projection ); + output.Color = input.Color; + + return output; +} + + +//-------------------------------------------------------------------------------------- +// Pixel Shader +//-------------------------------------------------------------------------------------- +float4 PS( PS_INPUT input) : SV_Target +{ + return input.Color; +} diff --git a/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial05/Tutorial05_PS.hlsl b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial05/Tutorial05_PS.hlsl new file mode 100644 index 000000000..acc900ff5 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial05/Tutorial05_PS.hlsl @@ -0,0 +1,3 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile ps_4_0 -entry PS +#include "Tutorial05.fx" diff --git a/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial05/Tutorial05_VS.hlsl b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial05/Tutorial05_VS.hlsl new file mode 100644 index 000000000..726f05979 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial05/Tutorial05_VS.hlsl @@ -0,0 +1,3 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VS +#include "Tutorial05.fx" diff --git a/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial06/Tutorial06.fx b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial06/Tutorial06.fx new file mode 100644 index 000000000..7d839009d --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial06/Tutorial06.fx @@ -0,0 +1,76 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VS -profile ps_4_0 -entry PS -entry PSSolid +//-------------------------------------------------------------------------------------- +// File: Tutorial06.fx +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + + +//-------------------------------------------------------------------------------------- +// Constant Buffer Variables +//-------------------------------------------------------------------------------------- +cbuffer ConstantBuffer : register( b0 ) +{ + matrix World; + matrix View; + matrix Projection; + float4 vLightDir[2]; + float4 vLightColor[2]; + float4 vOutputColor; +} + + +//-------------------------------------------------------------------------------------- +struct VS_INPUT +{ + float4 Pos : POSITION; + float3 Norm : NORMAL; +}; + +struct PS_INPUT +{ + float4 Pos : SV_POSITION; + float3 Norm : TEXCOORD0; +}; + + +//-------------------------------------------------------------------------------------- +// Vertex Shader +//-------------------------------------------------------------------------------------- +PS_INPUT VS( VS_INPUT input ) +{ + PS_INPUT output = (PS_INPUT)0; + output.Pos = mul( input.Pos, World ); + output.Pos = mul( output.Pos, View ); + output.Pos = mul( output.Pos, Projection ); + output.Norm = mul( float4( input.Norm, 1 ), World ).xyz; + + return output; +} + + +//-------------------------------------------------------------------------------------- +// Pixel Shader +//-------------------------------------------------------------------------------------- +float4 PS( PS_INPUT input) : SV_Target +{ + float4 finalColor = 0; + + //do NdotL lighting for 2 lights + for(int i=0; i<2; i++) + { + finalColor += saturate( dot( (float3)vLightDir[i],input.Norm) * vLightColor[i] ); + } + finalColor.a = 1; + return finalColor; +} + + +//-------------------------------------------------------------------------------------- +// PSSolid - render a solid color +//-------------------------------------------------------------------------------------- +float4 PSSolid( PS_INPUT input) : SV_Target +{ + return vOutputColor; +} diff --git a/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial06/Tutorial06_PS.hlsl b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial06/Tutorial06_PS.hlsl new file mode 100644 index 000000000..31ed082e7 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial06/Tutorial06_PS.hlsl @@ -0,0 +1,3 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile ps_4_0 -entry PS +#include "Tutorial06.fx" diff --git a/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial06/Tutorial06_VS.hlsl b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial06/Tutorial06_VS.hlsl new file mode 100644 index 000000000..a5512efb6 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial06/Tutorial06_VS.hlsl @@ -0,0 +1,3 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VS +#include "Tutorial06.fx" diff --git a/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial07/Tutorial07.fx b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial07/Tutorial07.fx new file mode 100644 index 000000000..0baad7a0c --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial07/Tutorial07.fx @@ -0,0 +1,67 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VS -profile ps_4_0 -entry PS +//-------------------------------------------------------------------------------------- +// File: Tutorial07.fx +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Constant Buffer Variables +//-------------------------------------------------------------------------------------- +Texture2D txDiffuse : register( t0 ); +SamplerState samLinear : register( s0 ); + +cbuffer cbNeverChanges : register( b0 ) +{ + matrix View; +}; + +cbuffer cbChangeOnResize : register( b1 ) +{ + matrix Projection; +}; + +cbuffer cbChangesEveryFrame : register( b2 ) +{ + matrix World; + float4 vMeshColor; +}; + + +//-------------------------------------------------------------------------------------- +struct VS_INPUT +{ + float4 Pos : POSITION; + float2 Tex : TEXCOORD0; +}; + +struct PS_INPUT +{ + float4 Pos : SV_POSITION; + float2 Tex : TEXCOORD0; +}; + + +//-------------------------------------------------------------------------------------- +// Vertex Shader +//-------------------------------------------------------------------------------------- +PS_INPUT VS( VS_INPUT input ) +{ + PS_INPUT output = (PS_INPUT)0; + output.Pos = mul( input.Pos, World ); + output.Pos = mul( output.Pos, View ); + output.Pos = mul( output.Pos, Projection ); + output.Tex = input.Tex; + + return output; +} + + +//-------------------------------------------------------------------------------------- +// Pixel Shader +//-------------------------------------------------------------------------------------- +float4 PS( PS_INPUT input) : SV_Target +{ + return txDiffuse.Sample( samLinear, input.Tex ) * vMeshColor; +} diff --git a/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial07/Tutorial07_PS.hlsl b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial07/Tutorial07_PS.hlsl new file mode 100644 index 000000000..c3c101943 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial07/Tutorial07_PS.hlsl @@ -0,0 +1,3 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile ps_4_0 -entry PS +#include "Tutorial07.fx" diff --git a/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial07/Tutorial07_VS.hlsl b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial07/Tutorial07_VS.hlsl new file mode 100644 index 000000000..4c287c790 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11Tutorials/Tutorial07/Tutorial07_VS.hlsl @@ -0,0 +1,3 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VS +#include "Tutorial07.fx" diff --git a/tests/hlsl/dxsdk/Direct3D11TutorialsDXUT/Tutorial08/Tutorial08.fx b/tests/hlsl/dxsdk/Direct3D11TutorialsDXUT/Tutorial08/Tutorial08.fx new file mode 100644 index 000000000..6ff313b97 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11TutorialsDXUT/Tutorial08/Tutorial08.fx @@ -0,0 +1,56 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VS -profile ps_4_0 -entry PS +//-------------------------------------------------------------------------------------- +// File: Tutorial08.fx +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Constant Buffer Variables +//-------------------------------------------------------------------------------------- +Texture2D txDiffuse : register( t0 ); +SamplerState samLinear : register( s0 ); + +cbuffer cbChangesEveryFrame : register( b0 ) +{ + matrix WorldViewProj; + matrix World; + float4 vMeshColor; +}; + + +//-------------------------------------------------------------------------------------- +struct VS_INPUT +{ + float4 Pos : POSITION; + float2 Tex : TEXCOORD; +}; + +struct PS_INPUT +{ + float4 Pos : SV_POSITION; + float2 Tex : TEXCOORD0; +}; + + +//-------------------------------------------------------------------------------------- +// Vertex Shader +//-------------------------------------------------------------------------------------- +PS_INPUT VS( VS_INPUT input ) +{ + PS_INPUT output = (PS_INPUT)0; + output.Pos = mul( input.Pos, WorldViewProj ); + output.Tex = input.Tex; + + return output; +} + + +//-------------------------------------------------------------------------------------- +// Pixel Shader +//-------------------------------------------------------------------------------------- +float4 PS( PS_INPUT input) : SV_Target +{ + return txDiffuse.Sample( samLinear, input.Tex ) * vMeshColor; +} diff --git a/tests/hlsl/dxsdk/Direct3D11TutorialsDXUT/Tutorial09/Tutorial09.fx b/tests/hlsl/dxsdk/Direct3D11TutorialsDXUT/Tutorial09/Tutorial09.fx new file mode 100644 index 000000000..04a395588 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11TutorialsDXUT/Tutorial09/Tutorial09.fx @@ -0,0 +1,69 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VS -profile ps_4_0 -entry PS +//-------------------------------------------------------------------------------------- +// File: Tutorial09.fx +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Constant Buffer Variables +//-------------------------------------------------------------------------------------- +Texture2D txDiffuse : register( t0 ); +SamplerState samLinear : register( s0 ); + +cbuffer cbNeverChanges : register( b0 ) +{ + float3 vLightDir; +}; + +cbuffer cbChangesEveryFrame : register( b1 ) +{ + matrix WorldViewProj; + matrix World; +}; + +struct VS_INPUT +{ + float3 Pos : POSITION; //position + float3 Norm : NORMAL; //normal + float2 Tex : TEXCOORD0; //texture coordinate +}; + +struct PS_INPUT +{ + float4 Pos : SV_POSITION; + float4 Diffuse : COLOR0; + float2 Tex : TEXCOORD1; +}; + + +//-------------------------------------------------------------------------------------- +// Vertex Shader +//-------------------------------------------------------------------------------------- +PS_INPUT VS( VS_INPUT input ) +{ + PS_INPUT output = (PS_INPUT)0; + output.Pos = mul( float4(input.Pos,1), WorldViewProj ); + float3 vNormalWorldSpace = normalize( mul( input.Norm, (float3x3)World ) ); + + float fLighting = saturate( dot( vNormalWorldSpace, vLightDir ) ); + output.Diffuse.rgb = fLighting; + output.Diffuse.a = 1.0f; + + output.Tex = input.Tex; + + return output; +} + + +//-------------------------------------------------------------------------------------- +// Pixel Shader +//-------------------------------------------------------------------------------------- +float4 PS( PS_INPUT input) : SV_Target +{ + //calculate lighting assuming light color is <1,1,1,1> + float4 outputColor = txDiffuse.Sample( samLinear, input.Tex ) * input.Diffuse; + outputColor.a = 1; + return outputColor; +} diff --git a/tests/hlsl/dxsdk/Direct3D11TutorialsDXUT/Tutorial10/Tutorial10.fx b/tests/hlsl/dxsdk/Direct3D11TutorialsDXUT/Tutorial10/Tutorial10.fx new file mode 100644 index 000000000..e9bded408 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11TutorialsDXUT/Tutorial10/Tutorial10.fx @@ -0,0 +1,73 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VS -profile ps_4_0 -entry PS +//-------------------------------------------------------------------------------------- +// File: Tutorial10.fx +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Constant Buffer Variables +//-------------------------------------------------------------------------------------- +Texture2D txDiffuse : register( t0 ); +SamplerState samLinear : register( s0 ); + +cbuffer cbNeverChanges : register( b0 ) +{ + float3 vLightDir; +}; + +cbuffer cbChangesEveryFrame : register( b1 ) +{ + matrix WorldViewProj; + matrix World; + float Puffiness; +}; + +struct VS_INPUT +{ + float3 Pos : POSITION; //position + float3 Norm : NORMAL; //normal + float2 Tex : TEXCOORD0; //texture coordinate +}; + +struct PS_INPUT +{ + float4 Pos : SV_POSITION; + float4 Diffuse : COLOR0; + float2 Tex : TEXCOORD1; +}; + + +//-------------------------------------------------------------------------------------- +// Vertex Shader +//-------------------------------------------------------------------------------------- +PS_INPUT VS( VS_INPUT input ) +{ + PS_INPUT output = (PS_INPUT)0; + + input.Pos += input.Norm * Puffiness; + + output.Pos = mul( float4(input.Pos,1), WorldViewProj ); + float3 vNormalWorldSpace = normalize( mul( input.Norm, (float3x3)World ) ); + + float fLighting = saturate( dot( vNormalWorldSpace, vLightDir ) ); + output.Diffuse.rgb = fLighting; + output.Diffuse.a = 1.0f; + + output.Tex = input.Tex; + + return output; +} + + +//-------------------------------------------------------------------------------------- +// Pixel Shader +//-------------------------------------------------------------------------------------- +float4 PS( PS_INPUT input) : SV_Target +{ + //calculate lighting assuming light color is <1,1,1,1> + float4 outputColor = txDiffuse.Sample( samLinear, input.Tex ) * input.Diffuse; + outputColor.a = 1; + return outputColor; +} diff --git a/tests/hlsl/dxsdk/Direct3D11TutorialsFX11/Tutorial11/Tutorial11.fx b/tests/hlsl/dxsdk/Direct3D11TutorialsFX11/Tutorial11/Tutorial11.fx new file mode 100644 index 000000000..a647a9079 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11TutorialsFX11/Tutorial11/Tutorial11.fx @@ -0,0 +1,117 @@ +//TEST_IGNORE_FILE: +//-------------------------------------------------------------------------------------- +// File: Tutorial11.fx +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + + +//-------------------------------------------------------------------------------------- +// Constant Buffer Variables +//-------------------------------------------------------------------------------------- +Texture2D g_txDiffuse; +SamplerState samLinear +{ + Filter = MIN_MAG_MIP_LINEAR; + AddressU = Wrap; + AddressV = Wrap; +}; + +cbuffer cbConstant +{ + float3 vLightDir = float3(-0.577,0.577,-0.577); +}; + +cbuffer cbChangesEveryFrame +{ + matrix World; + matrix View; + matrix Projection; + float Time; +}; + +cbuffer cbUserChanges +{ + float Waviness; +}; + +struct VS_INPUT +{ + float3 Pos : POSITION; + float3 Norm : NORMAL; + float2 Tex : TEXCOORD0; +}; + +struct PS_INPUT +{ + float4 Pos : SV_POSITION; + float3 Norm : TEXCOORD0; + float2 Tex : TEXCOORD1; +}; + +//-------------------------------------------------------------------------------------- +// DepthStates +//-------------------------------------------------------------------------------------- +DepthStencilState EnableDepth +{ + DepthEnable = TRUE; + DepthWriteMask = ALL; + DepthFunc = LESS_EQUAL; +}; + +BlendState NoBlending +{ + AlphaToCoverageEnable = FALSE; + BlendEnable[0] = FALSE; +}; + + +//-------------------------------------------------------------------------------------- +// Vertex Shader +//-------------------------------------------------------------------------------------- +PS_INPUT VS( VS_INPUT input ) +{ + PS_INPUT output = (PS_INPUT)0; + + output.Pos = mul( float4(input.Pos,1), World ); + + output.Pos.x += sin( output.Pos.y*0.1f + Time )*Waviness; + + output.Pos = mul( output.Pos, View ); + output.Pos = mul( output.Pos, Projection ); + output.Norm = mul( input.Norm, World ); + output.Tex = input.Tex; + + return output; +} + + +//-------------------------------------------------------------------------------------- +// Pixel Shader +//-------------------------------------------------------------------------------------- +float4 PS( PS_INPUT input) : SV_Target +{ + // Calculate lighting assuming light color is <1,1,1,1> + float fLighting = saturate( dot( input.Norm, vLightDir ) ); + float4 outputColor = g_txDiffuse.Sample( samLinear, input.Tex ) * fLighting; + outputColor.a = 1; + return outputColor; +} + + +//-------------------------------------------------------------------------------------- +// Technique +//-------------------------------------------------------------------------------------- +technique11 Render +{ + pass P0 + { + SetVertexShader( CompileShader( vs_4_0, VS() ) ); + SetGeometryShader( NULL ); + SetPixelShader( CompileShader( ps_4_0, PS() ) ); + + SetDepthStencilState( EnableDepth, 0 ); + SetBlendState( NoBlending, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF ); + } +} + diff --git a/tests/hlsl/dxsdk/Direct3D11TutorialsFX11/Tutorial12/Tutorial12.fx b/tests/hlsl/dxsdk/Direct3D11TutorialsFX11/Tutorial12/Tutorial12.fx new file mode 100644 index 000000000..aae7f9a87 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11TutorialsFX11/Tutorial12/Tutorial12.fx @@ -0,0 +1,129 @@ +//TEST_IGNORE_FILE: +// +// Constant Buffer Variables +// + +Texture2D g_txDiffuse; +SamplerState samLinear +{ + Filter = MIN_MAG_MIP_LINEAR; + AddressU = Wrap; + AddressV = Wrap; +}; + +TextureCube g_txEnvMap; +SamplerState samLinearClamp +{ + Filter = MIN_MAG_MIP_LINEAR; + AddressU = Clamp; + AddressV = Clamp; +}; + +cbuffer cbConstant +{ + float3 vLightDir = float3(-0.577,0.577,-0.577); +}; + +cbuffer cbChangesEveryFrame +{ + matrix World; + matrix View; + matrix Projection; + float Time; +}; + +cbuffer cbUserChanges +{ + float Waviness; +}; + +struct VS_INPUT +{ + float3 Pos : POSITION; //position + float3 Norm : NORMAL; //normal + float2 Tex : TEXCOORD0; //texture coordinate +}; + +struct PS_INPUT +{ + float4 Pos : SV_POSITION; + float3 Norm : TEXCOORD0; + float2 Tex : TEXCOORD1; + float3 ViewR : TEXCOORD2; +}; + +//-------------------------------------------------------------------------------------- +// DepthStates +//-------------------------------------------------------------------------------------- +DepthStencilState EnableDepth +{ + DepthEnable = TRUE; + DepthWriteMask = ALL; + DepthFunc = LESS_EQUAL; +}; + +BlendState NoBlending +{ + AlphaToCoverageEnable = FALSE; + BlendEnable[0] = FALSE; +}; + +// +// Vertex Shader +// +PS_INPUT VS( VS_INPUT input ) +{ + PS_INPUT output = (PS_INPUT)0; + + output.Pos = mul( float4(input.Pos,1), World ); + + output.Pos.x += sin( output.Pos.y*0.1f + Time )*Waviness; + + output.Pos = mul( output.Pos, View ); + output.Pos = mul( output.Pos, Projection ); + output.Norm = mul( input.Norm, (float3x3)World ); + output.Tex = input.Tex; + + // Calculate the reflection vector + float3 viewNorm = mul( output.Norm, (float3x3)View ); + output.ViewR = reflect( viewNorm, float3(0,0,-1.0) ); + + return output; +} + + +// +// Pixel Shader +// +float4 PS( PS_INPUT input) : SV_Target +{ + // Calculate lighting assuming light color is <1,1,1,1> + float fLighting = saturate( dot( input.Norm, vLightDir ) ); + + // Load the environment map texture + float4 cReflect = g_txEnvMap.Sample( samLinearClamp, input.ViewR ); + + // Load the diffuse texture and multiply by the lighting amount + float4 cDiffuse = g_txDiffuse.Sample( samLinear, input.Tex ) * fLighting; + + // Add diffuse to reflection and go + float4 cTotal = cDiffuse + cReflect; + cTotal.a = 1; + return cTotal; +} + +// +// Technique +// +technique11 Render +{ + pass P0 + { + SetVertexShader( CompileShader( vs_4_0, VS() ) ); + SetGeometryShader( NULL ); + SetPixelShader( CompileShader( ps_4_0, PS() ) ); + + SetDepthStencilState( EnableDepth, 0 ); + SetBlendState( NoBlending, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF ); + } +} diff --git a/tests/hlsl/dxsdk/Direct3D11TutorialsFX11/Tutorial13/Tutorial13.fx b/tests/hlsl/dxsdk/Direct3D11TutorialsFX11/Tutorial13/Tutorial13.fx new file mode 100644 index 000000000..a6f09ecc7 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11TutorialsFX11/Tutorial13/Tutorial13.fx @@ -0,0 +1,191 @@ +//TEST_IGNORE_FILE: +//-------------------------------------------------------------------------------------- +// File: Tutorial13.fx +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + + +//-------------------------------------------------------------------------------------- +// Constant Buffer Variables +//-------------------------------------------------------------------------------------- +Texture2D g_txDiffuse; +SamplerState samLinear +{ + Filter = MIN_MAG_MIP_LINEAR; + AddressU = Wrap; + AddressV = Wrap; +}; + +TextureCube g_txEnvMap; +SamplerState samLinearClamp +{ + Filter = MIN_MAG_MIP_LINEAR; + AddressU = Clamp; + AddressV = Clamp; +}; + +cbuffer cbConstant +{ + float3 vLightDir = float3(-0.577,0.577,-0.577); +}; + +cbuffer cbChangesEveryFrame +{ + matrix World; + matrix View; + matrix Projection; + float Time; +}; + +cbuffer cbUserChanges +{ + float Explode; +}; + +struct VS_INPUT +{ + float3 Pos : POSITION; + float3 Norm : NORMAL; + float2 Tex : TEXCOORD0; +}; + +struct GSPS_INPUT +{ + float4 Pos : SV_POSITION; + float3 Norm : TEXCOORD0; + float2 Tex : TEXCOORD1; +}; + +//-------------------------------------------------------------------------------------- +// DepthStates +//-------------------------------------------------------------------------------------- +DepthStencilState EnableDepth +{ + DepthEnable = TRUE; + DepthWriteMask = ALL; + DepthFunc = LESS_EQUAL; +}; + +BlendState NoBlending +{ + AlphaToCoverageEnable = FALSE; + BlendEnable[0] = FALSE; +}; + + +//-------------------------------------------------------------------------------------- +// Vertex Shader +//-------------------------------------------------------------------------------------- +GSPS_INPUT VS( VS_INPUT input ) +{ + GSPS_INPUT output = (GSPS_INPUT)0; + + output.Pos = mul( float4(input.Pos,1), World ); + output.Norm = mul( input.Norm, (float3x3)World ); + output.Tex = input.Tex; + + return output; +} + + +//-------------------------------------------------------------------------------------- +// Geometry Shader +//-------------------------------------------------------------------------------------- +[maxvertexcount(12)] +void GS( triangle GSPS_INPUT input[3], inout TriangleStream TriStream ) +{ + GSPS_INPUT output; + + // + // Calculate the face normal + // + float3 faceEdgeA = input[1].Pos - input[0].Pos; + float3 faceEdgeB = input[2].Pos - input[0].Pos; + float3 faceNormal = normalize( cross(faceEdgeA, faceEdgeB) ); + float3 ExplodeAmt = faceNormal*Explode; + + // + // Calculate the face center + // + float3 centerPos = (input[0].Pos.xyz + input[1].Pos.xyz + input[2].Pos.xyz)/3.0; + float2 centerTex = (input[0].Tex + input[1].Tex + input[2].Tex)/3.0; + centerPos += faceNormal*Explode; + + // + // Output the pyramid + // + for( int i=0; i<3; i++ ) + { + output.Pos = input[i].Pos + float4(ExplodeAmt,0); + output.Pos = mul( output.Pos, View ); + output.Pos = mul( output.Pos, Projection ); + output.Norm = input[i].Norm; + output.Tex = input[i].Tex; + TriStream.Append( output ); + + int iNext = (i+1)%3; + output.Pos = input[iNext].Pos + float4(ExplodeAmt,0); + output.Pos = mul( output.Pos, View ); + output.Pos = mul( output.Pos, Projection ); + output.Norm = input[iNext].Norm; + output.Tex = input[iNext].Tex; + TriStream.Append( output ); + + output.Pos = float4(centerPos,1) + float4(ExplodeAmt,0); + output.Pos = mul( output.Pos, View ); + output.Pos = mul( output.Pos, Projection ); + output.Norm = faceNormal; + output.Tex = centerTex; + TriStream.Append( output ); + + TriStream.RestartStrip(); + } + + for( int i=2; i>=0; i-- ) + { + output.Pos = input[i].Pos + float4(ExplodeAmt,0); + output.Pos = mul( output.Pos, View ); + output.Pos = mul( output.Pos, Projection ); + output.Norm = -input[i].Norm; + output.Tex = input[i].Tex; + TriStream.Append( output ); + } + TriStream.RestartStrip(); +} + + +//-------------------------------------------------------------------------------------- +// Pixel Shader +//-------------------------------------------------------------------------------------- +float4 PS( GSPS_INPUT input) : SV_Target +{ + // Calculate lighting assuming light color is <1,1,1,1> + float fLighting = saturate( dot( input.Norm, vLightDir ) ); + + // Load the diffuse texture and multiply by the lighting amount + float4 cDiffuse = g_txDiffuse.Sample( samLinear, input.Tex ) * fLighting; + cDiffuse.a = 1; + + // return diffuse + return cDiffuse; +} + + +//-------------------------------------------------------------------------------------- +// Technique +//-------------------------------------------------------------------------------------- +technique11 Render +{ + pass P0 + { + SetVertexShader( CompileShader( vs_4_0, VS() ) ); + SetGeometryShader( CompileShader( gs_4_0, GS() ) ); + SetPixelShader( CompileShader( ps_4_0, PS() ) ); + + SetBlendState( NoBlending, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF ); + SetDepthStencilState( EnableDepth, 0 ); + } +} + + diff --git a/tests/hlsl/dxsdk/Direct3D11TutorialsFX11/Tutorial14/Tutorial14.fx b/tests/hlsl/dxsdk/Direct3D11TutorialsFX11/Tutorial14/Tutorial14.fx new file mode 100644 index 000000000..b1e45b842 --- /dev/null +++ b/tests/hlsl/dxsdk/Direct3D11TutorialsFX11/Tutorial14/Tutorial14.fx @@ -0,0 +1,294 @@ +//TEST_IGNORE_FILE: +//-------------------------------------------------------------------------------------- +// File: Tutorial14.fx +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + + +//-------------------------------------------------------------------------------------- +// Constant Buffer Variables +//-------------------------------------------------------------------------------------- +Texture2D g_txDiffuse; +SamplerState samLinear +{ + Filter = MIN_MAG_MIP_LINEAR; + AddressU = Wrap; + AddressV = Wrap; +}; + +cbuffer cbConstant +{ + float3 vLightDir = float3(-0.577,0.577,-0.577); +}; + +cbuffer cbChangesEveryFrame +{ + matrix World; + matrix View; + matrix Projection; +}; + +struct VS_INPUT +{ + float3 Pos : POSITION; //position + float3 Norm : NORMAL; //normal + float2 Tex : TEXCOORD0; //texture coordinate +}; + +struct PS_INPUT +{ + float4 Pos : SV_POSITION; + float3 Norm : TEXCOORD0; + float2 Tex : TEXCOORD1; +}; + +struct QUADVS_INPUT +{ + float4 Pos : POSITION; + float2 Tex : TEXCOORD0; +}; + +struct QUADVS_OUTPUT +{ + float4 Pos : SV_POSITION; // Transformed position + float2 Tex : TEXCOORD0; +}; + +//-------------------------------------------------------------------------------------- +// Blending States +//-------------------------------------------------------------------------------------- +BlendState NoBlending +{ + BlendEnable[0] = FALSE; +}; + +BlendState SrcAlphaBlendingAdd +{ + BlendEnable[0] = TRUE; + SrcBlend = SRC_ALPHA; + DestBlend = ONE; + BlendOp = ADD; + SrcBlendAlpha = ZERO; + DestBlendAlpha = ZERO; + BlendOpAlpha = ADD; + RenderTargetWriteMask[0] = 0x0F; +}; + +BlendState SrcAlphaBlendingSub +{ + BlendEnable[0] = TRUE; + SrcBlend = SRC_ALPHA; + DestBlend = ONE; + BlendOp = SUBTRACT; + SrcBlendAlpha = ZERO; + DestBlendAlpha = ZERO; + BlendOpAlpha = ADD; + RenderTargetWriteMask[0] = 0x0F; +}; + +BlendState SrcColorBlendingAdd +{ + BlendEnable[0] = TRUE; + SrcBlend = SRC_COLOR; + DestBlend = ONE; + BlendOp = ADD; + SrcBlendAlpha = ZERO; + DestBlendAlpha = ZERO; + BlendOpAlpha = ADD; + RenderTargetWriteMask[0] = 0x0F; +}; + +BlendState SrcColorBlendingSub +{ + BlendEnable[0] = TRUE; + SrcBlend = SRC_COLOR; + DestBlend = ONE; + BlendOp = SUBTRACT; + SrcBlendAlpha = ZERO; + DestBlendAlpha = ZERO; + BlendOpAlpha = ADD; + RenderTargetWriteMask[0] = 0x0F; +}; + +//-------------------------------------------------------------------------------------- +// Depth/Stencil States +//-------------------------------------------------------------------------------------- +DepthStencilState RenderWithStencilState +{ + DepthEnable = false; + DepthWriteMask = ZERO; + DepthFunc = Less; + + // Setup stencil states + StencilEnable = true; + StencilReadMask = 0xFF; + StencilWriteMask = 0x00; + + FrontFaceStencilFunc = Not_Equal; + FrontFaceStencilPass = Keep; + FrontFaceStencilFail = Zero; + + BackFaceStencilFunc = Not_Equal; + BackFaceStencilPass = Keep; + BackFaceStencilFail = Zero; +}; + + + +//-------------------------------------------------------------------------------------- +// Scene Vertex Shader +//-------------------------------------------------------------------------------------- +PS_INPUT VS( VS_INPUT input ) +{ + PS_INPUT output = (PS_INPUT)0; + + output.Pos = mul( float4(input.Pos,1), World ); + output.Pos = mul( output.Pos, View ); + output.Pos = mul( output.Pos, Projection ); + output.Norm = mul( input.Norm, World ); + output.Tex = input.Tex; + + return output; +} + +//----------------------------------------------------------------------------- +// Quad Vertex Shaders +//----------------------------------------------------------------------------- +QUADVS_OUTPUT QuadVS( QUADVS_INPUT Input ) +{ + QUADVS_OUTPUT Output; + Output.Pos = mul( Input.Pos, World ); + Output.Pos = mul( Output.Pos, View ); + Output.Pos = mul( Output.Pos, Projection ); + Output.Tex = Input.Tex; + return Output; +} + +QUADVS_OUTPUT ScreenQuadVS( QUADVS_INPUT Input ) +{ + QUADVS_OUTPUT Output; + Output.Pos = Input.Pos; + Output.Tex = Input.Tex; + return Output; +} + +//-------------------------------------------------------------------------------------- +// Pixel Shader +//-------------------------------------------------------------------------------------- +float4 PS( PS_INPUT input) : SV_Target +{ + // Calculate lighting assuming light color is <1,1,1,1> + float fLighting = saturate( dot( input.Norm, vLightDir ) ); + float4 outputColor = g_txDiffuse.Sample( samLinear, input.Tex ) * fLighting; + outputColor.a = 1; + return outputColor; +} + +//-------------------------------------------------------------------------------------- +// Quad Pixel Shader +//-------------------------------------------------------------------------------------- +float4 QuadPS( QUADVS_OUTPUT input) : SV_Target +{ + return g_txDiffuse.Sample( samLinear, input.Tex ); +} + + +//-------------------------------------------------------------------------------------- +// Scene Techniques +//-------------------------------------------------------------------------------------- +technique11 RenderScene +{ + pass P0 + { + SetVertexShader( CompileShader( vs_4_0, VS() ) ); + SetGeometryShader( NULL ); + SetPixelShader( CompileShader( ps_4_0, PS() ) ); + SetBlendState( NoBlending, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF ); + } +} + +//-------------------------------------------------------------------------------------- +// RenderWithStencil - set the depth stencil state inside of the technique +//-------------------------------------------------------------------------------------- +technique11 RenderWithStencil +{ + pass P0 + { + SetVertexShader( CompileShader( vs_4_0, ScreenQuadVS() ) ); + SetGeometryShader( NULL ); + SetPixelShader( CompileShader( ps_4_0, QuadPS() ) ); + + SetBlendState( NoBlending, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF ); + SetDepthStencilState( RenderWithStencilState, 0 ); + } +} + +//-------------------------------------------------------------------------------------- +// Quad Techniques: Alpha blending state is set inside the technique +//-------------------------------------------------------------------------------------- +technique11 RenderQuadSolid +{ + pass P0 + { + SetVertexShader( CompileShader( vs_4_0, QuadVS() ) ); + SetGeometryShader( NULL ); + SetPixelShader( CompileShader( ps_4_0, QuadPS() ) ); + + SetBlendState( NoBlending, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF ); + } +} + +//-------------------------------------------------------------------------------------- +technique11 RenderQuadSrcAlphaAdd +{ + pass P0 + { + SetVertexShader( CompileShader( vs_4_0, QuadVS() ) ); + SetGeometryShader( NULL ); + SetPixelShader( CompileShader( ps_4_0, QuadPS() ) ); + + SetBlendState( SrcAlphaBlendingAdd, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF ); + } +} + +//-------------------------------------------------------------------------------------- +technique11 RenderQuadSrcAlphaSub +{ + pass P0 + { + SetVertexShader( CompileShader( vs_4_0, QuadVS() ) ); + SetGeometryShader( NULL ); + SetPixelShader( CompileShader( ps_4_0, QuadPS() ) ); + + SetBlendState( SrcAlphaBlendingSub, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF ); + } +} + +//-------------------------------------------------------------------------------------- +technique11 RenderQuadSrcColorAdd +{ + pass P0 + { + SetVertexShader( CompileShader( vs_4_0, QuadVS() ) ); + SetGeometryShader( NULL ); + SetPixelShader( CompileShader( ps_4_0, QuadPS() ) ); + + SetBlendState( SrcColorBlendingAdd, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF ); + } +} + +//-------------------------------------------------------------------------------------- +technique11 RenderQuadSrcColorSub +{ + pass P0 + { + SetVertexShader( CompileShader( vs_4_0, QuadVS() ) ); + SetGeometryShader( NULL ); + SetPixelShader( CompileShader( ps_4_0, QuadPS() ) ); + + SetBlendState( SrcColorBlendingSub, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF ); + } +} + + diff --git a/tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_LightPSH.h b/tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_LightPSH.h new file mode 100644 index 000000000..b44251829 --- /dev/null +++ b/tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_LightPSH.h @@ -0,0 +1,84 @@ +//-------------------------------------------------------------------------------------- +// File: DynamicShaderLinkage11_LightPSH.h +// +// The pixel shader light header file for the DynamicShaderLinkage11 sample. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Interfaces +//-------------------------------------------------------------------------------------- +interface iBaseLight +{ + float3 IlluminateAmbient(float3 vNormal); + + float3 IlluminateDiffuse(float3 vNormal); + + float3 IlluminateSpecular(float3 vNormal, int specularPower ); + +}; + +//-------------------------------------------------------------------------------------- +// Classes +//-------------------------------------------------------------------------------------- +class cAmbientLight : iBaseLight +{ + float3 m_vLightColor; + bool m_bEnable; + + float3 IlluminateAmbient(float3 vNormal); + + float3 IlluminateDiffuse(float3 vNormal) + { + return (float3)0; + } + + float3 IlluminateSpecular(float3 vNormal, int specularPower ) + { + return (float3)0; + } +}; + +class cHemiAmbientLight : cAmbientLight +{ + // inherited float4 m_vLightColor is the SkyColor + float4 m_vGroundColor; + float4 m_vDirUp; + + float3 IlluminateAmbient(float3 vNormal); + +}; + +class cDirectionalLight : cAmbientLight +{ + // inherited float4 m_vLightColor is the LightColor + float4 m_vLightDir; + + float3 IlluminateDiffuse( float3 vNormal ); + + float3 IlluminateSpecular( float3 vNormal, int specularPower ); + +}; + +class cOmniLight : cAmbientLight +{ + float3 m_vLightPosition; + float radius; + + float3 IlluminateDiffuse( float3 vNormal ); + +}; + +class cSpotLight : cAmbientLight +{ + float3 m_vLightPosition; + float3 m_vLightDir; +}; + +class cEnvironmentLight : cAmbientLight +{ + float3 IlluminateSpecular( float3 vNormal, int specularPower ); +}; + + diff --git a/tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_MaterialPSH.h b/tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_MaterialPSH.h new file mode 100644 index 000000000..7f6bc3d22 --- /dev/null +++ b/tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_MaterialPSH.h @@ -0,0 +1,103 @@ +//-------------------------------------------------------------------------------------- +// File: DynamicShaderLinkage11_MATERIALPSH.h +// +// The pixel shader material header file for the DynamicShaderLinkage11 sample. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Interfaces +//-------------------------------------------------------------------------------------- +interface iBaseMaterial +{ + float3 GetAmbientColor(float2 vTexcoord); + + float3 GetDiffuseColor(float2 vTexcoord); + + int GetSpecularPower(); + +}; + +//-------------------------------------------------------------------------------------- +// Classes +//-------------------------------------------------------------------------------------- +class cBaseMaterial : iBaseMaterial +{ + float3 m_vColor; + int m_iSpecPower; + + float3 GetAmbientColor(float2 vTexcoord) + { + return m_vColor; + } + + float3 GetDiffuseColor(float2 vTexcoord) + { + return (float3)m_vColor; + } + + int GetSpecularPower() + { + return m_iSpecPower; + } + +}; + +class cPlasticMaterial : cBaseMaterial +{ + +}; + +class cPlasticTexturedMaterial : cPlasticMaterial +{ + float3 GetAmbientColor(float2 vTexcoord); + + float3 GetDiffuseColor(float2 vTexcoord); + +}; + +class cPlasticLightingOnlyMaterial : cBaseMaterial +{ + float3 GetAmbientColor(float2 vTexcoord) + { + return (float3)1.0f; + } + + float3 GetDiffuseColor(float2 vTexcoord) + { + return (float3)1.0f; + } + +}; + +class cRoughMaterial : cBaseMaterial +{ + int GetSpecularPower() + { + return m_iSpecPower; + } +}; + +class cRoughTexturedMaterial : cRoughMaterial +{ + float3 GetAmbientColor(float2 vTexcoord); + + float3 GetDiffuseColor(float2 vTexcoord); + +}; + + +class cRoughLightingOnlyMaterial : cRoughMaterial +{ + float3 GetAmbientColor(float2 vTexcoord) + { + return (float3)1.0f; + } + + float3 GetDiffuseColor(float2 vTexcoord) + { + return (float3)1.0f; + } + +}; diff --git a/tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_PS.hlsl b/tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_PS.hlsl new file mode 100644 index 000000000..c3ee93057 --- /dev/null +++ b/tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_PS.hlsl @@ -0,0 +1,84 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile ps_4_0 -entry PSMain +//-------------------------------------------------------------------------------------- +// File: DynamicShaderLinkage11.psh +// +// The pixel shader header file for the DynamicShaderLinkage11 sample. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Header Includes +//-------------------------------------------------------------------------------------- +#include "DynamicShaderLinkage11_PSBuffers.h" + +// Defines for default static permutated setting +#if defined( STATIC_PERMUTE ) + #define HEMI_AMBIENT //CONST_AMBIENT //HEMI_AMBIENT + #define TEXTURE_ENABLE + #define SPECULAR_ENABLE +#endif + +//-------------------------------------------------------------------------------------- +// Input / Output structures +//-------------------------------------------------------------------------------------- +struct PS_INPUT +{ + float4 vPosition : SV_POSITION; + float3 vNormal : NORMAL; + float2 vTexcoord : TEXCOORD0; + float4 vMatrix : TEXCOORD1; +}; + +//-------------------------------------------------------------------------------------- +// Abstract Interface Instances for dyamic linkage / permutation +//-------------------------------------------------------------------------------------- +#if !defined( STATIC_PERMUTE ) + iBaseLight g_abstractAmbientLighting; + iBaseLight g_abstractDirectLighting; + iBaseLight g_abstractEnvironmentLighting; + iBaseMaterial g_abstractMaterial; +#else +//-------------------------------------------------------------------------------------- +// Concrete Instances for STATIC_PERMUTE - static permutation +//-------------------------------------------------------------------------------------- + #if defined( HEMI_AMBIENT ) + #define g_abstractAmbientLighting g_hemiAmbientLight + #else + // CONST_AMBIENT + #define g_abstractAmbientLighting g_ambientLight + #endif + #define g_abstractDirectLighting g_directionalLight + #define g_abstractEnvironmentLighting g_environmentLight + #if defined( TEXTURE_ENABLE ) + #define g_abstractMaterial g_plasticTexturedMaterial + #else + #define g_abstractMaterial g_plasticMaterial + #endif +#endif + +//-------------------------------------------------------------------------------------- +// Pixel Shader +//-------------------------------------------------------------------------------------- +float4 PSMain( PS_INPUT Input ) : SV_TARGET +{ + // Compute the Ambient term + float3 Ambient = (float3)0.0f; + Ambient = g_abstractMaterial.GetAmbientColor( Input.vTexcoord ) * g_abstractAmbientLighting.IlluminateAmbient( Input.vNormal ); + + // Accumulate the Diffuse contribution + float3 Diffuse = (float3)0.0f; + + Diffuse += g_abstractMaterial.GetDiffuseColor( Input.vTexcoord ) * g_abstractDirectLighting.IlluminateDiffuse( Input.vNormal ); + + // Compute the Specular contribution + float3 Specular = (float3)0.0f; + Specular += g_abstractDirectLighting.IlluminateSpecular( Input.vNormal, g_abstractMaterial.GetSpecularPower() ); + Specular += g_abstractEnvironmentLighting.IlluminateSpecular( Input.vNormal, g_abstractMaterial.GetSpecularPower() ); + + // Accumulate the lighting with saturation + float3 Lighting = saturate( Ambient + Diffuse + Specular ); + + return float4(Lighting,1.0f); +} diff --git a/tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_PSBuffers.h b/tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_PSBuffers.h new file mode 100644 index 000000000..e2263b832 --- /dev/null +++ b/tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_PSBuffers.h @@ -0,0 +1,129 @@ +//-------------------------------------------------------------------------------------- +// File: DynamicShaderLinkage11_LightPSH.hlsl +// +// The pixel shader light source module file for the DynamicShaderLinkage11 sample. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +#include "DynamicShaderLinkage11_LightPSH.h" +#include "DynamicShaderLinkage11_MaterialPSH.h" + +//-------------------------------------------------------------------------------------- +// Constant Buffers +//-------------------------------------------------------------------------------------- +cbuffer cbPerFrame : register( b0 ) +{ + cAmbientLight g_ambientLight; + cHemiAmbientLight g_hemiAmbientLight; + cDirectionalLight g_directionalLight; + cEnvironmentLight g_environmentLight; + float4 g_vEyeDir; +}; + +cbuffer cbPerPrimitive : register( b1 ) +{ + cPlasticMaterial g_plasticMaterial; + cPlasticTexturedMaterial g_plasticTexturedMaterial; + cPlasticLightingOnlyMaterial g_plasticLightingOnlyMaterial; + cRoughMaterial g_roughMaterial; + cRoughTexturedMaterial g_roughTexturedMaterial; + cRoughLightingOnlyMaterial g_roughLightingOnlyMaterial; +}; + +//-------------------------------------------------------------------------------------- +// Textures and Samplers +//-------------------------------------------------------------------------------------- +Texture2D g_txDiffuse : register( t0 ); +Texture2D g_txNormalMap : register( t1 ); +TextureCube g_txEnvironmentMap : register( t2 ); + +SamplerState g_samLinear : register( s0 ); + +//-------------------------------------------------------------------------------------- +// Lighting Class Methods +//-------------------------------------------------------------------------------------- +// Ambient Lighting Class Methods +float3 cAmbientLight::IlluminateAmbient(float3 vNormal) +{ + return float4( m_vLightColor * m_bEnable, 1.0f); +} + +float3 cHemiAmbientLight::IlluminateAmbient(float3 vNormal) +{ + float thetha = (dot( vNormal, m_vDirUp ) + 1.0f) / 2.0f; + + return lerp( m_vGroundColor, m_vLightColor, thetha) * m_bEnable; +} + +// Directional Light class +float3 cDirectionalLight::IlluminateDiffuse( float3 vNormal ) +{ + float lambert = saturate(dot( vNormal, m_vLightDir )); + return ((float3)lambert * m_vLightColor * m_bEnable); +} + +float3 cDirectionalLight::IlluminateSpecular( float3 vNormal, int specularPower ) +{ + float3 H = -normalize(g_vEyeDir) + m_vLightDir; + float3 halfAngle = normalize( H ); + float specular = pow( max(0,dot( halfAngle, normalize(vNormal) )), specularPower ); + + return ((float3)specular * m_vLightColor * m_bEnable); +} + +// Omni Light Class +float3 cOmniLight::IlluminateDiffuse( float3 vNormal ) +{ + return (float3)0.0f; // TO DO! +} + +// Environment Lighting +float3 cEnvironmentLight::IlluminateSpecular( float3 vNormal, int specularPower ) +{ + // compute reflection vector taking into account a cheap fresnel falloff; + float3 N = normalize(vNormal); + float3 E = normalize(g_vEyeDir); + float3 R = reflect( E, N ); + float fresnel = 1 - dot( -E, N ); + fresnel = (fresnel * fresnel * fresnel ); + + float3 specular = g_txEnvironmentMap.Sample( g_samLinear, R ) * fresnel; + + return (specular * (float3)m_bEnable); +// return ((float3)fresnel); + +} + +//-------------------------------------------------------------------------------------- +// Material Class Methods +//-------------------------------------------------------------------------------------- +// Plastic Material Methods +float3 cPlasticTexturedMaterial::GetAmbientColor(float2 vTexcoord) +{ + float4 vDiffuse = (float4)1.0f; + vDiffuse = g_txDiffuse.Sample( g_samLinear, vTexcoord ); + return m_vColor * vDiffuse; +} + +float3 cPlasticTexturedMaterial::GetDiffuseColor(float2 vTexcoord) +{ + float4 vDiffuse = (float4)1.0f; + vDiffuse = g_txDiffuse.Sample( g_samLinear, vTexcoord ); + return m_vColor * vDiffuse; +} + +// Rough Material Methods +float3 cRoughTexturedMaterial::GetAmbientColor(float2 vTexcoord) +{ + float4 vDiffuse = (float4)1.0f; + vDiffuse = g_txDiffuse.Sample( g_samLinear, vTexcoord ); + return m_vColor * vDiffuse; +} + +float3 cRoughTexturedMaterial::GetDiffuseColor(float2 vTexcoord) +{ + float4 vDiffuse = (float4)1.0f; + vDiffuse = g_txDiffuse.Sample( g_samLinear, vTexcoord ); + return m_vColor * vDiffuse; +} diff --git a/tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_VS.hlsl b/tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_VS.hlsl new file mode 100644 index 000000000..800dbf3b3 --- /dev/null +++ b/tests/hlsl/dxsdk/DynamicShaderLinkage11/DynamicShaderLinkage11_VS.hlsl @@ -0,0 +1,66 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VSMain +//-------------------------------------------------------------------------------------- +// File: DynamicShaderLinkage11_VS.hlsl +// +// The vertex shader file for the DynamicShaderLinkage11 sample. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Globals +//-------------------------------------------------------------------------------------- +cbuffer cbPerObject : register( b0 ) +{ + float4x4 g_mWorldViewProjection : packoffset( c0 ); + float4x4 g_mWorld : packoffset( c4 ); +}; + +//-------------------------------------------------------------------------------------- +// Input / Output structures +//-------------------------------------------------------------------------------------- +struct VS_INPUT +{ + float4 vPosition : POSITION; + float3 vNormal : NORMAL; + float2 vTexcoord : TEXCOORD0; +}; + +struct VS_OUTPUT +{ + float4 vPosition : SV_POSITION; + float3 vNormal : NORMAL; + float2 vTexcoord0 : TEXCOORD0; + float4 vMatrix : TEXCOORD1; // DEBUG +}; + +//-------------------------------------------------------------------------------------- +// Vertex Shader +//-------------------------------------------------------------------------------------- +// We aliased signed vectors as a unsigned format. +// Need to recover signed values. The values 1.0 and 2.0 +// are slightly inaccurate here. +float3 R10G10B10A2_UNORM_TO_R32G32B32_FLOAT( in float3 vVec ) +{ + vVec *= 2.0f; + return vVec >= 1.0f ? ( vVec - 2.0f ) : vVec; +} + +VS_OUTPUT VSMain( VS_INPUT Input ) +{ + + VS_OUTPUT Output; + float3 tmpNormal; + + Output.vPosition = mul( Input.vPosition, g_mWorldViewProjection ); + + // Expand compressed vectors + tmpNormal = R10G10B10A2_UNORM_TO_R32G32B32_FLOAT( Input.vNormal ); + Output.vNormal = mul( tmpNormal, (float3x3)g_mWorld ); + + Output.vTexcoord0 = Input.vTexcoord; + + Output.vMatrix = (float4)g_mWorld[0]; // DEBUG + return Output; +} + diff --git a/tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11.fx b/tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11.fx new file mode 100644 index 000000000..c72b98843 --- /dev/null +++ b/tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11.fx @@ -0,0 +1,192 @@ +//TEST_IGNORE_FILE: +//-------------------------------------------------------------------------------------- +// File: DynamicShaderLinkageFX11.fx +// +// The effect file for the DynamicShaderLinkageFX11 sample. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +#include "DynamicShaderLinkageFX11_VS.hlsl" +#include "DynamicShaderLinkageFX11_PS.hlsl" + +// +// Settings for static permutations. +// All of the pre-5.0 targets need static specialization +// since they don't support late binding. The below +// just selects a single specialization but you could +// create any number of them, each one representing +// a new shader with the interfaces compiled out +// due to the compile-time class references. +// + +#define StaticMaterial g_plasticTexturedMaterial +#define StaticAmbientLight g_ambientLight +#define StaticDirectLight g_directionalLight +#define StaticEnvironmentLight g_environmentLight + +technique11 FeatureLevel10 +{ + pass + { + SetRasterizerState(g_rasterizerState[g_fillMode]); + SetVertexShader(CompileShader(vs_4_0, + VSMain())); + SetPixelShader(CompileShader(ps_4_0, + PSMainUniform(StaticAmbientLight, + StaticDirectLight, + StaticEnvironmentLight, + StaticMaterial))); + } +} + +technique11 FeatureLevel10_1 +{ + pass + { + SetRasterizerState(g_rasterizerState[g_fillMode]); + SetVertexShader(CompileShader(vs_4_1, + VSMain())); + SetPixelShader(CompileShader(ps_4_1, + PSMainUniform(StaticAmbientLight, + StaticDirectLight, + StaticEnvironmentLight, + StaticMaterial))); + } +} + +// +// Variables for dynamic shader linkage. +// There are two variations here for dynamic usage. +// In the first we use the uniform entry point +// and pass in global interface variables. This +// creates a shader which refers to the global +// interface variables when running and we can bind +// concrete instances in our C++ code by using +// ID3DX11EffectInterfaceVariable::SetClassInstance. +// This approach works well when you have several +// independent variations and want to bind them +// individually in your C++ code, such as the +// different lighting and material parameters in +// this sample. +// + +iBaseLight g_abstractAmbientLighting; +iBaseLight g_abstractDirectLighting; +iBaseLight g_abstractEnvironmentLighting; +iBaseMaterial g_abstractMaterial; + +technique11 FeatureLevel11 +{ + pass + { + SetRasterizerState(g_rasterizerState[g_fillMode]); + SetVertexShader(CompileShader(vs_5_0, + VSMain())); + SetPixelShader(CompileShader(ps_5_0, + PSMainUniform(g_abstractAmbientLighting, + g_abstractDirectLighting, + g_abstractEnvironmentLighting, + g_abstractMaterial))); + } +} + +// +// In this second variation we use the non-uniform +// entry point so that we don't have to specify +// any interfaces when compiling the shader. We +// then reuse the compiled shader with different +// BindInterfaces calls so that all bindings are +// handled automatically by the effect runtime. +// Below we have multiple techniques where +// we've given a concrete binding for the material. +// Lighting parameters are left as interfaces for +// binding via effect variables, but could also +// be specified concretely if the number of variations +// is manageable. +// This approach works well for a small number of variations +// that are known in advance, as you can just list them +// in your effect and you don't need to do the +// binding work explicitly in your C++ code. +// + +VertexShader g_NonUniVS = CompileShader(vs_5_0, VSMain()); +PixelShader g_NonUniPS = CompileShader(ps_5_0, PSMainNonUniform()); + +technique11 FeatureLevel11_g_plasticMaterial +{ + pass + { + SetVertexShader(g_NonUniVS); + SetPixelShader(BindInterfaces(g_NonUniPS, + g_abstractAmbientLighting, + g_abstractDirectLighting, + g_abstractEnvironmentLighting, + g_plasticMaterial)); + } +} + +technique11 FeatureLevel11_g_plasticTexturedMaterial +{ + pass + { + SetVertexShader(g_NonUniVS); + SetPixelShader(BindInterfaces(g_NonUniPS, + g_abstractAmbientLighting, + g_abstractDirectLighting, + g_abstractEnvironmentLighting, + g_plasticTexturedMaterial)); + } +} + +technique11 FeatureLevel11_g_plasticLightingOnlyMaterial +{ + pass + { + SetVertexShader(g_NonUniVS); + SetPixelShader(BindInterfaces(g_NonUniPS, + g_abstractAmbientLighting, + g_abstractDirectLighting, + g_abstractEnvironmentLighting, + g_plasticLightingOnlyMaterial)); + } +} + +technique11 FeatureLevel11_g_roughMaterial +{ + pass + { + SetVertexShader(g_NonUniVS); + SetPixelShader(BindInterfaces(g_NonUniPS, + g_abstractAmbientLighting, + g_abstractDirectLighting, + g_abstractEnvironmentLighting, + g_roughMaterial)); + } +} + +technique11 FeatureLevel11_g_roughTexturedMaterial +{ + pass + { + SetVertexShader(g_NonUniVS); + SetPixelShader(BindInterfaces(g_NonUniPS, + g_abstractAmbientLighting, + g_abstractDirectLighting, + g_abstractEnvironmentLighting, + g_roughTexturedMaterial)); + } +} + +technique11 FeatureLevel11_g_roughLightingOnlyMaterial +{ + pass + { + SetVertexShader(g_NonUniVS); + SetPixelShader(BindInterfaces(g_NonUniPS, + g_abstractAmbientLighting, + g_abstractDirectLighting, + g_abstractEnvironmentLighting, + g_roughLightingOnlyMaterial)); + } +} diff --git a/tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_LightPSH.h b/tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_LightPSH.h new file mode 100644 index 000000000..6f9a0f4d8 --- /dev/null +++ b/tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_LightPSH.h @@ -0,0 +1,82 @@ +//-------------------------------------------------------------------------------------- +// File: DynamicShaderLinkageFX11_LightPSH.h +// +// The pixel shader light header file for the DynamicShaderLinkageFX11 sample. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Interfaces +//-------------------------------------------------------------------------------------- +interface iBaseLight +{ + float3 IlluminateAmbient(float3 vNormal); + + float3 IlluminateDiffuse(float3 vNormal); + + float3 IlluminateSpecular(float3 vNormal, int specularPower ); + +}; + +//-------------------------------------------------------------------------------------- +// Classes +//-------------------------------------------------------------------------------------- +class cAmbientLight : iBaseLight +{ + float3 m_vLightColor; + bool m_bEnable; + + float3 IlluminateAmbient(float3 vNormal); + + float3 IlluminateDiffuse(float3 vNormal) + { + return (float3)0; + } + + float3 IlluminateSpecular(float3 vNormal, int specularPower ) + { + return (float3)0; + } +}; + +class cHemiAmbientLight : cAmbientLight +{ + // inherited float4 m_vLightColor is the SkyColor + float4 m_vGroundColor; + float4 m_vDirUp; + + float3 IlluminateAmbient(float3 vNormal); + +}; + +class cDirectionalLight : cAmbientLight +{ + // inherited float4 m_vLightColor is the LightColor + float4 m_vLightDir; + + float3 IlluminateDiffuse( float3 vNormal ); + + float3 IlluminateSpecular( float3 vNormal, int specularPower ); + +}; + +class cOmniLight : cAmbientLight +{ + float3 m_vLightPosition; + float radius; + + float3 IlluminateDiffuse( float3 vNormal ); + +}; + +class cSpotLight : cAmbientLight +{ + float3 m_vLightPosition; + float3 m_vLightDir; +}; + +class cEnvironmentLight : cAmbientLight +{ + float3 IlluminateSpecular( float3 vNormal, int specularPower ); +}; diff --git a/tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_MaterialPSH.h b/tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_MaterialPSH.h new file mode 100644 index 000000000..cd54a283d --- /dev/null +++ b/tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_MaterialPSH.h @@ -0,0 +1,103 @@ +//-------------------------------------------------------------------------------------- +// File: DynamicShaderLinkageFX11_MaterialPSH.h +// +// The pixel shader material header file for the DynamicShaderLinkageFX11 sample. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Interfaces +//-------------------------------------------------------------------------------------- +interface iBaseMaterial +{ + float3 GetAmbientColor(float2 vTexcoord); + + float3 GetDiffuseColor(float2 vTexcoord); + + int GetSpecularPower(); + +}; + +//-------------------------------------------------------------------------------------- +// Classes +//-------------------------------------------------------------------------------------- +class cBaseMaterial : iBaseMaterial +{ + float3 m_vColor; + int m_iSpecPower; + + float3 GetAmbientColor(float2 vTexcoord) + { + return m_vColor; + } + + float3 GetDiffuseColor(float2 vTexcoord) + { + return (float3)m_vColor; + } + + int GetSpecularPower() + { + return m_iSpecPower; + } + +}; + +class cPlasticMaterial : cBaseMaterial +{ + +}; + +class cPlasticTexturedMaterial : cPlasticMaterial +{ + float3 GetAmbientColor(float2 vTexcoord); + + float3 GetDiffuseColor(float2 vTexcoord); + +}; + +class cPlasticLightingOnlyMaterial : cBaseMaterial +{ + float3 GetAmbientColor(float2 vTexcoord) + { + return (float3)1.0f; + } + + float3 GetDiffuseColor(float2 vTexcoord) + { + return (float3)1.0f; + } + +}; + +class cRoughMaterial : cBaseMaterial +{ + int GetSpecularPower() + { + return m_iSpecPower; + } +}; + +class cRoughTexturedMaterial : cRoughMaterial +{ + float3 GetAmbientColor(float2 vTexcoord); + + float3 GetDiffuseColor(float2 vTexcoord); + +}; + + +class cRoughLightingOnlyMaterial : cRoughMaterial +{ + float3 GetAmbientColor(float2 vTexcoord) + { + return (float3)1.0f; + } + + float3 GetDiffuseColor(float2 vTexcoord) + { + return (float3)1.0f; + } + +}; diff --git a/tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_PSBuffers.h b/tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_PSBuffers.h new file mode 100644 index 000000000..3b4c528be --- /dev/null +++ b/tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_PSBuffers.h @@ -0,0 +1,152 @@ +//-------------------------------------------------------------------------------------- +// File: DynamicShaderLinkageFX11_LightPSH.hlsl +// +// The pixel shader light source module file for the DynamicShaderLinkageFX11 sample. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +#include "DynamicShaderLinkageFX11_LightPSH.h" +#include "DynamicShaderLinkageFX11_MaterialPSH.h" + +//-------------------------------------------------------------------------------------- +// Constant Buffers +//-------------------------------------------------------------------------------------- +cbuffer cbPerFrame : register( b0 ) +{ + cAmbientLight g_ambientLight; + cHemiAmbientLight g_hemiAmbientLight; + cDirectionalLight g_directionalLight; + cEnvironmentLight g_environmentLight; + float4 g_vEyeDir; +}; + +cbuffer cbPerPrimitive : register( b1 ) +{ + cPlasticMaterial g_plasticMaterial; + cPlasticTexturedMaterial g_plasticTexturedMaterial; + cPlasticLightingOnlyMaterial g_plasticLightingOnlyMaterial; + cRoughMaterial g_roughMaterial; + cRoughTexturedMaterial g_roughTexturedMaterial; + cRoughLightingOnlyMaterial g_roughLightingOnlyMaterial; +}; + +//-------------------------------------------------------------------------------------- +// Textures and Samplers +//-------------------------------------------------------------------------------------- +Texture2D g_txDiffuse : register( t0 ); +Texture2D g_txNormalMap : register( t1 ); +TextureCube g_txEnvironmentMap : register( t2 ); + +SamplerState g_samLinear : register( s0 ) +{ + Filter = MIN_MAG_MIP_LINEAR; + AddressU = WRAP; + AddressV = WRAP; + AddressW = WRAP; +}; + +//-------------------------------------------------------------------------------------- +// Rasterization State +//-------------------------------------------------------------------------------------- +uint g_fillMode = 0; + +RasterizerState g_rasterizerState[2] +{ +{ + FillMode = SOLID; + MultisampleEnable = true; +}, +{ + FillMode = WIREFRAME; + MultisampleEnable = true; +} +}; + +//-------------------------------------------------------------------------------------- +// Lighting Class Methods +//-------------------------------------------------------------------------------------- +// Ambient Lighting Class Methods +float3 cAmbientLight::IlluminateAmbient(float3 vNormal) +{ + return m_vLightColor * m_bEnable; +} + +float3 cHemiAmbientLight::IlluminateAmbient(float3 vNormal) +{ + float thetha = (dot( vNormal, m_vDirUp.xyz ) + 1.0f) / 2.0f; + + return lerp( m_vGroundColor.xyz, m_vLightColor, thetha) * m_bEnable; +} + +// Directional Light class +float3 cDirectionalLight::IlluminateDiffuse( float3 vNormal ) +{ + float lambert = saturate(dot( vNormal, m_vLightDir.xyz )); + return ((float3)lambert * m_vLightColor * m_bEnable); +} + +float3 cDirectionalLight::IlluminateSpecular( float3 vNormal, int specularPower ) +{ + float3 H = -normalize(g_vEyeDir.xyz) + m_vLightDir.xyz; + float3 halfAngle = normalize( H ); + float specular = pow( max(0,dot( halfAngle, normalize(vNormal) )), specularPower ); + + return ((float3)specular * m_vLightColor * m_bEnable); +} + +// Omni Light Class +float3 cOmniLight::IlluminateDiffuse( float3 vNormal ) +{ + return (float3)0.0f; // TO DO! +} + +// Environment Lighting +float3 cEnvironmentLight::IlluminateSpecular( float3 vNormal, int specularPower ) +{ + // compute reflection vector taking into account a cheap fresnel falloff; + float3 N = normalize(vNormal); + float3 E = normalize(g_vEyeDir.xyz); + float3 R = reflect( E, N ); + float fresnel = 1 - dot( -E, N ); + fresnel = (fresnel * fresnel * fresnel ); + + float3 specular = g_txEnvironmentMap.Sample( g_samLinear, R ).xyz * fresnel; + + return (specular * (float3)m_bEnable); +// return ((float3)fresnel); + +} + +//-------------------------------------------------------------------------------------- +// Material Class Methods +//-------------------------------------------------------------------------------------- +// Plastic Material Methods +float3 cPlasticTexturedMaterial::GetAmbientColor(float2 vTexcoord) +{ + float4 vDiffuse = (float4)1.0f; + vDiffuse = g_txDiffuse.Sample( g_samLinear, vTexcoord ); + return m_vColor * vDiffuse.xyz; +} + +float3 cPlasticTexturedMaterial::GetDiffuseColor(float2 vTexcoord) +{ + float4 vDiffuse = (float4)1.0f; + vDiffuse = g_txDiffuse.Sample( g_samLinear, vTexcoord ); + return m_vColor * vDiffuse.xyz; +} + +// Rough Material Methods +float3 cRoughTexturedMaterial::GetAmbientColor(float2 vTexcoord) +{ + float4 vDiffuse = (float4)1.0f; + vDiffuse = g_txDiffuse.Sample( g_samLinear, vTexcoord ); + return m_vColor * vDiffuse.xyz; +} + +float3 cRoughTexturedMaterial::GetDiffuseColor(float2 vTexcoord) +{ + float4 vDiffuse = (float4)1.0f; + vDiffuse = g_txDiffuse.Sample( g_samLinear, vTexcoord ); + return m_vColor * vDiffuse.xyz; +} diff --git a/tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_ps.hlsl b/tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_ps.hlsl new file mode 100644 index 000000000..55d206259 --- /dev/null +++ b/tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_ps.hlsl @@ -0,0 +1,113 @@ +//TEST_IGNORE_FILE: +//-------------------------------------------------------------------------------------- +// File: DynamicShaderLinkageFX11.psh +// +// The pixel shader header file for the DynamicShaderLinkageFX11 sample. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Header Includes +//-------------------------------------------------------------------------------------- +#include "DynamicShaderLinkageFX11_PSBuffers.h" + +//-------------------------------------------------------------------------------------- +// Input / Output structures +//-------------------------------------------------------------------------------------- +struct PS_INPUT +{ + float4 vPosition : SV_POSITION; + float3 vNormal : NORMAL; + float2 vTexcoord : TEXCOORD0; + float4 vMatrix : TEXCOORD1; +}; + +//-------------------------------------------------------------------------------------- +// Pixel Shader +//-------------------------------------------------------------------------------------- + +// This pixel shader uses several interfaces during its +// work. We show three different ways of providing interface +// bindings for the PS and those have two different +// entry points so we've separated the base PS code +// into a worker routine that's called by the entry +// points. Normally only one technique would be used +// and this layering of entry point and worker would +// not be necessary. +float4 PSMainWorker( iBaseLight ambientLighting, + iBaseLight directLighting, + iBaseLight environmentLighting, + iBaseMaterial material, + PS_INPUT Input ) +{ + // Compute the Ambient term + float3 Ambient = (float3)0.0f; + Ambient = material.GetAmbientColor( Input.vTexcoord ) * ambientLighting.IlluminateAmbient( Input.vNormal ); + + // Accumulate the Diffuse contribution + float3 Diffuse = (float3)0.0f; + + Diffuse += material.GetDiffuseColor( Input.vTexcoord ) * directLighting.IlluminateDiffuse( Input.vNormal ); + + // Compute the Specular contribution + float3 Specular = (float3)0.0f; + Specular += directLighting.IlluminateSpecular( Input.vNormal, material.GetSpecularPower() ); + Specular += environmentLighting.IlluminateSpecular( Input.vNormal, material.GetSpecularPower() ); + + // Accumulate the lighting with saturation + float3 Lighting = saturate( Ambient + Diffuse + Specular); + + return float4(Lighting,1.0f); +} + +// One way to provide bindings for shaders in Effects 11 is +// to use uniform interface parameters. As with non-interface +// uniform parameters you must specify a value for these +// parameters in your CompileShader invocations in the effect. +// You can provide concrete class instances if you want +// to statically specialize your shaders, such as for targets +// that don't support abstract interfaces; or you can provide +// other interfaces that you bind using effect variables. +// Both are shown in this sample's technique passes. +float4 PSMainUniform( uniform iBaseLight ambientLighting, + uniform iBaseLight directLighting, + uniform iBaseLight environmentLighting, + uniform iBaseMaterial material, + PS_INPUT Input ) : SV_Target +{ + return PSMainWorker(ambientLighting, + directLighting, + environmentLighting, + material, + Input); +} + +// Another way to use Effects 11 with interfaces is +// to have non-uniform parameters, which then are +// bound with a BindInterfaces in a technique pass. +// BindInterfaces gives concrete instances to use +// with a shader but does not do static specialization, +// it just saves information for the effect runtime +// to use when setting up the shader to run. +// This lets you share a single shader, compiled with +// interface usage, while still getting the convenience +// of declaring concrete bindings in the effect and +// not needed explicit binding in code via effect +// variable updates. If you have many different +// variations it may be simpler to use bindings +// through effect variables, as then you don't +// need to list every possible binding set in your +// techniques. +float4 PSMainNonUniform( iBaseLight ambientLighting, + iBaseLight directLighting, + iBaseLight environmentLighting, + iBaseMaterial material, + PS_INPUT Input ) : SV_Target +{ + return PSMainWorker(ambientLighting, + directLighting, + environmentLighting, + material, + Input); +} diff --git a/tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_vs.hlsl b/tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_vs.hlsl new file mode 100644 index 000000000..4791e5786 --- /dev/null +++ b/tests/hlsl/dxsdk/DynamicShaderLinkageFX11/DynamicShaderLinkageFX11_vs.hlsl @@ -0,0 +1,65 @@ +//TEST_IGNORE_FILE: +//-------------------------------------------------------------------------------------- +// File: DynamicShaderLinkageFX11_VS.hlsl +// +// The vertex shader file for the DynamicShaderLinkageFX11 sample. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Globals +//-------------------------------------------------------------------------------------- +cbuffer cbPerObject : register( b0 ) +{ + float4x4 g_mWorldViewProjection : packoffset( c0 ); + float4x4 g_mWorld : packoffset( c4 ); +}; + +//-------------------------------------------------------------------------------------- +// Input / Output structures +//-------------------------------------------------------------------------------------- +struct VS_INPUT +{ + float4 vPosition : POSITION; + float3 vNormal : NORMAL; + float2 vTexcoord : TEXCOORD0; +}; + +struct VS_OUTPUT +{ + float4 vPosition : SV_POSITION; + float3 vNormal : NORMAL; + float2 vTexcoord0 : TEXCOORD0; + float4 vMatrix : TEXCOORD1; // DEBUG +}; + +//-------------------------------------------------------------------------------------- +// Vertex Shader +//-------------------------------------------------------------------------------------- +// We aliased signed vectors as a unsigned format. +// Need to recover signed values. The values 1.0 and 2.0 +// are slightly inaccurate here. +float3 R10G10B10A2_UNORM_TO_R32G32B32_FLOAT( in float3 vVec ) +{ + vVec *= 2.0f; + return vVec >= 1.0f ? ( vVec - 2.0f ) : vVec; +} + +VS_OUTPUT VSMain( VS_INPUT Input ) +{ + + VS_OUTPUT Output; + float3 tmpNormal; + + Output.vPosition = mul( Input.vPosition, g_mWorldViewProjection ); + + // Expand compressed vectors + tmpNormal = R10G10B10A2_UNORM_TO_R32G32B32_FLOAT( Input.vNormal ); + Output.vNormal = mul( tmpNormal, (float3x3)g_mWorld ); + + Output.vTexcoord0 = Input.vTexcoord; + + Output.vMatrix = (float4)g_mWorld[0]; // DEBUG + return Output; +} diff --git a/tests/hlsl/dxsdk/FixedFuncEMUFX11/FixedFuncEMU.fx b/tests/hlsl/dxsdk/FixedFuncEMUFX11/FixedFuncEMU.fx new file mode 100644 index 000000000..699df8655 --- /dev/null +++ b/tests/hlsl/dxsdk/FixedFuncEMUFX11/FixedFuncEMU.fx @@ -0,0 +1,468 @@ +//TEST_IGNORE_FILE: +// FixedFuncEMU.fx +// Copyright (c) 2005 Microsoft Corporation. All rights reserved. +// + +struct VSSceneIn +{ + float3 pos : POSITION; //position of the particle + float3 norm : NORMAL; //velocity of the particle + float2 tex : TEXTURE0; //tex coords +}; + +struct VSSceneOut +{ + float4 pos : SV_Position; //position + float2 tex : TEXTURE0; //texture coordinate + float3 wPos : TEXTURE1; //world space pos + float3 wNorm : TEXTURE2; //world space normal + float4 colorD : COLOR0; //color for gouraud and flat shading + float4 colorS : COLOR1; //color for specular + float fogDist : FOGDISTANCE; //distance used for fog calculations + float3 planeDist : SV_ClipDistance0; //clip distance for 3 planes +}; + +struct PSSceneIn +{ + float4 pos : SV_Position; //position + float2 tex : TEXTURE0; //texture coordinate + float3 wPos : TEXTURE1; //world space pos + float3 wNorm : TEXTURE2; //world space normal + float4 colorD : COLOR0; //color for gouraud and flat shading + float4 colorS : COLOR1; //color for specular + float fogDist : FOGDISTANCE; //distance used for fog calculations +}; + +struct Light +{ + float4 Position; + float4 Diffuse; + float4 Specular; + float4 Ambient; + float4 Atten; +}; + +#define FOGMODE_NONE 0 +#define FOGMODE_LINEAR 1 +#define FOGMODE_EXP 2 +#define FOGMODE_EXP2 3 +#define E 2.71828 + +cbuffer cbLights +{ + float4 g_clipplanes[3]; + Light g_lights[8]; +}; + +cbuffer cbPerFrame +{ + float4x4 g_mWorld; + float4x4 g_mView; + float4x4 g_mProj; + float4x4 g_mInvProj; + float4x4 g_mLightViewProj; +}; + +cbuffer cbPerTechnique +{ + bool g_bEnableLighting = true; + bool g_bEnableClipping = true; + bool g_bPointScaleEnable = false; + float g_pointScaleA; + float g_pointScaleB; + float g_pointScaleC; + float g_pointSize; + + //fog params + int g_fogMode = FOGMODE_NONE; + float g_fogStart; + float g_fogEnd; + float g_fogDensity; + float4 g_fogColor; +}; + +cbuffer cbPerViewChange +{ + //viewport params + float g_viewportHeight; + float g_viewportWidth; + float g_nearPlane; +}; + +cbuffer cbImmutable +{ + float3 g_positions[4] = + { + float3( -0.5, 0.5, 0 ), + float3( 0.5, 0.5, 0 ), + float3( -0.5, -0.5, 0 ), + float3( 0.5, -0.5, 0 ), + }; +}; + +Texture2D g_txDiffuse; +Texture2D g_txProjected; +SamplerState g_samLinear +{ + Filter = MIN_MAG_MIP_LINEAR; + AddressU = Clamp; + AddressV = Clamp; +}; + +DepthStencilState DisableDepth +{ + DepthEnable = FALSE; + DepthWriteMask = ZERO; +}; + +DepthStencilState EnableDepth +{ + DepthEnable = TRUE; + DepthWriteMask = ALL; +}; + +struct ColorsOutput +{ + float4 Diffuse; + float4 Specular; +}; + +ColorsOutput CalcLighting( float3 worldNormal, float3 worldPos, float3 cameraPos ) +{ + ColorsOutput output = (ColorsOutput)0.0; + + for(int i=0; i<8; i++) + { + float3 toLight = g_lights[i].Position.xyz - worldPos; + float lightDist = length( toLight ); + float fAtten = 1.0/dot( g_lights[i].Atten, float4(1,lightDist,lightDist*lightDist,0) ); + float3 lightDir = normalize( toLight ); + float3 halfAngle = normalize( normalize(-cameraPos) + lightDir ); + + output.Diffuse += max(0,dot( lightDir, worldNormal ) * g_lights[i].Diffuse * fAtten) + g_lights[i].Ambient; + output.Specular += max(0,pow( dot( halfAngle, worldNormal ), 64 ) * g_lights[i].Specular * fAtten ); + } + + return output; +} + +// +// VS for emulating fixed function pipeline +// +VSSceneOut VSScenemain(VSSceneIn input) +{ + VSSceneOut output = (VSSceneOut)0.0; + + //output our final position in clipspace + float4 worldPos = mul( float4( input.pos, 1 ), g_mWorld ); + float4 cameraPos = mul( worldPos, g_mView ); //Save cameraPos for fog calculations + output.pos = mul( cameraPos, g_mProj ); + + //save world pos for later + output.wPos = worldPos; + + //save the fog distance for later + output.fogDist = cameraPos.z; + + //find our clipping planes (fixed function clipping is done in world space) + if( g_bEnableClipping ) + { + worldPos.w = 1; + + //calc the distance from the 3 clipping planes + output.planeDist.x = dot( worldPos, g_clipplanes[0] ); + output.planeDist.y = dot( worldPos, g_clipplanes[1] ); + output.planeDist.z = dot( worldPos, g_clipplanes[2] ); + } + else + { + output.planeDist.x = 1; + output.planeDist.y = 1; + output.planeDist.z = 1; + } + + //do gouraud lighting + if( g_bEnableLighting ) + { + float3 worldNormal = normalize( mul( input.norm, (float3x3)g_mWorld ) ); + output.wNorm = worldNormal; + ColorsOutput cOut = CalcLighting( worldNormal, worldPos, cameraPos ); + output.colorD = cOut.Diffuse; + output.colorS = cOut.Specular; + } + else + { + output.colorD = float4(1,1,1,1); + } + + //propogate texture coordinate + output.tex = input.tex; + + return output; +} + +// +// VS for rendering in screen space +// +PSSceneIn VSScreenSpacemain(VSSceneIn input) +{ + PSSceneIn output = (PSSceneIn)0.0; + + //output our final position + output.pos.x = (input.pos.x / (g_viewportWidth/2.0)) -1; + output.pos.y = -(input.pos.y / (g_viewportHeight/2.0)) +1; + output.pos.z = input.pos.z; + output.pos.w = 1; + + //propogate texture coordinate + output.tex = input.tex; + output.colorD = float4(1,1,1,1); + + return output; +} + +// +// GS for flat shaded rendering +// + +[maxvertexcount(3)] +void GSFlatmain( triangle VSSceneOut input[3], inout TriangleStream FlatTriStream ) +{ + VSSceneOut output; + + // + // Calculate the face normal + // + float3 faceEdgeA = input[1].wPos - input[0].wPos; + float3 faceEdgeB = input[2].wPos - input[0].wPos; + + // + // Cross product + // + float3 faceNormal = cross(faceEdgeA, faceEdgeB); + + // + //calculate the face center + // + float3 faceCenter = (input[0].wPos + input[1].wPos + input[2].wPos)/3.0; + + //find world pos and camera pos + float4 worldPos = float4( faceCenter, 1 ); + float4 cameraPos = mul( worldPos, g_mView ); + + //do shading + float3 worldNormal = normalize( faceNormal ); + ColorsOutput cOut = CalcLighting( worldNormal, worldPos, cameraPos ); + + for(int i=0; i<3; i++) + { + output = input[i]; + output.colorD = cOut.Diffuse; + output.colorS = cOut.Specular; + + FlatTriStream.Append( output ); + } + FlatTriStream.RestartStrip(); +} + +// +// GS for point rendering +// +[maxvertexcount(12)] +void GSPointmain( triangle VSSceneOut input[3], inout TriangleStream PointTriStream ) +{ + VSSceneOut output; + + // + // Calculate the point size + // + //float fSizeX = (g_pointSize/g_viewportWidth)/4.0; + float fSizeY = (g_pointSize/g_viewportHeight)/4.0; + float fSizeX = fSizeY; + + for(int i=0; i<3; i++) + { + output = input[i]; + + //find world pos and camera pos + float4 worldPos = float4(input[i].wPos,1); + float4 cameraPos = mul( worldPos, g_mView ); + + //find our size + if( g_bPointScaleEnable ) + { + float dEye = length( cameraPos.xyz ); + fSizeX = fSizeY = g_viewportHeight * g_pointSize * + sqrt( 1.0f/( g_pointScaleA + g_pointScaleB*dEye + g_pointScaleC*(dEye*dEye) ) ); + } + + //do shading + if(g_bEnableLighting) + { + float3 worldNormal = input[i].wNorm; + ColorsOutput cOut = CalcLighting( worldNormal, worldPos, cameraPos ); + + output.colorD = cOut.Diffuse; + output.colorS = cOut.Specular; + } + else + { + output.colorD = float4(1,1,1,1); + } + + output.tex = input[i].tex; + + // + // Emit two new triangles + // + for(int i=0; i<4; i++) + { + float4 outPos = mul( worldPos, g_mView ); + output.pos = mul( outPos, g_mProj ); + float zoverNear = (outPos.z)/g_nearPlane; + float4 posSize = float4( g_positions[i].x*fSizeX*zoverNear, + g_positions[i].y*fSizeY*zoverNear, + 0, + 0 ); + output.pos += posSize; + + PointTriStream.Append(output); + } + PointTriStream.RestartStrip(); + } +} + +// +// Calculates fog factor based upon distance +// +float CalcFogFactor( float d ) +{ + float fogCoeff = 1.0; + + if( FOGMODE_LINEAR == g_fogMode ) + { + fogCoeff = (g_fogEnd - d)/(g_fogEnd - g_fogStart); + } + else if( FOGMODE_EXP == g_fogMode ) + { + fogCoeff = 1.0 / pow( E, d*g_fogDensity ); + } + else if( FOGMODE_EXP2 == g_fogMode ) + { + fogCoeff = 1.0 / pow( E, d*d*g_fogDensity*g_fogDensity ); + } + + return clamp( fogCoeff, 0, 1 ); +} + +// +// PS for rendering with clip planes +// +float4 PSScenemain(PSSceneIn input) : SV_Target +{ + //calculate the fog factor + float fog = CalcFogFactor( input.fogDist ); + + //calculate the color based off of the normal, textures, etc + float4 normalColor = g_txDiffuse.Sample( g_samLinear, input.tex ) * input.colorD + input.colorS; + + //calculate the color from the projected texture + float4 cookieCoord = mul( float4(input.wPos,1), g_mLightViewProj ); + //since we don't have texldp, we must perform the w divide ourselves befor the texture lookup + cookieCoord.xy = 0.5 * cookieCoord.xy / cookieCoord.w + float2( 0.5, 0.5 ); + float4 cookieColor = float4(0,0,0,0); + if( cookieCoord.z > 0 ) + cookieColor = g_txProjected.Sample( g_samLinear, cookieCoord.xy ); + + //for standard light-modulating effects just multiply normalcolor and coookiecolor + normalColor += cookieColor; + + return fog * normalColor + (1.0 - fog)*g_fogColor; +} + +// +// PS for rendering with alpha test +// +float4 PSAlphaTestmain(PSSceneIn input) : SV_Target +{ + float4 color = g_txDiffuse.Sample( g_samLinear, input.tex ) * input.colorD; + if( color.a < 0.5 ) + discard; + return color; +} + +// +// RenderSceneGouraud - renders gouraud-shaded primitives +// +technique10 RenderSceneGouraud +{ + pass p0 + { + SetVertexShader( CompileShader( vs_4_0, VSScenemain() ) ); + SetGeometryShader( NULL ); + SetPixelShader( CompileShader( ps_4_0, PSScenemain() ) ); + + SetDepthStencilState( EnableDepth, 0 ); + } +} + +// +// RenderSceneFlat - renders flat-shaded primitives +// +technique10 RenderSceneFlat +{ + pass p0 + { + SetVertexShader( CompileShader( vs_4_0, VSScenemain() ) ); + SetGeometryShader( CompileShader( gs_4_0, GSFlatmain() ) ); + SetPixelShader( CompileShader( ps_4_0, PSScenemain() ) ); + + SetDepthStencilState( EnableDepth, 0 ); + } +} + +// +// RenderScenePoint - replaces d3dfill_point +// +technique10 RenderScenePoint +{ + pass p0 + { + SetVertexShader( CompileShader( vs_4_0, VSScenemain() ) ); + SetGeometryShader( CompileShader( gs_4_0, GSPointmain() ) ); + SetPixelShader( CompileShader( ps_4_0, PSScenemain() ) ); + + SetDepthStencilState( EnableDepth, 0 ); + } +} + +// +// RenderScreneSpace - shows how to render something in screenspace +// +technique10 RenderScreenSpaceAlphaTest +{ + pass p0 + { + SetVertexShader( CompileShader( vs_4_0, VSScreenSpacemain() ) ); + SetGeometryShader( NULL ); + SetPixelShader( CompileShader( ps_4_0, PSAlphaTestmain() ) ); + + SetDepthStencilState( DisableDepth, 0 ); + } +} + +// +// RenderScreneSpace - shows how to render something in screenspace +// +technique10 RenderTextureOnly +{ + pass p0 + { + SetVertexShader( CompileShader( vs_4_0, VSScenemain() ) ); + SetGeometryShader( NULL ); + SetPixelShader( CompileShader( ps_4_0, PSScenemain() ) ); + + SetDepthStencilState( EnableDepth, 0 ); + } +} + diff --git a/tests/hlsl/dxsdk/FluidCS11/ComputeShaderSort11.hlsl b/tests/hlsl/dxsdk/FluidCS11/ComputeShaderSort11.hlsl new file mode 100644 index 000000000..db7bd5136 --- /dev/null +++ b/tests/hlsl/dxsdk/FluidCS11/ComputeShaderSort11.hlsl @@ -0,0 +1,75 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile cs_4_0 -entry BitonicSort -entry MatrixTranspose +//-------------------------------------------------------------------------------------- +// File: ComputeShaderSort11.hlsl +// +// This file contains the compute shaders to perform GPU sorting using DirectX 11. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +#define BITONIC_BLOCK_SIZE 512 + +#define TRANSPOSE_BLOCK_SIZE 16 + +//-------------------------------------------------------------------------------------- +// Constant Buffers +//-------------------------------------------------------------------------------------- +cbuffer CB : register( b0 ) +{ + unsigned int g_iLevel; + unsigned int g_iLevelMask; + unsigned int g_iWidth; + unsigned int g_iHeight; +}; + +//-------------------------------------------------------------------------------------- +// Structured Buffers +//-------------------------------------------------------------------------------------- +StructuredBuffer Input : register( t0 ); +RWStructuredBuffer Data : register( u0 ); + +//-------------------------------------------------------------------------------------- +// Bitonic Sort Compute Shader +//-------------------------------------------------------------------------------------- +groupshared unsigned int shared_data[BITONIC_BLOCK_SIZE]; + +[numthreads(BITONIC_BLOCK_SIZE, 1, 1)] +void BitonicSort( uint3 Gid : SV_GroupID, + uint3 DTid : SV_DispatchThreadID, + uint3 GTid : SV_GroupThreadID, + uint GI : SV_GroupIndex ) +{ + // Load shared data + shared_data[GI] = Data[DTid.x]; + GroupMemoryBarrierWithGroupSync(); + + // Sort the shared data + for (unsigned int j = g_iLevel >> 1 ; j > 0 ; j >>= 1) + { + unsigned int result = ((shared_data[GI & ~j] <= shared_data[GI | j]) == (bool)(g_iLevelMask & DTid.x))? shared_data[GI ^ j] : shared_data[GI]; + GroupMemoryBarrierWithGroupSync(); + shared_data[GI] = result; + GroupMemoryBarrierWithGroupSync(); + } + + // Store shared data + Data[DTid.x] = shared_data[GI]; +} + +//-------------------------------------------------------------------------------------- +// Matrix Transpose Compute Shader +//-------------------------------------------------------------------------------------- +groupshared unsigned int transpose_shared_data[TRANSPOSE_BLOCK_SIZE * TRANSPOSE_BLOCK_SIZE]; + +[numthreads(TRANSPOSE_BLOCK_SIZE, TRANSPOSE_BLOCK_SIZE, 1)] +void MatrixTranspose( uint3 Gid : SV_GroupID, + uint3 DTid : SV_DispatchThreadID, + uint3 GTid : SV_GroupThreadID, + uint GI : SV_GroupIndex ) +{ + transpose_shared_data[GI] = Input[DTid.y * g_iWidth + DTid.x]; + GroupMemoryBarrierWithGroupSync(); + uint2 XY = DTid.yx - GTid.yx + GTid.xy; + Data[XY.y * g_iHeight + XY.x] = transpose_shared_data[GTid.x * TRANSPOSE_BLOCK_SIZE + GTid.y]; +} diff --git a/tests/hlsl/dxsdk/FluidCS11/FluidCS11.hlsl b/tests/hlsl/dxsdk/FluidCS11/FluidCS11.hlsl new file mode 100644 index 000000000..26e6cdf60 --- /dev/null +++ b/tests/hlsl/dxsdk/FluidCS11/FluidCS11.hlsl @@ -0,0 +1,529 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile cs_4_0 -entry BuildGridCS -entry ClearGridIndicesCS -entry BuildGridIndicesCS -entry RearrangeParticlesCS -entry DensityCS_Simple -entry DensityCS_Shared -entry DensityCS_Grid -entry ForceCS_Simple -entry ForceCS_Shared -entry ForceCS_Grid -entry IntegrateCS +//-------------------------------------------------------------------------------------- +// File: FluidCS11.hlsl +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Smoothed Particle Hydrodynamics Algorithm Based Upon: +// Particle-Based Fluid Simulation for Interactive Applications +// Matthias Müller +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Optimized Grid Algorithm Based Upon: +// Broad-Phase Collision Detection with CUDA +// Scott Le Grand +//-------------------------------------------------------------------------------------- + +struct Particle +{ + float2 position; + float2 velocity; +}; + +struct ParticleForces +{ + float2 acceleration; +}; + +struct ParticleDensity +{ + float density; +}; + +cbuffer cbSimulationConstants : register( b0 ) +{ + uint g_iNumParticles; + float g_fTimeStep; + float g_fSmoothlen; + float g_fPressureStiffness; + float g_fRestDensity; + float g_fDensityCoef; + float g_fGradPressureCoef; + float g_fLapViscosityCoef; + float g_fWallStiffness; + + float4 g_vGravity; + float4 g_vGridDim; + float3 g_vPlanes[4]; +}; + +//-------------------------------------------------------------------------------------- +// Fluid Simulation +//-------------------------------------------------------------------------------------- + +#define SIMULATION_BLOCK_SIZE 256 + +//-------------------------------------------------------------------------------------- +// Structured Buffers +//-------------------------------------------------------------------------------------- +RWStructuredBuffer ParticlesRW : register( u0 ); +StructuredBuffer ParticlesRO : register( t0 ); + +RWStructuredBuffer ParticlesDensityRW : register( u0 ); +StructuredBuffer ParticlesDensityRO : register( t1 ); + +RWStructuredBuffer ParticlesForcesRW : register( u0 ); +StructuredBuffer ParticlesForcesRO : register( t2 ); + +RWStructuredBuffer GridRW : register( u0 ); +StructuredBuffer GridRO : register( t3 ); + +RWStructuredBuffer GridIndicesRW : register( u0 ); +StructuredBuffer GridIndicesRO : register( t4 ); + + +//-------------------------------------------------------------------------------------- +// Grid Construction +//-------------------------------------------------------------------------------------- + +// For simplicity, this sample uses a 16-bit hash based on the grid cell and +// a 16-bit particle ID to keep track of the particles while sorting +// This imposes a limitation of 64K particles and 256x256 grid work +// You could extended the implementation to support large scenarios by using a uint2 + +float2 GridCalculateCell(float2 position) +{ + return clamp(position * g_vGridDim.xy + g_vGridDim.zw, float2(0, 0), float2(255, 255)); +} + +unsigned int GridConstuctKey(uint2 xy) +{ + // Bit pack [-----UNUSED-----][----Y---][----X---] + // 16-bit 8-bit 8-bit + return dot(xy.yx, uint2(256, 1)); +} + +unsigned int GridConstuctKeyValuePair(uint2 xy, uint value) +{ + // Bit pack [----Y---][----X---][-----VALUE------] + // 8-bit 8-bit 16-bit + return dot(uint3(xy.yx, value), uint3(256*256*256, 256*256, 1)); +} + +unsigned int GridGetKey(unsigned int keyvaluepair) +{ + return (keyvaluepair >> 16); +} + +unsigned int GridGetValue(unsigned int keyvaluepair) +{ + return (keyvaluepair & 0xFFFF); +} + + +//-------------------------------------------------------------------------------------- +// Build Grid +//-------------------------------------------------------------------------------------- + +[numthreads(SIMULATION_BLOCK_SIZE, 1, 1)] +void BuildGridCS( uint3 Gid : SV_GroupID, uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI : SV_GroupIndex ) +{ + const unsigned int P_ID = DTid.x; // Particle ID to operate on + + float2 position = ParticlesRO[P_ID].position; + float2 grid_xy = GridCalculateCell( position ); + + GridRW[P_ID] = GridConstuctKeyValuePair((uint2)grid_xy, P_ID); +} + + +//-------------------------------------------------------------------------------------- +// Build Grid Indices +//-------------------------------------------------------------------------------------- + +[numthreads(SIMULATION_BLOCK_SIZE, 1, 1)] +void ClearGridIndicesCS( uint3 Gid : SV_GroupID, uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI : SV_GroupIndex ) +{ + GridIndicesRW[DTid.x] = uint2(0, 0); +} + +[numthreads(SIMULATION_BLOCK_SIZE, 1, 1)] +void BuildGridIndicesCS( uint3 Gid : SV_GroupID, uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI : SV_GroupIndex ) +{ + const unsigned int G_ID = DTid.x; // Grid ID to operate on + unsigned int G_ID_PREV = (G_ID == 0)? g_iNumParticles : G_ID; G_ID_PREV--; + unsigned int G_ID_NEXT = G_ID + 1; if (G_ID_NEXT == g_iNumParticles) { G_ID_NEXT = 0; } + + unsigned int cell = GridGetKey( GridRO[G_ID] ); + unsigned int cell_prev = GridGetKey( GridRO[G_ID_PREV] ); + unsigned int cell_next = GridGetKey( GridRO[G_ID_NEXT] ); + if (cell != cell_prev) + { + // I'm the start of a cell + GridIndicesRW[cell].x = G_ID; + } + if (cell != cell_next) + { + // I'm the end of a cell + GridIndicesRW[cell].y = G_ID + 1; + } +} + + +//-------------------------------------------------------------------------------------- +// Rearrange Particles +//-------------------------------------------------------------------------------------- + +[numthreads(SIMULATION_BLOCK_SIZE, 1, 1)] +void RearrangeParticlesCS( uint3 Gid : SV_GroupID, uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI : SV_GroupIndex ) +{ + const unsigned int ID = DTid.x; // Particle ID to operate on + const unsigned int G_ID = GridGetValue( GridRO[ ID ] ); + ParticlesRW[ID] = ParticlesRO[ G_ID ]; +} + + +//-------------------------------------------------------------------------------------- +// Density Calculation +//-------------------------------------------------------------------------------------- + +float CalculateDensity(float r_sq) +{ + const float h_sq = g_fSmoothlen * g_fSmoothlen; + // Implements this equation: + // W_poly6(r, h) = 315 / (64 * pi * h^9) * (h^2 - r^2)^3 + // g_fDensityCoef = fParticleMass * 315.0f / (64.0f * PI * fSmoothlen^9) + return g_fDensityCoef * (h_sq - r_sq) * (h_sq - r_sq) * (h_sq - r_sq); +} + + +//-------------------------------------------------------------------------------------- +// Simple N^2 Algorithm +//-------------------------------------------------------------------------------------- + +[numthreads(SIMULATION_BLOCK_SIZE, 1, 1)] +void DensityCS_Simple( uint3 Gid : SV_GroupID, uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI : SV_GroupIndex ) +{ + const unsigned int P_ID = DTid.x; + const float h_sq = g_fSmoothlen * g_fSmoothlen; + float2 P_position = ParticlesRO[P_ID].position; + + float density = 0; + + // Calculate the density based on all neighbors + for (uint N_ID = 0 ; N_ID < g_iNumParticles ; N_ID++) + { + float2 N_position = ParticlesRO[N_ID].position; + + float2 diff = N_position - P_position; + float r_sq = dot(diff, diff); + if (r_sq < h_sq) + { + density += CalculateDensity(r_sq); + } + } + + ParticlesDensityRW[P_ID].density = density; +} + + +//-------------------------------------------------------------------------------------- +// Shared Memory Optimized N^2 Algorithm +//-------------------------------------------------------------------------------------- + +groupshared float2 density_shared_pos[SIMULATION_BLOCK_SIZE]; + +[numthreads(SIMULATION_BLOCK_SIZE, 1, 1)] +void DensityCS_Shared( uint3 Gid : SV_GroupID, uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI : SV_GroupIndex ) +{ + const unsigned int P_ID = DTid.x; + const float h_sq = g_fSmoothlen * g_fSmoothlen; + float2 P_position = ParticlesRO[P_ID].position; + + float density = 0; + + // Calculate the density based on all neighbors + [loop] + for (uint N_block_ID = 0 ; N_block_ID < g_iNumParticles ; N_block_ID += SIMULATION_BLOCK_SIZE) + { + // Cache a tile of particles unto shared memory to increase IO efficiency + density_shared_pos[GI] = ParticlesRO[N_block_ID + GI].position; + + GroupMemoryBarrierWithGroupSync(); + + for (uint N_tile_ID = 0; N_tile_ID < SIMULATION_BLOCK_SIZE; N_tile_ID++) + { + float2 N_position = density_shared_pos[N_tile_ID]; + + float2 diff = N_position - P_position; + float r_sq = dot(diff, diff); + if (r_sq < h_sq) + { + density += CalculateDensity(r_sq); + } + } + + GroupMemoryBarrierWithGroupSync(); + } + + ParticlesDensityRW[P_ID].density = density; +} + + +//-------------------------------------------------------------------------------------- +// Optimized Grid + Sort Algorithm +//-------------------------------------------------------------------------------------- + +[numthreads(SIMULATION_BLOCK_SIZE, 1, 1)] +void DensityCS_Grid( uint3 Gid : SV_GroupID, uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI : SV_GroupIndex ) +{ + const unsigned int P_ID = DTid.x; + const float h_sq = g_fSmoothlen * g_fSmoothlen; + float2 P_position = ParticlesRO[P_ID].position; + + float density = 0; + + // Calculate the density based on neighbors from the 8 adjacent cells + current cell + int2 G_XY = (int2)GridCalculateCell( P_position ); + for (int Y = max(G_XY.y - 1, 0) ; Y <= min(G_XY.y + 1, 255) ; Y++) + { + for (int X = max(G_XY.x - 1, 0) ; X <= min(G_XY.x + 1, 255) ; X++) + { + unsigned int G_CELL = GridConstuctKey(uint2(X, Y)); + uint2 G_START_END = GridIndicesRO[G_CELL]; + for (unsigned int N_ID = G_START_END.x ; N_ID < G_START_END.y ; N_ID++) + { + float2 N_position = ParticlesRO[N_ID].position; + + float2 diff = N_position - P_position; + float r_sq = dot(diff, diff); + if (r_sq < h_sq) + { + density += CalculateDensity(r_sq); + } + } + } + } + + ParticlesDensityRW[P_ID].density = density; +} + + +//-------------------------------------------------------------------------------------- +// Force Calculation +//-------------------------------------------------------------------------------------- + +float CalculatePressure(float density) +{ + // Implements this equation: + // Pressure = B * ((rho / rho_0)^y - 1) + return g_fPressureStiffness * max(pow(density / g_fRestDensity, 3) - 1, 0); +} + +float2 CalculateGradPressure(float r, float P_pressure, float N_pressure, float N_density, float2 diff) +{ + const float h = g_fSmoothlen; + float avg_pressure = 0.5f * (N_pressure + P_pressure); + // Implements this equation: + // W_spkiey(r, h) = 15 / (pi * h^6) * (h - r)^3 + // GRAD( W_spikey(r, h) ) = -45 / (pi * h^6) * (h - r)^2 + // g_fGradPressureCoef = fParticleMass * -45.0f / (PI * fSmoothlen^6) + return g_fGradPressureCoef * avg_pressure / N_density * (h - r) * (h - r) / r * (diff); +} + +float2 CalculateLapVelocity(float r, float2 P_velocity, float2 N_velocity, float N_density) +{ + const float h = g_fSmoothlen; + float2 vel_diff = (N_velocity - P_velocity); + // Implements this equation: + // W_viscosity(r, h) = 15 / (2 * pi * h^3) * (-r^3 / (2 * h^3) + r^2 / h^2 + h / (2 * r) - 1) + // LAPLACIAN( W_viscosity(r, h) ) = 45 / (pi * h^6) * (h - r) + // g_fLapViscosityCoef = fParticleMass * fViscosity * 45.0f / (PI * fSmoothlen^6) + return g_fLapViscosityCoef / N_density * (h - r) * vel_diff; +} + + +//-------------------------------------------------------------------------------------- +// Simple N^2 Algorithm +//-------------------------------------------------------------------------------------- + +[numthreads(SIMULATION_BLOCK_SIZE, 1, 1)] +void ForceCS_Simple( uint3 Gid : SV_GroupID, uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI : SV_GroupIndex ) +{ + const unsigned int P_ID = DTid.x; // Particle ID to operate on + + float2 P_position = ParticlesRO[P_ID].position; + float2 P_velocity = ParticlesRO[P_ID].velocity; + float P_density = ParticlesDensityRO[P_ID].density; + float P_pressure = CalculatePressure(P_density); + + const float h_sq = g_fSmoothlen * g_fSmoothlen; + + float2 acceleration = float2(0, 0); + + // Calculate the acceleration based on all neighbors + for (uint N_ID = 0 ; N_ID < g_iNumParticles ; N_ID++) + { + float2 N_position = ParticlesRO[N_ID].position; + + float2 diff = N_position - P_position; + float r_sq = dot(diff, diff); + if (r_sq < h_sq && P_ID != N_ID) + { + float2 N_velocity = ParticlesRO[N_ID].velocity; + float N_density = ParticlesDensityRO[N_ID].density; + float N_pressure = CalculatePressure(N_density); + float r = sqrt(r_sq); + + // Pressure Term + acceleration += CalculateGradPressure(r, P_pressure, N_pressure, N_density, diff); + + // Viscosity Term + acceleration += CalculateLapVelocity(r, P_velocity, N_velocity, N_density); + } + } + + ParticlesForcesRW[P_ID].acceleration = acceleration / P_density; +} + + +//-------------------------------------------------------------------------------------- +// Shared Memory Optimized N^2 Algorithm +//-------------------------------------------------------------------------------------- + +groupshared struct { float2 position; float2 velocity; float density; } force_shared_pos[SIMULATION_BLOCK_SIZE]; + +[numthreads(SIMULATION_BLOCK_SIZE, 1, 1)] +void ForceCS_Shared( uint3 Gid : SV_GroupID, uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI : SV_GroupIndex ) +{ + const unsigned int P_ID = DTid.x; // Particle ID to operate on + + float2 P_position = ParticlesRO[P_ID].position; + float2 P_velocity = ParticlesRO[P_ID].velocity; + float P_density = ParticlesDensityRO[P_ID].density; + float P_pressure = CalculatePressure(P_density); + + const float h_sq = g_fSmoothlen * g_fSmoothlen; + + float2 acceleration = float2(0, 0); + + // Calculate the acceleration based on all neighbors + [loop] + for (uint N_block_ID = 0 ; N_block_ID < g_iNumParticles ; N_block_ID += SIMULATION_BLOCK_SIZE) + { + // Cache a tile of particles unto shared memory to increase IO efficiency + force_shared_pos[GI].position = ParticlesRO[N_block_ID + GI].position; + force_shared_pos[GI].velocity = ParticlesRO[N_block_ID + GI].velocity; + force_shared_pos[GI].density = ParticlesDensityRO[N_block_ID + GI].density; + + GroupMemoryBarrierWithGroupSync(); + + [loop] + for (uint N_tile_ID = 0; N_tile_ID < SIMULATION_BLOCK_SIZE; N_tile_ID++ ) + { + uint N_ID = N_block_ID + N_tile_ID; + float2 N_position = force_shared_pos[N_tile_ID].position; + + float2 diff = N_position - P_position; + float r_sq = dot(diff, diff); + if (r_sq < h_sq && P_ID != N_ID) + { + float2 N_velocity = force_shared_pos[N_tile_ID].velocity; + float N_density = force_shared_pos[N_tile_ID].density; + float N_pressure = CalculatePressure(N_density); + float r = sqrt(r_sq); + + // Pressure Term + acceleration += CalculateGradPressure(r, P_pressure, N_pressure, N_density, diff); + + // Viscosity Term + acceleration += CalculateLapVelocity(r, P_velocity, N_velocity, N_density); + } + } + + GroupMemoryBarrierWithGroupSync(); + } + + ParticlesForcesRW[P_ID].acceleration = acceleration / P_density; +} + + +//-------------------------------------------------------------------------------------- +// Optimized Grid + Sort Algorithm +//-------------------------------------------------------------------------------------- + +[numthreads(SIMULATION_BLOCK_SIZE, 1, 1)] +void ForceCS_Grid( uint3 Gid : SV_GroupID, uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI : SV_GroupIndex ) +{ + const unsigned int P_ID = DTid.x; // Particle ID to operate on + + float2 P_position = ParticlesRO[P_ID].position; + float2 P_velocity = ParticlesRO[P_ID].velocity; + float P_density = ParticlesDensityRO[P_ID].density; + float P_pressure = CalculatePressure(P_density); + + const float h_sq = g_fSmoothlen * g_fSmoothlen; + + float2 acceleration = float2(0, 0); + + // Calculate the acceleration based on neighbors from the 8 adjacent cells + current cell + int2 G_XY = (int2)GridCalculateCell( P_position ); + for (int Y = max(G_XY.y - 1, 0) ; Y <= min(G_XY.y + 1, 255) ; Y++) + { + for (int X = max(G_XY.x - 1, 0) ; X <= min(G_XY.x + 1, 255) ; X++) + { + unsigned int G_CELL = GridConstuctKey(uint2(X, Y)); + uint2 G_START_END = GridIndicesRO[G_CELL]; + for (unsigned int N_ID = G_START_END.x ; N_ID < G_START_END.y ; N_ID++) + { + float2 N_position = ParticlesRO[N_ID].position; + + float2 diff = N_position - P_position; + float r_sq = dot(diff, diff); + if (r_sq < h_sq && P_ID != N_ID) + { + float2 N_velocity = ParticlesRO[N_ID].velocity; + float N_density = ParticlesDensityRO[N_ID].density; + float N_pressure = CalculatePressure(N_density); + float r = sqrt(r_sq); + + // Pressure Term + acceleration += CalculateGradPressure(r, P_pressure, N_pressure, N_density, diff); + + // Viscosity Term + acceleration += CalculateLapVelocity(r, P_velocity, N_velocity, N_density); + } + } + } + } + + ParticlesForcesRW[P_ID].acceleration = acceleration / P_density; +} + + +//-------------------------------------------------------------------------------------- +// Integration +//-------------------------------------------------------------------------------------- + +[numthreads(SIMULATION_BLOCK_SIZE, 1, 1)] +void IntegrateCS( uint3 Gid : SV_GroupID, uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI : SV_GroupIndex ) +{ + const unsigned int P_ID = DTid.x; // Particle ID to operate on + + float2 position = ParticlesRO[P_ID].position; + float2 velocity = ParticlesRO[P_ID].velocity; + float2 acceleration = ParticlesForcesRO[P_ID].acceleration; + + // Apply the forces from the map walls + [unroll] + for (unsigned int i = 0 ; i < 4 ; i++) + { + float dist = dot(float3(position, 1), g_vPlanes[i]); + acceleration += min(dist, 0) * -g_fWallStiffness * g_vPlanes[i].xy; + } + + // Apply gravity + acceleration += g_vGravity.xy; + + // Integrate + velocity += g_fTimeStep * acceleration; + position += g_fTimeStep * velocity; + + // Update + ParticlesRW[P_ID].position = position; + ParticlesRW[P_ID].velocity = velocity; +} diff --git a/tests/hlsl/dxsdk/FluidCS11/FluidRender.hlsl b/tests/hlsl/dxsdk/FluidCS11/FluidRender.hlsl new file mode 100644 index 000000000..d7e24b7bc --- /dev/null +++ b/tests/hlsl/dxsdk/FluidCS11/FluidRender.hlsl @@ -0,0 +1,112 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry ParticleVS -profile gs_4_0 -entry ParticleGS -profile ps_4_0 -entry ParticlePS +//-------------------------------------------------------------------------------------- +// File: FluidRender.hlsl +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Particle Rendering +//-------------------------------------------------------------------------------------- + +struct Particle { + float2 position; + float2 velocity; +}; + +struct ParticleDensity { + float density; +}; + +StructuredBuffer ParticlesRO : register( t0 ); +StructuredBuffer ParticleDensityRO : register( t1 ); + +cbuffer cbRenderConstants : register( b0 ) +{ + matrix g_mViewProjection; + float g_fParticleSize; +}; + +struct VSParticleOut +{ + float2 position : POSITION; + float4 color : COLOR; +}; + +struct GSParticleOut +{ + float4 position : SV_Position; + float4 color : COLOR; + float2 texcoord : TEXCOORD; +}; + + +//-------------------------------------------------------------------------------------- +// Visualization Helper +//-------------------------------------------------------------------------------------- + +static const float4 Rainbow[5] = { + float4(1, 0, 0, 1), // red + float4(1, 1, 0, 1), // orange + float4(0, 1, 0, 1), // green + float4(0, 1, 1, 1), // teal + float4(0, 0, 1, 1), // blue +}; + +float4 VisualizeNumber(float n) +{ + return lerp( Rainbow[ floor(n * 4.0f) ], Rainbow[ ceil(n * 4.0f) ], frac(n * 4.0f) ); +} + +float4 VisualizeNumber(float n, float lower, float upper) +{ + return VisualizeNumber( saturate( (n - lower) / (upper - lower) ) ); +} + + +//-------------------------------------------------------------------------------------- +// Vertex Shader +//-------------------------------------------------------------------------------------- + +VSParticleOut ParticleVS(uint ID : SV_VertexID) +{ + VSParticleOut Out = (VSParticleOut)0; + Out.position = ParticlesRO[ID].position; + Out.color = VisualizeNumber(ParticleDensityRO[ID].density, 1000.0f, 2000.0f); + return Out; +} + + +//-------------------------------------------------------------------------------------- +// Particle Geometry Shader +//-------------------------------------------------------------------------------------- + +static const float2 g_positions[4] = { float2(-1, 1), float2(1, 1), float2(-1, -1), float2(1, -1) }; +static const float2 g_texcoords[4] = { float2(0, 1), float2(1, 1), float2(0, 0), float2(1, 0) }; + +[maxvertexcount(4)] +void ParticleGS(point VSParticleOut In[1], inout TriangleStream SpriteStream) +{ + [unroll] + for (int i = 0; i < 4; i++) + { + GSParticleOut Out = (GSParticleOut)0; + float4 position = float4(In[0].position, 0, 1) + g_fParticleSize * float4(g_positions[i], 0, 0); + Out.position = mul(position, g_mViewProjection); + Out.color = In[0].color; + Out.texcoord = g_texcoords[i]; + SpriteStream.Append(Out); + } + SpriteStream.RestartStrip(); +} + + +//-------------------------------------------------------------------------------------- +// Pixel Shader +//-------------------------------------------------------------------------------------- + +float4 ParticlePS(GSParticleOut In) : SV_Target +{ + return In.color; +} diff --git a/tests/hlsl/dxsdk/HDRToneMappingCS11/BrightPassAndHorizFilterCS.hlsl b/tests/hlsl/dxsdk/HDRToneMappingCS11/BrightPassAndHorizFilterCS.hlsl new file mode 100644 index 000000000..87bad46ed --- /dev/null +++ b/tests/hlsl/dxsdk/HDRToneMappingCS11/BrightPassAndHorizFilterCS.hlsl @@ -0,0 +1,64 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile cs_4_0 -entry CSMain +//-------------------------------------------------------------------------------------- +// File: BrightPassAndHorizFilterCS.hlsl +// +// The CS for bright pass and horizontal blur, used in CS path of +// HDRToneMappingCS11 sample +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- +static const float MIDDLE_GRAY = 0.72f; +static const float LUM_WHITE = 1.5f; +static const float BRIGHT_THRESHOLD = 0.5f; + +Texture2D Input : register( t0 ); +StructuredBuffer lum : register( t1 ); +RWStructuredBuffer Result : register( u0 ); + +cbuffer cb0 +{ + float4 g_avSampleWeights[15]; + uint g_outputwidth; + float g_inverse; + int2 g_inputsize; +} + +#define kernelhalf 7 +#define groupthreads 128 +groupshared float4 temp[groupthreads]; + +[numthreads( groupthreads, 1, 1 )] +void CSMain( uint3 Gid : SV_GroupID, uint GI : SV_GroupIndex ) +{ + int2 coord = int2( GI - kernelhalf + (groupthreads - kernelhalf * 2) * Gid.x, Gid.y ); + coord = coord.xy * 8 + int2(4, 3); + coord = clamp( coord, int2(0, 0), int2(g_inputsize.x-1, g_inputsize.y-1) ); + float4 vColor = Input.Load( int3(coord, 0) ); + + float fLum = lum[0]*g_inverse; + + // Bright pass and tone mapping + vColor = max( 0.0f, vColor - BRIGHT_THRESHOLD ); + vColor *= MIDDLE_GRAY / (fLum + 0.001f); + vColor *= (1.0f + vColor/LUM_WHITE); + vColor /= (1.0f + vColor); + + temp[GI] = vColor; + + GroupMemoryBarrierWithGroupSync(); + + // Horizontal blur + if ( GI >= kernelhalf && + GI < (groupthreads - kernelhalf) && + ( (Gid.x * (groupthreads - 2 * kernelhalf) + GI - kernelhalf) < g_outputwidth) ) + { + float4 vOut = 0; + + [unroll] + for ( int i = -kernelhalf; i <= kernelhalf; ++i ) + vOut += temp[GI + i] * g_avSampleWeights[i + kernelhalf]; + + Result[GI - kernelhalf + (groupthreads - kernelhalf * 2) * Gid.x + Gid.y * g_outputwidth] = float4(vOut.rgb, 1.0f); + } +} diff --git a/tests/hlsl/dxsdk/HDRToneMappingCS11/DumpToTexture.hlsl b/tests/hlsl/dxsdk/HDRToneMappingCS11/DumpToTexture.hlsl new file mode 100644 index 000000000..d2d9611ce --- /dev/null +++ b/tests/hlsl/dxsdk/HDRToneMappingCS11/DumpToTexture.hlsl @@ -0,0 +1,29 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile ps_4_0 -entry PSDump +//-------------------------------------------------------------------------------------- +// File: DumpToTexture.hlsl +// +// The PS for converting CS output buffer to a texture, used in CS path of +// HDRToneMappingCS11 sample +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- +StructuredBuffer buffer : register( t0 ); + +struct QuadVS_Output +{ + float4 Pos : SV_POSITION; + float2 Tex : TEXCOORD0; +}; + +cbuffer cbPS : register( b0 ) +{ + uint4 g_param; +}; + +float4 PSDump( QuadVS_Output Input ) : SV_TARGET +{ + // To calculate the buffer offset, it is natural to use the screen space coordinates, + // Input.Pos is the screen space coordinates of the pixel being written + return buffer[ (Input.Pos.x - 0.5) + (Input.Pos.y - 0.5) * g_param.x ]; +} diff --git a/tests/hlsl/dxsdk/HDRToneMappingCS11/FilterCS.hlsl b/tests/hlsl/dxsdk/HDRToneMappingCS11/FilterCS.hlsl new file mode 100644 index 000000000..09c91669a --- /dev/null +++ b/tests/hlsl/dxsdk/HDRToneMappingCS11/FilterCS.hlsl @@ -0,0 +1,73 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile cs_4_0 -entry CSVerticalFilter -entry CSHorizFilter +//-------------------------------------------------------------------------------------- +// File: FilterCS.hlsl +// +// The CSs for doing vertical and horizontal blur, used in CS path of +// HDRToneMappingCS11 sample +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- +StructuredBuffer InputBuf : register( t0 ); +Texture2D InputTex : register( t1 ); +RWStructuredBuffer Result : register( u0 ); + +cbuffer cb0 +{ + float4 g_avSampleWeights[15]; + int2 g_outputsize; + int2 g_inputsize; +} + +#define kernelhalf 7 +#define groupthreads 128 +groupshared float4 temp[groupthreads]; + +[numthreads( groupthreads, 1, 1 )] +void CSVerticalFilter( uint3 Gid : SV_GroupID, uint GI : SV_GroupIndex ) +{ + int offsety = GI - kernelhalf + (groupthreads - kernelhalf * 2) * Gid.y; + offsety = clamp( offsety, 0, g_inputsize.y-1 ); + int offset = Gid.x + offsety * g_inputsize.x; + temp[GI] = InputBuf[offset]; + + GroupMemoryBarrierWithGroupSync(); + + // Vertical blur + if ( GI >= kernelhalf && + GI < (groupthreads - kernelhalf) && + ( (GI - kernelhalf + (groupthreads - kernelhalf * 2) * Gid.y) < g_outputsize.y) ) + { + float4 vOut = 0; + + [unroll] + for ( int i = -kernelhalf; i <= kernelhalf; ++i ) + vOut += temp[GI + i] * g_avSampleWeights[i + kernelhalf]; + + Result[Gid.x + (GI - kernelhalf + (groupthreads - kernelhalf * 2) * Gid.y) * g_outputsize.x] = float4(vOut.rgb, 1.0f); + } +} + +[numthreads( groupthreads, 1, 1 )] +void CSHorizFilter( uint3 Gid : SV_GroupID, uint GI : SV_GroupIndex ) +{ + int2 coord = int2( GI - kernelhalf + (groupthreads - kernelhalf * 2) * Gid.x, Gid.y ); + coord = clamp( coord, int2(0, 0), int2(g_inputsize.x-1, g_inputsize.y-1) ); + temp[GI] = InputTex.Load( int3(coord, 0) ); + + GroupMemoryBarrierWithGroupSync(); + + // Horizontal blur + if ( GI >= kernelhalf && + GI < (groupthreads - kernelhalf) && + ( (Gid.x * (groupthreads - 2 * kernelhalf) + GI - kernelhalf) < g_outputsize.x) ) + { + float4 vOut = 0; + + [unroll] + for ( int i = -kernelhalf; i <= kernelhalf; ++i ) + vOut += temp[GI + i] * g_avSampleWeights[i + kernelhalf]; + + Result[GI - kernelhalf + (groupthreads - kernelhalf * 2) * Gid.x + Gid.y * g_outputsize.x] = float4(vOut.rgb, 1.0f); + } +} diff --git a/tests/hlsl/dxsdk/HDRToneMappingCS11/FinalPass.hlsl b/tests/hlsl/dxsdk/HDRToneMappingCS11/FinalPass.hlsl new file mode 100644 index 000000000..a4673c237 --- /dev/null +++ b/tests/hlsl/dxsdk/HDRToneMappingCS11/FinalPass.hlsl @@ -0,0 +1,79 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry QuadVS -profile ps_4_0 -entry PSFinalPass -entry PSFinalPassForCPUReduction +//-------------------------------------------------------------------------------------- +// File: FinalPass.hlsl +// +// The PSs for doing tone-mapping based on the input luminance, used in CS path of +// HDRToneMappingCS11 sample +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- +struct QuadVS_Input +{ + float4 Pos : POSITION; + float2 Tex : TEXCOORD0; +}; + +struct QuadVS_Output +{ + float4 Pos : SV_POSITION; + float2 Tex : TEXCOORD0; +}; + +QuadVS_Output QuadVS( QuadVS_Input Input ) +{ + QuadVS_Output Output; + Output.Pos = Input.Pos; + Output.Tex = Input.Tex; + return Output; +} + +Texture2D tex : register( t0 ); +StructuredBuffer lum : register( t1 ); +Texture2D bloom : register( t2 ); + +SamplerState PointSampler : register (s0); +SamplerState LinearSampler : register (s1); + + +static const float MIDDLE_GRAY = 0.72f; +static const float LUM_WHITE = 1.5f; + +cbuffer cbPS : register( b0 ) +{ + float4 g_param; +}; + +float4 PSFinalPass( QuadVS_Output Input ) : SV_TARGET +{ + float4 vColor = tex.Sample( PointSampler, Input.Tex ); + float fLum = lum[0]*g_param.x; + float3 vBloom = bloom.Sample( LinearSampler, Input.Tex ); + + // Tone mapping + vColor.rgb *= MIDDLE_GRAY / (fLum + 0.001f); + vColor.rgb *= (1.0f + vColor/LUM_WHITE); + vColor.rgb /= (1.0f + vColor); + + vColor.rgb += 0.6f * vBloom; + vColor.a = 1.0f; + + return vColor; +} + +float4 PSFinalPassForCPUReduction( QuadVS_Output Input ) : SV_TARGET +{ + float4 vColor = tex.Sample( PointSampler, Input.Tex ); + float fLum = g_param.x; + float3 vBloom = bloom.Sample( LinearSampler, Input.Tex ); + + // Tone mapping + vColor.rgb *= MIDDLE_GRAY / (fLum + 0.001f); + vColor.rgb *= (1.0f + vColor/LUM_WHITE); + vColor.rgb /= (1.0f + vColor); + + vColor.rgb += 0.6f * vBloom; + vColor.a = 1.0f; + + return vColor; +} diff --git a/tests/hlsl/dxsdk/HDRToneMappingCS11/PSApproach.hlsl b/tests/hlsl/dxsdk/HDRToneMappingCS11/PSApproach.hlsl new file mode 100644 index 000000000..2b18cf0a1 --- /dev/null +++ b/tests/hlsl/dxsdk/HDRToneMappingCS11/PSApproach.hlsl @@ -0,0 +1,129 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile ps_4_0 -entry DownScale2x2_Lum -entry DownScale3x3 -entry FinalPass -entry DownScale3x3_BrightPass -entry Bloom +//-------------------------------------------------------------------------------------- +// File: PSApproach.hlsl +// +// The PSs for doing post-processing, used in PS path of +// HDRToneMappingCS11 sample +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- +static const float4 LUM_VECTOR = float4(.299, .587, .114, 0); +static const float MIDDLE_GRAY = 0.72f; +static const float LUM_WHITE = 1.5f; +static const float BRIGHT_THRESHOLD = 0.5f; + +SamplerState PointSampler : register (s0); +SamplerState LinearSampler : register (s1); + +struct QuadVS_Output +{ + float4 Pos : SV_POSITION; + float2 Tex : TEXCOORD0; +}; + +Texture2D s0 : register(t0); +Texture2D s1 : register(t1); +Texture2D s2 : register(t2); + +float4 DownScale2x2_Lum ( QuadVS_Output Input ) : SV_TARGET +{ + float4 vColor = 0.0f; + float fAvg = 0.0f; + + for( int y = -1; y < 1; y++ ) + { + for( int x = -1; x < 1; x++ ) + { + // Compute the sum of color values + vColor = s0.Sample( PointSampler, Input.Tex, int2(x,y) ); + + fAvg += dot( vColor, LUM_VECTOR ); + } + } + + fAvg /= 4; + + return float4(fAvg, fAvg, fAvg, 1.0f); +} + +float4 DownScale3x3( QuadVS_Output Input ) : SV_TARGET +{ + float fAvg = 0.0f; + float4 vColor; + + for( int y = -1; y <= 1; y++ ) + { + for( int x = -1; x <= 1; x++ ) + { + // Compute the sum of color values + vColor = s0.Sample( PointSampler, Input.Tex, int2(x,y) ); + + fAvg += vColor.r; + } + } + + // Divide the sum to complete the average + fAvg /= 9; + + return float4(fAvg, fAvg, fAvg, 1.0f); +} + +float4 FinalPass( QuadVS_Output Input ) : SV_TARGET +{ + //float4 vColor = 0; + float4 vColor = s0.Sample( PointSampler, Input.Tex ); + float4 vLum = s1.Sample( PointSampler, float2(0,0) ); + float3 vBloom = s2.Sample( LinearSampler, Input.Tex ); + + // Tone mapping + vColor.rgb *= MIDDLE_GRAY / (vLum.r + 0.001f); + vColor.rgb *= (1.0f + vColor/LUM_WHITE); + vColor.rgb /= (1.0f + vColor); + + vColor.rgb += 0.6f * vBloom; + vColor.a = 1.0f; + + return vColor; +} + +float4 DownScale3x3_BrightPass( QuadVS_Output Input ) : SV_TARGET +{ + float3 vColor = 0.0f; + float4 vLum = s1.Sample( PointSampler, float2(0, 0) ); + float fLum = vLum.r; + + vColor = s0.Sample( PointSampler, Input.Tex ).rgb; + + // Bright pass and tone mapping + vColor = max( 0.0f, vColor - BRIGHT_THRESHOLD ); + vColor *= MIDDLE_GRAY / (fLum + 0.001f); + vColor *= (1.0f + vColor/LUM_WHITE); + vColor /= (1.0f + vColor); + + return float4(vColor, 1.0f); +} + +cbuffer cb0 +{ + float2 g_avSampleOffsets[15]; + float4 g_avSampleWeights[15]; +} + +float4 Bloom( QuadVS_Output Input ) : SV_TARGET +{ + float4 vSample = 0.0f; + float4 vColor = 0.0f; + float2 vSamplePosition; + + for( int iSample = 0; iSample < 15; iSample++ ) + { + // Sample from adjacent points + vSamplePosition = Input.Tex + g_avSampleOffsets[iSample]; + vColor = s0.Sample( PointSampler, vSamplePosition); + + vSample += g_avSampleWeights[iSample]*vColor; + } + + return vSample; +} diff --git a/tests/hlsl/dxsdk/HDRToneMappingCS11/ReduceTo1DCS.hlsl b/tests/hlsl/dxsdk/HDRToneMappingCS11/ReduceTo1DCS.hlsl new file mode 100644 index 000000000..027838743 --- /dev/null +++ b/tests/hlsl/dxsdk/HDRToneMappingCS11/ReduceTo1DCS.hlsl @@ -0,0 +1,72 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile cs_4_0 -entry CSMain +//----------------------------------------------------------------------------- +// File: ReduceTo1DCS.hlsl +// +// Desc: Reduce an input Texture2D to a buffer +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//----------------------------------------------------------------------------- +Texture2D Input : register( t0 ); +RWStructuredBuffer Result : register( u0 ); + +cbuffer cbCS : register( b0 ) +{ + uint4 g_param; // (g_param.x, g_param.y) is the x and y dimensions of the Dispatch call + // (g_param.z, g_param.w) is the size of the above Input Texture2D +}; + +//#define CS_FULL_PIXEL_REDUCITON // Defining this or not must be the same as in HDRToneMappingCS11.cpp + +#define blocksize 8 +#define blocksizeY 8 +#define groupthreads (blocksize*blocksizeY) +groupshared float accum[groupthreads]; + +static const float4 LUM_VECTOR = float4(.299, .587, .114, 0); + +[numthreads(blocksize,blocksizeY,1)] +void CSMain( uint3 Gid : SV_GroupID, uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI : SV_GroupIndex ) +{ + float4 s = +#ifdef CS_FULL_PIXEL_REDUCITON + Input.Load( uint3(DTid.xy , 0) )+ + Input.Load( uint3(DTid.xy + uint2(blocksize*g_param.x, 0), 0) ) + + Input.Load( uint3(DTid.xy + uint2(0, blocksizeY*g_param.y), 0) ) + + Input.Load( uint3(DTid.xy + uint2(blocksize*g_param.x, blocksizeY*g_param.y), 0) ); +#else + Input.Load( uint3((float)DTid.x/81.0f*g_param.z, (float)DTid.y/81.0f*g_param.w, 0) ); +#endif + + accum[GI] = dot( s, LUM_VECTOR ); + + // Parallel reduction algorithm follows + GroupMemoryBarrierWithGroupSync(); + if ( GI < 32 ) + accum[GI] += accum[32+GI]; + + GroupMemoryBarrierWithGroupSync(); + if ( GI < 16 ) + accum[GI] += accum[16+GI]; + + GroupMemoryBarrierWithGroupSync(); + if ( GI < 8 ) + accum[GI] += accum[8+GI]; + + GroupMemoryBarrierWithGroupSync(); + if ( GI < 4 ) + accum[GI] += accum[4+GI]; + + GroupMemoryBarrierWithGroupSync(); + if ( GI < 2 ) + accum[GI] += accum[2+GI]; + + GroupMemoryBarrierWithGroupSync(); + if ( GI < 1 ) + accum[GI] += accum[1+GI]; + + if ( GI == 0 ) + { + Result[Gid.y*g_param.x+Gid.x] = accum[0]; + } +} diff --git a/tests/hlsl/dxsdk/HDRToneMappingCS11/ReduceToSingleCS.hlsl b/tests/hlsl/dxsdk/HDRToneMappingCS11/ReduceToSingleCS.hlsl new file mode 100644 index 000000000..cf506283e --- /dev/null +++ b/tests/hlsl/dxsdk/HDRToneMappingCS11/ReduceToSingleCS.hlsl @@ -0,0 +1,63 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile cs_4_0 -entry CSMain +//----------------------------------------------------------------------------- +// File: ReduceToSingleCS.hlsl +// +// Desc: Reduce an input buffer by a factor of groupthreads +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//----------------------------------------------------------------------------- + +StructuredBuffer Input : register( t0 ); +RWStructuredBuffer Result : register( u0 ); + +cbuffer cbCS : register( b0 ) +{ + uint4 g_param; // g_param.x is the actual elements contained in Input + // g_param.y is the x dimension of the Dispatch call +}; + +#define groupthreads 128 +groupshared float accum[groupthreads]; + +[numthreads(groupthreads,1,1)] +void CSMain( uint3 Gid : SV_GroupID, uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI : SV_GroupIndex ) +{ + if ( DTid.x < g_param.x ) + accum[GI] = Input[DTid.x]; + else + accum[GI] = 0; + + // Parallel reduction algorithm follows + GroupMemoryBarrierWithGroupSync(); + if ( GI < 64 ) + accum[GI] += accum[64+GI]; + + GroupMemoryBarrierWithGroupSync(); + if ( GI < 32 ) + accum[GI] += accum[32+GI]; + + GroupMemoryBarrierWithGroupSync(); + if ( GI < 16 ) + accum[GI] += accum[16+GI]; + + GroupMemoryBarrierWithGroupSync(); + if ( GI < 8 ) + accum[GI] += accum[8+GI]; + + GroupMemoryBarrierWithGroupSync(); + if ( GI < 4 ) + accum[GI] += accum[4+GI]; + + GroupMemoryBarrierWithGroupSync(); + if ( GI < 2 ) + accum[GI] += accum[2+GI]; + + GroupMemoryBarrierWithGroupSync(); + if ( GI < 1 ) + accum[GI] += accum[1+GI]; + + if ( GI == 0 ) + { + Result[Gid.x] = accum[0]; + } +} diff --git a/tests/hlsl/dxsdk/HDRToneMappingCS11/skybox11.hlsl b/tests/hlsl/dxsdk/HDRToneMappingCS11/skybox11.hlsl new file mode 100644 index 000000000..2728665e2 --- /dev/null +++ b/tests/hlsl/dxsdk/HDRToneMappingCS11/skybox11.hlsl @@ -0,0 +1,44 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry SkyboxVS -profile ps_4_0 -entry SkyboxPS +//----------------------------------------------------------------------------- +// File: SkyBox11.hlsl +// +// Desc: +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//----------------------------------------------------------------------------- + +cbuffer cbPerObject : register( b0 ) +{ + row_major matrix g_mWorldViewProjection : packoffset( c0 ); +} + +TextureCube g_EnvironmentTexture : register( t0 ); +SamplerState g_sam : register( s0 ); + +struct SkyboxVS_Input +{ + float4 Pos : POSITION; +}; + +struct SkyboxVS_Output +{ + float4 Pos : SV_POSITION; + float3 Tex : TEXCOORD0; +}; + +SkyboxVS_Output SkyboxVS( SkyboxVS_Input Input ) +{ + SkyboxVS_Output Output; + + Output.Pos = Input.Pos; + Output.Tex = normalize( mul(Input.Pos, g_mWorldViewProjection) ); + + return Output; +} + +float4 SkyboxPS( SkyboxVS_Output Input ) : SV_TARGET +{ + float4 color = g_EnvironmentTexture.Sample( g_sam, Input.Tex ); + return color; +} diff --git a/tests/hlsl/dxsdk/InstancingFX11/Instancing.fx b/tests/hlsl/dxsdk/InstancingFX11/Instancing.fx new file mode 100644 index 000000000..3c8d45078 --- /dev/null +++ b/tests/hlsl/dxsdk/InstancingFX11/Instancing.fx @@ -0,0 +1,591 @@ +//TEST_IGNORE_FILE: +//-------------------------------------------------------------------------------------- +// File: Instancing.fx +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Input and output structures +//-------------------------------------------------------------------------------------- +struct VSInstIn +{ + float3 pos : POSITION; + float3 norm : NORMAL; + float2 tex : TEXTURE0; + row_major float4x4 mTransform : mTransform; +}; + +struct VSSceneIn +{ + float3 pos : POSITION; + float3 norm : NORMAL; + float2 tex : TEXTURE0; +}; + +struct VSGrassIn +{ + float3 pos : POSITION; + float3 norm : NORMAL; + float2 tex : TEXTURE0; + row_major float4x4 mTransform : mTransform; + uint VertexID : SV_VertexID; +}; + +struct VSGrassOut +{ + float3 pos : POSITION; + float3 norm : NORMAL; + float2 tex : TEXTURE0; + uint VertexID : VERTID; +}; + +struct VSQuadIn +{ + float3 pos : POSITION; + float2 tex : TEXTURE0; + row_major float4x4 mTransform : mTransform; + float fOcc : fOcc; + uint InstanceId : SV_InstanceID; +}; + +struct PSSceneIn +{ + float4 pos : SV_Position; + float2 tex : TEXTURE0; + float4 color : COLOR0; +}; + +struct PSQuadIn +{ + float4 pos : SV_Position; + float3 tex : TEXTURE0; + float4 color : COLOR0; +}; + +//-------------------------------------------------------------------------------------- +// Constant buffers +//-------------------------------------------------------------------------------------- +cbuffer crarely +{ + float4x4 g_mTreeMatrices[50]; + uint g_iNumTrees; +}; + +cbuffer ceveryframe +{ + float4x4 g_mWorldViewProj; + float4x4 g_mWorldView; +}; + +cbuffer cmultipleperframe +{ + float g_GrassWidth; + float g_GrassHeight; + uint g_iGrassCoverage; +}; + +cbuffer cusercontrolled +{ + float g_GrassMessiness; +}; + +struct light_struct +{ + float4 direction; + float4 color; +}; + +cbuffer cimmutable +{ + light_struct g_lights[4] = { + { float4(0.620275, 0.683659, 0.384537, 1), float4(0.75, 0.599, 0.405, 1) }, //sun + { float4(0.063288, -0.987444, 0.144735, 1), float4(0.192, 0.273, 0.275, 1) }, //bottom + { float4(0.23007, 0.785579, -0.574422, 1), float4(0.300, 0.292, 0.223, 1) }, //highlight + { float4(-0.620275, -0.683659, -0.384537, 1), float4(0.0, 0.0, 0.1, 1) } //blue rim-light + }; + + float4 g_ambient = float4(0.4945,0.465,0.5,1); + + float g_occDimHeight = 2400.0; //scalar that tells us how much to darken the tree near the top +}; + +cbuffer cgrassblade +{ + float3 g_positions[6] = + { + float3( -1, 0, 0 ), + float3( -1, 2, 0 ), + float3( 1, 0, 0 ), + float3( 1, 2, 0 ), + + float3( -1, 0, 0 ), + float3( -1, 2, 0 ), + }; + float2 g_texcoords[6] = + { + float2(0,1), + float2(0,0), + float2(1,1), + float2(1,0), + + float2(0,1), + float2(0,0), + }; +}; + +//-------------------------------------------------------------------------------------- +// Textures and Samplers +//-------------------------------------------------------------------------------------- +Texture2D g_txDiffuse; +Texture2DArray g_tx2dArray; +SamplerState g_samLinear +{ + Filter = ANISOTROPIC; + AddressU = Wrap; + AddressV = Wrap; +}; + +Texture1D g_txRandom; +SamplerState g_samPoint +{ + Filter = MIN_MAG_MIP_POINT; + AddressU = Wrap; + AddressV = Wrap; +}; + +//-------------------------------------------------------------------------------------- +// State structures +//-------------------------------------------------------------------------------------- +BlendState QuadAlphaBlendState +{ + AlphaToCoverageEnable = TRUE; + RenderTargetWriteMask[0] = 0x0F; +}; + +RasterizerState EnableMSAA +{ + CullMode = BACK; + MultisampleEnable = TRUE; +}; + +DepthStencilState DisableDepthTestWrite +{ + DepthEnable = FALSE; + DepthWriteMask = ZERO; +}; + +DepthStencilState EnableDepthTestWrite +{ + DepthEnable = TRUE; + DepthWriteMask = ALL; +}; + +BlendState NoBlending +{ + AlphaToCoverageEnable = FALSE; + BlendEnable[0] = FALSE; +}; + +//-------------------------------------------------------------------------------------- +// Sky vertex shader +//-------------------------------------------------------------------------------------- +PSSceneIn VSSkymain(VSSceneIn input) +{ + PSSceneIn output; + + // + // Transform the vert to view-space + // + float4 v4Position = mul(float4(input.pos, 1), g_mWorldViewProj); + output.pos = v4Position; + + // + // Transfer the rest + // + output.tex = input.tex; + + output.color = float4(1,1,1,1); + + return output; +} + +//-------------------------------------------------------------------------------------- +// CalcLighting helper function. Calculates lighting from 4 light sources, adds ambient +// and attenuates for depth. Used by all techniques for lighting. +//-------------------------------------------------------------------------------------- +float4 CalcLighting( float3 norm, float depth ) +{ + float4 color = float4(0,0,0,0); + + // add the contributions of 4 directional lights + [unroll] for( int i=0; i<4; i++ ) + { + color += saturate( dot(g_lights[i].direction,norm) )*g_lights[i].color; + } + + // give some attenuation due to depth + float attenuate = depth / 10000.0; + float4 attenColor = float4(0.15, 0.2, 0.3, 0); + + // add it all up plus ambient + return (1-attenuate*0.23)*(color + g_ambient) + attenColor*attenuate; +} + +//-------------------------------------------------------------------------------------- +// Instancing vertex shader. Positions the vertices based upon the matrix stored +// in the second vertex stream. +//-------------------------------------------------------------------------------------- +PSSceneIn VSInstmain(VSInstIn input) +{ + PSSceneIn output; + + // + // Transform by our Sceneance matrix + // + float4 InstancePosition = mul(float4(input.pos, 1), input.mTransform); + float4 ViewPos = mul(InstancePosition, g_mWorldView ); + + // + // Transform the vert to view-space + // + float4 v4Position = mul(InstancePosition, g_mWorldViewProj); + output.pos = v4Position; + + // + // Transfer the rest + // + output.tex = input.tex; + + // + // dot the norm with the light dir + // + float3 norm = mul(input.norm,(float3x3)input.mTransform); + output.color = CalcLighting( norm, ViewPos.z ); + + // + // Dim the color by how far up the tree we are. + // This is a nice way to fake occlusion of the branches by the leaves. + // + output.color *= 1.0f - saturate(input.pos.y/g_occDimHeight); + + + return output; +} + +//-------------------------------------------------------------------------------------- +// Quad (leaf) vertex shader. Instances the quad over multiple leaf positions and +// multiple trees. This demonstrates how to do double instancing. +//-------------------------------------------------------------------------------------- +PSQuadIn VSQuadmain(VSQuadIn input) +{ + PSQuadIn output; + + // base our leaf texture upon which instance id we are + uint iLeaf = input.InstanceId/g_iNumTrees; + uint iLeafTex = iLeaf%3; + output.tex = float3(input.tex, float(iLeafTex) ); + + // + // Transform the position by the Instance matrix + // + int iTree = input.InstanceId - (input.InstanceId/g_iNumTrees)*g_iNumTrees; + float4 vInstancePos = mul( float4(input.pos, 1), input.mTransform ); + float4 InstancePosition = mul(vInstancePos, g_mTreeMatrices[iTree] ); + float4 ViewPos = mul(InstancePosition, g_mWorldView ); + + // + // Transform the Instance position to view-space + // + output.pos = mul(InstancePosition, g_mWorldViewProj); + + // pack distance from the eye into the color alpha channel + output.color = float4(input.fOcc,input.fOcc,input.fOcc,ViewPos.z); + + return output; +} + +//-------------------------------------------------------------------------------------- +// Grass vertex shader. Basically a passthrough except for instancing the island base +// mesh. +//-------------------------------------------------------------------------------------- +VSGrassOut VSGrassmain(VSGrassIn input) +{ + // simple transform into the instance space + VSGrassOut output; + output.pos = mul(float4(input.pos, 1), input.mTransform); + output.norm = mul(input.norm, (float3x3)input.mTransform); + output.tex = input.tex; + output.VertexID = input.VertexID; + + return output; +} + +//-------------------------------------------------------------------------------------- +// Quad (leaf) GS. Calculates the normal and lighting for the leaf. +//-------------------------------------------------------------------------------------- +[maxvertexcount(3)] +void GSQuadmain(triangle PSQuadIn input[3], inout TriangleStream QuadStream) +{ + PSQuadIn output; + + // + // Calculate the face normal + // + float4 faceNormalA = input[1].pos.xyzw - input[0].pos.xyzw; + float4 faceNormalB = input[2].pos.xyzw - input[0].pos.xyzw; + + // + // Cross product + // + float3 faceNormal = cross(faceNormalA, faceNormalB); + + // + // Normalize face normal + // + faceNormal = normalize(faceNormal); + + // + // Dot face normal with some arbitrary light vectors + // + float4 color1 = CalcLighting( faceNormal, input[0].color.a ); + color1 *= input[0].color; + + // + // Make sure we always have an alpha of 1 + // + color1.a = 1.0; + + // + // Emit out the new tri + // + for(int i=0; i<3; i++) + { + output.pos = input[i].pos; + output.color = color1; + output.tex = input[i].tex; + QuadStream.Append(output); + } + QuadStream.RestartStrip(); +} + +//-------------------------------------------------------------------------------------- +// RandomDir helper. Samples a random dir out of our 1d random texture. In this case +// we use a texture because the offset could be anywhere. If we were sampling linearly +// then we would probably just use a buffer and load from that. +//-------------------------------------------------------------------------------------- +float3 RandomDir(float fOffset) +{ + float tCoord = (fOffset) / 300.0; + return g_txRandom.SampleLevel( g_samPoint, tCoord, 0 ); +} + +//-------------------------------------------------------------------------------------- +// Helper to determing if a point is within a triangle +//-------------------------------------------------------------------------------------- +bool IsInTriangle( float3 P, float3 A, float3 B, float3 C ) +{ + float3 crossA = cross( B-A, P-A ); + float3 crossB = cross( C-B, P-B ); + float3 crossC = cross( A-C, P-C ); + + if( dot( crossA, crossB ) > 0 && + dot( crossB, crossC ) > 0 ) + { + return true; + } + else + { + return false; + } +} + +//-------------------------------------------------------------------------------------- +// Gets a random orientation matrix based upon the RandomDir funciton +//-------------------------------------------------------------------------------------- +float4x4 GetRandomOrientation( float3 Pos, float3 Norm, float fRandOffset ) +{ + float3 Tangent = RandomDir(fRandOffset); + + float3 Bitangent = normalize( cross( Tangent, Norm ) ); + Tangent = normalize( cross( Bitangent, Norm ) ); + + float4x4 matWorld = { float4( Tangent, 0 ), + float4( Norm, 0 ), + float4( Bitangent, 0 ), + float4( Pos, 1 ) }; + return matWorld; +} + +//-------------------------------------------------------------------------------------- +// Generates an actual grass blade +//-------------------------------------------------------------------------------------- +void OutputGrassBlade( VSGrassOut midPoint, inout TriangleStream GrassStream, int iGrassTex ) +{ + PSQuadIn output; + + float4x4 mWorld = GetRandomOrientation( midPoint.pos, midPoint.norm, (float)midPoint.VertexID ); + float4 ViewPos = mul( midPoint.pos, g_mWorldView ); + + float3 grassNorm = midPoint.norm; + float4 color1 = CalcLighting( grassNorm, ViewPos.z ); + + for(int v=0; v<6; v++) + { + float3 pos = g_positions[v]; + pos.x *= g_GrassWidth; + pos.y *= g_GrassHeight; + + output.pos = mul( float4(pos,1), mWorld ); + output.pos = mul( output.pos, g_mWorldViewProj ); + output.tex = float3( g_texcoords[v], iGrassTex ); + output.color = color1; + + GrassStream.Append( output ); + } + + GrassStream.RestartStrip(); +} + +//-------------------------------------------------------------------------------------- +// Midpoint of the three vertices A,B,C +//-------------------------------------------------------------------------------------- +VSGrassOut CalcMidPoint( VSGrassOut A, VSGrassOut B, VSGrassOut C ) +{ + VSGrassOut MidPoint; + + MidPoint.pos = (A.pos + B.pos + C.pos)/3.0f; + MidPoint.norm = (A.norm + B.norm + C.norm)/3.0f; + MidPoint.tex = (A.tex + B.tex + C.tex)/3.0f; + MidPoint.VertexID = A.VertexID + B.VertexID + C.VertexID; + + return MidPoint; +} + +//-------------------------------------------------------------------------------------- +// The actual grass geometry shader. This generates grass blades based upon an input +// mesh (the tops of the islands) and a coverage texture. Each of the textures channels +// determines how much of each of the 4 types of grass to place at a particular spot. +//-------------------------------------------------------------------------------------- +[maxvertexcount(90)] +void GSGrassmain(triangle VSGrassOut input[3], inout TriangleStream GrassStream ) +{ + VSGrassOut MidPoint = CalcMidPoint( input[0], input[1], input[2] ); + + float4 CoverageMask = g_tx2dArray.SampleLevel( g_samPoint, float3(MidPoint.tex,4), 0 ); + float cm[4]; + cm[0] = CoverageMask.r; + cm[1] = CoverageMask.g; + cm[2] = CoverageMask.b; + cm[3] = CoverageMask.a; + + for(int g=0; g<4; g++) + { + float MaxBlades = float(g_iGrassCoverage)*cm[g]; + for(float i=0; i= vLightSpaceDepth ) ? 1.0f : 0.0f; + return dot( vBilinearWeights, vShadowTests ); +} + +//-------------------------------------------------------------------------------------- +// Diffuse lighting calculation, with angle and distance falloff +//-------------------------------------------------------------------------------------- +float4 CalcLightingColor( int iLight, float3 vPosWorld, float3 vPerPixelNormal ) +{ + float3 vLightPos = g_LightData[iLight].m_vLightPos.xyz; + float3 vLightDir = g_LightData[iLight].m_vLightDir.xyz; + float4 vLightColor = g_LightData[iLight].m_vLightColor; + float4 vFalloffs = g_LightData[iLight].m_vFalloffs; + + float3 vLightToPixelUnNormalized = vPosWorld - vLightPos; + + // Dist falloff = 0 at vFalloffs.x, 1 at vFalloffs.x - vFalloffs.y + float fDist = length( vLightToPixelUnNormalized ); + float fDistFalloff = saturate( ( vFalloffs.x - fDist ) / vFalloffs.y ); + + // Normalize from here on + float3 vLightToPixelNormalized = vLightToPixelUnNormalized / fDist; + + // Angle falloff = 0 at vFalloffs.z, 1 at vFalloffs.z - vFalloffs.w + float fCosAngle = dot( vLightToPixelNormalized, vLightDir ); + float fAngleFalloff = saturate( ( fCosAngle - vFalloffs.z ) / vFalloffs.w ); + + // Diffuse contribution + float fNDotL = saturate( -dot( vLightToPixelNormalized, vPerPixelNormal ) ); + + return vLightColor * fNDotL * fDistFalloff * fAngleFalloff; +} + +//-------------------------------------------------------------------------------------- +// Pixel Shader +//-------------------------------------------------------------------------------------- +float4 PSMain( PS_INPUT Input ) : SV_TARGET +{ + // Manual clip test, so that objects which are behind the mirror + // don't show up in the mirror. + clip( dot( g_vMirrorPlane.xyz, Input.vPosWorld.xyz ) + g_vMirrorPlane.w ); + +#ifdef NO_DIFFUSE_MAP + float4 vDiffuse = 0.5f; +#else // #ifdef NO_DIFFUSE_MAP + float4 vDiffuse = g_txDiffuse.Sample( g_samLinearWrap, Input.vTexcoord ); +#endif // #ifdef NO_DIFFUSE_MAP #else + + // Compute per-pixel normal +#ifdef NO_NORMAL_MAP + float3 vPerPixelNormal = Input.vNormal; +#else // #ifdef NO_NORMAL_MAP + float3 vPerPixelNormal = CalcPerPixelNormal( Input.vTexcoord, Input.vNormal, Input.vTangent ); +#endif // #ifdef NO_NORMAL_MAP #else + + // Compute lighting contribution +#ifdef NO_AMBIENT + float4 vTotalLightingColor = 0.0f; +#else // #ifdef NO_AMBIENT + float4 vTotalLightingColor = g_vAmbientColor; +#endif // #ifdef NO_AMBIENT #else + +#ifndef NO_DYNAMIC_LIGHTING + for ( int iLight = 0; iLight < g_iNumLights; ++iLight ) + { + float4 vLightingColor = CalcLightingColor( iLight, Input.vPosWorld, vPerPixelNormal ); +#ifndef NO_SHADOW_MAP + if ( iLight < g_iNumShadows && any( vLightingColor.xyz ) > 0.0f ) // Don't bother checking shadow map if the pixel is unlit + { + vLightingColor *= CalcUnshadowedAmountPCF2x2( iLight, Input.vPosWorld ); + } +#endif // #ifndef NO_SHADOW_MAP + vTotalLightingColor += vLightingColor; + } +#endif // #ifndef NO_DYNAMIC_LIGHTING + + return vDiffuse * g_vTintColor * g_vObjectColor * vTotalLightingColor; +} diff --git a/tests/hlsl/dxsdk/MultithreadedRendering11/MultithreadedRendering11_VS.hlsl b/tests/hlsl/dxsdk/MultithreadedRendering11/MultithreadedRendering11_VS.hlsl new file mode 100644 index 000000000..0d8d32ffa --- /dev/null +++ b/tests/hlsl/dxsdk/MultithreadedRendering11/MultithreadedRendering11_VS.hlsl @@ -0,0 +1,75 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VSMain +//-------------------------------------------------------------------------------------- +// File: MultithreadedRendering11_VS.hlsl +// +// The vertex shader file for the MultithreadedRendering11 sample. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +// Various debug options +//#define UNCOMPRESSED_VERTEX_DATA // The sdkmesh file contained uncompressed vertex data + +//-------------------------------------------------------------------------------------- +// Globals +//-------------------------------------------------------------------------------------- +cbuffer cbPerObject : register( b0 ) +{ + matrix g_mWorld : packoffset( c0 ); +}; +cbuffer cbPerScene : register( b1 ) +{ + matrix g_mViewProj : packoffset( c0 ); +}; + +//-------------------------------------------------------------------------------------- +// Input / Output structures +//-------------------------------------------------------------------------------------- +struct VS_INPUT +{ + float4 vPosition : POSITION; + float3 vNormal : NORMAL; + float2 vTexcoord : TEXCOORD0; + float3 vTangent : TANGENT; +}; + +struct VS_OUTPUT +{ + float3 vNormal : NORMAL; + float3 vTangent : TANGENT; + float2 vTexcoord : TEXCOORD0; + float4 vPosWorld : TEXCOORD1; + float4 vPosition : SV_POSITION; +}; + +// We aliased signed vectors as a unsigned format. +// Need to recover signed values. The values 1.0 and 2.0 +// are slightly inaccurate here. +float3 R10G10B10A2_UNORM_TO_R32G32B32_FLOAT( in float3 vVec ) +{ + vVec *= 2.0f; + return vVec >= 1.0f ? ( vVec - 2.0f ) : vVec; +} + +//-------------------------------------------------------------------------------------- +// Vertex Shader +//-------------------------------------------------------------------------------------- +VS_OUTPUT VSMain( VS_INPUT Input ) +{ + VS_OUTPUT Output; + +#ifndef UNCOMPRESSED_VERTEX_DATA + // Expand compressed vectors + Input.vNormal = R10G10B10A2_UNORM_TO_R32G32B32_FLOAT( Input.vNormal ); + Input.vTangent = R10G10B10A2_UNORM_TO_R32G32B32_FLOAT( Input.vTangent ); +#endif // #ifndef UNCOMPRESSED_VERTEX_DATA + + Output.vPosWorld = mul( Input.vPosition, g_mWorld ); + Output.vPosition = mul( Output.vPosWorld, g_mViewProj ); + Output.vNormal = mul( Input.vNormal, (float3x3)g_mWorld ); + Output.vTangent = mul( Input.vTangent, (float3x3)g_mWorld ); + Output.vTexcoord = Input.vTexcoord; + + return Output; +} + diff --git a/tests/hlsl/dxsdk/NBodyGravityCS11/NBodyGravityCS11.hlsl b/tests/hlsl/dxsdk/NBodyGravityCS11/NBodyGravityCS11.hlsl new file mode 100644 index 000000000..0a694450c --- /dev/null +++ b/tests/hlsl/dxsdk/NBodyGravityCS11/NBodyGravityCS11.hlsl @@ -0,0 +1,103 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile cs_4_0 -entry CSMain +//-------------------------------------------------------------------------------------- +// File: NBodyGravityCS11.hlsl +// +// Demonstrates how to use Compute Shader to do n-body gravity computation +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +static float softeningSquared = 0.0012500000*0.0012500000; +static float g_fG = 6.67300e-11f * 10000.0f; +static float g_fParticleMass = g_fG*10000.0f * 10000.0f; + +#define blocksize 128 +groupshared float4 sharedPos[blocksize]; + +// Body to body interaction, acceleration of the particle at position bi is updated +void bodyBodyInteraction(inout float3 ai, float4 bj, float4 bi, float mass, int particles ) +{ + float3 r = bj.xyz - bi.xyz; + + float distSqr = dot(r, r); + distSqr += softeningSquared; + + float invDist = 1.0f / sqrt(distSqr); + float invDistCube = invDist * invDist * invDist; + + float s = mass * invDistCube * particles; + + ai += r * s; +} + +cbuffer cbCS : register( b0 ) +{ + uint4 g_param; // pcbCS->param[0] = MAX_PARTICLES; + // pcbCS->param[1] = dimx; + float4 g_paramf; // pcbCS->paramf[0] = 0.1f; + // pcbCS->paramf[1] = 1; +}; + +struct PosVelo +{ + float4 pos; + float4 velo; +}; + +StructuredBuffer oldPosVelo; +RWStructuredBuffer newPosVelo; + +[numthreads(blocksize, 1, 1)] +void CSMain( uint3 Gid : SV_GroupID, uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI : SV_GroupIndex ) +{ + // Each thread of the CS updates one of the particles + + float4 pos = oldPosVelo[DTid.x].pos; + float4 vel = oldPosVelo[DTid.x].velo; + float3 accel = 0; + float mass = g_fParticleMass; + + // Update current particle using all other particles + [loop] + for (uint tile = 0; tile < g_param.y; tile++) + { + // Cache a tile of particles unto shared memory to increase IO efficiency + sharedPos[GI] = oldPosVelo[tile * blocksize + GI].pos; + + GroupMemoryBarrierWithGroupSync(); + + [unroll] + for (uint counter = 0; counter < blocksize; counter+=8 ) + { + bodyBodyInteraction(accel, sharedPos[counter], pos, mass, 1); + bodyBodyInteraction(accel, sharedPos[counter+1], pos, mass, 1); + bodyBodyInteraction(accel, sharedPos[counter+2], pos, mass, 1); + bodyBodyInteraction(accel, sharedPos[counter+3], pos, mass, 1); + bodyBodyInteraction(accel, sharedPos[counter+4], pos, mass, 1); + bodyBodyInteraction(accel, sharedPos[counter+5], pos, mass, 1); + bodyBodyInteraction(accel, sharedPos[counter+6], pos, mass, 1); + bodyBodyInteraction(accel, sharedPos[counter+7], pos, mass, 1); + } + + GroupMemoryBarrierWithGroupSync(); + } + + // g_param.x is the number of our particles, however this number might not be an exact multiple of the tile size. + // In such cases, out of bound reads occur in the process above, which means there will be + // tooManyParticles "phantom" particles generating false gravity at position (0, 0, 0), so we have to substract them here. + // NOTE, out of bound reads always return 0 in CS + const uint tooManyParticles = g_param.y * blocksize - g_param.x; + bodyBodyInteraction(accel, float4(0, 0, 0, 0), pos, mass, -tooManyParticles); + + // Update the velocity and position of current particle using the acceleration computed above + vel.xyz += accel.xyz * g_paramf.x; //deltaTime; + vel.xyz *= g_paramf.y; //damping; + pos.xyz += vel.xyz * g_paramf.x; //deltaTime; + + if ( DTid.x < g_param.x ) + { + newPosVelo[DTid.x].pos = pos; + newPosVelo[DTid.x].velo = float4(vel.xyz, length(accel)); + } +} diff --git a/tests/hlsl/dxsdk/NBodyGravityCS11/ParticleDraw.hlsl b/tests/hlsl/dxsdk/NBodyGravityCS11/ParticleDraw.hlsl new file mode 100644 index 000000000..ea56e20e9 --- /dev/null +++ b/tests/hlsl/dxsdk/NBodyGravityCS11/ParticleDraw.hlsl @@ -0,0 +1,128 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VSParticleDraw -profile gs_4_0 -entry GSParticleDraw -profile ps_4_0 -entry PSParticleDraw +//-------------------------------------------------------------------------------------- +// File: ParticleDraw.hlsl +// +// Shaders for rendering the particle as point sprite +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +struct VSParticleIn +{ + float4 color : COLOR; + uint id : SV_VERTEXID; +}; + +struct VSParticleDrawOut +{ + float3 pos : POSITION; + float4 color : COLOR; +}; + +struct GSParticleDrawOut +{ + float2 tex : TEXCOORD0; + float4 color : COLOR; + float4 pos : SV_POSITION; +}; + +struct PSParticleDrawIn +{ + float2 tex : TEXCOORD0; + float4 color : COLOR; +}; + +struct PosVelo +{ + float4 pos; + float4 velo; +}; + +Texture2D g_txDiffuse; +StructuredBuffer g_bufPosVelo; + + +SamplerState g_samLinear +{ + Filter = MIN_MAG_MIP_LINEAR; + AddressU = Clamp; + AddressV = Clamp; +}; + +cbuffer cb0 +{ + row_major float4x4 g_mWorldViewProj; + row_major float4x4 g_mInvView; +}; + +cbuffer cb1 +{ + static float g_fParticleRad = 10.0f; +}; + +cbuffer cbImmutable +{ + static float3 g_positions[4] = + { + float3( -1, 1, 0 ), + float3( 1, 1, 0 ), + float3( -1, -1, 0 ), + float3( 1, -1, 0 ), + }; + + static float2 g_texcoords[4] = + { + float2(0,0), + float2(1,0), + float2(0,1), + float2(1,1), + }; +}; + +// +// Vertex shader for drawing the point-sprite particles +// +VSParticleDrawOut VSParticleDraw(VSParticleIn input) +{ + VSParticleDrawOut output; + + output.pos = g_bufPosVelo[input.id].pos; + + float mag = g_bufPosVelo[input.id].velo.w/9; + output.color = lerp( float4(1,0.1,0.1,1), input.color, mag ); + + return output; +} + +// +// GS for rendering point sprite particles. Takes a point and turns it into 2 tris. +// +[maxvertexcount(4)] +void GSParticleDraw(point VSParticleDrawOut input[1], inout TriangleStream SpriteStream) +{ + GSParticleDrawOut output; + + // + // Emit two new triangles + // + for(int i=0; i<4; i++) + { + float3 position = g_positions[i] * g_fParticleRad; + position = mul( position, (float3x3)g_mInvView ) + input[0].pos; + output.pos = mul( float4(position,1.0), g_mWorldViewProj ); + + output.color = input[0].color; + output.tex = g_texcoords[i]; + SpriteStream.Append(output); + } + SpriteStream.RestartStrip(); +} + +// +// PS for drawing particles +// +float4 PSParticleDraw(PSParticleDrawIn input) : SV_Target +{ + return g_txDiffuse.Sample( g_samLinear, input.tex ) * input.color; +} \ No newline at end of file diff --git a/tests/hlsl/dxsdk/OIT11/OIT_CS.hlsl b/tests/hlsl/dxsdk/OIT11/OIT_CS.hlsl new file mode 100644 index 000000000..dfc98b217 --- /dev/null +++ b/tests/hlsl/dxsdk/OIT11/OIT_CS.hlsl @@ -0,0 +1,277 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile cs_4_0 -entry VSParticleDraw -profile gs_4_0 -entry GSParticleDraw -profile ps_4_0 -entry PSParticleDraw +//----------------------------------------------------------------------------- +// File: OIT_CS.hlsl +// +// Desc: Compute shaders for used in the Order Independent Transparency sample. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//----------------------------------------------------------------------------- +// TODO: use structured buffers +RWBuffer deepBufferDepth : register( u0 ); +RWBuffer deepBufferColorUINT : register( u1 ); +RWTexture2D frameBuffer : register( u2 ); +RWBuffer prefixSum : register( u3 ); + +Texture2D fragmentCount : register ( t0 ); + +cbuffer CB : register( b0 ) +{ + uint g_nFrameWidth : packoffset( c0.x ); + uint g_nFrameHeight : packoffset( c0.y ); + uint g_nPassSize : packoffset( c0.z ); + uint g_nReserved : packoffset( c0.w ); +} + +#define blocksize 1 +#define groupthreads (blocksize*blocksize) +groupshared float accum[groupthreads]; + +// First pass of the prefix sum creation algorithm. Converts a 2D buffer to a 1D buffer, +// and sums every other value with the previous value. +[numthreads(1,1,1)] +void CreatePrefixSum_Pass0_CS( uint3 nGid : SV_GroupID, uint3 nDTid : SV_DispatchThreadID, uint3 nGTid : SV_GroupThreadID ) +{ + int nThreadNum = nGid.y*g_nFrameWidth + nGid.x; + if( nThreadNum%2 == 0 ) + { + prefixSum[nThreadNum] = fragmentCount[nGid.xy]; + + // Add the Fragment count to the next bin + if( (nThreadNum+1) < g_nFrameWidth * g_nFrameHeight ) + { + int2 nextUV; + nextUV.x = (nThreadNum+1) % g_nFrameWidth; + nextUV.y = (nThreadNum+1) / g_nFrameWidth; + prefixSum[ nThreadNum+1 ] = prefixSum[ nThreadNum ] + fragmentCount[ nextUV ]; + } + } +} + +// Second and following passes. Each pass distributes the sum of the first half of the group +// to the second half of the group. There are n/groupsize groups in each pass. +// Each pass increases the group size until it is the size of the buffer. +// The resulting buffer holds the prefix sum of all preceding values in each +// position +[numthreads(1,1,1)] +void CreatePrefixSum_Pass1_CS( uint3 nGid : SV_GroupID, uint3 nDTid : SV_DispatchThreadID, uint3 nGTid : SV_GroupThreadID ) +{ + int nThreadNum = nGid.x; + + int nValue = prefixSum[nThreadNum*g_nPassSize + g_nPassSize/2 - 1]; + for(int i = nThreadNum*g_nPassSize + g_nPassSize/2; i < nThreadNum*g_nPassSize + g_nPassSize && i < g_nFrameWidth*g_nFrameHeight; i++) + { + prefixSum[i] = prefixSum[i] + nValue; + } +} + +#if 1 + +// Sort the fragments using a bitonic sort, then accumulate the fragments into the final result. +groupshared int nIndex[32]; +#define NUM_THREADS 8 +[numthreads(1,1,1)] +void SortAndRenderCS( uint3 nGid : SV_GroupID, uint3 nDTid : SV_DispatchThreadID, uint3 nGTid : SV_GroupThreadID ) +{ + uint nThreadNum = nGid.y * g_nFrameWidth + nGid.x; + +// uint r0, r1, r2; +// float rd0, rd1, rd2, rd3, rd4, rd5, rd6, rd7; + + uint N = fragmentCount[nDTid.xy]; + + uint N2 = 1 << (int)(ceil(log2(N))); + + float fDepth[32]; + for(int i = 0; i < N; i++) + { + nIndex[i] = i; + fDepth[i] = deepBufferDepth[ prefixSum[nThreadNum-1] + i ]; + } + for(int i = N; i < N2; i++) + { + nIndex[i] = i; + fDepth[i] = 1.1f; + } + + uint idx = blocksize*nGTid.y + nGTid.x; + + // Bitonic sort + for( int k = 2; k <= N2; k = 2*k ) + { + for( int j = k>>1; j > 0 ; j = j>>1 ) + { + for( int i = 0; i < N2; i++ ) + { +// GroupMemoryBarrierWithGroupSync(); + //i = idx; + + float di = fDepth[ nIndex[ i ] ]; + int ixj = i^j; + if ( ( ixj ) > i ) + { + float dixj = fDepth[ nIndex[ ixj ] ]; + if ( ( i&k ) == 0 && di > dixj ) + { + int temp = nIndex[ i ]; + nIndex[ i ] = nIndex[ ixj ]; + nIndex[ ixj ] = temp; + } + if ( ( i&k ) != 0 && di < dixj ) + { + int temp = nIndex[ i ]; + nIndex[ i ] = nIndex[ ixj ]; + nIndex[ ixj ] = temp; + } + } + } + } + } + + // Output the final result to the frame buffer + if( idx == 0 ) + { + + /* + // Debug + uint color[8]; + for(int i = 0; i < 8; i++) + { + color[i] = deepBufferColorUINT[prefixSum[nThreadNum-1] + i]; + } + + for(int i = 0; i < 8; i++) + { + deepBufferDepth[nThreadNum*8+i] = fDepth[i];//fDepth[nIndex[i]]; + deepBufferColorUINT[nThreadNum*8+i] = color[nIndex[i]]; + } + */ + + // Accumulate fragments into final result + float4 result = 0.0f; + for( int x = N-1; x >= 0; x-- ) + { + uint bufferValue = deepBufferColorUINT[ prefixSum[nThreadNum-1] + nIndex[ x ] ]; + float4 color; + color.r = ( ( bufferValue >> 0 & 0xFF )) / 255.0f; + color.g = ( bufferValue >> 8 & 0xFF ) / 255.0f; + color.b = ( bufferValue >> 16 & 0xFF ) / 255.0f; + color.a = ( bufferValue >> 24 & 0xFF ) / 255.0f; + result = lerp( result, color, color.a ); + } + result.a = 1.0f; + frameBuffer[ nGid.xy ] = result; + } +} + +#else +[numthreads(1,1,1)] +void SortAndRenderCS( uint3 nGid : SV_GroupID, uint3 nDTid : SV_DispatchThreadID, uint3 nGTid : SV_GroupThreadID ) +{ + uint nThreadNum = nDTid.y * g_nFrameWidth + nDTid.x; + float d0 = deepBufferDepth[nThreadNum*8]; + float d1 = deepBufferDepth[nThreadNum*8+1]; + float d2 = deepBufferDepth[nThreadNum*8+2]; + + uint s0 = deepBufferColorUINT[nThreadNum*8 + 0]; + uint s1 = deepBufferColorUINT[nThreadNum*8 + 1]; + uint s2 = deepBufferColorUINT[nThreadNum*8 + 2]; + + uint r0, r1, r2; + float rd0, rd1, rd2; + if( d0 < d1 && d0 < d2 ) + { + r0 = s0; + rd0 = d0; + if( d1 < d2 ) + { + r1 = s1; + r2 = s2; + + rd1 = d1; + rd2 = d2; + } + else + { + r1 = s2; + r2 = s1; + + rd1 = d2; + rd2 = d1; + } + } + else if( d1 < d2 ) + { + r0 = s1; + rd0 = d1; + if( d0 < d2 ) + { + r1 = s0; + r2 = s2; + + rd1 = d0; + rd2 = d2; + } + else + { + r1 = s2; + r2 = s0; + + rd1 = d2; + rd2 = d0; + } + } + else + { + r0 = s2; + rd0 = d2; + if( d1 < d0 ) + { + r1 = s1; + r2 = s0; + + rd1 = d1; + rd2 = d0; + } + else + { + r1 = s0; + r2 = s1; + + rd1 = d0; + rd2 = d1; + } + } + + deepBufferDepth[nThreadNum*8] = rd0; + deepBufferDepth[nThreadNum*8+1] = rd1; + deepBufferDepth[nThreadNum*8+2] = rd2; + + deepBufferColorUINT[nThreadNum*8] = r0; + deepBufferColorUINT[nThreadNum*8+1] = r1; + deepBufferColorUINT[nThreadNum*8+2] = r2; + + // convert the color to floats + float4 color[3]; + color[0].r = (r0 >> 0 & 0xFF) / 255.0f; + color[0].g = (r0 >> 8 & 0xFF) / 255.0f; + color[0].b = (r0 >> 16 & 0xFF) / 255.0f; + color[0].a = (r0 >> 24 & 0xFF) / 255.0f; + + color[1].r = (r1 >> 0 & 0xFF) / 255.0f; + color[1].g = (r1 >> 8 & 0xFF) / 255.0f; + color[1].b = (r1 >> 16 & 0xFF) / 255.0f; + color[1].a = (r1 >> 24 & 0xFF) / 255.0f; + + color[2].r = (r2 >> 0 & 0xFF) / 255.0f; + color[2].g = (r2 >> 8 & 0xFF) / 255.0f; + color[2].b = (r2 >> 16 & 0xFF) / 255.0f; + color[2].a = (r2 >> 24 & 0xFF) / 255.0f; + + float4 result = lerp(lerp(lerp(0, color[2], color[2].a), color[1], color[1].a), color[0], color[0].a); + result.a = 1.0f; + + frameBuffer[nDTid.xy] = result; +} + +#endif \ No newline at end of file diff --git a/tests/hlsl/dxsdk/OIT11/OIT_PS.hlsl b/tests/hlsl/dxsdk/OIT11/OIT_PS.hlsl new file mode 100644 index 000000000..1fdb31622 --- /dev/null +++ b/tests/hlsl/dxsdk/OIT11/OIT_PS.hlsl @@ -0,0 +1,56 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile ps_4_0 -entry FragmentCountPS -entry FillDeepBufferPS +//----------------------------------------------------------------------------- +// File: OITPS.hlsl +// +// Desc: Pixel shaders used in the Order Independent Transparency sample. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//----------------------------------------------------------------------------- +//TODO: Use structured buffers +RWTexture2D fragmentCount : register( u1 ); +RWBuffer deepBufferDepth : register( u2 ); +RWBuffer deepBufferColor : register( u3 ); +RWBuffer prefixSum : register( u4 ); + +cbuffer CB : register( b0 ) +{ + uint g_nFrameWidth : packoffset( c0.x ); + uint g_nFrameHeight : packoffset( c0.y ); + uint g_nReserved0 : packoffset( c0.z ); + uint g_nReserved1 : packoffset( c0.w ); +} + +struct SceneVS_Output +{ + float4 pos : SV_POSITION; + float4 color : COLOR0; +}; + +void FragmentCountPS( SceneVS_Output input) +{ + // Increments need to be done atomically + InterlockedAdd(fragmentCount[input.pos.xy], 1); +} + +void FillDeepBufferPS( SceneVS_Output input ) +{ + uint x = input.pos.x; + uint y = input.pos.y; + + // Atomically allocate space in the deep buffer + uint fc; + InterlockedAdd(fragmentCount[input.pos.xy], 1, fc); + + uint nPrefixSumPos = y*g_nFrameWidth + x; + uint nDeepBufferPos; + if( nPrefixSumPos == 0 ) + nDeepBufferPos = fc; + else + nDeepBufferPos = prefixSum[nPrefixSumPos-1] + fc; + + // Store fragment data into the allocated space + deepBufferDepth[nDeepBufferPos] = input.pos.z; + deepBufferColor[nDeepBufferPos] = clamp(input.color, 0, 1)*255; +} + diff --git a/tests/hlsl/dxsdk/OIT11/SceneVS.hlsl b/tests/hlsl/dxsdk/OIT11/SceneVS.hlsl new file mode 100644 index 000000000..2f985d1d1 --- /dev/null +++ b/tests/hlsl/dxsdk/OIT11/SceneVS.hlsl @@ -0,0 +1,36 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry SceneVS +//----------------------------------------------------------------------------- +// File: SceneVS.hlsl +// +// Desc: Vertex shader for the scene. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//----------------------------------------------------------------------------- + + +cbuffer cbPerObject : register( b0 ) +{ + row_major matrix g_mWorldViewProjection : packoffset( c0 ); +} + +struct SceneVS_Input +{ + float4 pos : POSITION; + float4 color : COLOR; +}; + +struct SceneVS_Output +{ + float4 pos : SV_POSITION; + float4 color : COLOR0; +}; + +SceneVS_Output SceneVS( SceneVS_Input input ) +{ + SceneVS_Output output; + + output.color = input.color; + output.pos = mul(input.pos, g_mWorldViewProjection ); + + return output; +} diff --git a/tests/hlsl/dxsdk/README.md b/tests/hlsl/dxsdk/README.md new file mode 100644 index 000000000..dd0c0fb6b --- /dev/null +++ b/tests/hlsl/dxsdk/README.md @@ -0,0 +1,5 @@ +DirectX SDK Sample Shaders +========================== + +This directory contains shaders that have shipped as part of the DirectX SDK. +The licsense terms for these shaders are specificed at the top of the source files. \ No newline at end of file diff --git a/tests/hlsl/dxsdk/SimpleBezier11/SimpleBezier11.hlsl b/tests/hlsl/dxsdk/SimpleBezier11/SimpleBezier11.hlsl new file mode 100644 index 000000000..7b7a1489c --- /dev/null +++ b/tests/hlsl/dxsdk/SimpleBezier11/SimpleBezier11.hlsl @@ -0,0 +1,230 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry BezierVS -profile hs_5_0 -entry BezierHS -profile ds_5_0 -entry BezierDS -profile ps_4_0 -entry BezierPS -entry SolidColorPS +//-------------------------------------------------------------------------------------- +// File: SimpleBezier11.hlsl +// +// This sample shows an simple implementation of the DirectX 11 Hardware Tessellator +// for rendering a Bezier Patch. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +// This allows us to compile the shader with a #define to choose +// the different partition modes for the hull shader. +// See the hull shader: [partitioning(BEZIER_HS_PARTITION)] +// This sample demonstrates "integer", "fractional_even", and "fractional_odd" +#ifndef BEZIER_HS_PARTITION +#define BEZIER_HS_PARTITION "integer" +#endif // BEZIER_HS_PARTITION + +// The input patch size. In this sample, it is 16 control points. +// This value should match the call to IASetPrimitiveTopology() +#define INPUT_PATCH_SIZE 16 + +// The output patch size. In this sample, it is also 16 control points. +#define OUTPUT_PATCH_SIZE 16 + +//-------------------------------------------------------------------------------------- +// Constant Buffers +//-------------------------------------------------------------------------------------- +cbuffer cbPerFrame : register( b0 ) +{ + matrix g_mViewProjection; + float3 g_vCameraPosWorld; + float g_fTessellationFactor; +}; + +//-------------------------------------------------------------------------------------- +// Vertex shader section +//-------------------------------------------------------------------------------------- +struct VS_CONTROL_POINT_INPUT +{ + float3 vPosition : POSITION; +}; + +struct VS_CONTROL_POINT_OUTPUT +{ + float3 vPosition : POSITION; +}; + +// This simple vertex shader passes the control points straight through to the +// hull shader. In a more complex scene, you might transform the control points +// or perform skinning at this step. + +// The input to the vertex shader comes from the vertex buffer. + +// The output from the vertex shader will go into the hull shader. + +VS_CONTROL_POINT_OUTPUT BezierVS( VS_CONTROL_POINT_INPUT Input ) +{ + VS_CONTROL_POINT_OUTPUT Output; + + Output.vPosition = Input.vPosition; + + return Output; +} + +//-------------------------------------------------------------------------------------- +// Constant data function for the BezierHS. This is executed once per patch. +//-------------------------------------------------------------------------------------- +struct HS_CONSTANT_DATA_OUTPUT +{ + float Edges[4] : SV_TessFactor; + float Inside[2] : SV_InsideTessFactor; +}; + +struct HS_OUTPUT +{ + float3 vPosition : BEZIERPOS; +}; + +// This constant hull shader is executed once per patch. For the simple Mobius strip +// model, it will be executed 4 times. In this sample, we set the tessellation factor +// via SV_TessFactor and SV_InsideTessFactor for each patch. In a more complex scene, +// you might calculate a variable tessellation factor based on the camera's distance. + +HS_CONSTANT_DATA_OUTPUT BezierConstantHS( InputPatch ip, + uint PatchID : SV_PrimitiveID ) +{ + HS_CONSTANT_DATA_OUTPUT Output; + + float TessAmount = g_fTessellationFactor; + + Output.Edges[0] = Output.Edges[1] = Output.Edges[2] = Output.Edges[3] = TessAmount; + Output.Inside[0] = Output.Inside[1] = TessAmount; + + return Output; +} + +// The hull shader is called once per output control point, which is specified with +// outputcontrolpoints. For this sample, we take the control points from the vertex +// shader and pass them directly off to the domain shader. In a more complex scene, +// you might perform a basis conversion from the input control points into a Bezier +// patch, such as the SubD11 Sample. + +// The input to the hull shader comes from the vertex shader + +// The output from the hull shader will go to the domain shader. +// The tessellation factor, topology, and partition mode will go to the fixed function +// tessellator stage to calculate the UVW and domain points. + +[domain("quad")] +[partitioning(BEZIER_HS_PARTITION)] +[outputtopology("triangle_cw")] +[outputcontrolpoints(OUTPUT_PATCH_SIZE)] +[patchconstantfunc("BezierConstantHS")] +HS_OUTPUT BezierHS( InputPatch p, + uint i : SV_OutputControlPointID, + uint PatchID : SV_PrimitiveID ) +{ + HS_OUTPUT Output; + Output.vPosition = p[i].vPosition; + return Output; +} + +//-------------------------------------------------------------------------------------- +// Bezier evaluation domain shader section +//-------------------------------------------------------------------------------------- +struct DS_OUTPUT +{ + float4 vPosition : SV_POSITION; + float3 vWorldPos : WORLDPOS; + float3 vNormal : NORMAL; +}; + +//-------------------------------------------------------------------------------------- +float4 BernsteinBasis(float t) +{ + float invT = 1.0f - t; + + return float4( invT * invT * invT, + 3.0f * t * invT * invT, + 3.0f * t * t * invT, + t * t * t ); +} + +//-------------------------------------------------------------------------------------- +float4 dBernsteinBasis(float t) +{ + float invT = 1.0f - t; + + return float4( -3 * invT * invT, + 3 * invT * invT - 6 * t * invT, + 6 * t * invT - 3 * t * t, + 3 * t * t ); +} + +//-------------------------------------------------------------------------------------- +float3 EvaluateBezier( const OutputPatch bezpatch, + float4 BasisU, + float4 BasisV ) +{ + float3 Value = float3(0,0,0); + Value = BasisV.x * ( bezpatch[0].vPosition * BasisU.x + bezpatch[1].vPosition * BasisU.y + bezpatch[2].vPosition * BasisU.z + bezpatch[3].vPosition * BasisU.w ); + Value += BasisV.y * ( bezpatch[4].vPosition * BasisU.x + bezpatch[5].vPosition * BasisU.y + bezpatch[6].vPosition * BasisU.z + bezpatch[7].vPosition * BasisU.w ); + Value += BasisV.z * ( bezpatch[8].vPosition * BasisU.x + bezpatch[9].vPosition * BasisU.y + bezpatch[10].vPosition * BasisU.z + bezpatch[11].vPosition * BasisU.w ); + Value += BasisV.w * ( bezpatch[12].vPosition * BasisU.x + bezpatch[13].vPosition * BasisU.y + bezpatch[14].vPosition * BasisU.z + bezpatch[15].vPosition * BasisU.w ); + + return Value; +} + +// The domain shader is run once per vertex and calculates the final vertex's position +// and attributes. It receives the UVW from the fixed function tessellator and the +// control point outputs from the hull shader. Since we are using the DirectX 11 +// Tessellation pipeline, it is the domain shader's responsibility to calculate the +// final SV_POSITION for each vertex. In this sample, we evaluate the vertex's +// position using a Bernstein polynomial and the normal is calculated as the cross +// product of the U and V derivatives. + +// The input SV_DomainLocation to the domain shader comes from fixed function +// tessellator. And the OutputPatch comes from the hull shader. From these, you +// must calculate the final vertex position, color, texcoords, and other attributes. + +// The output from the domain shader will be a vertex that will go to the video card's +// rasterization pipeline and get drawn to the screen. + +[domain("quad")] +DS_OUTPUT BezierDS( HS_CONSTANT_DATA_OUTPUT input, + float2 UV : SV_DomainLocation, + const OutputPatch bezpatch ) +{ + float4 BasisU = BernsteinBasis( UV.x ); + float4 BasisV = BernsteinBasis( UV.y ); + float4 dBasisU = dBernsteinBasis( UV.x ); + float4 dBasisV = dBernsteinBasis( UV.y ); + + float3 WorldPos = EvaluateBezier( bezpatch, BasisU, BasisV ); + float3 Tangent = EvaluateBezier( bezpatch, dBasisU, BasisV ); + float3 BiTangent = EvaluateBezier( bezpatch, BasisU, dBasisV ); + float3 Norm = normalize( cross( Tangent, BiTangent ) ); + + DS_OUTPUT Output; + Output.vPosition = mul( float4(WorldPos,1), g_mViewProjection ); + Output.vWorldPos = WorldPos; + Output.vNormal = Norm; + + return Output; +} + +//-------------------------------------------------------------------------------------- +// Smooth shading pixel shader section +//-------------------------------------------------------------------------------------- + +// The pixel shader works the same as it would in a normal graphics pipeline. +// In this sample, it performs very simple N dot L lighting. + +float4 BezierPS( DS_OUTPUT Input ) : SV_TARGET +{ + float3 N = normalize(Input.vNormal); + float3 L = normalize(Input.vWorldPos - g_vCameraPosWorld); + return abs(dot(N, L)) * float4(1, 0, 0, 1); +} + +//-------------------------------------------------------------------------------------- +// Solid color shading pixel shader (used for wireframe overlay) +//-------------------------------------------------------------------------------------- +float4 SolidColorPS( DS_OUTPUT Input ) : SV_TARGET +{ + // Return a solid green color + return float4( 0, 1, 0, 1 ); +} diff --git a/tests/hlsl/dxsdk/SimpleSample11/SimpleSample.fx b/tests/hlsl/dxsdk/SimpleSample11/SimpleSample.fx new file mode 100644 index 000000000..00883ce70 --- /dev/null +++ b/tests/hlsl/dxsdk/SimpleSample11/SimpleSample.fx @@ -0,0 +1,112 @@ +//TEST_IGNORE_FILE: +//-------------------------------------------------------------------------------------- +// File: SimpleSample.fx +// +// The effect file for the SimpleSample sample. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + + +//-------------------------------------------------------------------------------------- +// Global variables +//-------------------------------------------------------------------------------------- +float4 g_MaterialAmbientColor; // Material's ambient color +float4 g_MaterialDiffuseColor; // Material's diffuse color +float3 g_LightDir; // Light's direction in world space +float4 g_LightDiffuse; // Light's diffuse color +texture g_MeshTexture; // Color texture for mesh + +float g_fTime; // App's time in seconds +float4x4 g_mWorld; // World matrix for object +float4x4 g_mWorldViewProjection; // World * View * Projection matrix + + + +//-------------------------------------------------------------------------------------- +// Texture samplers +//-------------------------------------------------------------------------------------- +sampler MeshTextureSampler = +sampler_state +{ + Texture = ; + MipFilter = LINEAR; + MinFilter = LINEAR; + MagFilter = LINEAR; +}; + + +//-------------------------------------------------------------------------------------- +// Vertex shader output structure +//-------------------------------------------------------------------------------------- +struct VS_OUTPUT +{ + float4 Position : POSITION; // vertex position + float4 Diffuse : COLOR0; // vertex diffuse color (note that COLOR0 is clamped from 0..1) + float2 TextureUV : TEXCOORD0; // vertex texture coords +}; + + +//-------------------------------------------------------------------------------------- +// This shader computes standard transform and lighting +//-------------------------------------------------------------------------------------- +VS_OUTPUT RenderSceneVS( float4 vPos : POSITION, + float3 vNormal : NORMAL, + float2 vTexCoord0 : TEXCOORD0 ) +{ + VS_OUTPUT Output; + float3 vNormalWorldSpace; + + // Transform the position from object space to homogeneous projection space + Output.Position = mul(vPos, g_mWorldViewProjection); + + // Transform the normal from object space to world space + vNormalWorldSpace = normalize(mul(vNormal, (float3x3)g_mWorld)); // normal (world space) + + // Calc diffuse color + Output.Diffuse.rgb = g_MaterialDiffuseColor * g_LightDiffuse * max(0,dot(vNormalWorldSpace, g_LightDir)) + + g_MaterialAmbientColor; + Output.Diffuse.a = 1.0f; + + // Just copy the texture coordinate through + Output.TextureUV = vTexCoord0; + + return Output; +} + + +//-------------------------------------------------------------------------------------- +// Pixel shader output structure +//-------------------------------------------------------------------------------------- +struct PS_OUTPUT +{ + float4 RGBColor : COLOR0; // Pixel color +}; + + +//-------------------------------------------------------------------------------------- +// This shader outputs the pixel's color by modulating the texture's +// color with diffuse material color +//-------------------------------------------------------------------------------------- +PS_OUTPUT RenderScenePS( VS_OUTPUT In ) +{ + PS_OUTPUT Output; + + // Lookup mesh texture and modulate it with diffuse + Output.RGBColor = tex2D(MeshTextureSampler, In.TextureUV) * In.Diffuse; + + return Output; +} + + +//-------------------------------------------------------------------------------------- +// Renders scene +//-------------------------------------------------------------------------------------- +technique RenderScene +{ + pass P0 + { + VertexShader = compile vs_2_0 RenderSceneVS(); + PixelShader = compile ps_2_0 RenderScenePS(); + } +} diff --git a/tests/hlsl/dxsdk/SimpleSample11/SimpleSample.hlsl b/tests/hlsl/dxsdk/SimpleSample11/SimpleSample.hlsl new file mode 100644 index 000000000..12f368f86 --- /dev/null +++ b/tests/hlsl/dxsdk/SimpleSample11/SimpleSample.hlsl @@ -0,0 +1,86 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry RenderSceneVS -profile ps_4_0 -entry RenderScenePS +//-------------------------------------------------------------------------------------- +// File: SimpleSample.hlsl +// +// The HLSL file for the SimpleSample sample for the Direct3D 11 device +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + + +//-------------------------------------------------------------------------------------- +// Constant Buffers +//-------------------------------------------------------------------------------------- +cbuffer cbPerObject : register( b0 ) +{ + matrix g_mWorldViewProjection : packoffset( c0 ); + matrix g_mWorld : packoffset( c4 ); + float4 g_MaterialAmbientColor : packoffset( c8 ); + float4 g_MaterialDiffuseColor : packoffset( c9 ); +} + +cbuffer cbPerFrame : register( b1 ) +{ + float3 g_vLightDir : packoffset( c0 ); + float g_fTime : packoffset( c0.w ); + float4 g_LightDiffuse : packoffset( c1 ); +}; + +//----------------------------------------------------------------------------------------- +// Textures and Samplers +//----------------------------------------------------------------------------------------- +Texture2D g_txDiffuse : register( t0 ); +SamplerState g_samLinear : register( s0 ); + +//-------------------------------------------------------------------------------------- +// shader input/output structure +//-------------------------------------------------------------------------------------- +struct VS_INPUT +{ + float4 Position : POSITION; // vertex position + float3 Normal : NORMAL; // this normal comes in per-vertex + float2 TextureUV : TEXCOORD0;// vertex texture coords +}; + +struct VS_OUTPUT +{ + float4 Position : SV_POSITION; // vertex position + float4 Diffuse : COLOR0; // vertex diffuse color (note that COLOR0 is clamped from 0..1) + float2 TextureUV : TEXCOORD0; // vertex texture coords +}; + +//-------------------------------------------------------------------------------------- +// This shader computes standard transform and lighting +//-------------------------------------------------------------------------------------- +VS_OUTPUT RenderSceneVS( VS_INPUT input ) +{ + VS_OUTPUT Output; + float3 vNormalWorldSpace; + + // Transform the position from object space to homogeneous projection space + Output.Position = mul( input.Position, g_mWorldViewProjection ); + + // Transform the normal from object space to world space + vNormalWorldSpace = normalize(mul(input.Normal, (float3x3)g_mWorld)); // normal (world space) + + // Calc diffuse color + Output.Diffuse.rgb = g_MaterialDiffuseColor * g_LightDiffuse * max(0,dot(vNormalWorldSpace, g_vLightDir)) + + g_MaterialAmbientColor; + Output.Diffuse.a = 1.0f; + + // Just copy the texture coordinate through + Output.TextureUV = input.TextureUV; + + return Output; +} + +//-------------------------------------------------------------------------------------- +// This shader outputs the pixel's color by modulating the texture's +// color with diffuse material color +//-------------------------------------------------------------------------------------- +float4 RenderScenePS( VS_OUTPUT In ) : SV_TARGET +{ + // Lookup mesh texture and modulate it with diffuse + return g_txDiffuse.Sample( g_samLinear, In.TextureUV ) * In.Diffuse; +} diff --git a/tests/hlsl/dxsdk/SubD11/SubD11.hlsl b/tests/hlsl/dxsdk/SubD11/SubD11.hlsl new file mode 100644 index 000000000..c4ebf9620 --- /dev/null +++ b/tests/hlsl/dxsdk/SubD11/SubD11.hlsl @@ -0,0 +1,1238 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry PatchSkinningVS -entry MeshSkinningVS -profile hs_5_0 -entry SubDToBezierHS -entry SubDToBezierHS4444 -profile ds_5_0 -entry BezierEvalDS -profile ps_4_0 -entry SmoothPS -entry SolidColorPS +//-------------------------------------------------------------------------------------- +// File: SubD11.hlsl +// +// This file contains functions to convert from a Catmull-Clark subdivision +// representation to a bicubic patch representation. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//Work-around for an optimization rule problem in the June 2010 HLSL Compiler (9.29.952.3111) +//see http://support.microsoft.com/kb/2448404 +#if D3DX_VERSION == 0xa2b +#pragma ruledisable 0x0802405f +#endif + +//-------------------------------------------------------------------------------------- +// A sample extraordinary SubD quad is represented by the following diagram: +// +// 15 Valences: +// / \ Vertex 0: 5 +// / 14 Vertex 1: 4 +// 17---------16 / \ Vertex 2: 5 +// | \ | / \ Vertex 3: 3 +// | \ | / 13 +// | \ |/ / Prefixes: +// | 3------2------12 Vertex 0: 9 +// | | | | Vertex 1: 12 +// | | | | Vertex 2: 16 +// 4----0------1------11 Vertex 3: 18 +// / /| | | +// / / | | | +// 5 / 8------9------10 +// \ / / +// 6 / +// \ / +// 7 +// +// Where the quad bounded by vertices 0,1,2,3 represents the actual subd surface of interest +// The 1-ring neighborhood of the quad is represented by vertices 4 through 17. The counter- +// clockwise winding of this 1-ring neighborhood is important, especially when it comes to compute +// the corner vertices of the bicubic patch that we will use to approximate the subd quad (0,1,2,3). +// +// The resulting bicubic patch fits within the subd quad (0,1,2,3) and has the following control +// point layout: +// +// 12--13--14--15 +// 8---9--10--11 +// 4---5---6---7 +// 0---1---2---3 +// +// The inner 4 control points of the bicubic patch are a combination of only the vertices (0,1,2,3) +// of the subd quad. However, the corner control points for the bicubic patch (0,3,15,12) are actually +// a much more complex weighting of the subd patch and the 1-ring neighborhood. In the example above +// the bicubic control point 0 is actually a weighted combination of subd points 0,1,2,3 and 1-ring +// neighborhood points 17, 4, 5, 6, 7, 8, and 9. We can see that the 1-ring neighbor hood is simply +// walked from the prefix value from the previous corner (corner 3 in this case) to the prefix +// prefix value for the current corner. We add one more vertex on either side of the prefix values +// and we have all the data necessary to calculate the value for the corner points. +// +// The edge control points of the bicubic patch (1,2,13,14,4,8,7,11) are also combinations of their +// neighbors, but fortunately each one is only a combination of 6 values and no walk is required. +//-------------------------------------------------------------------------------------- + +#define MOD4(x) ((x)&3) +#ifndef MAX_POINTS +#define MAX_POINTS 32 +#endif +#define MAX_BONE_MATRICES 80 + +//-------------------------------------------------------------------------------------- +// Textures +//-------------------------------------------------------------------------------------- +Texture2D g_txHeight : register( t0 ); // Height and Bump texture +Texture2D g_txDiffuse : register( t1 ); // Diffuse texture +Texture2D g_txSpecular : register( t2 ); // Specular texture + +//-------------------------------------------------------------------------------------- +// Samplers +//-------------------------------------------------------------------------------------- +SamplerState g_samLinear : register( s0 ); +SamplerState g_samPoint : register( s0 ); + +//-------------------------------------------------------------------------------------- +// Constant Buffers +//-------------------------------------------------------------------------------------- +cbuffer cbTangentStencilConstants : register( b0 ) +{ + float g_TanM[1024]; // Tangent patch stencils precomputed by the application + float g_fCi[16]; // Valence coefficients precomputed by the application +}; + +cbuffer cbPerMesh : register( b1 ) +{ + matrix g_mConstBoneWorld[MAX_BONE_MATRICES]; +}; + +cbuffer cbPerFrame : register( b2 ) +{ + matrix g_mViewProjection; + float3 g_vCameraPosWorld; + float g_fTessellationFactor; + float g_fDisplacementHeight; + float3 g_vSolidColor; +}; + +cbuffer cbPerSubset : register( b3 ) +{ + int g_iPatchStartIndex; +} + +//-------------------------------------------------------------------------------------- +Buffer g_ValencePrefixBuffer : register( t0 ); + +//-------------------------------------------------------------------------------------- +struct VS_CONTROL_POINT_OUTPUT +{ + float3 vPosition : WORLDPOS; + float2 vUV : TEXCOORD0; + float3 vTangent : TANGENT; +}; + +struct BEZIER_CONTROL_POINT +{ + float3 vPosition : BEZIERPOS; +}; + +struct PS_INPUT +{ + float3 vWorldPos : POSITION; + float3 vNormal : NORMAL; + float2 vUV : TEXCOORD; + float3 vTangent : TANGENT; + float3 vBiTangent : BITANGENT; +}; + +//-------------------------------------------------------------------------------------- +// SubD to Bezier helper functions +//-------------------------------------------------------------------------------------- +// Helps with getting tangent stencils from the g_TanM constant array +#define TANM(a,v) ( g_TanM[ Val[v]*64 + (a) ] ) + +//-------------------------------------------------------------------------------------- +float3 ComputeInteriorVertex( uint index, + uint Val[4], + const in InputPatch ip ) +{ + switch( index ) + { + case 0: + return (ip[0].vPosition*Val[0] + ip[1].vPosition*2 + ip[2].vPosition + ip[3].vPosition*2) / (5+Val[0]); + case 1: + return (ip[0].vPosition*2 + ip[1].vPosition*Val[1] + ip[2].vPosition*2 + ip[3].vPosition) / (5+Val[1]); + case 2: + return (ip[0].vPosition + ip[1].vPosition*2 + ip[2].vPosition*Val[2] + ip[3].vPosition*2) / (5+Val[2]); + case 3: + return (ip[0].vPosition*2 + ip[1].vPosition + ip[2].vPosition*2 + ip[3].vPosition*Val[3]) / (5+Val[3]); + } + + return float3(0,0,0); +} + +//-------------------------------------------------------------------------------------- +// Computes the corner vertices of the output UV patch. The corner vertices are +// a weighted combination of all points that are "connected" to that corner by an edge. +// The interior 4 points of the original subd quad are easy to get. The points in the +// 1-ring neighborhood around the interior quad are not. +// +// Because the valence of that corner could be any number between 3 and 16, we need to +// walk around the subd patch vertices connected to that point. This is there the +// Pref (prefix) values come into play. Each corner has a prefix value that is the index +// of the last value around the 1-ring neighborhood that should be used in calculating +// the coefficient of that corner. The walk goes from the prefix value of the previous +// corner to the prefix value of the current corner. +//-------------------------------------------------------------------------------------- +void ComputeCornerVertex( uint index, + out float3 CornerB, // Corner for the Bezier patch + out float3 CornerU, // Corner for the tangent patch + out float3 CornerV, // Corner for the bitangent patch + const in InputPatch ip, + const in uint Val[4], + const in uint Pref[4] ) +{ + const float fOWt = 1; + const float fEWt = 4; + + // Figure out where to start the walk by using the previous corner's prefix value + uint PrefIm1 = 0; + uint uStart = 4; + if( index ) + { + PrefIm1 = Pref[index-1]; + uStart = PrefIm1; + } + + // Setup the walk indices + uint uTIndexStart = 2 - (index&1); + uint uTIndex = uTIndexStart; + + // Calculate the N*N weight for the final value + CornerB = (Val[index]*Val[index])*ip[index].vPosition; // n^2 part + + // Zero out the corners + CornerU = float4(0,0,0,0); + CornerV = float4(0,0,0,0); + + const uint uV = Val[index] + ( ( index & 1 ) ? 1 : -1 ); + + // Start the walk with the uStart prefix (the prefix of the corner before us) + CornerB += ip[uStart].vPosition * fEWt; + CornerU += ip[uStart].vPosition * TANM( uTIndex * 2, index ); + CornerV += ip[uStart].vPosition * TANM( ( ( uTIndex + uV ) % Val[index] ) * 2, index); + + // Gather all vertices between the previous corner's prefix and our own prefix + // We'll do two at a time, since they always come in twos + while(uStart < Pref[index]-1) + { + ++uStart; + CornerB += ip[uStart].vPosition * fOWt; + CornerU += ip[uStart].vPosition * TANM( uTIndex * 2 + 1, index ); + CornerV += ip[uStart].vPosition * TANM( ( ( uTIndex + uV ) % Val[index] ) * 2 + 1, index ); + + ++uTIndex; + ++uStart; + CornerB += ip[uStart].vPosition * fEWt; + CornerU += ip[uStart].vPosition * TANM( ( uTIndex % Val[index] ) * 2, index ); + CornerV += ip[uStart].vPosition * TANM( ( ( uTIndex+uV)%Val[index]) * 2, index ); + } + ++uStart; + + // Add in the last guy and make sure to wrap to the beginning if we're the last corner + if (index == 3) + uStart = 4; + CornerB += ip[uStart].vPosition * fOWt; + CornerU += ip[uStart].vPosition * TANM( ( uTIndex % Val[index] ) * 2 + 1, index ); + CornerV += ip[uStart].vPosition * TANM( ( ( uTIndex + uV ) % Val[index] ) * 2 + 1, index ); + + // Add in the guy before the prefix as well + if (index) + uStart = PrefIm1-1; + else + uStart = Pref[3]-1; + uTIndex = uTIndexStart-1; + + CornerB += ip[uStart].vPosition * fOWt; + CornerU += ip[uStart].vPosition * TANM( ( uTIndex % Val[index] ) * 2 + 1, index ); + CornerV += ip[uStart].vPosition * TANM( ( ( uTIndex + uV ) % Val[index] ) * 2 + 1, index ); + + // We're done with the walk now. Now we need to add the contributions of the original subd quad. + CornerB += ip[MOD4(index+1)].vPosition * fEWt; + CornerB += ip[MOD4(index+2)].vPosition * fOWt; + CornerB += ip[MOD4(index+3)].vPosition * fEWt; + + uTIndex = 0 + (index&1)*(Val[index]-1); + uStart = MOD4(index+1); + CornerU += ip[uStart].vPosition * TANM( ( uTIndex % Val[index] ) * 2, index ); + CornerV += ip[uStart].vPosition * TANM( ( ( uTIndex + uV ) % Val[index] ) * 2, index ); + + uStart = MOD4(index+2); + CornerU += ip[uStart].vPosition * TANM( ( uTIndex % Val[index] ) * 2 + 1, index ); + CornerV += ip[uStart].vPosition * TANM( ( ( uTIndex + uV ) % Val[index] ) * 2 + 1, index ); + + uStart = MOD4(index+3); + uTIndex = (uTIndex+1)%Val[index]; + + CornerU += ip[uStart].vPosition * TANM( ( uTIndex % Val[index] ) * 2, index ); + CornerV += ip[uStart].vPosition * TANM( ( ( uTIndex + uV ) % Val[index] ) * 2, index ); + + // Normalize the corner weights + CornerB *= 1.0f / ( Val[index] * Val[index] + 5 * Val[index] ); // normalize + + // fixup signs from directional derivatives... + if( !((index - 1) & 2) ) // 1 and 2 + CornerU *= -1; + + if( index >= 2 ) // 2 and 3 + CornerV *= -1; +} + +void ComputeCornerVertex4444( uint index, + out float3 CornerB, // Corner for the Bezier patch + out float3 CornerU, // Corner for the tangent patch + out float3 CornerV, // Corner for the bitangent patch + const in InputPatch ip, + const in uint Val[4], + const in uint Pref[4] ) +{ + const float fOWt = 1; + const float fEWt = 4; + + // Figure out where to start the walk by using the previous corner's prefix value + uint PrefIm1 = 0; + uint uStart = 4; + if( index ) + { + PrefIm1 = Pref[index-1]; + uStart = PrefIm1; + } + + // Setup the walk indices + uint uTIndexStart = 2 - (index&1); + uint uTIndex = uTIndexStart; + + // Calculate the N*N weight for the final value + CornerB = (Val[index]*Val[index])*ip[index].vPosition; // n^2 part + + // Zero out the corners + CornerU = float4(0,0,0,0); + CornerV = float4(0,0,0,0); + + const uint uV = Val[index] + ( ( index & 1 ) ? 1 : -1 ); + + // Start the walk with the uStart prefix (the prefix of the corner before us) + CornerB += ip[uStart].vPosition * fEWt; + CornerU += ip[uStart].vPosition * TANM( uTIndex * 2, index ); + CornerV += ip[uStart].vPosition * TANM( ( ( uTIndex + uV ) % Val[index] ) * 2, index); + + // Gather all vertices between the previous corner's prefix and our own prefix + // We'll do two at a time, since they always come in twos + while(uStart < Pref[index]-1) + { + ++uStart; + CornerB += ip[uStart].vPosition * fOWt; + CornerU += ip[uStart].vPosition * TANM( uTIndex * 2 + 1, index ); + CornerV += ip[uStart].vPosition * TANM( ( ( uTIndex + uV ) % Val[index] ) * 2 + 1, index ); + + ++uTIndex; + ++uStart; + CornerB += ip[uStart].vPosition * fEWt; + CornerU += ip[uStart].vPosition * TANM( ( uTIndex % Val[index] ) * 2, index ); + CornerV += ip[uStart].vPosition * TANM( ( ( uTIndex+uV)%Val[index]) * 2, index ); + } + ++uStart; + + // Add in the last guy and make sure to wrap to the beginning if we're the last corner + if (index == 3) + uStart = 4; + CornerB += ip[uStart].vPosition * fOWt; + CornerU += ip[uStart].vPosition * TANM( ( uTIndex % Val[index] ) * 2 + 1, index ); + CornerV += ip[uStart].vPosition * TANM( ( ( uTIndex + uV ) % Val[index] ) * 2 + 1, index ); + + // Add in the guy before the prefix as well + if (index) + uStart = PrefIm1-1; + else + uStart = Pref[3]-1; + uTIndex = uTIndexStart-1; + + CornerB += ip[uStart].vPosition * fOWt; + CornerU += ip[uStart].vPosition * TANM( ( uTIndex % Val[index] ) * 2 + 1, index ); + CornerV += ip[uStart].vPosition * TANM( ( ( uTIndex + uV ) % Val[index] ) * 2 + 1, index ); + + // We're done with the walk now. Now we need to add the contributions of the original subd quad. + CornerB += ip[MOD4(index+1)].vPosition * fEWt; + CornerB += ip[MOD4(index+2)].vPosition * fOWt; + CornerB += ip[MOD4(index+3)].vPosition * fEWt; + + uTIndex = 0 + (index&1)*(Val[index]-1); + uStart = MOD4(index+1); + CornerU += ip[uStart].vPosition * TANM( ( uTIndex % Val[index] ) * 2, index ); + CornerV += ip[uStart].vPosition * TANM( ( ( uTIndex + uV ) % Val[index] ) * 2, index ); + + uStart = MOD4(index+2); + CornerU += ip[uStart].vPosition * TANM( ( uTIndex % Val[index] ) * 2 + 1, index ); + CornerV += ip[uStart].vPosition * TANM( ( ( uTIndex + uV ) % Val[index] ) * 2 + 1, index ); + + uStart = MOD4(index+3); + uTIndex = (uTIndex+1)%Val[index]; + + CornerU += ip[uStart].vPosition * TANM( ( uTIndex % Val[index] ) * 2, index ); + CornerV += ip[uStart].vPosition * TANM( ( ( uTIndex + uV ) % Val[index] ) * 2, index ); + + // Normalize the corner weights + CornerB *= 1.0f / ( Val[index] * Val[index] + 5 * Val[index] ); // normalize + + // fixup signs from directional derivatives... + if( !((index - 1) & 2) ) // 1 and 2 + CornerU *= -1; + + if( index >= 2 ) // 2 and 3 + CornerV *= -1; +} + +//-------------------------------------------------------------------------------------- +// Computes the edge vertices of the output bicubic patch. The edge vertices +// (1,2,4,7,8,11,13,14) are a weighted (by valence) combination of 6 interior and 1-ring +// neighborhood points. However, we don't have to do the walk on this one since we +// don't need all of the neighbor points attached to this vertex. +//-------------------------------------------------------------------------------------- +float3 ComputeEdgeVertex( in uint index /* 0-7 */, + const in InputPatch ip, + const in uint Val[4], + const in uint Pref[4] ) +{ + float val1 = 2 * Val[0] + 10; + float val2 = 2 * Val[1] + 10; + float val13 = 2 * Val[3] + 10; + float val14 = 2 * Val[2] + 10; + float val4 = val1; + float val8 = val13; + float val7 = val2; + float val11 = val14; + + float3 vRetVal = float3(0,0,0); + switch( index ) + { + // Horizontal + case 0: + vRetVal = (Val[0]*2*ip[0].vPosition + 4*ip[1].vPosition + ip[2].vPosition + ip[3].vPosition*2 + + 2*ip[Pref[0]-1].vPosition + ip[Pref[0]].vPosition) / val1; + break; + case 1: + vRetVal = (4*ip[0].vPosition + Val[1]*2*ip[1].vPosition + ip[2].vPosition*2 + ip[3].vPosition + + ip[Pref[0]-1].vPosition + 2*ip[Pref[0]].vPosition) / val2; + break; + case 2: + vRetVal = (2*ip[0].vPosition + ip[1].vPosition + 4*ip[2].vPosition + ip[3].vPosition*2*Val[3] + + 2*ip[Pref[2]].vPosition + ip[Pref[2]-1].vPosition) / val13; + break; + case 3: + vRetVal = (ip[0].vPosition + 2*ip[1].vPosition + Val[2]*2*ip[2].vPosition + ip[3].vPosition*4 + + ip[Pref[2]].vPosition + 2*ip[Pref[2]-1].vPosition) / val14; + break; + // Vertical + case 4: + vRetVal = (Val[0]*2*ip[0].vPosition + 2*ip[1].vPosition + ip[2].vPosition + ip[3].vPosition*4 + + 2*ip[4].vPosition + ip[Pref[3]-1].vPosition) / val4; + break; + case 5: + vRetVal = (4*ip[0].vPosition + ip[1].vPosition + 2*ip[2].vPosition + ip[3].vPosition*2*Val[3] + + ip[4].vPosition + 2*ip[Pref[3]-1].vPosition) / val8; + break; + case 6: + vRetVal = (2*ip[0].vPosition + Val[1]*2*ip[1].vPosition + 4*ip[2].vPosition + ip[3].vPosition + + 2*ip[Pref[1]-1].vPosition + ip[Pref[1]].vPosition) / val7; + break; + case 7: + vRetVal = (ip[0].vPosition + 4*ip[1].vPosition + Val[2]*2*ip[2].vPosition + 2*ip[3].vPosition + + ip[Pref[1]-1].vPosition + 2*ip[Pref[1]].vPosition) / val11; + break; + } + + return vRetVal; +} + +//-------------------------------------------------------------------------------------- +// Helper function +//-------------------------------------------------------------------------------------- +void BezierRaise(inout float3 pQ[3], out float3 pC[4]) +{ + pC[0] = pQ[0]; + pC[3] = pQ[2]; + + for( int i=1; i<3; i++ ) + { + pC[i] = ( 1.0f / 3.0f ) * ( pQ[i - 1] * i + ( 3.0f - i ) * pQ[i] ); + } +} + +//-------------------------------------------------------------------------------------- +// Computes the tangent patch from the input bezier patch +//-------------------------------------------------------------------------------------- +void ComputeTanPatch( const OutputPatch bezpatch, + inout float3 vOut[16], + in float fCWts[4], + in float3 vCorner[4], + in float3 vCornerLocal[4], + in const uint cX, + in const uint cY) +{ + float3 vQuad[3]; + float3 vQuadB[3]; + float3 vCubic[4]; + + // boundary edges are really simple... + vQuad[0] = vCornerLocal[0]; + vQuad[2] = vCornerLocal[1]; + vQuad[1] = 3.0f*(bezpatch[2*cX+0*cY].vPosition-bezpatch[1*cX+0*cY].vPosition); + + BezierRaise(vQuad,vCubic); + vOut[1*cX + 0*cY] = vCubic[1]; + vOut[2*cX + 0*cY] = vCubic[2]; + + vQuad[0] = vCornerLocal[2]; + vQuad[2] = vCornerLocal[3]; + vQuad[1] = 3.0f*(bezpatch[2*cX+3*cY].vPosition-bezpatch[1*cX+3*cY].vPosition); + + BezierRaise(vQuad,vCubic); + vOut[1*cX + 3*cY] = vCubic[1]; + vOut[2*cX + 3*cY] = vCubic[2]; + + // two internal edges - this is where work happens... + float3 vA,vB,vC,vD,vE; + float fC0,fC1; + vQuad[1] = 3.0f*(bezpatch[2*cX+2*cY].vPosition-bezpatch[1*cX+2*cY].vPosition); + // also do "second" scan line + vQuadB[1] = 3.0f*(bezpatch[2*cX+1*cY].vPosition-bezpatch[1*cX+1*cY].vPosition); + + vD = 3.0f*(bezpatch[1*cX + 2*cY].vPosition - bezpatch[0*cX + 2*cY].vPosition); + vE = 3.0f*(bezpatch[1*cX + 1*cY].vPosition - bezpatch[0*cX + 1*cY].vPosition); // used later... + + fC0 = fCWts[3]; + fC1 = fCWts[0]; + + // sign flip + vA = -vCorner[3]; + vB = 3.0f*(bezpatch[0*cX + 1*cY].vPosition - bezpatch[0*cX + 2*cY].vPosition); + vC = -vCorner[0]; + + vQuad[0] = 1.0f/3.0f*(2.0f*fC0*vB - fC1*vA) + vD; + vQuadB[0] = 1.0f/3.0f*(fC0*vC - 2.0f*fC1*vB) + vE; + + // do end of strip - same as before, but stuff is switched around... + vC = vCorner[2]; + vB = 3.0f*(bezpatch[3*cX + 2*cY].vPosition - bezpatch[3*cX + 1*cY].vPosition); + vA = vCorner[1]; + + vD = 3.0f*(bezpatch[2*cX + 1*cY].vPosition - bezpatch[3*cX + 1*cY].vPosition); + vE = 3.0f*(bezpatch[2*cX + 2*cY].vPosition - bezpatch[3*cX + 2*cY].vPosition); + + fC0 = fCWts[1]; + fC1 = fCWts[2]; + + vQuadB[2] = 1.0f/3.0f*(2.0f*fC0*vB - fC1*vA) + vD; + vQuad[2] = 1.0f/3.0f*(fC0*vC - 2.0f*fC1*vB) + vE; + + vQuadB[2] *= -1.0f; + vQuad[2] *= -1.0f; + + BezierRaise(vQuad,vCubic); + + vOut[0*cX + 2*cY] = vCubic[0]; + vOut[1*cX + 2*cY] = vCubic[1]; + vOut[2*cX + 2*cY] = vCubic[2]; + vOut[3*cX + 2*cY] = vCubic[3]; + + BezierRaise(vQuadB,vCubic); + + vOut[0*cX + 1*cY] = vCubic[0]; + vOut[1*cX + 1*cY] = vCubic[1]; + vOut[2*cX + 1*cY] = vCubic[2]; + vOut[3*cX + 1*cY] = vCubic[3]; +} + +//-------------------------------------------------------------------------------------- +// Skinning vertex shader Section +//-------------------------------------------------------------------------------------- +struct VS_CONTROL_POINT_INPUT +{ + float3 vPosition : POSITION; + float2 vUV : TEXCOORD0; + float3 vTangent : TANGENT; + uint4 vBones : BONES; + float4 vWeights : WEIGHTS; +}; + +VS_CONTROL_POINT_OUTPUT PatchSkinningVS( VS_CONTROL_POINT_INPUT Input ) +{ + VS_CONTROL_POINT_OUTPUT Output; + + float4 vInputPos = float4( Input.vPosition, 1 ); + float4 vWorldPos = float4( 0, 0, 0, 0 ); + + vWorldPos += mul( vInputPos, g_mConstBoneWorld[ Input.vBones.x ] ) * Input.vWeights.x; + vWorldPos += mul( vInputPos, g_mConstBoneWorld[ Input.vBones.y ] ) * Input.vWeights.y; + vWorldPos += mul( vInputPos, g_mConstBoneWorld[ Input.vBones.z ] ) * Input.vWeights.z; + vWorldPos += mul( vInputPos, g_mConstBoneWorld[ Input.vBones.w ] ) * Input.vWeights.w; + + float3 vWorldTan = float3( 0, 0, 0 ); + vWorldTan += mul( Input.vTangent, (float3x3)g_mConstBoneWorld[ Input.vBones.x ] ) * Input.vWeights.x; + vWorldTan += mul( Input.vTangent, (float3x3)g_mConstBoneWorld[ Input.vBones.y ] ) * Input.vWeights.y; + vWorldTan += mul( Input.vTangent, (float3x3)g_mConstBoneWorld[ Input.vBones.z ] ) * Input.vWeights.z; + vWorldTan += mul( Input.vTangent, (float3x3)g_mConstBoneWorld[ Input.vBones.w ] ) * Input.vWeights.w; + + Output.vPosition = vWorldPos; + Output.vUV = Input.vUV; + Output.vTangent = vWorldTan; + + return Output; +} + +struct VS_MESH_POINT_INPUT +{ + float3 vPosition : POSITION; + float2 vUV : TEXCOORD0; + float3 vNormal : NORMAL; + float3 vTangent : TANGENT; + uint4 vBones : BONES; + float4 vWeights : WEIGHTS; +}; + +struct VS_MESH_POINT_OUTPUT +{ + float3 vWorldPos : POSITION; + float3 vNormal : NORMAL; + float2 vUV : TEXCOORD; + float3 vTangent : TANGENT; + float3 vBiTangent : BITANGENT; + + float4 vPosition : SV_POSITION; +}; + +VS_MESH_POINT_OUTPUT MeshSkinningVS( VS_MESH_POINT_INPUT Input ) +{ + VS_MESH_POINT_OUTPUT Output; + + float4 vInputPos = float4( Input.vPosition, 1 ); + float4 vWorldPos = float4( 0, 0, 0, 0 ); + + vWorldPos += mul( vInputPos, g_mConstBoneWorld[ Input.vBones.x ] ) * Input.vWeights.x; + vWorldPos += mul( vInputPos, g_mConstBoneWorld[ Input.vBones.y ] ) * Input.vWeights.y; + vWorldPos += mul( vInputPos, g_mConstBoneWorld[ Input.vBones.z ] ) * Input.vWeights.z; + vWorldPos += mul( vInputPos, g_mConstBoneWorld[ Input.vBones.w ] ) * Input.vWeights.w; + + float3 vWorldTan = float3( 0, 0, 0 ); + vWorldTan += mul( Input.vTangent, (float3x3)g_mConstBoneWorld[ Input.vBones.x ] ) * Input.vWeights.x; + vWorldTan += mul( Input.vTangent, (float3x3)g_mConstBoneWorld[ Input.vBones.y ] ) * Input.vWeights.y; + vWorldTan += mul( Input.vTangent, (float3x3)g_mConstBoneWorld[ Input.vBones.z ] ) * Input.vWeights.z; + vWorldTan += mul( Input.vTangent, (float3x3)g_mConstBoneWorld[ Input.vBones.w ] ) * Input.vWeights.w; + + float3 vWorldNormal = float3( 0, 0, 0 ); + vWorldNormal += mul( Input.vNormal, (float3x3)g_mConstBoneWorld[ Input.vBones.x ] ) * Input.vWeights.x; + vWorldNormal += mul( Input.vNormal, (float3x3)g_mConstBoneWorld[ Input.vBones.y ] ) * Input.vWeights.y; + vWorldNormal += mul( Input.vNormal, (float3x3)g_mConstBoneWorld[ Input.vBones.z ] ) * Input.vWeights.z; + vWorldNormal += mul( Input.vNormal, (float3x3)g_mConstBoneWorld[ Input.vBones.w ] ) * Input.vWeights.w; + + Output.vWorldPos = vWorldPos.xyz; + Output.vPosition = mul( float4( vWorldPos.xyz, 1 ), g_mViewProjection ); + Output.vUV = Input.vUV; + Output.vTangent = vWorldTan; + Output.vNormal = vWorldNormal; + Output.vBiTangent = cross( vWorldNormal, vWorldTan ); + + return Output; +} + +//-------------------------------------------------------------------------------------- +// SubD to Bezier hull shader Section +//-------------------------------------------------------------------------------------- +struct HS_CONSTANT_DATA_OUTPUT +{ + float Edges[4] : SV_TessFactor; + float Inside[2] : SV_InsideTessFactor; + + float3 vTangent[4] : TANGENT; + float2 vUV[4] : TEXCOORD; + float3 vTanUCorner[4] : TANUCORNER; + float3 vTanVCorner[4] : TANVCORNER; + float4 vCWts : TANWEIGHTS; +}; + +//-------------------------------------------------------------------------------------- +// Load per-patch valence and prefix data +//-------------------------------------------------------------------------------------- +void LoadValenceAndPrefixData( in uint PatchID, out uint Val[4], out uint Prefixes[4] ) +{ + PatchID += g_iPatchStartIndex; + uint4 ValPack = g_ValencePrefixBuffer.Load( PatchID * 2 ); + uint4 PrefPack = g_ValencePrefixBuffer.Load( PatchID * 2 + 1 ); + + Val[0] = ValPack.x; + Val[1] = ValPack.y; + Val[2] = ValPack.z; + Val[3] = ValPack.w; + + Prefixes[0] = PrefPack.x; + Prefixes[1] = PrefPack.y; + Prefixes[2] = PrefPack.z; + Prefixes[3] = PrefPack.w; +} + + +//-------------------------------------------------------------------------------------- +// Constant data function for the SubDToBezierHS. This is executed once per patch. +//-------------------------------------------------------------------------------------- +HS_CONSTANT_DATA_OUTPUT SubDToBezierConstantsHS( InputPatch ip, + uint PatchID : SV_PrimitiveID ) +{ + HS_CONSTANT_DATA_OUTPUT Output; + + float TessAmount = g_fTessellationFactor; + + Output.Edges[0] = Output.Edges[1] = Output.Edges[2] = Output.Edges[3] = TessAmount; + Output.Inside[0] = Output.Inside[1] = TessAmount; + + Output.vTangent[0] = ip[0].vTangent; + Output.vTangent[1] = ip[1].vTangent; + Output.vTangent[2] = ip[2].vTangent; + Output.vTangent[3] = ip[3].vTangent; + + Output.vUV[0] = ip[0].vUV; + Output.vUV[1] = ip[1].vUV; + Output.vUV[2] = ip[2].vUV; + Output.vUV[3] = ip[3].vUV; + + // Compute part of our tangent patch here + uint Val[4]; + uint Prefixes[4]; + LoadValenceAndPrefixData( PatchID, Val, Prefixes ); + + [unroll] + for( int i=0; i<4; i++ ) + { + float3 CornerB, CornerU, CornerV; + ComputeCornerVertex( i, CornerB, CornerU, CornerV, ip, Val, Prefixes ); + Output.vTanUCorner[i] = CornerU; + Output.vTanVCorner[i] = CornerV; + } + + float fCWts[4]; + Output.vCWts.x = g_fCi[ Val[0]-3 ]; + Output.vCWts.y = g_fCi[ Val[1]-3 ]; + Output.vCWts.z = g_fCi[ Val[2]-3 ]; + Output.vCWts.w = g_fCi[ Val[3]-3 ]; + + return Output; +} + +HS_CONSTANT_DATA_OUTPUT SubDToBezierConstantsHS4444( InputPatch ip, + uint PatchID : SV_PrimitiveID ) +{ + HS_CONSTANT_DATA_OUTPUT Output; + + float TessAmount = g_fTessellationFactor; + + Output.Edges[0] = Output.Edges[1] = Output.Edges[2] = Output.Edges[3] = TessAmount; + Output.Inside[0] = Output.Inside[1] = TessAmount; + + Output.vTangent[0] = ip[0].vTangent; + Output.vTangent[1] = ip[1].vTangent; + Output.vTangent[2] = ip[2].vTangent; + Output.vTangent[3] = ip[3].vTangent; + + Output.vUV[0] = ip[0].vUV; + Output.vUV[1] = ip[1].vUV; + Output.vUV[2] = ip[2].vUV; + Output.vUV[3] = ip[3].vUV; + + // Compute part of our tangent patch here + static const uint Val[4] = (uint[4])uint4(4,4,4,4); + static const uint Prefixes[4] = (uint[4])uint4(7,10,13,16); + + [unroll] + for( int i=0; i<4; i++ ) + { + float3 CornerB, CornerU, CornerV; + ComputeCornerVertex4444( i, CornerB, CornerU, CornerV, ip, Val, Prefixes ); + Output.vTanUCorner[i] = CornerU; + Output.vTanVCorner[i] = CornerV; + } + + float fCWts[4]; + Output.vCWts.x = g_fCi[ Val[0]-3 ]; + Output.vCWts.y = g_fCi[ Val[1]-3 ]; + Output.vCWts.z = g_fCi[ Val[2]-3 ]; + Output.vCWts.w = g_fCi[ Val[3]-3 ]; + + return Output; +} + + +//-------------------------------------------------------------------------------------- +// HS for SubDToBezier. This outputcontrolpoints(16) specifies that we will produce +// 16 control points. Therefore this function will be invoked 16x, one for each output +// control point. +// +// !! PERFORMANCE NOTE: This hull shader is written for maximum readability, and its +// performance is not expected to be optimal on D3D11 hardware. The switch statement +// below that determines the codepath for each patch control point generates sub-optimal +// code for parallel execution on the GPU. A future implementation of this hull shader +// will combine the 16 codepaths and 3 variants (corner, edge, interior) into one shared +// codepath; this change is expected to increase performance at the expense of readability. +//-------------------------------------------------------------------------------------- +[domain("quad")] +[partitioning("integer")] +[outputtopology("triangle_cw")] +[outputcontrolpoints(16)] +[patchconstantfunc("SubDToBezierConstantsHS")] +BEZIER_CONTROL_POINT SubDToBezierHS( InputPatch p, + uint i : SV_OutputControlPointID, + uint PatchID : SV_PrimitiveID ) +{ + // Valences and prefixes are loaded from a buffer + uint Val[4]; + uint Prefixes[4]; + LoadValenceAndPrefixData( PatchID, Val, Prefixes ); + + float3 CornerB = float3(0,0,0); + float3 CornerU = float3(0,0,0); + float3 CornerV = float3(0,0,0); + + BEZIER_CONTROL_POINT Output; + Output.vPosition = float3(0,0,0); + + // !! PERFORMANCE NOTE: As mentioned above, this switch statement generates + // inefficient code for the sake of readability. + switch( i ) + { + // Interior vertices + case 5: + Output.vPosition = ComputeInteriorVertex( 0, Val, p ); + break; + case 6: + Output.vPosition = ComputeInteriorVertex( 1, Val, p ); + break; + case 10: + Output.vPosition = ComputeInteriorVertex( 2, Val, p ); + break; + case 9: + Output.vPosition = ComputeInteriorVertex( 3, Val, p ); + break; + + // Corner vertices + case 0: + ComputeCornerVertex( 0, CornerB, CornerU, CornerV, p, Val, Prefixes ); + Output.vPosition = CornerB; + break; + case 3: + ComputeCornerVertex( 1, CornerB, CornerU, CornerV, p, Val, Prefixes ); + Output.vPosition = CornerB; + break; + case 15: + ComputeCornerVertex( 2, CornerB, CornerU, CornerV, p, Val, Prefixes ); + Output.vPosition = CornerB; + break; + case 12: + ComputeCornerVertex( 3, CornerB, CornerU, CornerV, p, Val, Prefixes ); + Output.vPosition = CornerB; + break; + + // Edge vertices + case 1: + Output.vPosition = ComputeEdgeVertex( 0, p, Val, Prefixes ); + break; + case 2: + Output.vPosition = ComputeEdgeVertex( 1, p, Val, Prefixes ); + break; + case 13: + Output.vPosition = ComputeEdgeVertex( 2, p, Val, Prefixes ); + break; + case 14: + Output.vPosition = ComputeEdgeVertex( 3, p, Val, Prefixes ); + break; + case 4: + Output.vPosition = ComputeEdgeVertex( 4, p, Val, Prefixes ); + break; + case 8: + Output.vPosition = ComputeEdgeVertex( 5, p, Val, Prefixes ); + break; + case 7: + Output.vPosition = ComputeEdgeVertex( 6, p, Val, Prefixes ); + break; + case 11: + Output.vPosition = ComputeEdgeVertex( 7, p, Val, Prefixes ); + break; + } + + return Output; +} + +//-------------------------------------------------------------------------------------- +// Specialised version for Regular (4,4,4,4) patches, this is much simpler and has less +// branching compared to the general one above +//-------------------------------------------------------------------------------------- +[domain("quad")] +[partitioning("integer")] +[outputtopology("triangle_cw")] +[outputcontrolpoints(16)] +[patchconstantfunc("SubDToBezierConstantsHS4444")] +BEZIER_CONTROL_POINT SubDToBezierHS4444( InputPatch p, + uint i : SV_OutputControlPointID, + uint PatchID : SV_PrimitiveID ) +{ + // Valences and prefixes are Constant for this case (4,4,4,4) + static const uint Val[4] = (uint[4])uint4(4,4,4,4); + static const uint Prefixes[4] = (uint[4])uint4(7,10,13,16); + + float3 CornerB = float3(0,0,0); + float3 CornerU = float3(0,0,0); + float3 CornerV = float3(0,0,0); + + BEZIER_CONTROL_POINT Output; + Output.vPosition = float3(0,0,0); + + // !! PERFORMANCE NOTE: As mentioned above, this switch statement generates + // inefficient code for the sake of readability. + switch( i ) + { + // Interior vertices + case 5: + Output.vPosition = ComputeInteriorVertex( 0, Val, p ); + break; + case 6: + Output.vPosition = ComputeInteriorVertex( 1, Val, p ); + break; + case 10: + Output.vPosition = ComputeInteriorVertex( 2, Val, p ); + break; + case 9: + Output.vPosition = ComputeInteriorVertex( 3, Val, p ); + break; + + // Corner vertices + case 0: + ComputeCornerVertex4444( 0, CornerB, CornerU, CornerV, p, Val, Prefixes ); + Output.vPosition = CornerB; + break; + case 3: + ComputeCornerVertex4444( 1, CornerB, CornerU, CornerV, p, Val, Prefixes ); + Output.vPosition = CornerB; + break; + case 15: + ComputeCornerVertex4444( 2, CornerB, CornerU, CornerV, p, Val, Prefixes ); + Output.vPosition = CornerB; + break; + case 12: + ComputeCornerVertex4444( 3, CornerB, CornerU, CornerV, p, Val, Prefixes ); + Output.vPosition = CornerB; + break; + + // Edge vertices + case 1: + Output.vPosition = ComputeEdgeVertex( 0, p, Val, Prefixes ); + break; + case 2: + Output.vPosition = ComputeEdgeVertex( 1, p, Val, Prefixes ); + break; + case 13: + Output.vPosition = ComputeEdgeVertex( 2, p, Val, Prefixes ); + break; + case 14: + Output.vPosition = ComputeEdgeVertex( 3, p, Val, Prefixes ); + break; + case 4: + Output.vPosition = ComputeEdgeVertex( 4, p, Val, Prefixes ); + break; + case 8: + Output.vPosition = ComputeEdgeVertex( 5, p, Val, Prefixes ); + break; + case 7: + Output.vPosition = ComputeEdgeVertex( 6, p, Val, Prefixes ); + break; + case 11: + Output.vPosition = ComputeEdgeVertex( 7, p, Val, Prefixes ); + break; + } + + return Output; +} + + +//-------------------------------------------------------------------------------------- +// Bezier evaluation domain shader section +//-------------------------------------------------------------------------------------- +struct DS_OUTPUT +{ + float3 vWorldPos : POSITION; + float3 vNormal : NORMAL; + float2 vUV : TEXCOORD; + float3 vTangent : TANGENT; + float3 vBiTangent : BITANGENT; + + float4 vPosition : SV_POSITION; +}; + +//-------------------------------------------------------------------------------------- +float4 BernsteinBasis(float t) +{ + float invT = 1.0f - t; + + return float4( invT * invT * invT, + 3.0f * t * invT * invT, + 3.0f * t * t * invT, + t * t * t ); +} + +//-------------------------------------------------------------------------------------- +float4 dBernsteinBasis(float t) +{ + float invT = 1.0f - t; + + return float4( -3 * invT * invT, + 3 * invT * invT - 6 * t * invT, + 6 * t * invT - 3 * t * t, + 3 * t * t ); +} + +//-------------------------------------------------------------------------------------- +float3 EvaluateBezier( const OutputPatch bezpatch, + float4 BasisU, + float4 BasisV ) +{ + float3 Value = float3(0,0,0); + Value = BasisV.x * ( bezpatch[0].vPosition * BasisU.x + bezpatch[1].vPosition * BasisU.y + bezpatch[2].vPosition * BasisU.z + bezpatch[3].vPosition * BasisU.w ); + Value += BasisV.y * ( bezpatch[4].vPosition * BasisU.x + bezpatch[5].vPosition * BasisU.y + bezpatch[6].vPosition * BasisU.z + bezpatch[7].vPosition * BasisU.w ); + Value += BasisV.z * ( bezpatch[8].vPosition * BasisU.x + bezpatch[9].vPosition * BasisU.y + bezpatch[10].vPosition * BasisU.z + bezpatch[11].vPosition * BasisU.w ); + Value += BasisV.w * ( bezpatch[12].vPosition * BasisU.x + bezpatch[13].vPosition * BasisU.y + bezpatch[14].vPosition * BasisU.z + bezpatch[15].vPosition * BasisU.w ); + + return Value; +} + +//-------------------------------------------------------------------------------------- +float3 EvaluateBezierTan( const float3 bezpatch[16], + float4 BasisU, + float4 BasisV ) +{ + float3 Value = float3(0,0,0); + Value = BasisV.x * ( bezpatch[0] * BasisU.x + bezpatch[1] * BasisU.y + bezpatch[2] * BasisU.z + bezpatch[3] * BasisU.w ); + Value += BasisV.y * ( bezpatch[4] * BasisU.x + bezpatch[5] * BasisU.y + bezpatch[6] * BasisU.z + bezpatch[7] * BasisU.w ); + Value += BasisV.z * ( bezpatch[8] * BasisU.x + bezpatch[9] * BasisU.y + bezpatch[10] * BasisU.z + bezpatch[11] * BasisU.w ); + Value += BasisV.w * ( bezpatch[12] * BasisU.x + bezpatch[13] * BasisU.y + bezpatch[14] * BasisU.z + bezpatch[15] * BasisU.w ); + + return Value; +} + +//-------------------------------------------------------------------------------------- +// Compute a two full tangent patches from the Tangent corner data created in the +// HS constant data function. +//-------------------------------------------------------------------------------------- +void CreatTangentPatches( in HS_CONSTANT_DATA_OUTPUT input, + const OutputPatch bezpatch, + out float3 TanU[16], + out float3 TanV[16] ) +{ + TanV[0] = input.vTanVCorner[0]; + TanV[3] = input.vTanVCorner[1]; + TanV[15] = input.vTanVCorner[2]; + TanV[12] = input.vTanVCorner[3]; + + TanU[0] = input.vTanUCorner[0]; + TanU[3] = input.vTanUCorner[1]; + TanU[15] = input.vTanUCorner[2]; + TanU[12] = input.vTanUCorner[3]; + + float fCWts[4]; + fCWts[0] = input.vCWts.x; + fCWts[1] = input.vCWts.y; + fCWts[2] = input.vCWts.z; + fCWts[3] = input.vCWts.w; + + float3 vCorner[4]; + float3 vCornerLocal[4]; + + vCorner[0] = TanV[0]; + vCorner[1] = TanV[3]; + vCorner[2] = TanV[15]; + vCorner[3] = TanV[12]; + vCornerLocal[0] = TanU[0]; + vCornerLocal[1] = TanU[3]; + vCornerLocal[2] = TanU[12]; + vCornerLocal[3] = TanU[15]; + + ComputeTanPatch( bezpatch, TanU, fCWts, vCorner, vCornerLocal, 1, 4 ); + + fCWts[3] = input.vCWts.y; + fCWts[1] = input.vCWts.w; + + vCorner[0] = TanU[0]; + vCorner[3] = TanU[3]; + vCorner[2] = TanU[15]; + vCorner[1] = TanU[12]; + vCornerLocal[0] = TanV[0]; + vCornerLocal[1] = TanV[12]; + vCornerLocal[2] = TanV[3]; + vCornerLocal[3] = TanV[15]; + + ComputeTanPatch( bezpatch, TanV, fCWts, vCorner, vCornerLocal, 4, 1 ); +} + +//-------------------------------------------------------------------------------------- +// For each input UV (from the Tessellator), evaluate the Bezier patch at this position. +//-------------------------------------------------------------------------------------- +[domain("quad")] +DS_OUTPUT BezierEvalDS( HS_CONSTANT_DATA_OUTPUT input, + float2 UV : SV_DomainLocation, + const OutputPatch bezpatch ) +{ + float4 BasisU = BernsteinBasis( UV.x ); + float4 BasisV = BernsteinBasis( UV.y ); + + float3 WorldPos = EvaluateBezier( bezpatch, BasisU, BasisV ); + + float3 TanU[16]; + float3 TanV[16]; + CreatTangentPatches( input, bezpatch, TanU, TanV ); + float3 Tangent = EvaluateBezierTan( TanU, BasisU, BasisV ); + float3 BiTangent = EvaluateBezierTan( TanV, BasisU, BasisV ); + + // To see what the patch looks like without using the tangent patches to fix the normals, uncomment this section + /* + float4 dBasisU = dBernsteinBasis( UV.x ); + float4 dBasisV = dBernsteinBasis( UV.y ); + Tangent = EvaluateBezier( bezpatch, dBasisU, BasisV ); + BiTangent = EvaluateBezier( bezpatch, BasisU, dBasisV ); + */ + + float3 Norm = normalize( cross( Tangent, BiTangent ) ); + + DS_OUTPUT Output; + Output.vNormal = Norm; + + // Evalulate the tangent vectors through bilinear interpolation. + // These tangents are the texture-space tangents. They should not be confused with the parametric + // tangents that we use to get the normals for the bicubic patch. + float3 TextureTanU0 = input.vTangent[0]; + float3 TextureTanU1 = input.vTangent[1]; + float3 TextureTanU2 = input.vTangent[2]; + float3 TextureTanU3 = input.vTangent[3]; + + float3 UVbottom = lerp( TextureTanU0, TextureTanU1, UV.x ); + float3 UVtop = lerp( TextureTanU3, TextureTanU2, UV.x ); + float3 Tan = lerp( UVbottom, UVtop, UV.y ); + + Output.vTangent = Tan; + + // This is an optimization. We assume that the UV mapping of the mesh will result in a "relatively" orthogonal + // tangent basis. If we assume this, then we can avoid fetching and bilerping the BiTangent along with the tangent. + Output.vBiTangent = cross( Norm, Tan ); + + // bilerp the texture coordinates + float2 tex0 = input.vUV[0]; + float2 tex1 = input.vUV[1]; + float2 tex2 = input.vUV[2]; + float2 tex3 = input.vUV[3]; + + float2 bottom = lerp( tex0, tex1, UV.x ); + float2 top = lerp( tex3, tex2, UV.x ); + float2 TexUV = lerp( bottom, top, UV.y ); + Output.vUV = TexUV; + + if( g_fDisplacementHeight > 0 ) + { + // On this sample displacement can go into or out of the mesh. This is why we bias the heigh amount. + float height = g_fDisplacementHeight * ( g_txHeight.SampleLevel( g_samPoint, TexUV, 0 ).a * 2 - 1 ); + float3 WorldPosMiddle = Norm * height; + WorldPos += WorldPosMiddle; + } + + Output.vPosition = mul( float4(WorldPos,1), g_mViewProjection ); + Output.vWorldPos = WorldPos; + + return Output; +} + +//-------------------------------------------------------------------------------------- +// Smooth shading pixel shader section +//-------------------------------------------------------------------------------------- + +float3 safe_normalize( float3 vInput ) +{ + float len2 = dot( vInput, vInput ); + if( len2 > 0 ) + { + return vInput * rsqrt( len2 ); + } + return vInput; +} + +static const float g_fSpecularExponent = 32.0f; +static const float g_fSpecularIntensity = 0.6f; +static const float g_fNormalMapIntensity = 1.5f; + +float2 ComputeDirectionalLight( float3 vWorldPos, float3 vWorldNormal, float3 vDirLightDir ) +{ + // Result.x is diffuse illumination, Result.y is specular illumination + float2 Result = float2( 0, 0 ); + Result.x = pow( saturate( dot( vWorldNormal, -vDirLightDir ) ), 2 ); + + float3 vPointToCamera = normalize( g_vCameraPosWorld - vWorldPos ); + float3 vHalfAngle = normalize( vPointToCamera - vDirLightDir ); + Result.y = pow( saturate( dot( vHalfAngle, vWorldNormal ) ), g_fSpecularExponent ); + + return Result; +} + +float3 ColorGamma( float3 Input ) +{ + return pow( Input, 2.2f ); +} + +float4 SmoothPS( PS_INPUT Input ) : SV_TARGET +{ + float4 vNormalMapSampleRaw = g_txHeight.Sample( g_samLinear, Input.vUV ); + float3 vNormalMapSampleBiased = ( vNormalMapSampleRaw.xyz * 2 ) - 1; + vNormalMapSampleBiased.xy *= g_fNormalMapIntensity; + float3 vNormalMapSample = normalize( vNormalMapSampleBiased ); + + float3 vNormal = safe_normalize( Input.vNormal ) * vNormalMapSample.z; + vNormal += safe_normalize( Input.vTangent ) * vNormalMapSample.x; + vNormal += safe_normalize( Input.vBiTangent ) * vNormalMapSample.y; + + //float3 vColor = float3( 1, 1, 1 ); + float3 vColor = g_txDiffuse.Sample( g_samLinear, Input.vUV ).rgb; + float vSpecular = g_txSpecular.Sample( g_samLinear, Input.vUV ).r * g_fSpecularIntensity; + + const float3 DirLightDirections[4] = + { + // key light + normalize( float3( -63.345150, -58.043934, 27.785097 ) ), + // fill light + normalize( float3( 23.652107, -17.391443, 54.972504 ) ), + // back light 1 + normalize( float3( 20.470509, -22.939510, -33.929531 ) ), + // back light 2 + normalize( float3( -31.003685, 24.242104, -41.352859 ) ), + }; + + const float3 DirLightColors[4] = + { + // key light + ColorGamma( float3( 1.0f, 0.964f, 0.706f ) * 1.0f ), + // fill light + ColorGamma( float3( 0.446f, 0.641f, 1.0f ) * 1.0f ), + // back light 1 + ColorGamma( float3( 1.0f, 0.862f, 0.419f ) * 1.0f ), + // back light 2 + ColorGamma( float3( 0.405f, 0.630f, 1.0f ) * 1.0f ), + }; + + float3 fLightColor = 0; + for( int i = 0; i < 4; ++i ) + { + float2 LightDiffuseSpecular = ComputeDirectionalLight( Input.vWorldPos, vNormal, DirLightDirections[i] ); + fLightColor += DirLightColors[i] * vColor * LightDiffuseSpecular.x; + fLightColor += DirLightColors[i] * LightDiffuseSpecular.y * vSpecular; + } + + return float4( fLightColor, 1 ); +} + +//-------------------------------------------------------------------------------------- +// Solid color shading pixel shader (used for wireframe overlay) +//-------------------------------------------------------------------------------------- +float4 SolidColorPS( PS_INPUT Input ) : SV_TARGET +{ + return float4( g_vSolidColor, 1 ); +} diff --git a/tests/hlsl/dxsdk/VarianceShadows11/2DQuadShaders.hlsl b/tests/hlsl/dxsdk/VarianceShadows11/2DQuadShaders.hlsl new file mode 100644 index 000000000..c4401f010 --- /dev/null +++ b/tests/hlsl/dxsdk/VarianceShadows11/2DQuadShaders.hlsl @@ -0,0 +1,211 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VSMain -profile ps_4_0 -entry PSBlurX -entry PSBlurY +//-------------------------------------------------------------------------------------- +// File: Skinning10.fx +// +// The effect file for the Skinning10 sample. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +#ifndef SEPERABLE_BLUR_KERNEL_SIZE +#define SEPERABLE_BLUR_KERNEL_SIZE 3 +#endif + +static const int BLUR_KERNEL_BEGIN = SEPERABLE_BLUR_KERNEL_SIZE / -2; +static const int BLUR_KERNEL_END = SEPERABLE_BLUR_KERNEL_SIZE / 2 + 1; +static const float FLOAT_BLUR_KERNEL_SIZE = (float)SEPERABLE_BLUR_KERNEL_SIZE; + +cbuffer cbblurVS : register( b2) +{ + int2 g_iWidthHeight : packoffset( c0 ); + int g_iKernelStart : packoffset( c0.z ); + int g_iKernelEnd : packoffset( c0.w ); +}; + +//-------------------------------------------------------------------------------------- +// defines +//-------------------------------------------------------------------------------------- + +Texture2DArray g_txShadow : register( t5 ); +SamplerState g_samShadow : register( s5 ); + +//-------------------------------------------------------------------------------------- +// Input/Output structures +//-------------------------------------------------------------------------------------- + +struct PSIn +{ + float4 Pos : SV_Position; //Position + float2 Tex : TEXCOORD; //Texture coordinate + float2 ITex : TEXCOORD2; +}; + +struct VSIn +{ + uint Pos : SV_VertexID ; +}; + + +PSIn VSMain(VSIn inn) +{ + PSIn output; + + output.Pos.y = -1.0f + (inn.Pos%2) * 2.0f ; + output.Pos.x = -1.0f + (inn.Pos/2) * 2.0f; + output.Pos.z = .5; + output.Pos.w = 1; + output.Tex.x = inn.Pos/2; + output.Tex.y = 1.0f - inn.Pos%2; + output.ITex.x = (float)(g_iWidthHeight.x * output.Tex.x); + output.ITex.y = (float)(g_iWidthHeight.y * output.Tex.y); + return output; +} + +//float PSDepth + +//------------------------------------------------------------------------------ +// Logarithmic filtering +//------------------------------------------------------------------------------ + +float log_conv ( float x0, float X, float y0, float Y ) +{ + return (X + log(x0 + (y0 * exp(Y - X)))); +} + + +//-------------------------------------------------------------------------------------- +// Pixel shader that performs bump mapping on the final vertex +//-------------------------------------------------------------------------------------- +float2 PSBlurX(PSIn input) : SV_Target +{ +/* + float2 centerDistance; + if ( input.Tex.x < .5 ) centerDistance.x = (1.0 - input.Tex.x); + else centerDistance.x = input.Tex.x; + if ( input.Tex.y < .5 ) centerDistance.y = (1.0 - input.Tex.y); + else centerDistance.y = input.Tex.y; + if (centerDistance.x < centerDistance.y) centerDistance.x = centerDistance.y; + centerDistance.x -= .2; + centerDistance.x *= (1.0f / .8); + + float store_samples[8]; + int ind = 0; + for (int x = g_iKernelStart; x < g_iKernelEnd; ++x) { + store_samples[ind] = g_txShadow.Load( int3(input.ITex.x+(float)x * centerDistance.x , input.ITex.y, 0) ).r; + ind++; + } + const float c = (1.f/5.f); + + float accum; + accum = log_conv( c, store_samples[0], c, store_samples[1] ); + + ind = 0; + for (x = g_iKernelStart - 2; x < g_iKernelEnd; ++x) { + ind++; + accum += log_conv( 1.0f, accum, c, store_samples[ind] ); + } + float2 rt; + rt.x = accum; + return rt; + */ + /* + float2 dep = 0; + float2 centerDistance; + if ( input.Tex.x < .5 ) centerDistance.x = (1.0 - input.Tex.x); + else centerDistance.x = input.Tex.x; + if ( input.Tex.y < .5 ) centerDistance.y = (1.0 - input.Tex.y); + else centerDistance.y = input.Tex.y; + if (centerDistance.x < centerDistance.y) centerDistance.x = centerDistance.y; + centerDistance.x -= .2; + centerDistance.x *= ( 1.0f / 0.8f ); + + for (int x = g_iKernelStart; x < g_iKernelEnd; ++x) { + dep += g_txShadow.Load( int3(input.ITex.x+(float)x * centerDistance.x , input.ITex.y, 0) ).rg; + } + dep /= (g_iKernelEnd - g_iKernelStart); + return dep; + */ + + float2 dep=0; + [unroll]for ( int x = BLUR_KERNEL_BEGIN; x < BLUR_KERNEL_END; ++x ) { + dep += g_txShadow.Sample( g_samShadow, float3( input.Tex.x, input.Tex.y, 0 ), int2( x,0 ) ).rg; + } + dep /= FLOAT_BLUR_KERNEL_SIZE; + return dep; + +// return g_txShadow.Sample(g_samShadow, float3(input.Tex.x, input.Tex.y, 0) ).rg; + +} + +//-------------------------------------------------------------------------------------- +// Pixel shader that performs bump mapping on the final vertex +//-------------------------------------------------------------------------------------- +float2 PSBlurY(PSIn input) : SV_Target +{ +/* + float2 centerDistance; + if ( input.Tex.x < .5 ) centerDistance.x = (1.0 - input.Tex.x); + else centerDistance.x = input.Tex.x; + if ( input.Tex.y < .5 ) centerDistance.y = (1.0 - input.Tex.y); + else centerDistance.y = input.Tex.y; + if (centerDistance.x < centerDistance.y) centerDistance.x = centerDistance.y; + centerDistance.x -= .2; + centerDistance.x *= (1.0f / .8); + + float store_samples[8]; + int ind = 0; + for (int y = g_iKernelStart; y < g_iKernelEnd; ++y) { + store_samples[ind] = g_txShadow.Load( int3(input.ITex.x, input.ITex.y+(float)y * centerDistance.x, 0) ).r; + } + const float c = (1.f/5.f); + + float accum; + accum = log_conv( c, store_samples[0], c, store_samples[1] ); + + ind = 0; + for (y = g_iKernelStart; y < g_iKernelEnd; ++y) { + ind++; + accum += log_conv( 1.0f, accum, c, store_samples[ind] ); + } + float2 rt; + rt.x = accum; + return rt; + */ + + + /* + float2 dep = 0; + + float2 centerDistance; + if ( input.Tex.x < .5 ) centerDistance.x = (1.0 - input.Tex.x); + else centerDistance.x = input.Tex.x; + if ( input.Tex.y < .5 ) centerDistance.y = (1.0 - input.Tex.y); + else centerDistance.y = input.Tex.y; + if (centerDistance.x < centerDistance.y) centerDistance.x = centerDistance.y; + centerDistance.x -= 0; + centerDistance.x *= (1.0f / 1.0f); + + if (centerDistance.x < centerDistance.y) centerDistance.x = centerDistance.y; + for (int y = g_iKernelStart; y < g_iKernelEnd; ++y) { + dep += g_txShadow.Load( int3(input.ITex.x, input.ITex.y+(float)y * centerDistance.x, 0) ).rg; + } + + + dep /= (g_iKernelEnd - g_iKernelStart); + return dep; + + */ + + + float2 dep=0; + [unroll]for ( int y = BLUR_KERNEL_BEGIN; y < BLUR_KERNEL_END; ++y ) { + dep += g_txShadow.Sample( g_samShadow, float3( input.Tex.x, input.Tex.y, 0 ), int2( 0,y ) ).rg; + } + dep /= FLOAT_BLUR_KERNEL_SIZE; + return dep; + + //return g_txShadow.Sample(g_samShadow, float3(input.Tex.x, input.Tex.y, 0) ).rg; +} + + + diff --git a/tests/hlsl/dxsdk/VarianceShadows11/RenderVarianceScene.hlsl b/tests/hlsl/dxsdk/VarianceShadows11/RenderVarianceScene.hlsl new file mode 100644 index 000000000..0b2e43b5c --- /dev/null +++ b/tests/hlsl/dxsdk/VarianceShadows11/RenderVarianceScene.hlsl @@ -0,0 +1,412 @@ +//TEST_IGNORE_FILE: Currently failing due to Spire compiler issues. +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VSMain -profile ps_4_0 -entry PSBlurX -entry PSBlurY +//-------------------------------------------------------------------------------------- +// File: RenderCascadeScene.hlsl +// +// This is the main shader file. This shader is compiled with several different flags +// to provide different customizations based on user controls. +// +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------- +// Globals +//-------------------------------------------------------------------------------------- + +// This flag enables the shadow to blend between cascades. This is most useful when the +// the shadow maps are small and artifact can be seen between the various cascade layers. +#ifndef BLEND_BETWEEN_CASCADE_LAYERS_FLAG +#define BLEND_BETWEEN_CASCADE_LAYERS_FLAG 0 +#endif + +// There are two methods for selecting the proper cascade a fragment lies in. Interval selection +// compares the depth of the fragment against the frustum's depth partition. +// Map based selection compares the texture coordinates against the acutal cascade maps. +// Map based selection gives better coverage. +// Interval based selection is easier to extend and understand. +#ifndef SELECT_CASCADE_BY_INTERVAL_FLAG +#define SELECT_CASCADE_BY_INTERVAL_FLAG 0 +#endif + +// The number of cascades +#ifndef CASCADE_COUNT_FLAG +#define CASCADE_COUNT_FLAG 3 +#endif + + +// Most titles will find that 3-4 cascades with +// BLEND_BETWEEN_CASCADE_LAYERS_FLAG, is good for lower end PCs. + +cbuffer cbAllShadowData : register( b0 ) +{ + matrix m_mWorldViewProjection; + matrix m_mWorld; + matrix m_mWorldView; + matrix m_mShadow; + float4 m_vCascadeOffset[8]; + float4 m_vCascadeScale[8]; + int m_nCascadeLevels; // Number of Cascades + int m_iVisualizeCascades; // 1 is to visualize the cascades in different colors. 0 is to just draw the scene + + // For Map based selection scheme, this keeps the pixels inside of the the valid range. + // When there is no boarder, these values are 0 and 1 respectivley. + float m_fMinBorderPadding; + float m_fMaxBorderPadding; + + float m_fCascadeBlendArea; // Amount to overlap when blending between cascades. + float m_fTexelSize; // Padding variables exist because CBs must be a multiple of 16 bytes. + float m_fNativeTexelSizeInX; + float4 m_fCascadeFrustumsEyeSpaceDepthsData[2]; // The values along Z that seperate the cascades. + // This code creates an array based pointer that points towards the vectorized input data. + // This is the only way to index arbitrary arrays of data. + // If the array is used at run time, the compiler will generate code that uses logic to index the correct component. + + static float m_fCascadeFrustumsEyeSpaceDepths[8] = (float[8])m_fCascadeFrustumsEyeSpaceDepthsData; + + float3 m_vLightDir; + float m_fPaddingCB4; + +}; + + + +//-------------------------------------------------------------------------------------- +// Textures and Samplers +//-------------------------------------------------------------------------------------- +Texture2D g_txDiffuse : register( t0 ); +Texture2DArray g_txShadow : register( t5 ); + +SamplerState g_samLinear : register( s0 ); +SamplerState g_samShadow : register( s5 ); + +//-------------------------------------------------------------------------------------- +// Input / Output structures +//-------------------------------------------------------------------------------------- +struct VS_INPUT +{ + float4 vPosition : POSITION; + float3 vNormal : NORMAL; + float2 vTexcoord : TEXCOORD0; +}; + +struct VS_OUTPUT +{ + float3 vNormal : NORMAL; + float2 vTexcoord : COLOR0; + float4 vTexShadow : TEXCOORD1; + float4 vPosition : SV_POSITION; + float4 vInterpPos : TEXCOORD2; + float vDepth : TEXCOORD3; +}; + +//-------------------------------------------------------------------------------------- +// Vertex Shader +//-------------------------------------------------------------------------------------- +VS_OUTPUT VSMain( VS_INPUT Input ) +{ + VS_OUTPUT Output; + + Output.vPosition = mul( Input.vPosition, m_mWorldViewProjection ); + Output.vNormal = mul( Input.vNormal, (float3x3)m_mWorld ); + Output.vTexcoord = Input.vTexcoord; + Output.vInterpPos = Input.vPosition; + Output.vDepth = mul( Input.vPosition, m_mWorldView ).z ; + + // Transform the shadow texture coordinates for all the cascades. + Output.vTexShadow = mul( Input.vPosition, m_mShadow ); + + return Output; +} + + + +static const float4 vCascadeColorsMultiplier[8] = +{ + float4 ( 1.5f, 0.0f, 0.0f, 1.0f ), + float4 ( 0.0f, 1.5f, 0.0f, 1.0f ), + float4 ( 0.0f, 0.0f, 5.5f, 1.0f ), + float4 ( 1.5f, 0.0f, 5.5f, 1.0f ), + float4 ( 1.5f, 1.5f, 0.0f, 1.0f ), + float4 ( 1.0f, 1.0f, 1.0f, 1.0f ), + float4 ( 0.0f, 1.0f, 5.5f, 1.0f ), + float4 ( 0.5f, 3.5f, 0.75f, 1.0f ) +}; + + +void ComputeCoordinatesTransform( in int iCascadeIndex, + in float4 InterpolatedPosition, + in out float4 vShadowTexCoord, + in out float4 vShadowTexCoordViewSpace ) +{ + // Now that we know the correct map, we can transform the world space position of the current fragment + if( SELECT_CASCADE_BY_INTERVAL_FLAG ) + { + vShadowTexCoord = vShadowTexCoordViewSpace * m_vCascadeScale[iCascadeIndex]; + vShadowTexCoord += m_vCascadeOffset[iCascadeIndex]; + } + vShadowTexCoord.w = vShadowTexCoord.z; // We put the z value in w so that we can index the texture array with Z. + vShadowTexCoord.z = iCascadeIndex; + +} + +//-------------------------------------------------------------------------------------- +// Use PCF to sample the depth map and return a percent lit value. +//-------------------------------------------------------------------------------------- +void CalculateVarianceShadow ( in float4 vShadowTexCoord, in float4 vShadowMapTextureCoordViewSpace, int iCascade, out float fPercentLit ) +{ + fPercentLit = 0.0f; + // This loop could be unrolled, and texture immediate offsets could be used if the kernel size were fixed. + // This would be a performance improvment. + + float2 mapDepth = 0; + + + // In orderto pull the derivative out of divergent flow control we calculate the + // derivative off of the view space coordinates an then scale the deriviative. + + float3 vShadowTexCoordDDX = + ddx(vShadowMapTextureCoordViewSpace ); + vShadowTexCoordDDX *= m_vCascadeScale[iCascade].xyz; + float3 vShadowTexCoordDDY = + ddy(vShadowMapTextureCoordViewSpace ); + vShadowTexCoordDDY *= m_vCascadeScale[iCascade].xyz; + + mapDepth += g_txShadow.SampleGrad( g_samShadow, vShadowTexCoord.xyz, + vShadowTexCoordDDX, + vShadowTexCoordDDY); + // The sample instruction uses gradients for some filters. + + float fAvgZ = mapDepth.x; // Filtered z + float fAvgZ2 = mapDepth.y; // Filtered z-squared + + if ( vShadowTexCoord.w <= fAvgZ ) // We put the z value in w so that we can index the texture array with Z. + { + fPercentLit = 1; + } + else + { + float variance = ( fAvgZ2 ) - ( fAvgZ * fAvgZ ); + variance = min( 1.0f, max( 0.0f, variance + 0.00001f ) ); + + float mean = fAvgZ; + float d = vShadowTexCoord.w - mean; // We put the z value in w so that we can index the texture array with Z. + float p_max = variance / ( variance + d*d ); + + // To combat light-bleeding, experiment with raising p_max to some power + // (Try values from 0.1 to 100.0, if you like.) + fPercentLit = pow( p_max, 4 ); + + } + +} + +//-------------------------------------------------------------------------------------- +// Calculate amount to blend between two cascades and the band where blending will occure. +//-------------------------------------------------------------------------------------- +void CalculateBlendAmountForInterval ( in int iNextCascadeIndex, + in out float fPixelDepth, + in out float fCurrentPixelsBlendBandLocation, + out float fBlendBetweenCascadesAmount + ) +{ + + // We need to calculate the band of the current shadow map where it will fade into the next cascade. + // We can then early out of the expensive PCF for loop. + // + float fBlendInterval = m_fCascadeFrustumsEyeSpaceDepths[ iNextCascadeIndex - 1 ]; + if( iNextCascadeIndex > 1 ) + { + fPixelDepth -= m_fCascadeFrustumsEyeSpaceDepths[ iNextCascadeIndex-2 ]; + fBlendInterval -= m_fCascadeFrustumsEyeSpaceDepths[ iNextCascadeIndex-2 ]; + } + // The current pixel's blend band location will be used to determine when we need to blend and by how much. + fCurrentPixelsBlendBandLocation = fPixelDepth / fBlendInterval; + fCurrentPixelsBlendBandLocation = 1.0f - fCurrentPixelsBlendBandLocation; + // The fBlendBetweenCascadesAmount is our location in the blend band. + fBlendBetweenCascadesAmount = fCurrentPixelsBlendBandLocation / m_fCascadeBlendArea; +} + + +//-------------------------------------------------------------------------------------- +// Calculate amount to blend between two cascades and the band where blending will occure. +//-------------------------------------------------------------------------------------- +void CalculateBlendAmountForMap ( in float4 vShadowMapTextureCoord, + in out float fCurrentPixelsBlendBandLocation, + out float fBlendBetweenCascadesAmount ) +{ + // Calcaulte the blend band for the map based selection. + float2 distanceToOne = float2 ( 1.0f - vShadowMapTextureCoord.x, 1.0f - vShadowMapTextureCoord.y ); + fCurrentPixelsBlendBandLocation = min( vShadowMapTextureCoord.x, vShadowMapTextureCoord.y ); + float fCurrentPixelsBlendBandLocation2 = min( distanceToOne.x, distanceToOne.y ); + fCurrentPixelsBlendBandLocation = + min( fCurrentPixelsBlendBandLocation, fCurrentPixelsBlendBandLocation2 ); + fBlendBetweenCascadesAmount = fCurrentPixelsBlendBandLocation / m_fCascadeBlendArea; +} + +//-------------------------------------------------------------------------------------- +// Calculate the shadow based on several options and rende the scene. +//-------------------------------------------------------------------------------------- + +float4 PSMain( VS_OUTPUT Input ) : SV_TARGET +{ + float4 vDiffuse = g_txDiffuse.Sample( g_samLinear, Input.vTexcoord ); + + + float4 vShadowMapTextureCoordViewSpace = 0.0f; + float4 vShadowMapTextureCoord = 0.0f; + float4 vShadowMapTextureCoord_blend = 0.0f; + + float4 vVisualizeCascadeColor = float4(0.0f,0.0f,0.0f,1.0f); + + float fPercentLit = 0.0f; + float fPercentLit_blend = 0.0f; + + int iCascadeFound = 0; + int iCurrentCascadeIndex=1; + int iNextCascadeIndex = 0; + + float fCurrentPixelDepth; + + // The interval based selection technique compares the pixel's depth against the frustum's cascade divisions. + fCurrentPixelDepth = Input.vDepth; + + // This for loop is not necessary when the frustum is uniformaly divided and interval based selection is used. + // In this case fCurrentPixelDepth could be used as an array lookup into the correct frustum. + vShadowMapTextureCoordViewSpace = Input.vTexShadow; + + + if( SELECT_CASCADE_BY_INTERVAL_FLAG ) + { + iCurrentCascadeIndex = 0; + if (CASCADE_COUNT_FLAG > 1 ) + { + float4 vCurrentPixelDepth = Input.vDepth; + float4 fComparison = ( vCurrentPixelDepth > m_fCascadeFrustumsEyeSpaceDepthsData[0]); + float4 fComparison2 = ( vCurrentPixelDepth > m_fCascadeFrustumsEyeSpaceDepthsData[1]); + float fIndex = dot( + float4( CASCADE_COUNT_FLAG > 0, + CASCADE_COUNT_FLAG > 1, + CASCADE_COUNT_FLAG > 2, + CASCADE_COUNT_FLAG > 3) + , fComparison ) + + dot( + float4( + CASCADE_COUNT_FLAG > 4, + CASCADE_COUNT_FLAG > 5, + CASCADE_COUNT_FLAG > 6, + CASCADE_COUNT_FLAG > 7) + , fComparison2 ) ; + + fIndex = min( fIndex, CASCADE_COUNT_FLAG - 1 ); + iCurrentCascadeIndex = (int)fIndex; + } + } + + if ( !SELECT_CASCADE_BY_INTERVAL_FLAG ) + { + iCurrentCascadeIndex = 0; + if ( CASCADE_COUNT_FLAG == 1 ) + { + vShadowMapTextureCoord = vShadowMapTextureCoordViewSpace * m_vCascadeScale[0]; + vShadowMapTextureCoord += m_vCascadeOffset[0]; + } + if ( CASCADE_COUNT_FLAG > 1 ) { + for( int iCascadeIndex = 0; iCascadeIndex < CASCADE_COUNT_FLAG && iCascadeFound == 0; ++iCascadeIndex ) + { + vShadowMapTextureCoord = vShadowMapTextureCoordViewSpace * m_vCascadeScale[iCascadeIndex]; + vShadowMapTextureCoord += m_vCascadeOffset[iCascadeIndex]; + + if ( min( vShadowMapTextureCoord.x, vShadowMapTextureCoord.y ) > m_fMinBorderPadding + && max( vShadowMapTextureCoord.x, vShadowMapTextureCoord.y ) < m_fMaxBorderPadding ) + { + iCurrentCascadeIndex = iCascadeIndex; + iCascadeFound = 1; + } + } + } + } + // Found the correct map. + vVisualizeCascadeColor = vCascadeColorsMultiplier[iCurrentCascadeIndex]; + + ComputeCoordinatesTransform( iCurrentCascadeIndex, Input.vInterpPos, vShadowMapTextureCoord, vShadowMapTextureCoordViewSpace ); + + if( BLEND_BETWEEN_CASCADE_LAYERS_FLAG && CASCADE_COUNT_FLAG > 1 ) + { + // Repeat text coord calculations for the next cascade. + // The next cascade index is used for blurring between maps. + iNextCascadeIndex = min ( CASCADE_COUNT_FLAG - 1, iCurrentCascadeIndex + 1 ); + if( !SELECT_CASCADE_BY_INTERVAL_FLAG ) + { + vShadowMapTextureCoord_blend = vShadowMapTextureCoordViewSpace * m_vCascadeScale[iNextCascadeIndex]; + vShadowMapTextureCoord_blend += m_vCascadeOffset[iNextCascadeIndex]; + } + ComputeCoordinatesTransform( iNextCascadeIndex, Input.vInterpPos, vShadowMapTextureCoord_blend, vShadowMapTextureCoordViewSpace ); + } + float fBlendBetweenCascadesAmount = 1.0f; + float fCurrentPixelsBlendBandLocation = 1.0f; + + if( SELECT_CASCADE_BY_INTERVAL_FLAG ) + { + if( CASCADE_COUNT_FLAG > 1 && BLEND_BETWEEN_CASCADE_LAYERS_FLAG ) + { + CalculateBlendAmountForInterval ( iNextCascadeIndex, fCurrentPixelDepth, + fCurrentPixelsBlendBandLocation, fBlendBetweenCascadesAmount ); + + } + } + else + { + if( CASCADE_COUNT_FLAG > 1 && BLEND_BETWEEN_CASCADE_LAYERS_FLAG ) + { + CalculateBlendAmountForMap ( vShadowMapTextureCoord, + fCurrentPixelsBlendBandLocation, fBlendBetweenCascadesAmount ); + } + } + + // Because the Z coordinate specifies the texture array, + // the derivative will be 0 when there is no divergence + //float fDivergence = abs( ddy( vShadowMapTextureCoord.z ) ) + abs( ddx( vShadowMapTextureCoord.z ) ); + CalculateVarianceShadow ( vShadowMapTextureCoord, vShadowMapTextureCoordViewSpace, + iCurrentCascadeIndex, fPercentLit); + + // We repeat the calcuation for the next cascade layer, when blending between maps. + if( BLEND_BETWEEN_CASCADE_LAYERS_FLAG && CASCADE_COUNT_FLAG > 1 ) + { + if( fCurrentPixelsBlendBandLocation < m_fCascadeBlendArea ) + { // the current pixel is within the blend band. + + // Because the Z coordinate species the texture array, + // the derivative will be 0 when there is no divergence + float fDivergence = abs( ddy( vShadowMapTextureCoord_blend.z ) ) + + abs( ddx( vShadowMapTextureCoord_blend.z) ); + CalculateVarianceShadow ( vShadowMapTextureCoord_blend, vShadowMapTextureCoordViewSpace, + iNextCascadeIndex, fPercentLit_blend ); + + // Blend the two calculated shadows by the blend amount. + fPercentLit = lerp( fPercentLit_blend, fPercentLit, fBlendBetweenCascadesAmount ); + + } + } + + if( !m_iVisualizeCascades ) vVisualizeCascadeColor = float4( 1.0f, 1.0f, 1.0f, 1.0f ); + + float3 vLightDir1 = float3( -1.0f, 1.0f, -1.0f ); + float3 vLightDir2 = float3( 1.0f, 1.0f, -1.0f ); + float3 vLightDir3 = float3( 0.0f, -1.0f, 0.0f ); + float3 vLightDir4 = float3( 1.0f, 1.0f, 1.0f ); + // Some ambient-like lighting. + float fLighting = + saturate( dot( vLightDir1 , Input.vNormal ) )*0.05f + + saturate( dot( vLightDir2 , Input.vNormal ) )*0.05f + + saturate( dot( vLightDir3 , Input.vNormal ) )*0.05f + + saturate( dot( vLightDir4 , Input.vNormal ) )*0.05f ; + + float4 vShadowLighting = fLighting * 0.5f; + fLighting += saturate( dot( m_vLightDir , Input.vNormal ) ); + fLighting = lerp( vShadowLighting, fLighting, fPercentLit ); + + return fLighting * vVisualizeCascadeColor * vDiffuse; + +} + diff --git a/tests/hlsl/dxsdk/VarianceShadows11/RenderVarianceShadow.hlsl b/tests/hlsl/dxsdk/VarianceShadows11/RenderVarianceShadow.hlsl new file mode 100644 index 000000000..9837bf299 --- /dev/null +++ b/tests/hlsl/dxsdk/VarianceShadows11/RenderVarianceShadow.hlsl @@ -0,0 +1,45 @@ +//TEST:COMPARE_HLSL: -target dxbc-assembly -profile vs_4_0 -entry VSMain -profile ps_4_0 -entry PSMain + + +//-------------------------------------------------------------------------------------- +// Globals +//-------------------------------------------------------------------------------------- +cbuffer cbPerObject : register( b0 ) +{ + matrix g_mWorldViewProjection : packoffset( c0 ); +}; + +//-------------------------------------------------------------------------------------- +// Input / Output structures +//-------------------------------------------------------------------------------------- +struct VS_INPUT +{ + float4 vPosition : POSITION; +}; + +struct VS_OUTPUT +{ + float4 vPosition : SV_POSITION; +}; + +//-------------------------------------------------------------------------------------- +// Vertex Shader +//-------------------------------------------------------------------------------------- +VS_OUTPUT VSMain( VS_INPUT Input ) +{ + VS_OUTPUT Output; + + + Output.vPosition = mul( Input.vPosition, g_mWorldViewProjection ); + + return Output; +} + + +float2 PSMain (VS_OUTPUT Input) : SV_TARGET +{ + float2 rt; + rt.x = Input.vPosition.z; + rt.y = rt.x * rt.x; + return rt; +} \ No newline at end of file diff --git a/tests/hlsl/simple/compute-numthreads.hlsl b/tests/hlsl/simple/compute-numthreads.hlsl new file mode 100644 index 000000000..3843c401f --- /dev/null +++ b/tests/hlsl/simple/compute-numthreads.hlsl @@ -0,0 +1,11 @@ +//TEST:COMPARE_HLSL: -no-checking -target dxbc-assembly -profile cs_5_0 -entry main + +// Confirm that we properly pass along the `numthreads` attribute on an entry point. + +RWStructuredBuffer b; + +[numthreads(32,1,1)] +void main(uint3 tid : SV_DispatchThreadID) +{ + b[tid.x] = b[tid.x + 1] + 1.0f; +} \ No newline at end of file diff --git a/tests/preprocessor/define-function-like.spire b/tests/preprocessor/define-function-like.spire new file mode 100644 index 000000000..f1dd9caa4 --- /dev/null +++ b/tests/preprocessor/define-function-like.spire @@ -0,0 +1,19 @@ +//TEST:SIMPLE: +// support for function-like macros + +#define FOO(x) 1.0 + x + +float foo(float y) { return FOO(y) * 2.0; } + +// simple token pasting + +#define PASTE(a,b) a##b + +PASTE(flo,at) bar() { return 0.0; } + +// no space before parens? not a function-like macro + +#define M (x) - (x) + +// Error: undefined identifier `x` +float bar(float a) { return M(a); } diff --git a/tests/preprocessor/define-function-like.spire.expected b/tests/preprocessor/define-function-like.spire.expected new file mode 100644 index 000000000..e7b2a582a --- /dev/null +++ b/tests/preprocessor/define-function-like.spire.expected @@ -0,0 +1,7 @@ +result code = -1 +standard error = { +Tests/Preprocessor/define-function-like.spire(16): error 30015: undefined identifier 'x'. +Tests/Preprocessor/define-function-like.spire(16): error 30015: undefined identifier 'x'. +} +standard output = { +} diff --git a/tests/preprocessor/define-simple.spire b/tests/preprocessor/define-simple.spire new file mode 100644 index 000000000..26436b258 --- /dev/null +++ b/tests/preprocessor/define-simple.spire @@ -0,0 +1,14 @@ +//TEST:SIMPLE: +// #define support + +#define FOO 1.0f + +float foo() { return FOO + 2.0; } + +#define BAR 99 + +#if BAR > 10 +int bar() { return 0; } +#else +BadThing shouldntCompile; +#endif diff --git a/tests/preprocessor/if.spire b/tests/preprocessor/if.spire new file mode 100644 index 000000000..fe5948c33 --- /dev/null +++ b/tests/preprocessor/if.spire @@ -0,0 +1,15 @@ +//TEST:SIMPLE: +// #ifdef support + + +#if (1 - 1*2) < 0 +int foo() { return 0; } +#else +BadThing thatWontCompile; +#endif + +#if (1 >> 1) && ~999 +AnotherError onThisLine; +#else +int bar() { return foo(); } +#endif \ No newline at end of file diff --git a/tests/preprocessor/ifdef.spire b/tests/preprocessor/ifdef.spire new file mode 100644 index 000000000..a3ca82838 --- /dev/null +++ b/tests/preprocessor/ifdef.spire @@ -0,0 +1,16 @@ +//TEST:SIMPLE: +// #ifdef support + +#define A + +#ifdef A +int foo() { return 0; } +#else +BadThing thatWontCompile; +#endif + +#ifdef BadThing +AnotherError onThisLine; +#else +int bar() { return foo(); } +#endif \ No newline at end of file diff --git a/tests/preprocessor/include-a.spireh b/tests/preprocessor/include-a.spireh new file mode 100644 index 000000000..8fecc6a98 --- /dev/null +++ b/tests/preprocessor/include-a.spireh @@ -0,0 +1,3 @@ +// #include support + +int bar() { return foo(); } \ No newline at end of file diff --git a/tests/preprocessor/include.spire b/tests/preprocessor/include.spire new file mode 100644 index 000000000..8feca21cc --- /dev/null +++ b/tests/preprocessor/include.spire @@ -0,0 +1,8 @@ +//TEST:SIMPLE: +// #include support + +int foo() { return 0; } + +#include "include-a.spireh" + +int baz() { return bar(); } \ No newline at end of file diff --git a/tests/reflection/arrays.hlsl b/tests/reflection/arrays.hlsl new file mode 100644 index 000000000..8880aaebd --- /dev/null +++ b/tests/reflection/arrays.hlsl @@ -0,0 +1,27 @@ +//TEST:SIMPLE:-profile ps_4_0 -target reflection-json + +// Confirm that we can generate reflection info for arrays +// +// Note: just working with fixed-size arrays for now. +// Unbounded arrays may require more work. + +cbuffer MyConstantBuffer +{ + float x; + + float a[10]; + + float y; +} + +Texture2D tx; +Texture2D ta[16]; +Texture2D ty; +SamplerState sx; +SamplerState sa[4]; +SamplerState sy; + +float4 main() : SV_Target +{ + return 0.0; +} \ No newline at end of file diff --git a/tests/reflection/arrays.hlsl.expected b/tests/reflection/arrays.hlsl.expected new file mode 100644 index 000000000..052bd3927 --- /dev/null +++ b/tests/reflection/arrays.hlsl.expected @@ -0,0 +1,103 @@ +result code = 0 +standard error = { +} +standard output = { +{ + "parameters": [ + { + "name": "MyConstantBuffer", + "binding": {"kind": "constantBuffer", "index": 0}, + "type": { + "kind": "constantBuffer", + "elementType": { + "kind": "struct", + "fields": [ + { + "name": "x", + "type": { + "kind": "scalar", + "scalarType": "float32" + }, + "binding": {"kind": "uniform", "offset": 0, "size": 4} + }, + { + "name": "a", + "type": { + "kind": "array", + "elementCount": 10, + "elementType": { + "kind": "scalar", + "scalarType": "float32" + }, + "uniformStride": 16 + }, + "binding": {"kind": "uniform", "offset": 16, "size": 160} + }, + { + "name": "y", + "type": { + "kind": "scalar", + "scalarType": "float32" + }, + "binding": {"kind": "uniform", "offset": 176, "size": 4} + } + ] + } + } + }, + { + "name": "tx", + "binding": {"kind": "shaderResource", "index": 0}, + "type": { + "kind": "resource", + "baseShape": "texture2D" + } + }, + { + "name": "ta", + "binding": {"kind": "shaderResource", "index": 1, "count": 16}, + "type": { + "kind": "array", + "elementCount": 16, + "elementType": { + "kind": "resource", + "baseShape": "texture2D" + } + } + }, + { + "name": "ty", + "binding": {"kind": "shaderResource", "index": 17}, + "type": { + "kind": "resource", + "baseShape": "texture2D" + } + }, + { + "name": "sx", + "binding": {"kind": "samplerState", "index": 0}, + "type": { + "kind": "samplerState" + } + }, + { + "name": "sa", + "binding": {"kind": "samplerState", "index": 1, "count": 4}, + "type": { + "kind": "array", + "elementCount": 4, + "elementType": { + "kind": "samplerState" + } + } + }, + { + "name": "sy", + "binding": {"kind": "samplerState", "index": 5}, + "type": { + "kind": "samplerState" + } + } + ] +} +} diff --git a/tests/reflection/global-uniforms.hlsl b/tests/reflection/global-uniforms.hlsl new file mode 100644 index 000000000..7845af4b6 --- /dev/null +++ b/tests/reflection/global-uniforms.hlsl @@ -0,0 +1,21 @@ +//TEST:SIMPLE:-profile ps_4_0 -target reflection-json + +// Confirm that we handle uniforms at global scope + + +float4 u; + +Texture2D t; +SamplerState s; + +cbuffer CB +{ + float4 v; +} + +float4 w; + +float4 main() : SV_Target +{ + return u + v + w + t.Sample(s, u.xy); +} \ No newline at end of file diff --git a/tests/reflection/global-uniforms.hlsl.expected b/tests/reflection/global-uniforms.hlsl.expected new file mode 100644 index 000000000..b40b2d69c --- /dev/null +++ b/tests/reflection/global-uniforms.hlsl.expected @@ -0,0 +1,72 @@ +result code = 0 +standard error = { +} +standard output = { +{ + "parameters": [ + { + "name": "u", + "binding": {"kind": "uniform", "offset": 0, "size": 16}, + "type": { + "kind": "vector", + "elementCount": 4, + "elementType": { + "kind": "scalar", + "scalarType": "float32" + } + } + }, + { + "name": "t", + "binding": {"kind": "shaderResource", "index": 0}, + "type": { + "kind": "resource", + "baseShape": "texture2D" + } + }, + { + "name": "s", + "binding": {"kind": "samplerState", "index": 0}, + "type": { + "kind": "samplerState" + } + }, + { + "name": "CB", + "binding": {"kind": "constantBuffer", "index": 1}, + "type": { + "kind": "constantBuffer", + "elementType": { + "kind": "struct", + "fields": [ + { + "name": "v", + "type": { + "kind": "vector", + "elementCount": 4, + "elementType": { + "kind": "scalar", + "scalarType": "float32" + } + }, + "binding": {"kind": "uniform", "offset": 0, "size": 16} + } + ] + } + } + }, + { + "name": "w", + "binding": {"kind": "uniform", "offset": 16, "size": 16}, + "type": { + "kind": "vector", + "elementCount": 4, + "elementType": { + "kind": "scalar", + "scalarType": "float32" + } + } + } + ] +} +} diff --git a/tests/reflection/multi-file-extra.hlsl b/tests/reflection/multi-file-extra.hlsl new file mode 100644 index 000000000..569ec2ce9 --- /dev/null +++ b/tests/reflection/multi-file-extra.hlsl @@ -0,0 +1,63 @@ +//TEST_IGNORE_FILE: + +// Here we are going to test that we can correctly generating bindings when we +// are presented with a program spanning multiple input files (and multiple entry points) + +// This file provides the fragment shader, and is only meant to be tested in combination with `multi-file.hlsl` + +// Let's make sure we generate correct output in cases +// where there are non-trivial `packoffset`s needed + +#ifdef __SPIRE__ +#define R(X) /**/ +#else +#define R(X) X +#endif + +float4 use(float val) { return val; }; +float4 use(float2 val) { return float4(val,0.0,0.0); }; +float4 use(float3 val) { return float4(val,0.0); }; +float4 use(float4 val) { return val; }; +float4 use(Texture2D t, SamplerState s) { return t.Sample(s, 0.0); } + +// Start with some parameters that will appear in both shaders +Texture2D sharedT; +SamplerState sharedS; +cbuffer sharedC +{ + float3 sharedCA; + float sharedCB; + float3 sharedCC; + float2 sharedCD; +} + +// Then some parameters specific to this shader. +// These will be placed *after* the ones from the main file, +// and even after the parameters further down in this file +// that end up being shared between the two files. + +Texture2D fragmentT; +SamplerState fragmentS; +cbuffer fragmentC +{ + float3 fragmentCA; + float fragmentCB; + float3 fragmentCC; + float2 fragmentCD; +} + +// And end with some shared parameters again +Texture2D sharedTV; +Texture2D sharedTF; + + +float4 main() : SV_Target +{ + // Go ahead and use everything here, just to make sure things got placed correctly + return use(sharedT, sharedS) + + use(sharedCD) + + use(fragmentT, fragmentS) + + use(fragmentCD) + + use(sharedTF, sharedS) + ; +} \ No newline at end of file diff --git a/tests/reflection/multi-file.hlsl b/tests/reflection/multi-file.hlsl new file mode 100644 index 000000000..b263a6b71 --- /dev/null +++ b/tests/reflection/multi-file.hlsl @@ -0,0 +1,56 @@ +//TEST:SIMPLE:-profile ps_4_0 -target reflection-json Tests/bindings/multi-file-extra.hlsl + +// Here we are testing the case where multiple translation units are provided +// at once, so that we want combined reflection information for the resulting +// program. The other part of this program is in `multi-file-extra.hlsl`. + +float4 use(float val) { return val; }; +float4 use(float2 val) { return float4(val,0.0,0.0); }; +float4 use(float3 val) { return float4(val,0.0); }; +float4 use(float4 val) { return val; }; +float4 use(Texture2D t, SamplerState s) +{ + // This is the vertex shader, so we can't do implicit-gradient sampling + return t.SampleGrad(s, 0.0, 0.0, 0.0); +} + +// Start with some parameters that will appear in both shaders +Texture2D sharedT; +SamplerState sharedS; +cbuffer sharedC +{ + float3 sharedCA; + float sharedCB; + float3 sharedCC; + float2 sharedCD; +} + +// Then some parameters specific to this shader +// (these will get placed before the ones in the `extra` file, +// based on how they get named on the command-line) + +Texture2D vertexT; +SamplerState vertexS; +cbuffer vertexC +{ + float3 vertexCA; + float vertexCB; + float3 vertexCC; + float2 vertexCD; +} + +// And end with some shared parameters again +Texture2D sharedTV; +Texture2D sharedTF; + + +float4 main() : SV_Position +{ + // Go ahead and use everything here, just to make sure things got placed correctly + return use(sharedT, sharedS) + + use(sharedCD) + + use(vertexT, vertexS) + + use(vertexCD) + + use(sharedTV, vertexS) + ; +} \ No newline at end of file diff --git a/tests/reflection/multi-file.hlsl.expected b/tests/reflection/multi-file.hlsl.expected new file mode 100644 index 000000000..38d028ffe --- /dev/null +++ b/tests/reflection/multi-file.hlsl.expected @@ -0,0 +1,238 @@ +result code = 0 +standard error = { +} +standard output = { +{ + "parameters": [ + { + "name": "sharedT", + "binding": {"kind": "shaderResource", "index": 0}, + "type": { + "kind": "resource", + "baseShape": "texture2D" + } + }, + { + "name": "sharedS", + "binding": {"kind": "samplerState", "index": 0}, + "type": { + "kind": "samplerState" + } + }, + { + "name": "sharedC", + "binding": {"kind": "constantBuffer", "index": 0}, + "type": { + "kind": "constantBuffer", + "elementType": { + "kind": "struct", + "fields": [ + { + "name": "sharedCA", + "type": { + "kind": "vector", + "elementCount": 3, + "elementType": { + "kind": "scalar", + "scalarType": "float32" + } + }, + "binding": {"kind": "uniform", "offset": 0, "size": 12} + }, + { + "name": "sharedCB", + "type": { + "kind": "scalar", + "scalarType": "float32" + }, + "binding": {"kind": "uniform", "offset": 12, "size": 4} + }, + { + "name": "sharedCC", + "type": { + "kind": "vector", + "elementCount": 3, + "elementType": { + "kind": "scalar", + "scalarType": "float32" + } + }, + "binding": {"kind": "uniform", "offset": 16, "size": 12} + }, + { + "name": "sharedCD", + "type": { + "kind": "vector", + "elementCount": 2, + "elementType": { + "kind": "scalar", + "scalarType": "float32" + } + }, + "binding": {"kind": "uniform", "offset": 32, "size": 8} + } + ] + } + } + }, + { + "name": "vertexT", + "binding": {"kind": "shaderResource", "index": 1}, + "type": { + "kind": "resource", + "baseShape": "texture2D" + } + }, + { + "name": "vertexS", + "binding": {"kind": "samplerState", "index": 1}, + "type": { + "kind": "samplerState" + } + }, + { + "name": "vertexC", + "binding": {"kind": "constantBuffer", "index": 1}, + "type": { + "kind": "constantBuffer", + "elementType": { + "kind": "struct", + "fields": [ + { + "name": "vertexCA", + "type": { + "kind": "vector", + "elementCount": 3, + "elementType": { + "kind": "scalar", + "scalarType": "float32" + } + }, + "binding": {"kind": "uniform", "offset": 0, "size": 12} + }, + { + "name": "vertexCB", + "type": { + "kind": "scalar", + "scalarType": "float32" + }, + "binding": {"kind": "uniform", "offset": 12, "size": 4} + }, + { + "name": "vertexCC", + "type": { + "kind": "vector", + "elementCount": 3, + "elementType": { + "kind": "scalar", + "scalarType": "float32" + } + }, + "binding": {"kind": "uniform", "offset": 16, "size": 12} + }, + { + "name": "vertexCD", + "type": { + "kind": "vector", + "elementCount": 2, + "elementType": { + "kind": "scalar", + "scalarType": "float32" + } + }, + "binding": {"kind": "uniform", "offset": 32, "size": 8} + } + ] + } + } + }, + { + "name": "sharedTV", + "binding": {"kind": "shaderResource", "index": 2}, + "type": { + "kind": "resource", + "baseShape": "texture2D" + } + }, + { + "name": "sharedTF", + "binding": {"kind": "shaderResource", "index": 3}, + "type": { + "kind": "resource", + "baseShape": "texture2D" + } + }, + { + "name": "fragmentT", + "binding": {"kind": "shaderResource", "index": 4}, + "type": { + "kind": "resource", + "baseShape": "texture2D" + } + }, + { + "name": "fragmentS", + "binding": {"kind": "samplerState", "index": 2}, + "type": { + "kind": "samplerState" + } + }, + { + "name": "fragmentC", + "binding": {"kind": "constantBuffer", "index": 2}, + "type": { + "kind": "constantBuffer", + "elementType": { + "kind": "struct", + "fields": [ + { + "name": "fragmentCA", + "type": { + "kind": "vector", + "elementCount": 3, + "elementType": { + "kind": "scalar", + "scalarType": "float32" + } + }, + "binding": {"kind": "uniform", "offset": 0, "size": 12} + }, + { + "name": "fragmentCB", + "type": { + "kind": "scalar", + "scalarType": "float32" + }, + "binding": {"kind": "uniform", "offset": 12, "size": 4} + }, + { + "name": "fragmentCC", + "type": { + "kind": "vector", + "elementCount": 3, + "elementType": { + "kind": "scalar", + "scalarType": "float32" + } + }, + "binding": {"kind": "uniform", "offset": 16, "size": 12} + }, + { + "name": "fragmentCD", + "type": { + "kind": "vector", + "elementCount": 2, + "elementType": { + "kind": "scalar", + "scalarType": "float32" + } + }, + "binding": {"kind": "uniform", "offset": 32, "size": 8} + } + ] + } + } + } + ] +} +} diff --git a/tests/reflection/reflection0.hlsl b/tests/reflection/reflection0.hlsl new file mode 100644 index 000000000..1f138894f --- /dev/null +++ b/tests/reflection/reflection0.hlsl @@ -0,0 +1,19 @@ +//TEST:SIMPLE:-profile ps_4_0 -target reflection-json + +// Confirm that basic reflection info can be output + +float4 use(float4 val) { return val; }; +float4 use(Texture2D t, SamplerState s) { return t.Sample(s, 0.0); } + +Texture2D t; +SamplerState s; + +cbuffer C +{ + float c; +} + +float4 main() : SV_Target +{ + return use(t,s) + use(c); +} \ No newline at end of file diff --git a/tests/reflection/reflection0.hlsl.expected b/tests/reflection/reflection0.hlsl.expected new file mode 100644 index 000000000..3b74988b2 --- /dev/null +++ b/tests/reflection/reflection0.hlsl.expected @@ -0,0 +1,44 @@ +result code = 0 +standard error = { +} +standard output = { +{ + "parameters": [ + { + "name": "t", + "binding": {"kind": "shaderResource", "index": 0}, + "type": { + "kind": "resource", + "baseShape": "texture2D" + } + }, + { + "name": "s", + "binding": {"kind": "samplerState", "index": 0}, + "type": { + "kind": "samplerState" + } + }, + { + "name": "C", + "binding": {"kind": "constantBuffer", "index": 0}, + "type": { + "kind": "constantBuffer", + "elementType": { + "kind": "struct", + "fields": [ + { + "name": "c", + "type": { + "kind": "scalar", + "scalarType": "float32" + }, + "binding": {"kind": "uniform", "offset": 0, "size": 4} + } + ] + } + } + } + ] +} +} diff --git a/tests/reflection/resource-in-cbuffer.hlsl b/tests/reflection/resource-in-cbuffer.hlsl new file mode 100644 index 000000000..956387587 --- /dev/null +++ b/tests/reflection/resource-in-cbuffer.hlsl @@ -0,0 +1,21 @@ +//TEST:SIMPLE:-profile ps_4_0 -target reflection-json + +// Confirm that we can generate reflection +// information for resources nested inside +// a cbuffer: + +cbuffer MyConstantBuffer +{ + float3 v; + + Texture2D myTexture; + + float c; + + SamplerState mySampler; +} + +float4 main() : SV_Target +{ + return 0.0; +} \ No newline at end of file diff --git a/tests/reflection/resource-in-cbuffer.hlsl.expected b/tests/reflection/resource-in-cbuffer.hlsl.expected new file mode 100644 index 000000000..faae1c8b7 --- /dev/null +++ b/tests/reflection/resource-in-cbuffer.hlsl.expected @@ -0,0 +1,60 @@ +result code = 0 +standard error = { +} +standard output = { +{ + "parameters": [ + { + "name": "MyConstantBuffer", + "bindings": [ + {"kind": "constantBuffer", "index": 0}, + {"kind": "shaderResource", "index": 0}, + {"kind": "samplerState", "index": 0} + ], + "type": { + "kind": "constantBuffer", + "elementType": { + "kind": "struct", + "fields": [ + { + "name": "v", + "type": { + "kind": "vector", + "elementCount": 3, + "elementType": { + "kind": "scalar", + "scalarType": "float32" + } + }, + "binding": {"kind": "uniform", "offset": 0, "size": 12} + }, + { + "name": "myTexture", + "type": { + "kind": "resource", + "baseShape": "texture2D" + }, + "binding": {"kind": "shaderResource", "index": 0} + }, + { + "name": "c", + "type": { + "kind": "scalar", + "scalarType": "float32" + }, + "binding": {"kind": "uniform", "offset": 12, "size": 4} + }, + { + "name": "mySampler", + "type": { + "kind": "samplerState" + }, + "binding": {"kind": "samplerState", "index": 0} + } + ] + } + } + } + ] +} +} diff --git a/tests/render/cross-compile0.hlsl b/tests/render/cross-compile0.hlsl new file mode 100644 index 000000000..9a9dd1cdc --- /dev/null +++ b/tests/render/cross-compile0.hlsl @@ -0,0 +1,76 @@ +//TEST:COMPARE_HLSL_CROSS_COMPILE_RENDER: + +// Now we are going to test that we can cross-compile a Spire/HLSL +// input file over to GLSL and render with it. + +cbuffer Uniforms +{ + float4x4 modelViewProjection; +} + +struct AssembledVertex +{ + float3 position; + float3 color; +}; + +struct CoarseVertex +{ + float3 color; +}; + +struct Fragment +{ + float4 color; +}; + + +// Vertex Shader + +struct VertexStageInput +{ + AssembledVertex assembledVertex : A; +}; + +struct VertexStageOutput +{ + CoarseVertex coarseVertex : CoarseVertex; + float4 sv_position : SV_Position; +}; + +VertexStageOutput vertexMain(VertexStageInput input) +{ + VertexStageOutput output; + + float3 position = input.assembledVertex.position; + float3 color = input.assembledVertex.color; + + output.coarseVertex.color = color; + output.sv_position = mul(modelViewProjection, float4(position, 1.0)); + + return output; +} + +// Fragment Shader + +struct FragmentStageInput +{ + CoarseVertex coarseVertex : CoarseVertex; +}; + +struct FragmentStageOutput +{ + Fragment fragment : SV_Target; +}; + +FragmentStageOutput fragmentMain(FragmentStageInput input) +{ + FragmentStageOutput output; + + float3 color = input.coarseVertex.color; + + output.fragment.color = float4(color, 1.0); + + return output; +} + diff --git a/tests/render/render0.hlsl b/tests/render/render0.hlsl new file mode 100644 index 000000000..3ecd582f3 --- /dev/null +++ b/tests/render/render0.hlsl @@ -0,0 +1,74 @@ +//TEST:COMPARE_HLSL_RENDER: +// Starting with a basic test for the ability to render stuff... + +cbuffer Uniforms +{ + float4x4 modelViewProjection; +} + +struct AssembledVertex +{ + float3 position; + float3 color; +}; + +struct CoarseVertex +{ + float3 color; +}; + +struct Fragment +{ + float4 color; +}; + + +// Vertex Shader + +struct VertexStageInput +{ + AssembledVertex assembledVertex : A; +}; + +struct VertexStageOutput +{ + CoarseVertex coarseVertex : CoarseVertex; + float4 sv_position : SV_Position; +}; + +VertexStageOutput vertexMain(VertexStageInput input) +{ + VertexStageOutput output; + + float3 position = input.assembledVertex.position; + float3 color = input.assembledVertex.color; + + output.coarseVertex.color = color; + output.sv_position = mul(modelViewProjection, float4(position, 1.0)); + + return output; +} + +// Fragment Shader + +struct FragmentStageInput +{ + CoarseVertex coarseVertex : CoarseVertex; +}; + +struct FragmentStageOutput +{ + Fragment fragment : SV_Target; +}; + +FragmentStageOutput fragmentMain(FragmentStageInput input) +{ + FragmentStageOutput output; + + float3 color = input.coarseVertex.color; + + output.fragment.color = float4(color, 1.0); + + return output; +} + diff --git a/tests/rewriter/error0.hlsl b/tests/rewriter/error0.hlsl new file mode 100644 index 000000000..dc3e84fda --- /dev/null +++ b/tests/rewriter/error0.hlsl @@ -0,0 +1,19 @@ +//TEST:COMPARE_HLSL: -no-checking -target dxbc-assembly -profile ps_4_0 -entry main + +// We need to confirm that when there is an error in +// the input code, we allow the downstream compiler +// to detect and report the error, not us... + +// This file presents a simple case, where we forgot a semicolon. + +float4 main() : SV_Target +{ + float a = 1.0; + + // no semicolon at the end of this line! + float b = 2.0 + + float c = a + b; + + return float4(c); +} \ No newline at end of file diff --git a/tools/glslang/glslang.cpp b/tools/glslang/glslang.cpp new file mode 100644 index 000000000..cf563faff --- /dev/null +++ b/tools/glslang/glslang.cpp @@ -0,0 +1,175 @@ +// glslang.cpp +#include "glslang.h" + + +#include "StandAlone/ResourceLimits.h" +#include "StandAlone/Worklist.h" +#include "glslang/Include/ShHandle.h" +#include "glslang/Include/revision.h" +#include "glslang/Public/ShaderLang.h" +#include "SPIRV/GlslangToSpv.h" +#include "SPIRV/GLSL.std.450.h" +#include "SPIRV/doc.h" +#include "SPIRV/disassemble.h" + +#include "../../Slang.h" + +#if 0 +#include +#include +#include +#include +#include +#include +#include +#endif + +#ifdef _WIN32 +#include +#endif + +#include + +// This is a wrapper to allow us to run the `glslang` compiler +// in a controlled fashion. + +#define UNLIMITED 9999 + +static TBuiltInResource gResources = +{ + UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, + UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, + UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, + UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, + UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, + UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, + UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, + UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, + UNLIMITED, UNLIMITED, UNLIMITED, + + { true, true, true, true, true, true, true, true, true, } +}; + +static void dump( + std::string const& text, + glslang_OutputFunc outputFunc, + void* outputUserData, + FILE* fallbackStream) +{ + if( outputFunc ) + { + outputFunc(text.c_str(), outputUserData); + } + else + { + fprintf(fallbackStream, "%s", text.c_str()); + + // also output it for debug purposes + OutputDebugStringA(text.c_str()); + } +} + +static void dumpDiagnostics( + glslang_CompileRequest* request, + std::string const& log) +{ + dump(log, request->diagnosticFunc, request->diagnosticUserData, stderr); +} + +extern "C" +_declspec(dllexport) +int glslang_compile(glslang_CompileRequest* request) +{ + glslang::InitializeProcess(); + + EShLanguage glslangStage; + switch( request->slangStage ) + { +#define CASE(SP, GL) case SLANG_STAGE_##SP: glslangStage = EShLang##GL; break + CASE(VERTEX, Vertex); + CASE(FRAGMENT, Fragment); + CASE(GEOMETRY, Geometry); + CASE(HULL, TessControl); + CASE(DOMAIN, TessEvaluation); + CASE(COMPUTE, Compute); + +#undef CASE + + default: + return 1; + } + + // TODO: compute glslang stage to use + + glslang::TShader* shader = new glslang::TShader(glslangStage); + auto shaderPtr = std::unique_ptr(shader); + + glslang::TProgram* program = new glslang::TProgram(); + auto programPtr = std::unique_ptr(program); + + int sourceTextLength = (int) strlen(request->sourceText); + + shader->setPreamble("#extension GL_GOOGLE_cpp_style_line_directive : require\n"); + + shader->setStringsWithLengthsAndNames( + &request->sourceText, + &sourceTextLength, + &request->sourcePath, + 1); + + // Note: this seems required to get past a bug where + // glslang complains about a declaration of `out gl_PerVertex` + // that it (seemingly) *should* allow according to the GLSL-for-Vulkan + // extension. + shader->setAutoMapLocations(true); + + // Let's auto-map the bindings too, just because we can + shader->setAutoMapBindings(true); + + EShMessages messages = EShMessages(EShMsgSpvRules | EShMsgVulkanRules); + + if( !shader->parse(&gResources, 110, false, messages) ) + { + dumpDiagnostics(request, shader->getInfoLog()); + return 1; + } + + program->addShader(shader); + + if( !program->link(messages) ) + { + dumpDiagnostics(request, program->getInfoLog()); + return 1; + } + + if( !program->mapIO() ) + { + dumpDiagnostics(request, program->getInfoLog()); + return 1; + } + + for(int stage = 0; stage < EShLangCount; ++stage) + { + auto stageIntermediate = program->getIntermediate((EShLanguage)stage); + if(!stageIntermediate) + continue; + + std::vector spirv; + std::string warningsErrors; + spv::SpvBuildLogger logger; + glslang::GlslangToSpv(*stageIntermediate, spirv, &logger); + + dumpDiagnostics(request, logger.getAllMessages()); + + std::stringstream spirvAsmStream; + + spv::Disassemble(spirvAsmStream, spirv); + + dump(spirvAsmStream.str(), request->outputFunc, request->outputUserData, stdout); + } + + + glslang::FinalizeProcess(); + + return 0; +} diff --git a/tools/glslang/glslang.h b/tools/glslang/glslang.h new file mode 100644 index 000000000..73c8a978e --- /dev/null +++ b/tools/glslang/glslang.h @@ -0,0 +1,23 @@ +// glslang.h +#ifndef GLSLANG_H_INCLUDED +#define GLSLANG_H_INCLUDED + +typedef void (*glslang_OutputFunc)(char const* text, void* userData); + +struct glslang_CompileRequest +{ + char const* sourcePath; + char const* sourceText; + + glslang_OutputFunc diagnosticFunc; + void* diagnosticUserData; + + glslang_OutputFunc outputFunc; + void* outputUserData; + + int slangStage; +}; + +typedef int (*glslang_CompileFunc)(glslang_CompileRequest* request); + +#endif diff --git a/tools/glslang/glslang.vcxproj b/tools/glslang/glslang.vcxproj new file mode 100644 index 000000000..b8034e0bc --- /dev/null +++ b/tools/glslang/glslang.vcxproj @@ -0,0 +1,237 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + {C495878A-832C-485B-B347-0998A90CC936} + Win32Proj + glslang + 8.1 + + + + DynamicLibrary + true + v140 + Unicode + + + DynamicLibrary + false + v140 + true + Unicode + + + DynamicLibrary + true + v140 + Unicode + + + DynamicLibrary + false + v140 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + + + + true + $(SolutionDir)external\glslang\;$(IncludePath) + + + true + $(SolutionDir)external\glslang\;$(IncludePath) + + + false + $(SolutionDir)external\glslang\;$(IncludePath) + + + false + $(SolutionDir)external\glslang\;$(IncludePath) + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;GLSLANG_EXPORTS;%(PreprocessorDefinitions) + + + Windows + true + + + + + + + Level3 + Disabled + _DEBUG;_WINDOWS;_USRDLL;GLSLANG_EXPORTS;%(PreprocessorDefinitions) + + + Windows + true + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;GLSLANG_EXPORTS;%(PreprocessorDefinitions) + + + Windows + true + true + true + + + + + Level3 + + + MaxSpeed + true + true + NDEBUG;_WINDOWS;_USRDLL;GLSLANG_EXPORTS;%(PreprocessorDefinitions) + + + Windows + true + true + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tools/glslang/glslang.vcxproj.filters b/tools/glslang/glslang.vcxproj.filters new file mode 100644 index 000000000..79a7657ce --- /dev/null +++ b/tools/glslang/glslang.vcxproj.filters @@ -0,0 +1,253 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + \ No newline at end of file diff --git a/tools/render-test/README.md b/tools/render-test/README.md new file mode 100644 index 000000000..6d0d9111f --- /dev/null +++ b/tools/render-test/README.md @@ -0,0 +1,4 @@ +Render Test +=========== + +This is a simple tool for running end-to-end tests that render with Spire, so that we can validate that it generates correct code. diff --git a/tools/render-test/main.cpp b/tools/render-test/main.cpp new file mode 100644 index 000000000..e444a8387 --- /dev/null +++ b/tools/render-test/main.cpp @@ -0,0 +1,369 @@ +// main.cpp + +#include "options.h" +#include "render.h" +#include "render-d3d11.h" +#include "render-gl.h" +#include "slang-support.h" + +#include +#include + +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#undef WIN32_LEAN_AND_MEAN +#undef NOMINMAX + +namespace renderer_test { + +// + + +int gWindowWidth = 1024; +int gWindowHeight = 768; + +// +// For the purposes of a small example, we will define the vertex data for a +// single triangle directly in the source file. It should be easy to extend +// this example to load data from an external source, if desired. +// + +struct Vertex +{ + float position[3]; + float color[3]; +}; + +static const int kVertexCount = 3; +static const Vertex kVertexData[kVertexCount] = { + { { 0, 0, 0.5 }, {1, 0, 0} }, + { { 0, 1, 0.5 }, {0, 0, 1} }, + { { 1, 0, 0.5 }, {0, 1, 0} }, +}; + + +// Global variables for state to be used for rendering... + +uintptr_t gConstantBufferSize; + +Buffer* gConstantBuffer; +InputLayout* gInputLayout; +Buffer* gVertexBuffer; +ShaderProgram* gShaderProgram; + +// Entry point name to use for vertex/fragment shader +static char const* vertexEntryPointName = "vertexMain"; +static char const* fragmentEntryPointName = "fragmentMain"; + +// "Profile" to use when compiling for HLSL targets +// TODO: does this belong here? +static char const* vertexProfileName = "vs_4_0"; +static char const* fragmentProfileName = "ps_4_0"; + +Error initializeShaders( + ShaderCompiler* shaderCompiler) +{ + // Read in the source code + char const* sourcePath = gOptions.sourcePath; + FILE* sourceFile = fopen(sourcePath, "rb"); + if( !sourceFile ) + { + fprintf(stderr, "error: failed to open '%s' for reading\n", sourcePath); + exit(1); + } + fseek(sourceFile, 0, SEEK_END); + size_t sourceSize = ftell(sourceFile); + fseek(sourceFile, 0, SEEK_SET); + char* sourceText = (char*) malloc(sourceSize + 1); + if( !sourceText ) + { + fprintf(stderr, "error: out of memory"); + exit(1); + } + fread(sourceText, sourceSize, 1, sourceFile); + fclose(sourceFile); + sourceText[sourceSize] = 0; + + ShaderCompileRequest::SourceInfo sourceInfo; + sourceInfo.path = sourcePath; + sourceInfo.text = sourceText; + + ShaderCompileRequest compileRequest; + compileRequest.source = sourceInfo; + compileRequest.vertexShader.source = sourceInfo; + compileRequest.vertexShader.name = vertexEntryPointName; + compileRequest.vertexShader.profile = vertexProfileName; + compileRequest.fragmentShader.source = sourceInfo; + compileRequest.fragmentShader.name = fragmentEntryPointName; + compileRequest.fragmentShader.profile = fragmentProfileName; + + gShaderProgram = shaderCompiler->compileProgram(compileRequest); + if( !gShaderProgram ) + { + return Error::Unexpected; + } + + return Error::None; +} + +// +// At initialization time, we are going to load and compile our Slang shader +// code, and then create the D3D11 API objects we need for rendering. +// +Error initializeInner( + Renderer* renderer, + ShaderCompiler* shaderCompiler) +{ + Error err = Error::None; + + err = initializeShaders(shaderCompiler); + if(err != Error::None) return err; + + + // Do other initialization that doesn't depend on the source language. + + // TODO(tfoley): use each API's reflection interface to query the constant-buffer size needed + gConstantBufferSize = 16 * sizeof(float); + + BufferDesc constantBufferDesc; + constantBufferDesc.size = gConstantBufferSize; + constantBufferDesc.flavor = BufferFlavor::Constant; + + gConstantBuffer = renderer->createBuffer(constantBufferDesc); + if(!gConstantBuffer) + return Error::Unexpected; + + // Input Assembler (IA) + + InputElementDesc inputElements[] = { + { "A", 0, Format::RGB_Float32, offsetof(Vertex, position) }, + { "A", 1, Format::RGB_Float32, offsetof(Vertex, color) }, + }; + + gInputLayout = renderer->createInputLayout(&inputElements[0], 2); + if(!gInputLayout) + return Error::Unexpected; + + BufferDesc vertexBufferDesc; + vertexBufferDesc.size = kVertexCount * sizeof(Vertex); + vertexBufferDesc.flavor = BufferFlavor::Vertex; + vertexBufferDesc.initData = &kVertexData[0]; + + gVertexBuffer = renderer->createBuffer(vertexBufferDesc); + if(!gVertexBuffer) + return Error::Unexpected; + + return Error::None; +} + +void renderFrameInner( + Renderer* renderer) +{ + auto mappedData = renderer->map(gConstantBuffer, MapFlavor::WriteDiscard); + if(mappedData) + { + static const float kIdentity[] = + { 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 }; + memcpy(mappedData, kIdentity, sizeof(kIdentity)); + + renderer->unmap(gConstantBuffer); + } + + // Input Assembler (IA) + + renderer->setInputLayout(gInputLayout); + renderer->setPrimitiveTopology(PrimitiveTopology::TriangleList); + + renderer->setVertexBuffer(0, gVertexBuffer, sizeof(Vertex)); + + // Vertex Shader (VS) + // Pixel Shader (PS) + + renderer->setShaderProgram(gShaderProgram); + renderer->setConstantBuffer(0, gConstantBuffer); + + // + + renderer->draw(3); +} + +void finalize() +{ +} + + + +// +// We use a bare-minimum window procedure to get things up and running. +// + +static LRESULT CALLBACK windowProc( + HWND windowHandle, + UINT message, + WPARAM wParam, + LPARAM lParam) +{ + switch (message) + { + case WM_CLOSE: + PostQuitMessage(0); + return 0; + } + + return DefWindowProcW(windowHandle, message, wParam, lParam); +} + + +} // renderer_test + + +// + +int main( + int argc, + char** argv) +{ + using namespace renderer_test; + + // Parse command-line options + parseOptions(&argc, argv); + + + // Do initial window-creation stuff here, rather than in the renderer-specific files + + HINSTANCE instance = GetModuleHandleA(0); + int showCommand = SW_SHOW; + + // First we register a window class. + + WNDCLASSEXW windowClassDesc; + windowClassDesc.cbSize = sizeof(windowClassDesc); + windowClassDesc.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW; + windowClassDesc.lpfnWndProc = &windowProc; + windowClassDesc.cbClsExtra = 0; + windowClassDesc.cbWndExtra = 0; + windowClassDesc.hInstance = instance; + windowClassDesc.hIcon = 0; + windowClassDesc.hCursor = 0; + windowClassDesc.hbrBackground = 0; + windowClassDesc.lpszMenuName = 0; + windowClassDesc.lpszClassName = L"HelloWorld"; + windowClassDesc.hIconSm = 0; + ATOM windowClassAtom = RegisterClassExW(&windowClassDesc); + if(!windowClassAtom) + { + fprintf(stderr, "error: failed to register window class\n"); + return 1; + } + + // Next, we create a window using that window class. + + DWORD windowExtendedStyle = 0; + DWORD windowStyle = 0; + LPWSTR windowName = L"Slang Hello World"; + HWND windowHandle = CreateWindowExW( + windowExtendedStyle, + (LPWSTR)windowClassAtom, + windowName, + windowStyle, + 0, 0, // x, y + gWindowWidth, gWindowHeight, + NULL, // parent + NULL, // menu + instance, + NULL); + if(!windowHandle) + { + fprintf(stderr, "error: failed to create window\n"); + return 1; + } + + + Renderer* renderer = nullptr; + switch( gOptions.mode ) + { + case Mode::Slang: + case Mode::HLSL: + renderer = createD3D11Renderer(); + break; + + case Mode::GLSLCrossCompile: + renderer = createGLRenderer(); + break; + + default: + fprintf(stderr, "error: unexpected\n"); + exit(1); + break; + } + + renderer->initialize(windowHandle); + + auto shaderCompiler = renderer->getShaderCompiler(); + switch( gOptions.mode ) + { + case Mode::Slang: + shaderCompiler = createSlangShaderCompiler(shaderCompiler, SLANG_HLSL); + break; + + case Mode::GLSLCrossCompile: + shaderCompiler = createSlangShaderCompiler(shaderCompiler, SLANG_GLSL); + break; + + default: + break; + } + + Error err = initializeInner(renderer, shaderCompiler); + if( err != Error::None ) + { + exit(1); + } + + + // Once initialization is all complete, we show the window... + ShowWindow(windowHandle, showCommand); + + // ... and enter the event loop: + for(;;) + { + MSG message; + + int result = PeekMessageW(&message, NULL, 0, 0, PM_REMOVE); + if (result != 0) + { + if (message.message == WM_QUIT) + { + return (int)message.wParam; + } + + TranslateMessage(&message); + DispatchMessageW(&message); + } + else + { + // Whenver we don't have Windows events to process, + // we render a frame. + + renderer->clearFrame(); + + renderFrameInner(renderer); + + // If we are in a mode where output is requested, we need to snapshot the back buffer here + if( gOptions.outputPath ) + { + renderer->captureScreenShot(gOptions.outputPath); + return 0; + } + + renderer->presentFrame(); + } + } + + return 0; +} + diff --git a/tools/render-test/options.cpp b/tools/render-test/options.cpp new file mode 100644 index 000000000..9cfbb81fb --- /dev/null +++ b/tools/render-test/options.cpp @@ -0,0 +1,95 @@ +// options.cpp + +#include "options.h" + +#include +#include +#include + +namespace renderer_test { + +Options gOptions; + +void parseOptions(int* argc, char** argv) +{ + int argCount = *argc; + char const* const* argCursor = argv; + char const* const* argEnd = argCursor + argCount; + + char const** writeCursor = (char const**) argv; + + // first argument is the application name + if( argCursor != argEnd ) + { + gOptions.appName = *argCursor++; + } + + // now iterate over arguments to collect options + while(argCursor != argEnd) + { + char const* arg = *argCursor++; + if( arg[0] != '-' ) + { + *writeCursor++ = arg; + continue; + } + + if( strcmp(arg, "--") == 0 ) + { + while(argCursor != argEnd) + { + char const* arg = *argCursor++; + *writeCursor++ = arg; + } + break; + } + else if( strcmp(arg, "-o") == 0 ) + { + if( argCursor == argEnd ) + { + fprintf(stderr, "expected argument for '%s' option\n", arg); + exit(1); + } + gOptions.outputPath = *argCursor++; + } + else if( strcmp(arg, "-hlsl") == 0 ) + { + gOptions.mode = Mode::HLSL; + } + else if( strcmp(arg, "-slang") == 0 ) + { + gOptions.mode = Mode::Slang; + } + else if( strcmp(arg, "-glsl-cross") == 0 ) + { + gOptions.mode = Mode::GLSLCrossCompile; + } + else + { + fprintf(stderr, "unknown option '%s'\n", arg); + exit(1); + } + } + + // any arguments left over were positional arguments + argCount = (int)(writeCursor - argv); + argCursor = argv; + argEnd = argCursor + argCount; + + // first positional argument is source shader path + if( argCursor != argEnd ) + { + gOptions.sourcePath = *argCursor++; + } + + // any remaining arguments represent an error + if(argCursor != argEnd) + { + fprintf(stderr, "unexpected arguments\n"); + exit(1); + } + + *argc = 0; +} + +} // renderer_test diff --git a/tools/render-test/options.h b/tools/render-test/options.h new file mode 100644 index 000000000..ffb07bc93 --- /dev/null +++ b/tools/render-test/options.h @@ -0,0 +1,41 @@ +// options.h +#pragma once + +#include + +namespace renderer_test { + +typedef intptr_t Int; +typedef uintptr_t UInt; + +enum class Mode +{ + Slang, + HLSL, + GLSLCrossCompile, +}; + +struct Options +{ + char const* appName = "render-test"; + char const* sourcePath = nullptr; + char const* outputPath = nullptr; + Mode mode = Mode::Slang; +}; + +extern Options gOptions; + +extern int gWindowWidth; +extern int gWindowHeight; + + +void parseOptions(int* argc, char** argv); + +enum class Error +{ + None = 0, + InvalidParam, + Unexpected, +}; + +} // renderer_test diff --git a/tools/render-test/render-d3d11.cpp b/tools/render-test/render-d3d11.cpp new file mode 100644 index 000000000..ab981bd45 --- /dev/null +++ b/tools/render-test/render-d3d11.cpp @@ -0,0 +1,900 @@ +// render-d3d11.cpp +#include "render-d3d11.h" + +#include "options.h" +#include "render.h" + +// In order to use the Slang API, we need to include its header + +#include + +#define STB_IMAGE_WRITE_IMPLEMENTATION +#include "external/stb/stb_image_write.h" + +// We will be rendering with Direct3D 11, so we need to include +// the Windows and D3D11 headers + +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#undef WIN32_LEAN_AND_MEAN +#undef NOMINMAX + +#include +#include + +// We will use the C standard library just for printing error messages. +#include + +#ifdef _MSC_VER +#include +#if (_MSC_VER < 1900) +#define snprintf sprintf_s +#endif +#endif +// + +namespace renderer_test { + +// + + +// + +// Global variabels for the various D3D11 API objects to be used for rendering +ID3D11Buffer* dxConstantBuffer; +ID3D11InputLayout* dxInputLayout; +ID3D11Buffer* dxVertexBuffer; +ID3D11VertexShader* dxVertexShader; +ID3D11PixelShader* dxPixelShader; + +// The Slang compiler currently generates HLSL source, so we'll need a utility +// routine (defined later) to translate that into D3D11 shader bytecode. +ID3DBlob* compileHLSLShader( + char const* sourcePath, + char const* source, + char const* entryPointName, + char const* dxProfileName); + +static char const* vertexEntryPointName = "vertexMain"; +static char const* fragmentEntryPointName = "fragmentMain"; + +static char const* vertexProfileName = "vs_4_0"; +static char const* fragmentProfileName = "ps_4_0"; + +ID3DBlob* gVertexShaderBlob; +ID3DBlob* gPixelShaderBlob; + +// Initialization when using HLSL for shaders +HRESULT initializeHLSLInner(ID3D11Device* dxDevice, char const* sourcePath, char const* sourceText) +{ + // Compile the generated HLSL code + gVertexShaderBlob = compileHLSLShader(sourcePath, sourceText, vertexEntryPointName, vertexProfileName); + if(!gVertexShaderBlob) return E_FAIL; + + gPixelShaderBlob = compileHLSLShader(sourcePath, sourceText, fragmentEntryPointName, fragmentProfileName); + if(!gPixelShaderBlob) return E_FAIL; + + + return S_OK; +} + +// Initialization when using HLSL for shaders +HRESULT initializeHLSL(ID3D11Device* dxDevice, char const* sourceText) +{ + HRESULT hr = initializeHLSLInner(dxDevice, gOptions.sourcePath, sourceText); + if(FAILED(hr)) + return hr; + + // TODO: any reflection stuff to do here? + + return S_OK; +} + +// Initialization when using Slang for shaders +HRESULT initializeSlang(ID3D11Device* dxDevice, char const* sourceText) +{ + // + // First, we will load and compile our Slang source code. + // + + // The argument here is an optional directory where the Slang compiler + // can cache files to speed up compilation of many kernels. + SlangSession* slangSession = spCreateSession(NULL); + + // A compile request represents a single invocation of the compiler, + // to process some inputs and produce outputs (or errors). + SlangCompileRequest* slangRequest = spCreateCompileRequest(slangSession); + + // Instruct Slang to generate code as HLSL + spSetCodeGenTarget(slangRequest, SLANG_HLSL); + + int translationUnitIndex = spAddTranslationUnit(slangRequest, SLANG_SOURCE_LANGUAGE_SLANG, nullptr); + + spAddTranslationUnitSourceString(slangRequest, translationUnitIndex, gOptions.sourcePath, sourceText); + + spAddTranslationUnitEntryPoint(slangRequest, translationUnitIndex, vertexEntryPointName, spFindProfile(slangSession, vertexProfileName)); + spAddTranslationUnitEntryPoint(slangRequest, translationUnitIndex, fragmentEntryPointName, spFindProfile(slangSession, fragmentProfileName)); + + int compileErr = spCompile(slangRequest); + if(auto diagnostics = spGetDiagnosticOutput(slangRequest)) + { + OutputDebugStringA(diagnostics); + fprintf(stderr, "%s", diagnostics); + } + if(compileErr) + { + return E_FAIL; + } + + char const* translatedCode = spGetTranslationUnitSource(slangRequest, translationUnitIndex); + + // Compile the generated HLSL code + HRESULT hr = initializeHLSLInner(dxDevice, "slangGeneratedCode", translatedCode); + if(FAILED(hr)) + return hr; + + // We clean up the Slang compilation context and result *after* + // we have done the HLSL-to-bytecode compilation, because Slang + // owns the memory allocation for the generated HLSL, and will + // free it when we destroy the compilation result. + spDestroyCompileRequest(slangRequest); + spDestroySession(slangSession); + + return S_OK; +} + +#if 0 + +// +// At initialization time, we are going to load and compile our Slang shader +// code, and then create the D3D11 API objects we need for rendering. +// +HRESULT initializeInner( ID3D11Device* dxDevice ) +{ + HRESULT hr = S_OK; + + // Read in the source code + char const* sourcePath = gOptions.sourcePath; + FILE* sourceFile = fopen(sourcePath, "rb"); + if( !sourceFile ) + { + fprintf(stderr, "error: failed to open '%s' for reading\n", sourcePath); + exit(1); + } + fseek(sourceFile, 0, SEEK_END); + size_t sourceSize = ftell(sourceFile); + fseek(sourceFile, 0, SEEK_SET); + char* sourceText = (char*) malloc(sourceSize + 1); + if( !sourceText ) + { + fprintf(stderr, "error: out of memory"); + exit(1); + } + fread(sourceText, sourceSize, 1, sourceFile); + fclose(sourceFile); + sourceText[sourceSize] = 0; + + switch( gOptions.mode ) + { + case Mode::HLSL: + hr = initializeHLSL(dxDevice, sourceText); + break; + + case Mode::Slang: + hr = initializeSlang(dxDevice, sourceText); + break; + + default: + hr = E_FAIL; + break; + } + if( FAILED(hr) ) + { + return hr; + } + + // Do other initialization that doesn't depend on the source language. + + // TODO(tfoley): use each API's reflection interface to query the constant-buffer size needed + gConstantBufferSize = 16 * sizeof(float); + + + D3D11_BUFFER_DESC dxConstantBufferDesc = { 0 }; + dxConstantBufferDesc.ByteWidth = gConstantBufferSize; + dxConstantBufferDesc.Usage = D3D11_USAGE_DYNAMIC; + dxConstantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + dxConstantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + + hr = dxDevice->CreateBuffer( + &dxConstantBufferDesc, + NULL, + &dxConstantBuffer); + if(FAILED(hr)) return hr; + + + // Input Assembler (IA) + + // In Slang-generated HLSL, all vertex shader inputs have a semantic + // like: `A0`, `A1`, `A2`, etc., rather than trying to do by-name + // matching. The user is thus responsibile for ensuring that the + // order of their "input element descs" here matches the order + // in which inputs are declared in the shader code. + D3D11_INPUT_ELEMENT_DESC dxInputElements[] = { + {"A", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(Vertex, position), D3D11_INPUT_PER_VERTEX_DATA, 0 }, + {"A", 1, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(Vertex, color), D3D11_INPUT_PER_VERTEX_DATA, 0 }, + }; + hr = dxDevice->CreateInputLayout( + &dxInputElements[0], + 2, + gVertexShaderBlob->GetBufferPointer(), + gVertexShaderBlob->GetBufferSize(), + &dxInputLayout); + if(FAILED(hr)) return hr; + + D3D11_BUFFER_DESC dxVertexBufferDesc = { 0 }; + dxVertexBufferDesc.ByteWidth = kVertexCount * sizeof(Vertex); + dxVertexBufferDesc.Usage = D3D11_USAGE_IMMUTABLE; + dxVertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + + D3D11_SUBRESOURCE_DATA dxVertexBufferInitData = { 0 }; + dxVertexBufferInitData.pSysMem = &kVertexData[0]; + + hr = dxDevice->CreateBuffer( + &dxVertexBufferDesc, + &dxVertexBufferInitData, + &dxVertexBuffer); + if(FAILED(hr)) return hr; + + // Vertex Shader (VS) + + hr = dxDevice->CreateVertexShader( + gVertexShaderBlob->GetBufferPointer(), + gVertexShaderBlob->GetBufferSize(), + NULL, + &dxVertexShader); + gVertexShaderBlob->Release(); + if(FAILED(hr)) return hr; + + // Pixel Shader (PS) + + hr = dxDevice->CreatePixelShader( + gPixelShaderBlob->GetBufferPointer(), + gPixelShaderBlob->GetBufferSize(), + NULL, + &dxPixelShader); + gPixelShaderBlob->Release(); + if(FAILED(hr)) return hr; + + return S_OK; +} + +void renderFrameInner(ID3D11DeviceContext* dxContext) +{ + // We update our constant buffer per-frame, just for the purposes + // of the example, but we don't actually load different data + // per-frame (we always use an identity projection). + D3D11_MAPPED_SUBRESOURCE mapped; + HRESULT hr = dxContext->Map(dxConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped); + if(!FAILED(hr)) + { + float* data = (float*) mapped.pData; + + static const float kIdentity[] = + { 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 }; + memcpy(data, kIdentity, sizeof(kIdentity)); + + dxContext->Unmap(dxConstantBuffer, 0); + } + + // Input Assembler (IA) + + dxContext->IASetInputLayout(dxInputLayout); + dxContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + + UINT dxVertexStride = sizeof(Vertex); + UINT dxVertexBufferOffset = 0; + dxContext->IASetVertexBuffers(0, 1, &dxVertexBuffer, &dxVertexStride, &dxVertexBufferOffset); + + // Vertex Shader (VS) + + dxContext->VSSetShader(dxVertexShader, NULL, 0); + dxContext->VSSetConstantBuffers(0, 1, &dxConstantBuffer); + + // Pixel Shader (PS) + + dxContext->PSSetShader(dxPixelShader, NULL, 0); + dxContext->VSSetConstantBuffers(0, 1, &dxConstantBuffer); + + // + + dxContext->Draw(3, 0); +} + +void finalize() +{ +} + +#endif + +// +// Definition of the HLSL-to-bytecode compilation logic. +// +ID3DBlob* compileHLSLShader( + char const* sourcePath, + char const* source, + char const* entryPointName, + char const* dxProfileName ) +{ + // Rather than statically link against the `d3dcompile` library, we + // dynamically load it. + // + // Note: A more realistic application would compile from HLSL text to D3D + // shader bytecode as part of an offline process, rather than doing it + // on-the-fly like this + // + static pD3DCompile D3DCompile_ = nullptr; + if( !D3DCompile_ ) + { + // TODO(tfoley): maybe want to search for one of a few versions of the DLL + HMODULE d3dcompiler = LoadLibraryA("d3dcompiler_47.dll"); + if(!d3dcompiler) + { + fprintf(stderr, "error: failed load 'd3dcompiler_47.dll'\n"); + exit(1); + } + + D3DCompile_ = (pD3DCompile)GetProcAddress(d3dcompiler, "D3DCompile"); + if( !D3DCompile_ ) + { + fprintf(stderr, "error: failed load symbol 'D3DCompile'\n"); + exit(1); + } + } + + // For this example, we turn on debug output, and turn off all + // optimization. A real application would only use these flags + // when shader debugging is needed. + UINT flags = 0; + flags |= D3DCOMPILE_DEBUG; + flags |= D3DCOMPILE_OPTIMIZATION_LEVEL0 | D3DCOMPILE_SKIP_OPTIMIZATION; + + // The `D3DCompile` entry point takes a bunch of parameters, but we + // don't really need most of them for Slang-generated code. + ID3DBlob* dxShaderBlob = nullptr; + ID3DBlob* dxErrorBlob = nullptr; + HRESULT hr = D3DCompile_( + source, + strlen(source), + sourcePath, + nullptr, + nullptr, + entryPointName, + dxProfileName, + flags, + 0, + &dxShaderBlob, + &dxErrorBlob); + + // If the HLSL-to-bytecode compilation produced any diagnostic messages + // then we will print them out (whether or not the compilation failed). + if( dxErrorBlob ) + { + OutputDebugStringA( + (char const*)dxErrorBlob->GetBufferPointer()); + dxErrorBlob->Release(); + } + + if( FAILED(hr) ) + { + return nullptr; + } + + return dxShaderBlob; +} + + + + +// Capture a texture to a file + +static HRESULT captureTextureToFile( + ID3D11Device* dxDevice, + ID3D11DeviceContext* dxContext, + ID3D11Texture2D* dxTexture, + char const* outputPath) +{ + if(!dxContext) return E_INVALIDARG; + if(!dxTexture) return E_INVALIDARG; + + D3D11_TEXTURE2D_DESC dxTextureDesc; + dxTexture->GetDesc(&dxTextureDesc); + + // Don't bother supporing MSAA for right now + if(dxTextureDesc.SampleDesc.Count > 1) + return E_INVALIDARG; + + HRESULT hr = S_OK; + ID3D11Texture2D* dxStagingTexture = nullptr; + + if( dxTextureDesc.Usage == D3D11_USAGE_STAGING && (dxTextureDesc.CPUAccessFlags & D3D11_CPU_ACCESS_READ) ) + { + dxStagingTexture = dxTexture; + dxStagingTexture->AddRef(); + } + else + { + // Modify the descriptor to give us a staging texture + dxTextureDesc.BindFlags = 0; + dxTextureDesc.MiscFlags &= D3D11_RESOURCE_MISC_TEXTURECUBE; + dxTextureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; + dxTextureDesc.Usage = D3D11_USAGE_STAGING; + + hr = dxDevice->CreateTexture2D(&dxTextureDesc, 0, &dxStagingTexture); + if(FAILED(hr)) + return hr; + + dxContext->CopyResource(dxStagingTexture, dxTexture); + } + + // Now just read back texels from the staging textures + + D3D11_MAPPED_SUBRESOURCE dxMappedResource; + hr = dxContext->Map(dxStagingTexture, 0, D3D11_MAP_READ, 0, &dxMappedResource); + if(FAILED(hr)) + return hr; + + int stbResult = stbi_write_png( + outputPath, + dxTextureDesc.Width, + dxTextureDesc.Height, + 4, + dxMappedResource.pData, + dxMappedResource.RowPitch); + if( !stbResult ) + { + return E_UNEXPECTED; + } + + dxContext->Unmap(dxStagingTexture, 0); + + dxStagingTexture->Release(); + + return S_OK; +} + +// + +class D3D11Renderer : public Renderer, public ShaderCompiler +{ +public: + IDXGISwapChain* dxSwapChain = NULL; + ID3D11Device* dxDevice = NULL; + ID3D11DeviceContext* dxImmediateContext = NULL; + ID3D11Texture2D* dxBackBufferTexture = NULL; + ID3D11RenderTargetView* dxBackBufferRTV = NULL; + + virtual void initialize(void* inWindowHandle) override + { + auto windowHandle = (HWND) inWindowHandle; + + // Rather than statically link against D3D, we load it dynamically. + + HMODULE d3d11 = LoadLibraryA("d3d11.dll"); + if(!d3d11) + { + fprintf(stderr, "error: failed load 'd3d11.dll'\n"); + exit(1); + } + + PFN_D3D11_CREATE_DEVICE_AND_SWAP_CHAIN D3D11CreateDeviceAndSwapChain_ = + (PFN_D3D11_CREATE_DEVICE_AND_SWAP_CHAIN)GetProcAddress( + d3d11, + "D3D11CreateDeviceAndSwapChain"); + if(!D3D11CreateDeviceAndSwapChain_) + { + fprintf(stderr, + "error: failed load symbol 'D3D11CreateDeviceAndSwapChain'\n"); + exit(1); + } + + // We create our device in debug mode, just so that we can check that the + // example doesn't trigger warnings. + UINT deviceFlags = 0; + deviceFlags |= D3D11_CREATE_DEVICE_DEBUG; + + // We will ask for the highest feature level that can be supported. + + D3D_FEATURE_LEVEL featureLevels[] = { + D3D_FEATURE_LEVEL_11_1, + D3D_FEATURE_LEVEL_11_0, + D3D_FEATURE_LEVEL_10_1, + D3D_FEATURE_LEVEL_10_0, + D3D_FEATURE_LEVEL_9_3, + D3D_FEATURE_LEVEL_9_2, + D3D_FEATURE_LEVEL_9_1, + }; + D3D_FEATURE_LEVEL dxFeatureLevel = D3D_FEATURE_LEVEL_9_1; + + // Our swap chain uses RGBA8 with sRGB, with double buffering. + + DXGI_SWAP_CHAIN_DESC dxSwapChainDesc = { 0 }; + dxSwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + dxSwapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; + dxSwapChainDesc.SampleDesc.Count = 1; + dxSwapChainDesc.SampleDesc.Quality = 0; + dxSwapChainDesc.BufferCount = 2; + dxSwapChainDesc.OutputWindow = windowHandle; + dxSwapChainDesc.Windowed = TRUE; + dxSwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; + dxSwapChainDesc.Flags = 0; + + // On a machine that does not have an up-to-date version of D3D installed, + // the `D3D11CreateDeviceAndSwapChain` call will fail with `E_INVALIDARG` + // if you ask for featuer level 11_1. The workaround is to call + // `D3D11CreateDeviceAndSwapChain` up to twice: the first time with 11_1 + // at the start of the list of requested feature levels, and the second + // time without it. + + HRESULT hr = S_OK; + for( int ii = 0; ii < 2; ++ii ) + { + hr = D3D11CreateDeviceAndSwapChain_( + NULL, // adapter (use default) + D3D_DRIVER_TYPE_HARDWARE, + NULL, // software + deviceFlags, + &featureLevels[ii], + (sizeof(featureLevels) / sizeof(featureLevels[0])) - 1, + D3D11_SDK_VERSION, + &dxSwapChainDesc, + &dxSwapChain, + &dxDevice, + &dxFeatureLevel, + &dxImmediateContext); + + // Failures with `E_INVALIDARG` might be due to feature level 11_1 + // not being supported. Other failures are real, though. + if( hr != E_INVALIDARG ) + break; + } + if( FAILED(hr) ) + { + exit(1); + } + + // After we've created the swap chain, we can request a pointer to the + // back buffer as a D3D11 texture, and create a render-target view from it. + + static const IID kIID_ID3D11Texture2D = { + 0x6f15aaf2, 0xd208, 0x4e89, 0x9a, 0xb4, 0x48, + 0x95, 0x35, 0xd3, 0x4f, 0x9c }; + dxSwapChain->GetBuffer( + 0, + kIID_ID3D11Texture2D, + (void**)&dxBackBufferTexture); + + dxDevice->CreateRenderTargetView( + dxBackBufferTexture, + NULL, + &dxBackBufferRTV); + + // We immediately bind the back-buffer render target view, and we aren't + // going to switch. We don't bother with a depth buffer. + dxImmediateContext->OMSetRenderTargets( + 1, + &dxBackBufferRTV, + NULL); + + // Similarly, we are going to set up a viewport once, and then never + // switch, since this is a simple test app. + D3D11_VIEWPORT dxViewport; + dxViewport.TopLeftX = 0; + dxViewport.TopLeftY = 0; + dxViewport.Width = (float) gWindowWidth; + dxViewport.Height = (float) gWindowHeight; + dxViewport.MaxDepth = 1; // TODO(tfoley): use reversed depth + dxViewport.MinDepth = 0; + dxImmediateContext->RSSetViewports(1, &dxViewport); + } + + virtual void clearFrame() override + { + static const float kClearColor[] = { 0.25, 0.25, 0.25, 1.0 }; + dxImmediateContext->ClearRenderTargetView( + dxBackBufferRTV, + kClearColor); + } + + virtual void presentFrame() override + { + dxSwapChain->Present(0, 0); + } + + virtual void captureScreenShot(char const* outputPath) override + { + HRESULT hr = captureTextureToFile( + dxDevice, + dxImmediateContext, + dxBackBufferTexture, + outputPath); + if( FAILED(hr) ) + { + fprintf(stderr, "error: could not capture screenshot to '%s'\n", outputPath); + exit(1); + } + } + + virtual ShaderCompiler* getShaderCompiler() override + { + return this; + } + + virtual Buffer* createBuffer(BufferDesc const& desc) override + { + D3D11_BUFFER_DESC dxBufferDesc = { 0 }; + dxBufferDesc.ByteWidth = desc.size; + + switch( desc.flavor ) + { + case BufferFlavor::Constant: + dxBufferDesc.Usage = D3D11_USAGE_DYNAMIC; + dxBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + dxBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + break; + + case BufferFlavor::Vertex: + break; + + default: + return nullptr; + } + + D3D11_SUBRESOURCE_DATA dxInitData = { 0 }; + dxInitData.pSysMem = desc.initData; + + + ID3D11Buffer* dxBuffer = nullptr; + HRESULT hr = dxDevice->CreateBuffer( + &dxBufferDesc, + desc.initData ? &dxInitData : nullptr, + &dxBuffer); + if(FAILED(hr)) return nullptr; + + return (Buffer*) dxBuffer; + } + + static DXGI_FORMAT mapFormat(Format format) + { + switch( format ) + { + case Format::RGB_Float32: + return DXGI_FORMAT_R32G32B32_FLOAT; + + default: + return DXGI_FORMAT_UNKNOWN; + } + } + + virtual InputLayout* createInputLayout(InputElementDesc const* inputElements, UInt inputElementCount) override + { + D3D11_INPUT_ELEMENT_DESC dxInputElements[16] = {}; + + char hlslBuffer[1024]; + char* hlslCursor = &hlslBuffer[0]; + + hlslCursor += sprintf(hlslCursor, "float4 main(\n"); + + for( UInt ii = 0; ii < inputElementCount; ++ii ) + { + dxInputElements[ii].SemanticName = inputElements[ii].semanticName; + dxInputElements[ii].SemanticIndex = inputElements[ii].semanticIndex; + dxInputElements[ii].Format = mapFormat(inputElements[ii].format); + dxInputElements[ii].InputSlot = 0; + dxInputElements[ii].AlignedByteOffset = inputElements[ii].offset; + dxInputElements[ii].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; + dxInputElements[ii].InstanceDataStepRate = 0; + + if(ii != 0) + { + hlslCursor+= sprintf(hlslCursor, ",\n"); + } + + char const* typeName = "Uknown"; + switch(inputElements[ii].format) + { + case Format::RGB_Float32: + typeName = "float3"; + break; + + default: + return nullptr; + } + + hlslCursor+= sprintf(hlslCursor, "%s a%d : %s%d", typeName, ii, + inputElements[ii].semanticName, + inputElements[ii].semanticIndex); + } + + hlslCursor += sprintf(hlslCursor, "\n) : SV_Position { return 0; }"); + + auto dxVertexShaderBlob = compileHLSLShader("inputLayout", hlslBuffer, "main", "vs_4_0"); + if(!dxVertexShaderBlob) + return nullptr; + + ID3D11InputLayout* dxInputLayout = nullptr; + HRESULT hr = dxDevice->CreateInputLayout( + &dxInputElements[0], + inputElementCount, + dxVertexShaderBlob->GetBufferPointer(), + dxVertexShaderBlob->GetBufferSize(), + &dxInputLayout); + + dxVertexShaderBlob->Release(); + + if(FAILED(hr)) + return nullptr; + + return (InputLayout*) dxInputLayout; + } + + virtual void* map(Buffer* buffer, MapFlavor flavor) override + { + auto dxContext = dxImmediateContext; + + auto dxBuffer = (ID3D11Buffer*) buffer; + + D3D11_MAP dxMapFlavor; + switch( flavor ) + { + case MapFlavor::WriteDiscard: + dxMapFlavor = D3D11_MAP_WRITE_DISCARD; + break; + + default: + return nullptr; + } + + // We update our constant buffer per-frame, just for the purposes + // of the example, but we don't actually load different data + // per-frame (we always use an identity projection). + D3D11_MAPPED_SUBRESOURCE dxMapped; + HRESULT hr = dxContext->Map(dxBuffer, 0, dxMapFlavor, 0, &dxMapped); + if(FAILED(hr)) + return nullptr; + + return dxMapped.pData; + } + + virtual void unmap(Buffer* buffer) override + { + auto dxContext = dxImmediateContext; + + auto dxBuffer = (ID3D11Buffer*) buffer; + + dxContext->Unmap(dxBuffer, 0); + } + + virtual void setInputLayout(InputLayout* inputLayout) override + { + auto dxContext = dxImmediateContext; + auto dxInputLayout = (ID3D11InputLayout*) inputLayout; + + dxContext->IASetInputLayout(dxInputLayout); + } + + virtual void setPrimitiveTopology(PrimitiveTopology topology) override + { + auto dxContext = dxImmediateContext; + + D3D11_PRIMITIVE_TOPOLOGY dxTopology; + switch( topology ) + { + case PrimitiveTopology::TriangleList: + dxTopology = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST; + break; + + default: + return; + } + + dxContext->IASetPrimitiveTopology(dxTopology); + } + + virtual void setVertexBuffers(UInt startSlot, UInt slotCount, Buffer* const* buffers, UInt const* strides, UInt const* offsets) override + { + auto dxContext = dxImmediateContext; + + static const int kMaxVertexBuffers = 16; + + UINT dxVertexStrides[kMaxVertexBuffers]; + UINT dxVertexOffsets[kMaxVertexBuffers]; + + for( UInt ii = 0; ii < slotCount; ++ii ) + { + dxVertexStrides[ii] = strides[ii]; + dxVertexOffsets[ii] = offsets[ii]; + } + + auto dxVertexBuffers = (ID3D11Buffer* const*) buffers; + + dxContext->IASetVertexBuffers(startSlot, slotCount, &dxVertexBuffers[0], &dxVertexStrides[0], &dxVertexOffsets[0]); + } + + virtual void setShaderProgram(ShaderProgram* inProgram) override + { + auto dxContext = dxImmediateContext; + + auto program = (D3D11ShaderProgram*) inProgram; + + dxContext->VSSetShader(program->dxVertexShader, NULL, 0); + dxContext->PSSetShader(program->dxPixelShader, NULL, 0); + } + + virtual void setConstantBuffers(UInt startSlot, UInt slotCount, Buffer* const* buffers, UInt const* offsets) override + { + auto dxContext = dxImmediateContext; + + // TODO: actually use those offsets + + auto dxConstantBuffers = (ID3D11Buffer* const*) buffers; + + dxContext->VSSetConstantBuffers(startSlot, slotCount, &dxConstantBuffers[0]); + dxContext->VSSetConstantBuffers(startSlot, slotCount, &dxConstantBuffers[0]); + } + + + virtual void draw(UInt vertexCount, UInt startVertex) override + { + auto dxContext = dxImmediateContext; + + dxContext->Draw(vertexCount, startVertex); + } + + + // ShaderCompiler interface + + struct D3D11ShaderProgram + { + ID3D11VertexShader* dxVertexShader; + ID3D11PixelShader* dxPixelShader; + }; + + virtual ShaderProgram* compileProgram(ShaderCompileRequest const& request) override + { + auto dxVertexShaderBlob = compileHLSLShader(request.source.path, request.source.text, request.vertexShader .name, request.vertexShader .profile); + if(!dxVertexShaderBlob) return nullptr; + + auto dxFragmentShaderBlob = compileHLSLShader(request.source.path, request.source.text, request.fragmentShader .name, request.fragmentShader .profile); + if(!dxFragmentShaderBlob) return nullptr; + + ID3D11VertexShader* dxVertexShader; + ID3D11PixelShader* dxPixelShader; + + HRESULT vsResult = dxDevice->CreateVertexShader( dxVertexShaderBlob ->GetBufferPointer(), dxVertexShaderBlob ->GetBufferSize(), nullptr, &dxVertexShader); + HRESULT psResult = dxDevice->CreatePixelShader( dxFragmentShaderBlob->GetBufferPointer(), dxFragmentShaderBlob->GetBufferSize(), nullptr, &dxPixelShader); + + dxVertexShaderBlob ->Release(); + dxFragmentShaderBlob->Release(); + + if(FAILED(vsResult)) return nullptr; + if(FAILED(psResult)) return nullptr; + + D3D11ShaderProgram* shaderProgram = new D3D11ShaderProgram(); + shaderProgram->dxVertexShader = dxVertexShader; + shaderProgram->dxPixelShader = dxPixelShader; + return (ShaderProgram*) shaderProgram; + } +}; + + + +Renderer* createD3D11Renderer() +{ + return new D3D11Renderer(); +} + +} // renderer_test diff --git a/tools/render-test/render-d3d11.h b/tools/render-test/render-d3d11.h new file mode 100644 index 000000000..59142731d --- /dev/null +++ b/tools/render-test/render-d3d11.h @@ -0,0 +1,10 @@ +// render-d3d11.h +#pragma once + +namespace renderer_test { + +class Renderer; + +Renderer* createD3D11Renderer(); + +} // renderer_test diff --git a/tools/render-test/render-gl.cpp b/tools/render-test/render-gl.cpp new file mode 100644 index 000000000..545dd2e44 --- /dev/null +++ b/tools/render-test/render-gl.cpp @@ -0,0 +1,242 @@ +// render-gl.cpp +#include "render-gl.h" + +#include "options.h" +#include "render.h" + +#include +#include + +// TODO(tfoley): eventually we should be able to run these +// tests on non-Windows targets to confirm that cross-compilation +// at least *works* on those platforms... +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#undef WIN32_LEAN_AND_MEAN +#undef NOMINMAX + +#ifdef _MSC_VER +#include +#if (_MSC_VER < 1900) +#define snprintf sprintf_s +#endif +#endif + +#pragma comment(lib, "opengl32") + +#include +#include "external/glext.h" + +// We define an "X-macro" for mapping over loadable OpenGL +// extension entry point that we will use, so that we can +// easily write generic code to iterate over them. +#define MAP_GL_EXTENSION_FUNCS(F) \ + F(glCreateProgram, PFNGLCREATEPROGRAMPROC) \ + F(glCreateShader, PFNGLCREATESHADERPROC) \ + F(glShaderSource, PFNGLSHADERSOURCEPROC) \ + F(glCompileShader, PFNGLCOMPILESHADERPROC) \ + F(glGetShaderiv, PFNGLGETSHADERIVPROC) \ + F(glDeleteShader, PFNGLDELETESHADERPROC) \ + F(glAttachShader, PFNGLATTACHSHADERPROC) \ + F(glLinkProgram, PFNGLLINKPROGRAMPROC) \ + F(glGetProgramiv, PFNGLGETPROGRAMIVPROC) \ + F(glGetProgramInfoLog, PFNGLGETPROGRAMINFOLOGPROC) \ + F(glDeleteProgram, PFNGLDELETEPROGRAMPROC) \ + F(glGetShaderInfoLog, PFNGLGETSHADERINFOLOGPROC) \ + /* emtty */ + +namespace renderer_test { + +class GLRenderer : public Renderer, public ShaderCompiler +{ +public: + HDC deviceContext; + HGLRC glContext; + + // Declre a function pointer for each OpenGL + // extension function we need to load + +#define DECLARE_GL_EXTENSION_FUNC(NAME, TYPE) TYPE NAME; + MAP_GL_EXTENSION_FUNCS(DECLARE_GL_EXTENSION_FUNC) +#undef DECLARE_GL_EXTENSION_FUNC + + // Renderer interface + + virtual void initialize(void* inWindowHandle) override + { + auto windowHandle = (HWND) inWindowHandle; + + deviceContext = GetDC(windowHandle); + + PIXELFORMATDESCRIPTOR pixelFormatDesc = { sizeof(PIXELFORMATDESCRIPTOR) }; + pixelFormatDesc.nVersion = 1; + pixelFormatDesc.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; + pixelFormatDesc.iPixelType = PFD_TYPE_RGBA; + pixelFormatDesc.cColorBits = 32; + pixelFormatDesc.cDepthBits = 24; + pixelFormatDesc.cStencilBits = 8; + pixelFormatDesc.iLayerType = PFD_MAIN_PLANE; + + int pixelFormatIndex = ChoosePixelFormat(deviceContext, &pixelFormatDesc); + SetPixelFormat(deviceContext, pixelFormatIndex, &pixelFormatDesc); + + glContext = wglCreateContext(deviceContext); + wglMakeCurrent(deviceContext, glContext); + + auto renderer = glGetString(GL_RENDERER); + auto extensions = glGetString(GL_EXTENSIONS); + + // Load ech of our etension functions by name + + #define LOAD_GL_EXTENSION_FUNC(NAME, TYPE) NAME = (TYPE) wglGetProcAddress(#NAME); + MAP_GL_EXTENSION_FUNCS(LOAD_GL_EXTENSION_FUNC) + #undef LOAD_GL_EXTENSION_FUNC + } + + virtual void clearFrame() override + { + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + } + + virtual void presentFrame() override + { + glFlush(); + SwapBuffers(deviceContext); + } + + virtual void captureScreenShot(char const* outputPath) override + { + + } + + virtual ShaderCompiler* getShaderCompiler() override + { + return this; + } + + virtual Buffer* createBuffer(BufferDesc const& desc) override + { + return nullptr; + } + + virtual InputLayout* createInputLayout(InputElementDesc const* inputElements, UInt inputElementCount) override + { + return nullptr; + } + + virtual void* map(Buffer* buffer, MapFlavor flavor) override + { + return nullptr; + } + + virtual void unmap(Buffer* buffer) override + { + } + + virtual void setInputLayout(InputLayout* inputLayout) override + { + } + + virtual void setPrimitiveTopology(PrimitiveTopology topology) override + { + } + + virtual void setVertexBuffers(UInt startSlot, UInt slotCount, Buffer* const* buffers, UInt const* strides, UInt const* offsets) override + { + } + + virtual void setShaderProgram(ShaderProgram* program) override + { + } + + virtual void setConstantBuffers(UInt startSlot, UInt slotCount, Buffer* const* buffers, UInt const* offsets) override + { + } + + + virtual void draw(UInt vertexCount, UInt startVertex = 0) override + { + } + + // ShaderCompiler interface + + virtual ShaderProgram* compileProgram(ShaderCompileRequest const& request) override + { + auto programID = glCreateProgram(); + + auto vertexShaderID = loadShader(GL_VERTEX_SHADER, request.vertexShader .source.text); + auto fragmentShaderID = loadShader(GL_FRAGMENT_SHADER, request.fragmentShader.source.text); + + glAttachShader(programID, vertexShaderID); + glAttachShader(programID, fragmentShaderID); + + glLinkProgram(programID); + + glDeleteShader(vertexShaderID); + glDeleteShader(fragmentShaderID); + + GLint success = GL_FALSE; + glGetProgramiv(programID, GL_LINK_STATUS, &success); + if( !success ) + { + int maxSize = 0; + glGetProgramiv(programID, GL_INFO_LOG_LENGTH, &maxSize); + + auto infoBuffer = (char*) malloc(maxSize); + + int infoSize = 0; + glGetProgramInfoLog(programID, maxSize, &infoSize, infoBuffer); + if( infoSize > 0 ) + { + fprintf(stderr, "%s", infoBuffer); + OutputDebugStringA(infoBuffer); + } + + glDeleteProgram(programID); + return 0; + } + + return (ShaderProgram*) (uintptr_t) programID; + } + + GLuint loadShader(GLenum stage, char const* source) + { + auto shaderID = glCreateShader(stage); + + glShaderSource(shaderID, 1, &source, nullptr); + glCompileShader(shaderID); + + GLint success = GL_FALSE; + glGetShaderiv(shaderID, GL_COMPILE_STATUS, &success); + if( !success ) + { + int maxSize = 0; + glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH, &maxSize); + + auto infoBuffer = (char*) malloc(maxSize); + + int infoSize = 0; + glGetShaderInfoLog(shaderID, maxSize, &infoSize, infoBuffer); + if( infoSize > 0 ) + { + fprintf(stderr, "%s", infoBuffer); + OutputDebugStringA(infoBuffer); + } + + glDeleteShader(shaderID); + return 0; + } + + return shaderID; + } +}; + + + +Renderer* createGLRenderer() +{ + return new GLRenderer(); +} + +} // renderer_test diff --git a/tools/render-test/render-gl.h b/tools/render-test/render-gl.h new file mode 100644 index 000000000..4e6de970c --- /dev/null +++ b/tools/render-test/render-gl.h @@ -0,0 +1,10 @@ +// render-d3d11.h +#pragma once + +namespace renderer_test { + +class Renderer; + +Renderer* createGLRenderer(); + +} // renderer_test diff --git a/tools/render-test/render-test.vcxproj b/tools/render-test/render-test.vcxproj new file mode 100644 index 000000000..dfe610681 --- /dev/null +++ b/tools/render-test/render-test.vcxproj @@ -0,0 +1,170 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + {96610759-07B9-4EEB-A974-5C634A2E742B} + Win32Proj + rendertest + 8.1 + + + + Application + true + v140 + Unicode + + + Application + false + v140 + true + Unicode + + + Application + true + v140 + Unicode + + + Application + false + v140 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + + + + true + $(SolutionDir);$(IncludePath) + + + true + $(SolutionDir);$(IncludePath) + + + false + $(SolutionDir);$(IncludePath) + + + false + $(SolutionDir);$(IncludePath) + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + + + Console + true + + + + + + + Level3 + Disabled + _DEBUG;_WINDOWS;%(PreprocessorDefinitions) + + + Console + true + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + + + Console + true + true + true + + + + + Level3 + + + MaxSpeed + true + true + NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + + + Console + true + true + true + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tools/render-test/render-test.vcxproj.filters b/tools/render-test/render-test.vcxproj.filters new file mode 100644 index 000000000..6e0ff295a --- /dev/null +++ b/tools/render-test/render-test.vcxproj.filters @@ -0,0 +1,54 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + \ No newline at end of file diff --git a/tools/render-test/render.h b/tools/render-test/render.h new file mode 100644 index 000000000..a30bf98f9 --- /dev/null +++ b/tools/render-test/render.h @@ -0,0 +1,118 @@ +// render.h +#pragma once + +#include "options.h" +#include "window.h" + +namespace renderer_test { + +typedef struct Buffer Buffer; +typedef struct InputLayout InputLayout; +typedef struct ShaderProgram ShaderProgram; + +struct ShaderCompileRequest +{ + struct SourceInfo + { + char const* path; + char const* text; + }; + + struct EntryPoint + { + char const* name; + char const* profile; + + SourceInfo source; + }; + + SourceInfo source; + EntryPoint vertexShader; + EntryPoint fragmentShader; +}; + +class ShaderCompiler +{ +public: + virtual ShaderProgram* compileProgram(ShaderCompileRequest const& request) = 0; +}; + +enum class Format +{ + Unknown, + RGB_Float32, +}; + +enum class BufferFlavor +{ + Constant, + Vertex, +}; + +struct BufferDesc +{ + UInt size = 0; + BufferFlavor flavor = BufferFlavor::Constant; + void const* initData = nullptr; +}; + +struct InputElementDesc +{ + char const* semanticName; + UInt semanticIndex; + Format format; + UInt offset; +}; + +enum class MapFlavor +{ + WriteDiscard, +}; + +enum class PrimitiveTopology +{ + TriangleList, +}; + +class Renderer +{ +public: + virtual void initialize(void* inWindowHandle) = 0; + + virtual void clearFrame() = 0; + virtual void presentFrame() = 0; + + virtual void captureScreenShot(char const* outputPath) = 0; + + virtual Buffer* createBuffer(BufferDesc const& desc) = 0; + + virtual InputLayout* createInputLayout(InputElementDesc const* inputElements, UInt inputElementCount) = 0; + + virtual ShaderCompiler* getShaderCompiler() = 0; + + virtual void* map(Buffer* buffer, MapFlavor flavor) = 0; + virtual void unmap(Buffer* buffer) = 0; + + virtual void setInputLayout(InputLayout* inputLayout) = 0; + virtual void setPrimitiveTopology(PrimitiveTopology topology) = 0; + + virtual void setVertexBuffers(UInt startSlot, UInt slotCount, Buffer* const* buffers, UInt const* strides, UInt const* offsets) = 0; + + inline void setVertexBuffer(UInt slot, Buffer* buffer, UInt stride, UInt offset = 0) + { + setVertexBuffers(slot, 1, &buffer, &stride, &offset); + } + + virtual void setShaderProgram(ShaderProgram* program) = 0; + + virtual void setConstantBuffers(UInt startSlot, UInt slotCount, Buffer* const* buffers, UInt const* offsets) = 0; + + inline void setConstantBuffer(UInt slot, Buffer* buffer, UInt offset = 0) + { + setConstantBuffers(slot, 1, &buffer, &offset); + } + + virtual void draw(UInt vertexCount, UInt startVertex = 0) = 0; +}; + +} // renderer_test diff --git a/tools/render-test/slang-support.cpp b/tools/render-test/slang-support.cpp new file mode 100644 index 000000000..5aafc562e --- /dev/null +++ b/tools/render-test/slang-support.cpp @@ -0,0 +1,84 @@ +// slang-support.cpp + +#define SLANG_INCLUDE_IMPLEMENTATION + +#include "slang-support.h" + +#include + +namespace renderer_test { + +struct SlangShaderCompilerWrapper : public ShaderCompiler +{ + ShaderCompiler* innerCompiler; + SlangCompileTarget target; + + virtual ShaderProgram* compileProgram(ShaderCompileRequest const& request) override + { + SlangSession* slangSession = spCreateSession(NULL); + SlangCompileRequest* slangRequest = spCreateCompileRequest(slangSession); + + spSetCodeGenTarget(slangRequest, target); + + int translationUnitIndex = spAddTranslationUnit(slangRequest, SLANG_SOURCE_LANGUAGE_SLANG, nullptr); + + spAddTranslationUnitSourceString(slangRequest, translationUnitIndex, request.source.path, request.source.text); + + int vertexEntryPoint = spAddTranslationUnitEntryPoint(slangRequest, translationUnitIndex, request.vertexShader.name, spFindProfile(slangSession, request.vertexShader.profile)); + int fragmentEntryPoint = spAddTranslationUnitEntryPoint(slangRequest, translationUnitIndex, request.fragmentShader.name, spFindProfile(slangSession, request.fragmentShader.profile)); + + int compileErr = spCompile(slangRequest); + if(auto diagnostics = spGetDiagnosticOutput(slangRequest)) + { + // TODO(tfoley): re-enable when I get a logging solution in place +// OutputDebugStringA(diagnostics); + fprintf(stderr, "%s", diagnostics); + } + if(compileErr) + { + return nullptr; + } + + char const* translatedCode = spGetTranslationUnitSource(slangRequest, translationUnitIndex); + char const* vertexCode = spGetEntryPointSource(slangRequest, translationUnitIndex, vertexEntryPoint); + char const* fragmentCode = spGetEntryPointSource(slangRequest, translationUnitIndex, fragmentEntryPoint); + + ShaderCompileRequest innerRequest = request; + innerRequest.source.text = translatedCode; + innerRequest.vertexShader.source.text = vertexCode; + innerRequest.fragmentShader.source.text = fragmentCode; + + + auto result = innerCompiler->compileProgram(innerRequest); + + // We clean up the Slang compilation context and result *after* + // we have run the downstream compiler, because Slang + // owns the memory allocation for the generated text, and will + // free it when we destroy the compilation result. + spDestroyCompileRequest(slangRequest); + spDestroySession(slangSession); + + return result; + } +}; + +ShaderCompiler* createSlangShaderCompiler(ShaderCompiler* innerCompiler, SlangCompileTarget target) +{ + auto result = new SlangShaderCompilerWrapper(); + result->innerCompiler = innerCompiler; + result->target = target; + + return result; + +} + + +} // renderer_test + +// +// In order to actually use Slang in our application, we need to link in its +// implementation. The easiest way to accomplish this is by directly inlcuding +// the (concatenated) Slang source code into our app. +// + +#include diff --git a/tools/render-test/slang-support.h b/tools/render-test/slang-support.h new file mode 100644 index 000000000..a191fbfef --- /dev/null +++ b/tools/render-test/slang-support.h @@ -0,0 +1,12 @@ +// slang-support.h +#pragma once + +#include "render.h" + +#include + +namespace renderer_test { + +ShaderCompiler* createSlangShaderCompiler(ShaderCompiler* innerCompiler, SlangCompileTarget target); + +} // renderer_test diff --git a/tools/render-test/window.h b/tools/render-test/window.h new file mode 100644 index 000000000..5d0a89ee4 --- /dev/null +++ b/tools/render-test/window.h @@ -0,0 +1,10 @@ +// window.h +#pragma once + +namespace renderer_test { + +typedef struct Window Window; + +Window* createWindow(); + +} // renderer_test diff --git a/tools/slang-test/main.cpp b/tools/slang-test/main.cpp new file mode 100644 index 000000000..d8a04a050 --- /dev/null +++ b/tools/slang-test/main.cpp @@ -0,0 +1,1030 @@ +// main.cpp + +#include "../../source/core/slang-io.h" + +using namespace CoreLib::Basic; +using namespace CoreLib::IO; + +#include "os.h" + +#define STB_IMAGE_IMPLEMENTATION +#include "external/stb/stb_image.h" + + +#ifdef _WIN32 +#define SLANG_TEST_SUPPORT_HLSL 1 +#include +#endif + +#include +#include +#include +#include +#include + +struct Options +{ + char const* appName = "slang-test"; + + // Directory to use when looking for binaries to run + char const* binDir = ""; + + // only run test cases with names that have this prefix + char const* testPrefix = nullptr; + + // generate extra output (notably: command lines we run) + bool shouldBeVerbose = false; + + // force generation of baselines for HLSL tests + bool generateHLSLBaselines = false; +}; +Options options; + +void parseOptions(int* argc, char** argv) +{ + int argCount = *argc; + char const* const* argCursor = argv; + char const* const* argEnd = argCursor + argCount; + + char const** writeCursor = (char const**) argv; + + // first argument is the application name + if( argCursor != argEnd ) + { + options.appName = *argCursor++; + } + + // now iterate over arguments to collect options + while(argCursor != argEnd) + { + char const* arg = *argCursor++; + if( arg[0] != '-' ) + { + *writeCursor++ = arg; + continue; + } + + if( strcmp(arg, "--") == 0 ) + { + while(argCursor != argEnd) + { + char const* arg = *argCursor++; + *writeCursor++ = arg; + } + break; + } + + if( strcmp(arg, "--bindir") == 0 ) + { + if( argCursor == argEnd ) + { + fprintf(stderr, "error: expected operand for '%s'\n", arg); + exit(1); + } + options.binDir = *argCursor++; + } + else if( strcmp(arg, "-v") == 0 ) + { + options.shouldBeVerbose = true; + } + else if( strcmp(arg, "-generate-hlsl-baselines") == 0 ) + { + options.generateHLSLBaselines = true; + } + else if( strcmp(arg, "-release") == 0 ) + { + // Assumed to be handle by .bat file that called us + } + else if( strcmp(arg, "-debug") == 0 ) + { + // Assumed to be handle by .bat file that called us + } + else + { + fprintf(stderr, "unknown option '%s'\n", arg); + exit(1); + } + } + + // any arguments left over were positional arguments + argCount = (int)(writeCursor - argv); + argCursor = argv; + argEnd = argCursor + argCount; + + // first positional argument is a "filter" to apply + if( argCursor != argEnd ) + { + options.testPrefix = *argCursor++; + } + + // any remaining arguments represent an error + if(argCursor != argEnd) + { + fprintf(stderr, "unexpected arguments\n"); + exit(1); + } + + *argc = 0; +} + +// Called for an error in the test-runner (not for an error involving +// a test itself). +void error(char const* message, ...) +{ + fprintf(stderr, "error: "); + + va_list args; + va_start(args, message); + vfprintf(stderr, message, args); + va_end(args); + + fprintf(stderr, "\n"); +} + +enum TestResult +{ + kTestResult_Fail, + kTestResult_Pass, + kTestResult_Ignored, +}; + +bool match(char const** ioCursor, char const* expected) +{ + char const* cursor = *ioCursor; + while(*expected && *cursor == *expected) + { + cursor++; + expected++; + } + if(*expected != 0) return false; + + *ioCursor = cursor; + return true; +} + +void skipHorizontalSpace(char const** ioCursor) +{ + char const* cursor = *ioCursor; + for( ;;) + { + switch( *cursor ) + { + case ' ': + case '\t': + cursor++; + continue; + + default: + break; + } + + break; + } + *ioCursor = cursor; +} + +void skipToEndOfLine(char const** ioCursor) +{ + char const* cursor = *ioCursor; + for( ;;) + { + int c = *cursor; + switch( c ) + { + default: + cursor++; + continue; + + case '\r': case '\n': + { + cursor++; + int d = *cursor; + if( (c ^ d) == ('\r' ^ '\n') ) + { + cursor++; + } + } + // fall through to: + case 0: + *ioCursor = cursor; + return; + } + } +} + +String getString(char const* textBegin, char const* textEnd) +{ + StringBuilder sb; + sb.Append(textBegin, textEnd - textBegin); + return sb.ProduceString(); +} + +String collectRestOfLine(char const** ioCursor) +{ + char const* cursor = *ioCursor; + + char const* textBegin = cursor; + skipToEndOfLine(&cursor); + char const* textEnd = cursor; + + *ioCursor = cursor; + return getString(textBegin, textEnd); +} + +// Optiosn for a particular test +struct TestOptions +{ + String command; + List args; +}; + +// Information on tests to run for a particular file +struct FileTestList +{ + List tests; +}; + +TestResult gatherTestOptions( + char const** ioCursor, + FileTestList* testList) +{ + char const* cursor = *ioCursor; + + // Start by scanning for the sub-command name: + char const* commandStart = cursor; + for(;;) + { + switch(*cursor) + { + default: + cursor++; + continue; + + case ':': + break; + + case 0: case '\r': case '\n': + return kTestResult_Fail; + } + + break; + } + char const* commandEnd = cursor; + if(*cursor == ':') + cursor++; + + TestOptions testOptions; + testOptions.command = getString(commandStart, commandEnd); + + // Now scan for arguments. For now we just assume that + // any whitespace separation indicates a new argument + // (we don't support quoting) + for(;;) + { + skipHorizontalSpace(&cursor); + + // End of line? then no more options. + switch( *cursor ) + { + case 0: case '\r': case '\n': + skipToEndOfLine(&cursor); + testList->tests.Add(testOptions); + return kTestResult_Pass; + + default: + break; + } + + // Let's try to read one option + char const* argBegin = cursor; + for(;;) + { + switch( *cursor ) + { + default: + cursor++; + continue; + + case 0: case '\r': case '\n': case ' ': case '\t': + break; + } + + break; + } + char const* argEnd = cursor; + assert(argBegin != argEnd); + + testOptions.args.Add(getString(argBegin, argEnd)); + } +} + +// Try to read command-line options from the test file itself +TestResult gatherTestsForFile( + String filePath, + FileTestList* testList) +{ + String fileContents; + try + { + fileContents = CoreLib::IO::File::ReadAllText(filePath); + } + catch (CoreLib::IO::IOException) + { + return kTestResult_Fail; + } + + + // Walk through the lines of the file, looking for test commands + char const* cursor = fileContents.begin(); + + while(*cursor) + { + // We are at the start of a line of input. + + skipHorizontalSpace(&cursor); + + // Look for a pattern that matches what we want + if(match(&cursor, "//TEST:")) + { + if(gatherTestOptions(&cursor, testList) != kTestResult_Pass) + return kTestResult_Fail; + } + else if(match(&cursor, "//TEST_IGNORE_FILE")) + { + return kTestResult_Ignored; + } + else + { + skipToEndOfLine(&cursor); + } + } + + return kTestResult_Pass; +} + +OSError spawnAndWait(String testPath, OSProcessSpawner& spawner) +{ + if( options.shouldBeVerbose ) + { + fprintf(stderr, "%s\n", spawner.commandLine_.Buffer()); + } + + OSError err = spawner.spawnAndWaitForCompletion(); + if (err != kOSError_None) + { + error("failed to run test '%S'", testPath.ToWString()); + } + return err; +} + +String getOutput(OSProcessSpawner& spawner) +{ + OSProcessSpawner::ResultCode resultCode = spawner.getResultCode(); + + String standardOuptut = spawner.getStandardOutput(); + String standardError = spawner.getStandardError(); + + // We construct a single output string that captures the results + StringBuilder actualOutputBuilder; + actualOutputBuilder.Append("result code = "); + actualOutputBuilder.Append(resultCode); + actualOutputBuilder.Append("\nstandard error = {\n"); + actualOutputBuilder.Append(standardError); + actualOutputBuilder.Append("}\nstandard output = {\n"); + actualOutputBuilder.Append(standardOuptut); + actualOutputBuilder.Append("}\n"); + + return actualOutputBuilder.ProduceString(); +} + +struct TestInput +{ + String filePath; + TestOptions const* testOptions; + FileTestList const* testList; +}; + +typedef TestResult (*TestCallback)(TestInput& input); + +TestResult runSimpleTest(TestInput& input) +{ + // need to execute the stand-alone Slang compiler on the file, and compare its output to what we expect + + auto filePath = input.filePath; + + OSProcessSpawner spawner; + + spawner.pushExecutableName(String(options.binDir) + "slangc.exe"); + spawner.pushArgument(filePath); + + for( auto arg : input.testOptions->args ) + { + spawner.pushArgument(arg); + } + + if (spawnAndWait(filePath, spawner) != kOSError_None) + { + return kTestResult_Fail; + } + + String actualOutput = getOutput(spawner); + + String expectedOutputPath = filePath + ".expected"; + String expectedOutput; + try + { + expectedOutput = CoreLib::IO::File::ReadAllText(expectedOutputPath); + } + catch (CoreLib::IO::IOException) + { + } + + // If no expected output file was found, then we + // expect everything to be empty + if (expectedOutput.Length() == 0) + { + expectedOutput = "result code = 0\nstandard error = {\n}\nstandard output = {\n}\n"; + } + + TestResult result = kTestResult_Pass; + + // Otherwise we compare to the expected output + if (actualOutput != expectedOutput) + { + result = kTestResult_Fail; + } + + // If the test failed, then we write the actual output to a file + // so that we can easily diff it from the command line and + // diagnose the problem. + if (result == kTestResult_Fail) + { + String actualOutputPath = filePath + ".actual"; + CoreLib::IO::File::WriteAllText(actualOutputPath, actualOutput); + } + + return result; +} + +#ifdef SLANG_TEST_SUPPORT_HLSL +TestResult generateHLSLBaseline(TestInput& input) +{ + auto filePath = input.filePath; + + OSProcessSpawner spawner; + spawner.pushExecutableName(String(options.binDir) + "slangc.exe"); + spawner.pushArgument(filePath); + + for( auto arg : input.testOptions->args ) + { + spawner.pushArgument(arg); + } + + spawner.pushArgument("-target"); + spawner.pushArgument("dxbc-assembly"); + spawner.pushArgument("-pass-through"); + spawner.pushArgument("fxc"); + + if (spawnAndWait(filePath, spawner) != kOSError_None) + { + return kTestResult_Fail; + } + + String expectedOutput = getOutput(spawner); + String expectedOutputPath = filePath + ".expected"; + try + { + CoreLib::IO::File::WriteAllText(expectedOutputPath, expectedOutput); + } + catch (CoreLib::IO::IOException) + { + return kTestResult_Fail; + } + return kTestResult_Pass; +} + +TestResult runHLSLComparisonTest(TestInput& input) +{ + auto filePath = input.filePath; + + // We will use the Microsoft compiler to generate out expected output here + String expectedOutputPath = filePath + ".expected"; + + // Generate the expected output using standard HLSL compiler + generateHLSLBaseline(input); + + // need to execute the stand-alone Slang compiler on the file, and compare its output to what we expect + + OSProcessSpawner spawner; + + spawner.pushExecutableName(String(options.binDir) + "slangc.exe"); + spawner.pushArgument(filePath); + + for( auto arg : input.testOptions->args ) + { + spawner.pushArgument(arg); + } + + // TODO: The compiler should probably define this automatically... + spawner.pushArgument("-D"); + spawner.pushArgument("__SLANG__"); + + spawner.pushArgument("-target"); + spawner.pushArgument("dxbc-assembly"); + + if (spawnAndWait(filePath, spawner) != kOSError_None) + { + return kTestResult_Fail; + } + + // We ignore output to stdout, and only worry about what the compiler + // wrote to stderr. + + OSProcessSpawner::ResultCode resultCode = spawner.getResultCode(); + + String standardOuptut = spawner.getStandardOutput(); + String standardError = spawner.getStandardError(); + + // We construct a single output string that captures the results + StringBuilder actualOutputBuilder; + actualOutputBuilder.Append("result code = "); + actualOutputBuilder.Append(resultCode); + actualOutputBuilder.Append("\nstandard error = {\n"); + actualOutputBuilder.Append(standardError); + actualOutputBuilder.Append("}\nstandard output = {\n"); + actualOutputBuilder.Append(standardOuptut); + actualOutputBuilder.Append("}\n"); + + String actualOutput = actualOutputBuilder.ProduceString(); + + String expectedOutput; + try + { + expectedOutput = CoreLib::IO::File::ReadAllText(expectedOutputPath); + } + catch (CoreLib::IO::IOException) + { + } + + TestResult result = kTestResult_Pass; + + // If no expected output file was found, then we + // expect everything to be empty + if (expectedOutput.Length() == 0) + { + if (resultCode != 0) result = kTestResult_Fail; + if (standardError.Length() != 0) result = kTestResult_Fail; + if (standardOuptut.Length() != 0) result = kTestResult_Fail; + } + // Otherwise we compare to the expected output + else if (actualOutput != expectedOutput) + { + result = kTestResult_Fail; + } + + // If the test failed, then we write the actual output to a file + // so that we can easily diff it from the command line and + // diagnose the problem. + if (result == kTestResult_Fail) + { + String actualOutputPath = filePath + ".actual"; + CoreLib::IO::File::WriteAllText(actualOutputPath, actualOutput); + } + + return result; +} +#endif + +TestResult doGLSLComparisonTestRun( + TestInput& input, + char const* langDefine, + char const* passThrough, + char const* outputKind, + String* outOutput) +{ + auto filePath = input.filePath; + + OSProcessSpawner spawner; + + spawner.pushExecutableName(String(options.binDir) + "slangc.exe"); + spawner.pushArgument(filePath); + + if( langDefine ) + { + spawner.pushArgument("-D"); + spawner.pushArgument(langDefine); + } + + if( passThrough ) + { + spawner.pushArgument("-pass-through"); + spawner.pushArgument(passThrough); + } + + spawner.pushArgument("-no-checking"); + + spawner.pushArgument("-target"); + spawner.pushArgument("spirv-assembly"); + + for( auto arg : input.testOptions->args ) + { + spawner.pushArgument(arg); + } + + if (spawnAndWait(filePath, spawner) != kOSError_None) + { + return kTestResult_Fail; + } + + OSProcessSpawner::ResultCode resultCode = spawner.getResultCode(); + + String standardOuptut = spawner.getStandardOutput(); + String standardError = spawner.getStandardError(); + + // We construct a single output string that captures the results + StringBuilder outputBuilder; + outputBuilder.Append("result code = "); + outputBuilder.Append(resultCode); + outputBuilder.Append("\nstandard error = {\n"); + outputBuilder.Append(standardError); + outputBuilder.Append("}\nstandard output = {\n"); + outputBuilder.Append(standardOuptut); + outputBuilder.Append("}\n"); + + String outputPath = filePath + outputKind; + String output = outputBuilder.ProduceString(); + + *outOutput = output; + + return kTestResult_Pass; +} + +TestResult runGLSLComparisonTest(TestInput& input) +{ + auto filePath = input.filePath; + + String expectedOutput; + String actualOutput; + + TestResult hlslResult = doGLSLComparisonTestRun(input, "__GLSL__", "glslang", ".expected", &expectedOutput); + TestResult slangResult = doGLSLComparisonTestRun(input, "__SLANG__", nullptr, ".actual", &actualOutput); + + CoreLib::IO::File::WriteAllText(filePath + ".expected", expectedOutput); + CoreLib::IO::File::WriteAllText(filePath + ".actual", actualOutput); + + if( hlslResult == kTestResult_Fail ) return kTestResult_Fail; + if( slangResult == kTestResult_Fail ) return kTestResult_Fail; + + if (actualOutput != expectedOutput) + { + return kTestResult_Fail; + } + + return kTestResult_Pass; +} + + + +TestResult doRenderComparisonTestRun(TestInput& input, char const* langOption, char const* outputKind, String* outOutput) +{ + // TODO: delete any existing files at the output path(s) to avoid stale outputs leading to a false pass + + auto filePath = input.filePath; + + OSProcessSpawner spawner; + + spawner.pushExecutableName(String(options.binDir) + "render-test.exe"); + spawner.pushArgument(filePath); + + for( auto arg : input.testOptions->args ) + { + spawner.pushArgument(arg); + } + + spawner.pushArgument(langOption); + spawner.pushArgument("-o"); + spawner.pushArgument(filePath + outputKind + ".png"); + + if (spawnAndWait(filePath, spawner) != kOSError_None) + { + return kTestResult_Fail; + } + + OSProcessSpawner::ResultCode resultCode = spawner.getResultCode(); + + String standardOuptut = spawner.getStandardOutput(); + String standardError = spawner.getStandardError(); + + // We construct a single output string that captures the results + StringBuilder outputBuilder; + outputBuilder.Append("result code = "); + outputBuilder.Append(resultCode); + outputBuilder.Append("\nstandard error = {\n"); + outputBuilder.Append(standardError); + outputBuilder.Append("}\nstandard output = {\n"); + outputBuilder.Append(standardOuptut); + outputBuilder.Append("}\n"); + + String outputPath = filePath + outputKind; + String output = outputBuilder.ProduceString(); + + *outOutput = output; + + return kTestResult_Pass; +} + +TestResult doImageComparison(String const& filePath) +{ + // Allow a difference in the low bits of the 8-bit result, just to play it safe + static const int kAbsoluteDiffCutoff = 2; + + // Allow a relatie 1% difference + static const float kRelativeDiffCutoff = 0.01f; + + String expectedPath = filePath + ".expected.png"; + String actualPath = filePath + ".actual.png"; + + int expectedX, expectedY, expectedN; + int actualX, actualY, actualN; + + + unsigned char* expectedData = stbi_load(expectedPath.begin(), &expectedX, &expectedY, &expectedN, 0); + unsigned char* actualData = stbi_load(actualPath.begin(), &actualX, &actualY, &actualN, 0); + + if(!expectedData) return kTestResult_Fail; + if(!actualData) return kTestResult_Fail; + + if(expectedX != actualX) return kTestResult_Fail; + if(expectedY != actualY) return kTestResult_Fail; + if(expectedN != actualN) return kTestResult_Fail; + + unsigned char* expectedCursor = expectedData; + unsigned char* actualCursor = actualData; + + for( int y = 0; y < actualY; ++y ) + for( int x = 0; x < actualX; ++x ) + for( int n = 0; n < actualN; ++n ) + { + int expectedVal = *expectedCursor++; + int actualVal = *actualCursor++; + + int absoluteDiff = actualVal - expectedVal; + if(absoluteDiff < 0) absoluteDiff = -absoluteDiff; + + if( absoluteDiff < kAbsoluteDiffCutoff ) + { + // There might be a difference, but we'll consider it to be inside tolerance + continue; + } + + if( expectedVal != 0 ) + { + float relativeDiff = fabsf(float(actualVal) - float(expectedVal)) / float(expectedVal); + + if( relativeDiff < kRelativeDiffCutoff ) + { + // relative difference was small enough + continue; + } + } + + // TODO: may need to do some local search sorts of things, to deal with + // cases where vertex shader results lead to rendering that is off + // by one pixel... + + // There was a difference we couldn't excuse! + return kTestResult_Fail; + } + + return kTestResult_Pass; +} + +TestResult runHLSLRenderComparisonTestImpl( + TestInput& input, + char const* expectedArg, + char const* actualArg) +{ + auto filePath = input.filePath; + + String expectedOutput; + String actualOutput; + + TestResult hlslResult = doRenderComparisonTestRun(input, expectedArg, ".expected", &expectedOutput); + TestResult slangResult = doRenderComparisonTestRun(input, actualArg, ".actual", &actualOutput); + + CoreLib::IO::File::WriteAllText(filePath + ".expected", expectedOutput); + CoreLib::IO::File::WriteAllText(filePath + ".actual", actualOutput); + + if( hlslResult == kTestResult_Fail ) return kTestResult_Fail; + if( slangResult == kTestResult_Fail ) return kTestResult_Fail; + + if (actualOutput != expectedOutput) + { + return kTestResult_Fail; + } + + // Next do an image comparison on the expected output images! + + TestResult imageCompareResult = doImageComparison(filePath); + if(imageCompareResult != kTestResult_Pass) + return imageCompareResult; + + return kTestResult_Pass; +} + +TestResult runHLSLRenderComparisonTest(TestInput& input) +{ + return runHLSLRenderComparisonTestImpl(input, "-hlsl", "-slang"); +} + +TestResult runHLSLCrossCompileRenderComparisonTest(TestInput& input) +{ + return runHLSLRenderComparisonTestImpl(input, "-slang", "-glsl-cross"); +} + +TestResult runTest( + String const& filePath, + TestOptions const& testOptions, + FileTestList const& testList) +{ + // based on command name, dispatch to an appropriate callback + static const struct TestCommands + { + char const* name; + TestCallback callback; + } kTestCommands[] = { + { "SIMPLE", &runSimpleTest }, + { "COMPARE_HLSL", &runHLSLComparisonTest }, + { "COMPARE_HLSL_RENDER", &runHLSLRenderComparisonTest }, + { "COMPARE_HLSL_CROSS_COMPILE_RENDER", &runHLSLCrossCompileRenderComparisonTest}, + { "COMPARE_GLSL", &runGLSLComparisonTest }, + { nullptr, nullptr }, + }; + + for( auto ii = kTestCommands; ii->name; ++ii ) + { + if(testOptions.command != ii->name) + continue; + + TestInput testInput; + testInput.filePath = filePath; + testInput.testOptions = &testOptions; + testInput.testList = &testList; + + return ii->callback(testInput); + } + + // No actual test runner found! + + return kTestResult_Fail; +} + + +struct TestContext +{ + int totalTestCount; + int passedTestCount; + int failedTestCount; +}; + +void runTestsOnFile( + TestContext* context, + String filePath) +{ + // Gather a list of tests to run + FileTestList testList; + + if( gatherTestsForFile(filePath, &testList) == kTestResult_Ignored ) + { + // Test was explicitly ignored + return; + } + + // Note cases where a test file exists, but we found nothing to run + if( testList.tests.Count() == 0 ) + { + context->totalTestCount++; + context->failedTestCount++; + + printf("FAILED test: '%S' (no test commands found)\n", filePath.ToWString()); + return; + } + + // We have found a test to run! + int subTestCount = 0; + for( auto& tt : testList.tests ) + { + context->totalTestCount++; + + int subTestIndex = subTestCount++; + + TestResult result = runTest(filePath, tt, testList); + if(result == kTestResult_Ignored) + return; + + if (result == kTestResult_Pass) + { + printf("passed"); + context->passedTestCount++; + } + else + { + printf("FAILED"); + context->failedTestCount++; + } + + printf(" test: '%S'", filePath.ToWString()); + if( subTestIndex ) + { + printf(" subtest:%d", subTestIndex); + } + printf("\n"); + } +} + + +static bool endsWithAllowedExtension( + TestContext* context, + String filePath) +{ + char const* allowedExtensions[] = { + ".slang", + ".hlsl", + ".fx", + ".glsl", + ".vert", + ".frag", + ".geom", + ".tesc", + ".tese", + ".comp", + nullptr }; + + for( auto ii = allowedExtensions; *ii; ++ii ) + { + if(filePath.EndsWith(*ii)) + return true; + } + + return false; +} + +static bool shouldRunTest( + TestContext* context, + String filePath) +{ + if(!endsWithAllowedExtension(context, filePath)) + return false; + + if( options.testPrefix ) + { + if( strncmp(options.testPrefix, filePath.begin(), strlen(options.testPrefix)) != 0 ) + { + return false; + } + } + + return true; +} + +void runTestsInDirectory( + TestContext* context, + String directoryPath) +{ + for (auto file : osFindFilesInDirectory(directoryPath)) + { + if( shouldRunTest(context, file) ) + { + runTestsOnFile(context, file); + } + } + for (auto subdir : osFindChildDirectories(directoryPath)) + { + runTestsInDirectory(context, subdir); + } +} + +// + +int main( + int argc, + char** argv) +{ + parseOptions(&argc, argv); + + TestContext context = { 0 }; + + // Enumerate test files according to policy + // TODO: add more directories to this list + // TODO: allow for a command-line argument to select a particular directory + runTestsInDirectory(&context, "tests/"); + + if (!context.totalTestCount) + { + printf("no tests run\n"); + return 0; + } + + printf("\n===\n%d%% of tests passed (%d/%d)\n===\n\n", (context.passedTestCount*100) / context.totalTestCount, context.passedTestCount, context.totalTestCount); + return context.passedTestCount == context.totalTestCount ? 0 : 1; +} diff --git a/tools/slang-test/os.cpp b/tools/slang-test/os.cpp new file mode 100644 index 000000000..8f5172ae6 --- /dev/null +++ b/tools/slang-test/os.cpp @@ -0,0 +1,370 @@ +// os.cpp +#include "os.h" + +#include +#include +#include + +using namespace CoreLib::Basic; + +// Platform-specific code follows + +#ifdef _WIN32 + +#include + +static bool advance(OSFindFilesResult& result) +{ + return FindNextFileW(result.findHandle_, &result.fileData_) != 0; +} + +static bool adjustToValidResult(OSFindFilesResult& result) +{ + for (;;) + { + if ((result.fileData_.dwFileAttributes & result.requiredMask_) != result.requiredMask_) + goto skip; + + if ((result.fileData_.dwFileAttributes & result.disallowedMask_) != 0) + goto skip; + + if (wcscmp(result.fileData_.cFileName, L".") == 0) + goto skip; + + if (wcscmp(result.fileData_.cFileName, L"..") == 0) + goto skip; + + result.filePath_ = result.directoryPath_ + String::FromWString(result.fileData_.cFileName); + if (result.fileData_.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + result.filePath_ = result.filePath_ + "/"; + + return true; + + skip: + if (!advance(result)) + return false; + } +} + + +bool OSFindFilesResult::findNextFile() +{ + if (!advance(*this)) return false; + return adjustToValidResult(*this); +} + +OSFindFilesResult osFindFilesInDirectoryMatchingPattern( + CoreLib::Basic::String directoryPath, + CoreLib::Basic::String pattern) +{ + // TODO: add separator to end of directory path if needed + + String searchPath = directoryPath + pattern; + + OSFindFilesResult result; + HANDLE findHandle = FindFirstFileW( + searchPath.ToWString(), + &result.fileData_); + + result.directoryPath_ = directoryPath; + result.findHandle_ = findHandle; + result.requiredMask_ = 0; + result.disallowedMask_ = FILE_ATTRIBUTE_DIRECTORY; + + if (findHandle == INVALID_HANDLE_VALUE) + { + result.findHandle_ = NULL; + result.error_ = kOSError_FileNotFound; + return result; + } + + result.error_ = kOSError_None; + if (!adjustToValidResult(result)) + { + result.findHandle_ = NULL; + } + return result; +} + +OSFindFilesResult osFindFilesInDirectory( + CoreLib::Basic::String directoryPath) +{ + return osFindFilesInDirectoryMatchingPattern(directoryPath, "*"); +} + +OSFindFilesResult osFindChildDirectories( + CoreLib::Basic::String directoryPath) +{ + // TODO: add separator to end of directory path if needed + + String searchPath = directoryPath + "*"; + + OSFindFilesResult result; + HANDLE findHandle = FindFirstFileW( + searchPath.ToWString(), + &result.fileData_); + + result.directoryPath_ = directoryPath; + result.findHandle_ = findHandle; + result.requiredMask_ = FILE_ATTRIBUTE_DIRECTORY; + result.disallowedMask_ = 0; + + if (findHandle == INVALID_HANDLE_VALUE) + { + result.findHandle_ = NULL; + result.error_ = kOSError_FileNotFound; + return result; + } + + result.error_ = kOSError_None; + if (!adjustToValidResult(result)) + { + result.findHandle_ = NULL; + } + return result; +} + +// OSProcessSpawner + +struct OSProcessSpawner_ReaderThreadInfo +{ + HANDLE file; + String output; +}; + +static DWORD WINAPI osReaderThreadProc(LPVOID threadParam) +{ + OSProcessSpawner_ReaderThreadInfo* info = (OSProcessSpawner_ReaderThreadInfo*)threadParam; + HANDLE file = info->file; + + static const int kChunkSize = 1024; + char buffer[kChunkSize]; + + StringBuilder outputBuilder; + + // We need to re-write the output to deal with line + // endings, so we check for paired '\r' and '\n' + // characters, which may span chunks. + int prevChar = -1; + + for (;;) + { + DWORD bytesRead = 0; + BOOL readResult = ReadFile(file, buffer, kChunkSize, &bytesRead, nullptr); + + if (!readResult || GetLastError() == ERROR_BROKEN_PIPE) + { + break; + } + + // walk the buffer and rewrite to eliminate '\r' '\n' pairs + char* readCursor = buffer; + char const* end = buffer + bytesRead; + char* writeCursor = buffer; + + while (readCursor != end) + { + int p = prevChar; + int c = *readCursor++; + prevChar = c; + switch (c) + { + case '\r': case '\n': + // swallow input if '\r' and '\n' appear in sequence + if ((p ^ c) == ('\r' ^ '\n')) + { + // but don't swallow the next byte + prevChar = -1; + continue; + } + // always replace '\r' with '\n' + c = '\n'; + break; + + default: + break; + } + + *writeCursor++ = c; + } + bytesRead = (DWORD)(writeCursor - buffer); + + // Note: Current Slang CoreLib gives no way to know + // the length of the buffer, so we ultimately have + // to just assume null termination... + outputBuilder.Append(buffer, bytesRead); + } + + info->output = outputBuilder.ProduceString(); + + return 0; +} + +void OSProcessSpawner::pushExecutableName( + CoreLib::Basic::String executableName) +{ + executableName_ = executableName; + commandLine_.Append(executableName); +} + +void OSProcessSpawner::pushArgument( + CoreLib::Basic::String argument) +{ + // TODO(tfoley): handle cases where arguments need some escaping + commandLine_.Append(" "); + commandLine_.Append(argument); +} + +OSError OSProcessSpawner::spawnAndWaitForCompletion() +{ + SECURITY_ATTRIBUTES securityAttributes; + securityAttributes.nLength = sizeof(securityAttributes); + securityAttributes.lpSecurityDescriptor = nullptr; + securityAttributes.bInheritHandle = true; + + // create stdout pipe for child process + HANDLE childStdOutReadTmp = nullptr; + HANDLE childStdOutWrite = nullptr; + if (!CreatePipe(&childStdOutReadTmp, &childStdOutWrite, &securityAttributes, 0)) + { + return kOSError_OperationFailed; + } + + // create stderr pipe for child process + HANDLE childStdErrReadTmp = nullptr; + HANDLE childStdErrWrite = nullptr; + if (!CreatePipe(&childStdErrReadTmp, &childStdErrWrite, &securityAttributes, 0)) + { + return kOSError_OperationFailed; + } + + // create stdin pipe for child process + HANDLE childStdInRead = nullptr; + HANDLE childStdInWriteTmp = nullptr; + if (!CreatePipe(&childStdInRead, &childStdInWriteTmp, &securityAttributes, 0)) + { + return kOSError_OperationFailed; + } + + HANDLE currentProcess = GetCurrentProcess(); + + // create a non-inheritable duplicate of the stdout reader + HANDLE childStdOutRead = nullptr; + if (!DuplicateHandle( + currentProcess, childStdOutReadTmp, + currentProcess, &childStdOutRead, + 0, FALSE, DUPLICATE_SAME_ACCESS)) + { + return kOSError_OperationFailed; + } + if (!CloseHandle(childStdOutReadTmp)) + { + return kOSError_OperationFailed; + } + + // create a non-inheritable duplicate of the stderr reader + HANDLE childStdErrRead = nullptr; + if (!DuplicateHandle( + currentProcess, childStdErrReadTmp, + currentProcess, &childStdErrRead, + 0, FALSE, DUPLICATE_SAME_ACCESS)) + { + return kOSError_OperationFailed; + } + if (!CloseHandle(childStdErrReadTmp)) + { + return kOSError_OperationFailed; + } + + // create a non-inheritable duplicate of the stdin writer + HANDLE childStdInWrite = nullptr; + if (!DuplicateHandle( + currentProcess, childStdInWriteTmp, + currentProcess, &childStdInWrite, + 0, FALSE, DUPLICATE_SAME_ACCESS)) + { + return kOSError_OperationFailed; + } + if (!CloseHandle(childStdInWriteTmp)) + { + return kOSError_OperationFailed; + } + + // Now we can actually get around to starting a process + PROCESS_INFORMATION processInfo; + ZeroMemory(&processInfo, sizeof(processInfo)); + + // TODO: switch to proper wide-character versions of these... + STARTUPINFOW startupInfo; + ZeroMemory(&startupInfo, sizeof(startupInfo)); + startupInfo.cb = sizeof(startupInfo); + startupInfo.hStdError = childStdErrWrite; + startupInfo.hStdOutput = childStdOutWrite; + startupInfo.hStdInput = childStdInRead; + startupInfo.dwFlags = STARTF_USESTDHANDLES; + + // `CreateProcess` requires write access to this, for some reason... + BOOL success = CreateProcessW( + executableName_.ToWString(), + (LPWSTR)commandLine_.ToString().ToWString(), + nullptr, + nullptr, + true, + CREATE_NO_WINDOW, + nullptr, // TODO: allow specifying environment variables? + nullptr, + &startupInfo, + &processInfo); + if (!success) + { + return kOSError_OperationFailed; + } + + // close handles we are now done with + CloseHandle(processInfo.hThread); + CloseHandle(childStdOutWrite); + CloseHandle(childStdErrWrite); + CloseHandle(childStdInRead); + + // Create a thread to read from the child's stdout. + OSProcessSpawner_ReaderThreadInfo stdOutThreadInfo; + stdOutThreadInfo.file = childStdOutRead; + HANDLE stdOutThread = CreateThread(nullptr, 0, &osReaderThreadProc, (LPVOID)&stdOutThreadInfo, 0, nullptr); + + // Create a thread to read from the child's stderr. + OSProcessSpawner_ReaderThreadInfo stdErrThreadInfo; + stdErrThreadInfo.file = childStdErrRead; + HANDLE stdErrThread = CreateThread(nullptr, 0, &osReaderThreadProc, (LPVOID)&stdErrThreadInfo, 0, nullptr); + + // wait for the process to exit + // TODO: set a timeout as a safety measure... + WaitForSingleObject(processInfo.hProcess, INFINITE); + + // get exit code for process + DWORD childExitCode = 0; + if (!GetExitCodeProcess(processInfo.hProcess, &childExitCode)) + { + return kOSError_OperationFailed; + } + + // wait for the reader threads + WaitForSingleObject(stdOutThread, INFINITE); + WaitForSingleObject(stdErrThread, INFINITE); + + CloseHandle(processInfo.hProcess); + CloseHandle(childStdOutRead); + CloseHandle(childStdErrRead); + CloseHandle(childStdInWrite); + + standardOutput_ = stdOutThreadInfo.output; + standardError_ = stdErrThreadInfo.output; + resultCode_ = childExitCode; + + return kOSError_None; +} + +#else + +// TODO(tfoley): write a default POSIX implementation + +#endif diff --git a/tools/slang-test/os.h b/tools/slang-test/os.h new file mode 100644 index 000000000..2996001e7 --- /dev/null +++ b/tools/slang-test/os.h @@ -0,0 +1,160 @@ +// os.h + +#include "../../source/core/slang-io.h" + +// This file encapsulates the platform-specific operations needed by the test +// runner that are not already provided by the core Slang libs + +#ifdef _WIN32 + +// Include Windows header in a way that minimized namespace pollution. +// TODO: We could try to avoid including this at all, but it would +// mean trying to hide certain struct layouts, which would add +// more dynamic allocation. +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#undef WIN32_LEAN_AND_MEAN +#undef NOMINMAX + +#else +#endif + +// A simple set of error codes for possible runtime failures +enum OSError +{ + kOSError_None = 0, + kOSError_InvalidArgument, + kOSError_OperationFailed, + kOSError_FileNotFound, +}; + +// A helper type used during enumeration of files in a directory. +struct OSFindFilesResult +{ + CoreLib::Basic::String directoryPath_; + CoreLib::Basic::String filePath_; +#ifdef WIN32 + HANDLE findHandle_; + WIN32_FIND_DATAW fileData_; + DWORD requiredMask_; + DWORD disallowedMask_; + OSError error_; +#else +#endif + + bool findNextFile(); + + struct Iterator + { + OSFindFilesResult* context_; + + bool operator!=(Iterator other) const { return context_ != other.context_; } + void operator++() + { + if (!context_->findNextFile()) + { + context_ = NULL; + } + } + CoreLib::Basic::String const& operator*() const + { + return context_->filePath_; + } + }; + + Iterator begin() + { +#ifdef WIN32 + Iterator result = { findHandle_ ? this : NULL }; +#else +#endif + return result; + } + + Iterator end() + { + Iterator result = { NULL }; + return result; + } +}; + +// Enumerate subdirectories in the given `directoryPath` and return a logical +// collection of the results that can be iterated with a range-based +// `for` loop: +// +// for( auto subdir : osFindChildDirectories(dir)) +// { ... } +// +// Each element in the range is a `CoreLib::Basic::String` representing the +// path to a subdirecotry of the directory. +OSFindFilesResult osFindChildDirectories( + CoreLib::Basic::String directoryPath); + +// Enumerate files in the given `directoryPath` that match the provided +// `pattern` as a simplified regex for files to return (e.g., "*.txt") +// and return a logical collection of the results +// that can be iterated with a range-based `for` loop: +// +// for( auto file : osFindFilesInDirectoryMatchingPattern(dir, "*.txt")) +// { ... } +// +// Each element in the range is a `CoreLib::Basic::String` representing the +// path to a file in the directory. +OSFindFilesResult osFindFilesInDirectoryMatchingPattern( + CoreLib::Basic::String directoryPath, + CoreLib::Basic::String pattern); + +// Enumerate files in the given `directoryPath` and return a logical +// collection of the results that can be iterated with a range-based +// `for` loop: +// +// for( auto file : osFindFilesInDirectory(dir)) +// { ... } +// +// Each element in the range is a `CoreLib::Basic::String` representing the +// path to a file in the directory. +OSFindFilesResult osFindFilesInDirectory( + CoreLib::Basic::String directoryPath); + + +// An `OSProcessSpawner` can be used to launch a process, and handles +// putting together the arguments in the form required by the target +// platform, as well as capturing any output from the process (both +// standard output and standard error) as strings. +struct OSProcessSpawner +{ + // Set the executable name for the process to be spawned. + // Note: this call must be made before any arguments are pushed. + void pushExecutableName( + CoreLib::Basic::String executableName); + + // Append an argument for the process to be spawned. + void pushArgument( + CoreLib::Basic::String argument); + + // Attempt to spawn the process, and wait for it to complete. + // Returns an error if the attempt to spawn and/or wait fails, + // but returns `kOSError_None` if the process is run to completion, + // whether or not the process returns "successfully" (with a zero + // result code); + OSError spawnAndWaitForCompletion(); + + // If the process is successfully spawned and completes, then + // the user can query the result code that the process produce + // on exit, along with the output it wrote to stdout and stderr. + typedef int ResultCode; + ResultCode getResultCode() { return resultCode_; } + CoreLib::Basic::String const& getStandardOutput() { return standardOutput_; } + CoreLib::Basic::String const& getStandardError() { return standardError_; } + + // "private" data follows + CoreLib::Basic::String standardOutput_; + CoreLib::Basic::String standardError_; + ResultCode resultCode_; +#ifdef WIN32 + CoreLib::Basic::String executableName_; + CoreLib::Basic::StringBuilder commandLine_; +#else +#endif +}; diff --git a/tools/slang-test/slang-test.vcxproj b/tools/slang-test/slang-test.vcxproj new file mode 100644 index 000000000..b8d23d569 --- /dev/null +++ b/tools/slang-test/slang-test.vcxproj @@ -0,0 +1,277 @@ + + + + + Debug_VS2013 + Win32 + + + Debug_VS2013 + x64 + + + Debug + Win32 + + + Release_VS2013 + Win32 + + + Release_VS2013 + x64 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + {0C768A18-1D25-4000-9F37-DA5FE99E3B64} + Win32Proj + SpireTestTool + 8.1 + + + + Application + true + v140 + Unicode + + + Application + false + v140 + true + Unicode + + + Application + false + v140 + true + Unicode + + + Application + true + v140 + Unicode + + + Application + false + v140 + true + Unicode + + + Application + false + v120 + true + Unicode + + + v140 + + + v120 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + $(SolutionDir);$(IncludePath) + + + true + $(SolutionDir);$(IncludePath) + + + false + $(SolutionDir);$(IncludePath) + + + false + $(SolutionDir);$(IncludePath) + + + false + $(SolutionDir);$(IncludePath) + + + false + $(SolutionDir);$(IncludePath) + + + $(SolutionDir);$(IncludePath) + + + $(SolutionDir);$(IncludePath) + + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Console + true + + + + + + + Level3 + Disabled + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Console + true + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreaded + + + Console + true + true + true + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreaded + + + Console + true + true + true + + + + + Level3 + + + MaxSpeed + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreaded + + + Console + true + true + true + + + + + Level3 + + + MaxSpeed + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreaded + + + Console + true + true + true + + + + + MultiThreadedDebug + Disabled + + + + + + + + + + + + {f9be7957-8399-899e-0c49-e714fddd4b65} + + + + + + \ No newline at end of file diff --git a/tools/slang-test/slang-test.vcxproj.filters b/tools/slang-test/slang-test.vcxproj.filters new file mode 100644 index 000000000..3549e6046 --- /dev/null +++ b/tools/slang-test/slang-test.vcxproj.filters @@ -0,0 +1,30 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + Source Files + + + + + Header Files + + + \ No newline at end of file -- cgit v1.2.3