diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index ec079e7..5497bd4 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -14,22 +14,27 @@ jobs: steps: - name: Expose GitHub Runtime uses: crazy-max/ghaction-github-runtime@v3 + - name: Add msbuild to PATH if: runner.os == 'Windows' uses: microsoft/setup-msbuild@v1.0.2 + - name: Install Linux dependencies if: runner.os == 'Linux' run: sudo apt-get install build-essential git make cmake autoconf automake pkg-config shell: bash + - name: Clone repository uses: actions/checkout@v4 with: submodules: recursive + - name: Run CAKE run: dotnet run --project ./build/Build.csproj -- --universalBinary=true env: ACTIONS_RUNTIME_TOKEN: ${{ env.ACTIONS_RUNTIME_TOKEN }} ACTIONS_RUNTIME_URL: "${{ env.ACTIONS_RUNTIME_URL }}" + deploy: name: deploy runs-on: ubuntu-latest @@ -41,17 +46,21 @@ jobs: steps: - name: Expose GitHub Runtime uses: crazy-max/ghaction-github-runtime@v3 + - name: Clone repository uses: actions/checkout@v4 with: submodules: recursive + - name: Run CAKE run: dotnet run --project ./build/Build.csproj -- --target=Package --universalBinary=true --libraryname=MojoShader --licensepath=mojoshader/LICENSE.txt env: ACTIONS_RUNTIME_TOKEN: ${{ env.ACTIONS_RUNTIME_TOKEN }} ACTIONS_RUNTIME_URL: "${{ env.ACTIONS_RUNTIME_URL }}" GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Make a release + if: github.ref_type == 'tag' uses: ncipollo/release-action@v1 with: name: 'MonoGame.Library.MojoShader ${{ github.ref_name }}' @@ -60,5 +69,8 @@ jobs: removeArtifacts: true artifacts: "bin/Release/*.nupkg" token: ${{ secrets.GITHUB_TOKEN }} + + - name: Push package to nuget if: github.ref_type == 'tag' + run: dotnet nuget push bin/Release/*.nupkg --api-key ${{ secrets.NUGET_DEPLOY_KEY }} --source https://api.nuget.org/v3/index.json --skip-duplicate diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..0f5fd77 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "cmake.sourceDirectory": "/Users/dominique/Projects/MonoGame/MonoGame.Library.MojoShader/mojoshader" +} \ No newline at end of file diff --git a/build/BuildLinuxTask.cs b/build/BuildLinuxTask.cs index abd9cc7..f862c2d 100644 --- a/build/BuildLinuxTask.cs +++ b/build/BuildLinuxTask.cs @@ -13,7 +13,7 @@ public override void Run(BuildContext context) { var buildWorkingDir = "mojoshaderbuild/"; context.CreateDirectory(buildWorkingDir); - context.StartProcess("cmake", new ProcessSettings { WorkingDirectory = buildWorkingDir, Arguments = "../mojoshader/CMakeLists.txt -DCMAKE_OSX_ARCHITECTURES=\"x86_64;arm64\"" }); + context.StartProcess("cmake", new ProcessSettings { WorkingDirectory = buildWorkingDir, Arguments = "../mojoshader/CMakeLists.txt -DBUILD_SHARED_LIBS=ON -DDEPTH_CLIPPING=ON -DPROFILE_GLSLES3=ON" }); context.StartProcess("cmake", new ProcessSettings { WorkingDirectory = buildWorkingDir, Arguments = "--build . --config release" }); context.CopyFile(System.IO.Path.Combine(buildWorkingDir, "libmojoshader.so"), $"{context.ArtifactsDir}/libmojoshader.so"); } diff --git a/build/BuildMacOSTask.cs b/build/BuildMacOSTask.cs index 51b9a47..051cee2 100644 --- a/build/BuildMacOSTask.cs +++ b/build/BuildMacOSTask.cs @@ -13,7 +13,7 @@ public override void Run(BuildContext context) { var buildWorkingDir = "mojoshaderbuild/"; context.CreateDirectory(buildWorkingDir); - context.StartProcess("cmake", new ProcessSettings { WorkingDirectory = buildWorkingDir, Arguments = "../mojoshader/CMakeLists.txt -DCMAKE_OSX_ARCHITECTURES=\"x86_64;arm64\"" }); + context.StartProcess("cmake", new ProcessSettings { WorkingDirectory = buildWorkingDir, Arguments = "../mojoshader/CMakeLists.txt -DCMAKE_OSX_ARCHITECTURES=\"x86_64;arm64\" -DBUILD_SHARED_LIBS=ON -DDEPTH_CLIPPING=ON -DPROFILE_GLSLES3=ON" }); context.StartProcess("cmake", new ProcessSettings { WorkingDirectory = buildWorkingDir, Arguments = "--build . --config release" }); context.CopyFile(System.IO.Path.Combine(buildWorkingDir, "libmojoshader.dylib"), $"{context.ArtifactsDir}/libmojoshader.dylib"); } diff --git a/build/BuildWindowsTask.cs b/build/BuildWindowsTask.cs index 81bb2c2..69b5327 100644 --- a/build/BuildWindowsTask.cs +++ b/build/BuildWindowsTask.cs @@ -13,7 +13,7 @@ public override void Run(BuildContext context) { var buildWorkingDir = "mojoshaderbuild/"; context.CreateDirectory(buildWorkingDir); - context.StartProcess("cmake", new ProcessSettings { WorkingDirectory = buildWorkingDir, Arguments = "../mojoshader/CMakeLists.txt" }); + context.StartProcess("cmake", new ProcessSettings { WorkingDirectory = buildWorkingDir, Arguments = "../mojoshader/CMakeLists.txt -DBUILD_SHARED_LIBS=ON -DDEPTH_CLIPPING=ON -DPROFILE_GLSLES3=ON" }); // Fix generated projects using the same obj folder var dirProps = @" diff --git a/mojoshader/CMakeLists.txt b/mojoshader/CMakeLists.txt index c4bc4d0..2885447 100644 --- a/mojoshader/CMakeLists.txt +++ b/mojoshader/CMakeLists.txt @@ -1,17 +1,24 @@ CMAKE_MINIMUM_REQUIRED(VERSION 3.12.0) PROJECT(MojoShader) +# !!! FIXME: can we lowercase this file, if nothing else? + +INCLUDE(CheckIncludeFile) +CHECK_INCLUDE_FILE(d3d11.h HAS_D3D11_H) + OPTION(BUILD_SHARED_LIBS "Build MojoShader as a shared library" OFF) OPTION(PROFILE_D3D "Build MojoShader with support for the D3D profile" ON) OPTION(PROFILE_BYTECODE "Build MojoShader with support for the BYTECODE profile" ON) +OPTION(PROFILE_HLSL "Build MojoShader with support for the HLSL profile" HAS_D3D11_H) OPTION(PROFILE_GLSL120 "Build MojoShader with support for the GLSL120 profile" ON) OPTION(PROFILE_GLSLES "Build MojoShader with support for the GLSLES profile" ON) OPTION(PROFILE_GLSL "Build MojoShader with support for the GLSL profile" ON) OPTION(PROFILE_ARB1 "Build MojoShader with support for the ARB1 profile" ON) OPTION(PROFILE_ARB1_NV "Build MojoShader with support for the ARB1_NV profile" ON) OPTION(PROFILE_METAL "Build MojoShader with support for the Metal profile" APPLE) +OPTION(PROFILE_SPIRV "Build MojoShader with support for the SPIR-V profile" ON) +OPTION(PROFILE_GLSPIRV "Build MojoShader with support for the ARB_gl_spirv profile" ON) OPTION(EFFECT_SUPPORT "Build MojoShader with support for Effect framework files" ON) -OPTION(COMPILER_SUPPORT "Build MojoShader with support for HLSL source files" !WIN32) # TODO: Fix lemon on Windows OPTION(FLIP_VIEWPORT "Build MojoShader with the ability to flip the GL viewport" OFF) OPTION(DEPTH_CLIPPING "Build MojoShader with the ability to simulate [0, 1] depth clipping" OFF) OPTION(XNA4_VERTEXTEXTURE "Build MojoShader with XNA4 vertex texturing behavior" OFF) @@ -19,7 +26,47 @@ OPTION(XNA4_VERTEXTEXTURE "Build MojoShader with XNA4 vertex texturing behavior" INCLUDE_DIRECTORIES(.) # This was a Mercurial thing. In Git, it's always -1. -SET(MOJOSHADER_VERSION 1) +SET(MOJOSHADER_VERSION -1) + +# If Git is installed and we are in a git repository, include the changeset as version information. +FIND_PROGRAM(GIT git DOC "Path to git command line app: https://git-scm.com/") +IF(NOT GIT) + MESSAGE(STATUS "Git not found. You can go on, but version info will be wrong.") + SET(MOJOSHADER_CHANGESET "???") +ELSE(NOT GIT) + MARK_AS_ADVANCED(GIT) + + # !!! FIXME: this didn't actually use the GIT variable... + + # See if we are in a git repository. + EXECUTE_PROCESS( + COMMAND git rev-parse --show-toplevel + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + OUTPUT_VARIABLE MOJOSHADER_GIT_TOPLEVEL_DIR + RESULT_VARIABLE GITVERSION_RC + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + IF(NOT GITVERSION_RC EQUAL 0) + MESSAGE(STATUS "Git repository not found. You can go on, but version info will be wrong.") + SET(MOJOSHADER_CHANGESET "???") + ELSE(NOT GITVERSION_RC EQUAL 0) + # Query the changeset. + EXECUTE_PROCESS( + COMMAND git rev-list HEAD~.. + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + RESULT_VARIABLE GITVERSION_RC + OUTPUT_VARIABLE MOJOSHADER_GIT_CHANGESET + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + IF(NOT GITVERSION_RC EQUAL 0) + SET(MOJOSHADER_CHANGESET "???") + ELSE(NOT GITVERSION_RC EQUAL 0) + SET(MOJOSHADER_CHANGESET "git-${MOJOSHADER_GIT_CHANGESET}") + ENDIF(NOT GITVERSION_RC EQUAL 0) + ENDIF(NOT GITVERSION_RC EQUAL 0) +ENDIF(NOT GIT) WRITE_FILE( "${CMAKE_CURRENT_SOURCE_DIR}/mojoshader_version.h" @@ -43,18 +90,6 @@ IF(MSVC) ADD_DEFINITIONS(-TP) # force .c files to compile as C++. ENDIF(MSVC) -# We build lemon, then use it to generate parser C code. -IF(COMPILER_SUPPORT) - ADD_EXECUTABLE(lemon "misc/lemon.c") - ADD_CUSTOM_COMMAND( - OUTPUT "${CMAKE_CURRENT_SOURCE_DIR}/mojoshader_parser_hlsl.h" - MAIN_DEPENDENCY "${CMAKE_CURRENT_SOURCE_DIR}/mojoshader_parser_hlsl.lemon" - DEPENDS lemon "${CMAKE_CURRENT_SOURCE_DIR}/misc/lempar.c" - COMMAND lemon - ARGS -q "-T${CMAKE_CURRENT_SOURCE_DIR}/misc/lempar.c" "${CMAKE_CURRENT_SOURCE_DIR}/mojoshader_parser_hlsl.lemon" - ) -ENDIF(COMPILER_SUPPORT) - IF(APPLE) IF(NOT IOS) find_library(CARBON_FRAMEWORK Carbon) # Stupid Gestalt. @@ -93,6 +128,12 @@ IF(NOT PROFILE_METAL) ELSE(NOT PROFILE_METAL) SET(LOBJC -lobjc) ENDIF(NOT PROFILE_METAL) +IF(NOT PROFILE_SPIRV) + ADD_DEFINITIONS(-DSUPPORT_PROFILE_SPIRV=0) +ENDIF(NOT PROFILE_SPIRV) +IF(NOT PROFILE_GLSPIRV) + ADD_DEFINITIONS(-DSUPPORT_PROFILE_GLSPIRV=0) +ENDIF(NOT PROFILE_GLSPIRV) IF(EFFECT_SUPPORT) IF(UNIX) @@ -113,54 +154,64 @@ IF(XNA4_VERTEXTEXTURE) ADD_DEFINITIONS(-DMOJOSHADER_XNA4_VERTEX_TEXTURES) ENDIF(XNA4_VERTEXTEXTURE) -ADD_LIBRARY(mojoshader SHARED +ADD_LIBRARY(mojoshader mojoshader.c mojoshader_common.c mojoshader_opengl.c + mojoshader_d3d11.c + mojoshader_sdlgpu.c + profiles/mojoshader_profile_arb1.c + profiles/mojoshader_profile_bytecode.c + profiles/mojoshader_profile_d3d.c + profiles/mojoshader_profile_hlsl.c + profiles/mojoshader_profile_glsl.c + profiles/mojoshader_profile_metal.c + profiles/mojoshader_profile_spirv.c + profiles/mojoshader_profile_common.c ) IF(EFFECT_SUPPORT) TARGET_SOURCES(mojoshader PRIVATE mojoshader_effects.c ) ENDIF(EFFECT_SUPPORT) -IF(COMPILER_SUPPORT) - TARGET_SOURCES(mojoshader PRIVATE - mojoshader_compiler.c - mojoshader_preprocessor.c - mojoshader_lexer.c - mojoshader_assembler.c - ) -ENDIF(COMPILER_SUPPORT) IF(BUILD_SHARED_LIBS) TARGET_LINK_LIBRARIES(mojoshader ${LIBM} ${LOBJC} ${CARBON_FRAMEWORK}) ENDIF(BUILD_SHARED_LIBS) -SET_SOURCE_FILES_PROPERTIES( - mojoshader_compiler.c - PROPERTIES OBJECT_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/mojoshader_parser_hlsl.h" +# These are fallback paths for D3D11, try to have this on the system instead! +TARGET_INCLUDE_DIRECTORIES(mojoshader PUBLIC + $ + $ + $ ) -FIND_PROGRAM(RE2C re2c DOC "Path to re2c command line app: http://re2c.org/") -IF(NOT RE2C) - MESSAGE(STATUS "re2c missing. You can go on, but can't rebuild the lexer.") -ELSE(NOT RE2C) - MARK_AS_ADVANCED(RE2C) - ADD_CUSTOM_COMMAND( - OUTPUT "${CMAKE_CURRENT_SOURCE_DIR}/mojoshader_lexer.c" - DEPENDS mojoshader_lexer.re - COMMAND "${RE2C}" - ARGS -is --no-generation-date -o "${CMAKE_CURRENT_SOURCE_DIR}/mojoshader_lexer.c" "${CMAKE_CURRENT_SOURCE_DIR}/mojoshader_lexer.re" - ) -ENDIF(NOT RE2C) - -IF(COMPILER_SUPPORT) - ADD_EXECUTABLE(finderrors utils/finderrors.c) -ENDIF(COMPILER_SUPPORT) - -IF(COMPILER_SUPPORT) - ADD_EXECUTABLE(mojoshader-compiler utils/mojoshader-compiler.c) - TARGET_LINK_LIBRARIES(mojoshader-compiler mojoshader ${LIBM} ${LOBJC} ${CARBON_FRAMEWORK}) -ENDIF(COMPILER_SUPPORT) +find_package(SDL2) +IF(SDL2_FOUND) + INCLUDE_DIRECTORIES(${SDL2_INCLUDE_DIRS}) + ADD_EXECUTABLE(glcaps utils/glcaps.c) + TARGET_LINK_LIBRARIES(glcaps ${SDL2_LIBRARIES} ${LIBM} ${LOBJC} ${CARBON_FRAMEWORK}) + ADD_EXECUTABLE(bestprofile utils/bestprofile.c) + TARGET_LINK_LIBRARIES(bestprofile mojoshader ${SDL2_LIBRARIES} ${LIBM} ${LOBJC} ${CARBON_FRAMEWORK}) + ADD_EXECUTABLE(availableprofiles utils/availableprofiles.c) + TARGET_LINK_LIBRARIES(availableprofiles mojoshader ${SDL2_LIBRARIES} ${LIBM} ${LOBJC} ${CARBON_FRAMEWORK}) + ADD_EXECUTABLE(testglcompile utils/testglcompile.c) + TARGET_LINK_LIBRARIES(testglcompile mojoshader ${SDL2_LIBRARIES} ${LIBM} ${LOBJC} ${CARBON_FRAMEWORK}) +ENDIF(SDL2_FOUND) + +FIND_PATH(SPIRV_TOOLS_INCLUDE_DIR "spirv-tools/libspirv.h" PATH_SUFFIXES "include") +FIND_LIBRARY(SPIRV_TOOLS_LIBRARY NAMES SPIRV-Tools-shared) +IF(SPIRV_TOOLS_INCLUDE_DIR AND SPIRV_TOOLS_LIBRARY) + INCLUDE_DIRECTORIES(${SPIRV_TOOLS_INCLUDE_DIR}) + ADD_DEFINITIONS(-DMOJOSHADER_HAS_SPIRV_TOOLS) +ENDIF(SPIRV_TOOLS_INCLUDE_DIR AND SPIRV_TOOLS_LIBRARY) + +ADD_EXECUTABLE(testparse utils/testparse.c) +TARGET_LINK_LIBRARIES(testparse mojoshader ${LIBM} ${LOBJC} ${CARBON_FRAMEWORK}) +IF(SPIRV_TOOLS_INCLUDE_DIR AND SPIRV_TOOLS_LIBRARY) + TARGET_LINK_LIBRARIES(testparse ${SPIRV_TOOLS_LIBRARY}) +ENDIF(SPIRV_TOOLS_INCLUDE_DIR AND SPIRV_TOOLS_LIBRARY) +ADD_EXECUTABLE(testoutput utils/testoutput.c) +TARGET_LINK_LIBRARIES(testoutput mojoshader ${LIBM} ${LOBJC} ${CARBON_FRAMEWORK}) # End of CMakeLists.txt ... diff --git a/mojoshader/GL/glext.h b/mojoshader/GL/glext.h index 4d4b3a3..e607161 100644 --- a/mojoshader/GL/glext.h +++ b/mojoshader/GL/glext.h @@ -5,52 +5,35 @@ extern "C" { #endif -/****************************************************************************** - - Copyright NVIDIA Corporation 2006 - - TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED - *AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS - OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL - NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR - CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR - LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, - OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE - THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH - DAMAGES. - -******************************************************************************/ - /* -** License Applicability. Except to the extent portions of this file are -** made subject to an alternative license as permitted in the SGI Free -** Software License B, Version 1.1 (the "License"), the contents of this -** file are subject only to the provisions of the License. You may not use -** this file except in compliance with the License. You may obtain a copy -** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 -** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** Copyright (c) 2007-2011 The Khronos Group Inc. ** -** http://oss.sgi.com/projects/FreeB +** 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: ** -** Note that, as provided in the License, the Software is distributed on an -** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS -** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND -** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A -** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** The above copyright notice and this permission notice shall be included +** in all copies or substantial portions of the Materials. ** -** Original Code. The Original Code is: OpenGL Sample Implementation, -** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, -** Inc. The Original Code is Copyright (c) 1991-2004 Silicon Graphics, Inc. -** Copyright in any portions created by third parties is as indicated -** elsewhere herein. All Rights Reserved. -** -** Additional Notice Provisions: This software was created using the -** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has -** not been independently verified as being compliant with the OpenGL(R) -** version 1.2.1 Specification. +** 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. */ +/* Header file version number, required by OpenGL ABI for Linux */ +/* glext.h last updated $Date: 2011-12-19 02:48:53 -0800 (Mon, 19 Dec 2011) $ */ +/* Current version at http://www.opengl.org/registry/ */ +#define GL_GLEXT_VERSION 74 +/* Function declaration macros - to move into glplatform.h */ + #if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) #define WIN32_LEAN_AND_MEAN 1 #include @@ -62,24 +45,18 @@ extern "C" { #ifndef APIENTRYP #define APIENTRYP APIENTRY * #endif -#ifndef extern -#define extern extern +#ifndef GLAPI +#define GLAPI extern #endif /*************************************************************/ -/* Header file version number, required by OpenGL ABI for Linux */ -/* glext.h last updated 2005/06/06 */ -/* Current version at http://oss.sgi.com/projects/ogl-sample/registry/ */ -#define GL_GLEXT_VERSION 28 - #ifndef GL_VERSION_1_2 #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_RESCALE_NORMAL 0x803A #define GL_TEXTURE_BINDING_3D 0x806A #define GL_PACK_SKIP_IMAGES 0x806B #define GL_PACK_IMAGE_HEIGHT 0x806C @@ -106,17 +83,21 @@ extern "C" { #define GL_TEXTURE_MAX_LOD 0x813B #define GL_TEXTURE_BASE_LEVEL 0x813C #define GL_TEXTURE_MAX_LEVEL 0x813D -#define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8 -#define GL_SINGLE_COLOR 0x81F9 -#define GL_SEPARATE_SPECULAR_COLOR 0x81FA #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_POINT_SIZE_RANGE 0x846D #define GL_ALIASED_LINE_WIDTH_RANGE 0x846E #endif +#ifndef GL_VERSION_1_2_DEPRECATED +#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 +#endif + #ifndef GL_ARB_imaging #define GL_CONSTANT_COLOR 0x8001 #define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 @@ -129,6 +110,9 @@ extern "C" { #define GL_BLEND_EQUATION 0x8009 #define GL_FUNC_SUBTRACT 0x800A #define GL_FUNC_REVERSE_SUBTRACT 0x800B +#endif + +#ifndef GL_ARB_imaging_DEPRECATED #define GL_CONVOLUTION_1D 0x8010 #define GL_CONVOLUTION_2D 0x8011 #define GL_SEPARABLE_2D 0x8012 @@ -229,12 +213,6 @@ extern "C" { #define GL_TEXTURE30 0x84DE #define GL_TEXTURE31 0x84DF #define GL_ACTIVE_TEXTURE 0x84E0 -#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 0x809D #define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E #define GL_SAMPLE_ALPHA_TO_ONE 0x809F @@ -243,9 +221,6 @@ extern "C" { #define GL_SAMPLES 0x80A9 #define GL_SAMPLE_COVERAGE_VALUE 0x80AA #define GL_SAMPLE_COVERAGE_INVERT 0x80AB -#define GL_MULTISAMPLE_BIT 0x20000000 -#define GL_NORMAL_MAP 0x8511 -#define GL_REFLECTION_MAP 0x8512 #define GL_TEXTURE_CUBE_MAP 0x8513 #define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 #define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 @@ -256,10 +231,6 @@ extern "C" { #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_ALPHA 0x84E9 -#define GL_COMPRESSED_LUMINANCE 0x84EA -#define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB -#define GL_COMPRESSED_INTENSITY 0x84EC #define GL_COMPRESSED_RGB 0x84ED #define GL_COMPRESSED_RGBA 0x84EE #define GL_TEXTURE_COMPRESSION_HINT 0x84EF @@ -268,6 +239,22 @@ extern "C" { #define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 #define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 #define GL_CLAMP_TO_BORDER 0x812D +#endif + +#ifndef GL_VERSION_1_3_DEPRECATED +#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 @@ -299,16 +286,26 @@ extern "C" { #define GL_BLEND_SRC_RGB 0x80C9 #define GL_BLEND_DST_ALPHA 0x80CA #define GL_BLEND_SRC_ALPHA 0x80CB -#define GL_POINT_SIZE_MIN 0x8126 -#define GL_POINT_SIZE_MAX 0x8127 #define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 -#define GL_POINT_DISTANCE_ATTENUATION 0x8129 -#define GL_GENERATE_MIPMAP 0x8191 -#define GL_GENERATE_MIPMAP_HINT 0x8192 #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 +#endif + +#ifndef GL_VERSION_1_4_DEPRECATED +#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 @@ -324,15 +321,8 @@ extern "C" { #define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C #define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D #define GL_SECONDARY_COLOR_ARRAY 0x845E -#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD #define GL_TEXTURE_FILTER_CONTROL 0x8500 -#define GL_TEXTURE_LOD_BIAS 0x8501 -#define GL_INCR_WRAP 0x8507 -#define GL_DECR_WRAP 0x8508 -#define GL_TEXTURE_DEPTH_SIZE 0x884A #define GL_DEPTH_TEXTURE_MODE 0x884B -#define GL_TEXTURE_COMPARE_MODE 0x884C -#define GL_TEXTURE_COMPARE_FUNC 0x884D #define GL_COMPARE_R_TO_TEXTURE 0x884E #endif @@ -347,15 +337,6 @@ extern "C" { #define GL_ELEMENT_ARRAY_BUFFER 0x8893 #define GL_ARRAY_BUFFER_BINDING 0x8894 #define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 -#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_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F #define GL_READ_ONLY 0x88B8 #define GL_WRITE_ONLY 0x88B9 @@ -373,31 +354,42 @@ extern "C" { #define GL_DYNAMIC_READ 0x88E9 #define GL_DYNAMIC_COPY 0x88EA #define GL_SAMPLES_PASSED 0x8914 -#define GL_FOG_COORD_SRC GL_FOG_COORDINATE_SOURCE -#define GL_FOG_COORD GL_FOG_COORDINATE -#define GL_CURRENT_FOG_COORD GL_CURRENT_FOG_COORDINATE -#define GL_FOG_COORD_ARRAY_TYPE GL_FOG_COORDINATE_ARRAY_TYPE -#define GL_FOG_COORD_ARRAY_STRIDE GL_FOG_COORDINATE_ARRAY_STRIDE -#define GL_FOG_COORD_ARRAY_POINTER GL_FOG_COORDINATE_ARRAY_POINTER -#define GL_FOG_COORD_ARRAY GL_FOG_COORDINATE_ARRAY -#define GL_FOG_COORD_ARRAY_BUFFER_BINDING GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING -#define GL_SRC0_RGB GL_SOURCE0_RGB -#define GL_SRC1_RGB GL_SOURCE1_RGB -#define GL_SRC2_RGB GL_SOURCE2_RGB -#define GL_SRC0_ALPHA GL_SOURCE0_ALPHA -#define GL_SRC1_ALPHA GL_SOURCE1_ALPHA -#define GL_SRC2_ALPHA GL_SOURCE2_ALPHA +#endif + +#ifndef GL_VERSION_1_5_DEPRECATED +#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_SRC1_ALPHA 0x8589 +#define GL_SRC2_ALPHA 0x858A #endif #ifndef GL_VERSION_2_0 -#define GL_BLEND_EQUATION_RGB GL_BLEND_EQUATION +#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_PROGRAM_TWO_SIDE 0x8643 #define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 #define GL_STENCIL_BACK_FUNC 0x8800 #define GL_STENCIL_BACK_FAIL 0x8801 @@ -421,11 +413,8 @@ extern "C" { #define GL_DRAW_BUFFER14 0x8833 #define GL_DRAW_BUFFER15 0x8834 #define GL_BLEND_EQUATION_ALPHA 0x883D -#define GL_POINT_SPRITE 0x8861 -#define GL_COORD_REPLACE 0x8862 #define GL_MAX_VERTEX_ATTRIBS 0x8869 #define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A -#define GL_MAX_TEXTURE_COORDS 0x8871 #define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 #define GL_FRAGMENT_SHADER 0x8B30 #define GL_VERTEX_SHADER 0x8B31 @@ -476,30 +465,702 @@ extern "C" { #define GL_STENCIL_BACK_WRITEMASK 0x8CA5 #endif +#ifndef GL_VERSION_2_0_DEPRECATED +#define GL_VERTEX_PROGRAM_TWO_SIDE 0x8643 +#define GL_POINT_SPRITE 0x8861 +#define GL_COORD_REPLACE 0x8862 +#define GL_MAX_TEXTURE_COORDS 0x8871 +#endif + #ifndef GL_VERSION_2_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 +#endif + +#ifndef GL_VERSION_2_1_DEPRECATED +#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_SRGB 0x8C48 -#define GL_COMPRESSED_SRGB_ALPHA 0x8C49 #define GL_COMPRESSED_SLUMINANCE 0x8C4A #define GL_COMPRESSED_SLUMINANCE_ALPHA 0x8C4B -#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_CURRENT_RASTER_SECONDARY_COLOR 0x845F +#endif + +#ifndef GL_VERSION_3_0 +#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 0x0001 +#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 +/* Reuse tokens from ARB_depth_buffer_float */ +/* reuse GL_DEPTH_COMPONENT32F */ +/* reuse GL_DEPTH32F_STENCIL8 */ +/* reuse GL_FLOAT_32_UNSIGNED_INT_24_8_REV */ +/* Reuse tokens from ARB_framebuffer_object */ +/* reuse GL_INVALID_FRAMEBUFFER_OPERATION */ +/* reuse GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING */ +/* reuse GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE */ +/* reuse GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE */ +/* reuse GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE */ +/* reuse GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE */ +/* reuse GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE */ +/* reuse GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE */ +/* reuse GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE */ +/* reuse GL_FRAMEBUFFER_DEFAULT */ +/* reuse GL_FRAMEBUFFER_UNDEFINED */ +/* reuse GL_DEPTH_STENCIL_ATTACHMENT */ +/* reuse GL_INDEX */ +/* reuse GL_MAX_RENDERBUFFER_SIZE */ +/* reuse GL_DEPTH_STENCIL */ +/* reuse GL_UNSIGNED_INT_24_8 */ +/* reuse GL_DEPTH24_STENCIL8 */ +/* reuse GL_TEXTURE_STENCIL_SIZE */ +/* reuse GL_TEXTURE_RED_TYPE */ +/* reuse GL_TEXTURE_GREEN_TYPE */ +/* reuse GL_TEXTURE_BLUE_TYPE */ +/* reuse GL_TEXTURE_ALPHA_TYPE */ +/* reuse GL_TEXTURE_DEPTH_TYPE */ +/* reuse GL_UNSIGNED_NORMALIZED */ +/* reuse GL_FRAMEBUFFER_BINDING */ +/* reuse GL_DRAW_FRAMEBUFFER_BINDING */ +/* reuse GL_RENDERBUFFER_BINDING */ +/* reuse GL_READ_FRAMEBUFFER */ +/* reuse GL_DRAW_FRAMEBUFFER */ +/* reuse GL_READ_FRAMEBUFFER_BINDING */ +/* reuse GL_RENDERBUFFER_SAMPLES */ +/* reuse GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE */ +/* reuse GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME */ +/* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL */ +/* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE */ +/* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER */ +/* reuse GL_FRAMEBUFFER_COMPLETE */ +/* reuse GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT */ +/* reuse GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT */ +/* reuse GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER */ +/* reuse GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER */ +/* reuse GL_FRAMEBUFFER_UNSUPPORTED */ +/* reuse GL_MAX_COLOR_ATTACHMENTS */ +/* reuse GL_COLOR_ATTACHMENT0 */ +/* reuse GL_COLOR_ATTACHMENT1 */ +/* reuse GL_COLOR_ATTACHMENT2 */ +/* reuse GL_COLOR_ATTACHMENT3 */ +/* reuse GL_COLOR_ATTACHMENT4 */ +/* reuse GL_COLOR_ATTACHMENT5 */ +/* reuse GL_COLOR_ATTACHMENT6 */ +/* reuse GL_COLOR_ATTACHMENT7 */ +/* reuse GL_COLOR_ATTACHMENT8 */ +/* reuse GL_COLOR_ATTACHMENT9 */ +/* reuse GL_COLOR_ATTACHMENT10 */ +/* reuse GL_COLOR_ATTACHMENT11 */ +/* reuse GL_COLOR_ATTACHMENT12 */ +/* reuse GL_COLOR_ATTACHMENT13 */ +/* reuse GL_COLOR_ATTACHMENT14 */ +/* reuse GL_COLOR_ATTACHMENT15 */ +/* reuse GL_DEPTH_ATTACHMENT */ +/* reuse GL_STENCIL_ATTACHMENT */ +/* reuse GL_FRAMEBUFFER */ +/* reuse GL_RENDERBUFFER */ +/* reuse GL_RENDERBUFFER_WIDTH */ +/* reuse GL_RENDERBUFFER_HEIGHT */ +/* reuse GL_RENDERBUFFER_INTERNAL_FORMAT */ +/* reuse GL_STENCIL_INDEX1 */ +/* reuse GL_STENCIL_INDEX4 */ +/* reuse GL_STENCIL_INDEX8 */ +/* reuse GL_STENCIL_INDEX16 */ +/* reuse GL_RENDERBUFFER_RED_SIZE */ +/* reuse GL_RENDERBUFFER_GREEN_SIZE */ +/* reuse GL_RENDERBUFFER_BLUE_SIZE */ +/* reuse GL_RENDERBUFFER_ALPHA_SIZE */ +/* reuse GL_RENDERBUFFER_DEPTH_SIZE */ +/* reuse GL_RENDERBUFFER_STENCIL_SIZE */ +/* reuse GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE */ +/* reuse GL_MAX_SAMPLES */ +/* Reuse tokens from ARB_framebuffer_sRGB */ +/* reuse GL_FRAMEBUFFER_SRGB */ +/* Reuse tokens from ARB_half_float_vertex */ +/* reuse GL_HALF_FLOAT */ +/* Reuse tokens from ARB_map_buffer_range */ +/* reuse GL_MAP_READ_BIT */ +/* reuse GL_MAP_WRITE_BIT */ +/* reuse GL_MAP_INVALIDATE_RANGE_BIT */ +/* reuse GL_MAP_INVALIDATE_BUFFER_BIT */ +/* reuse GL_MAP_FLUSH_EXPLICIT_BIT */ +/* reuse GL_MAP_UNSYNCHRONIZED_BIT */ +/* Reuse tokens from ARB_texture_compression_rgtc */ +/* reuse GL_COMPRESSED_RED_RGTC1 */ +/* reuse GL_COMPRESSED_SIGNED_RED_RGTC1 */ +/* reuse GL_COMPRESSED_RG_RGTC2 */ +/* reuse GL_COMPRESSED_SIGNED_RG_RGTC2 */ +/* Reuse tokens from ARB_texture_rg */ +/* reuse GL_RG */ +/* reuse GL_RG_INTEGER */ +/* reuse GL_R8 */ +/* reuse GL_R16 */ +/* reuse GL_RG8 */ +/* reuse GL_RG16 */ +/* reuse GL_R16F */ +/* reuse GL_R32F */ +/* reuse GL_RG16F */ +/* reuse GL_RG32F */ +/* reuse GL_R8I */ +/* reuse GL_R8UI */ +/* reuse GL_R16I */ +/* reuse GL_R16UI */ +/* reuse GL_R32I */ +/* reuse GL_R32UI */ +/* reuse GL_RG8I */ +/* reuse GL_RG8UI */ +/* reuse GL_RG16I */ +/* reuse GL_RG16UI */ +/* reuse GL_RG32I */ +/* reuse GL_RG32UI */ +/* Reuse tokens from ARB_vertex_array_object */ +/* reuse GL_VERTEX_ARRAY_BINDING */ +#endif + +#ifndef GL_VERSION_3_0_DEPRECATED +#define GL_CLAMP_VERTEX_COLOR 0x891A +#define GL_CLAMP_FRAGMENT_COLOR 0x891B +#define GL_ALPHA_INTEGER 0x8D97 +/* Reuse tokens from ARB_framebuffer_object */ +/* reuse GL_TEXTURE_LUMINANCE_TYPE */ +/* reuse GL_TEXTURE_INTENSITY_TYPE */ +#endif + +#ifndef GL_VERSION_3_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_BUFFER_FORMAT 0x8C2E +#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_RED_SNORM 0x8F90 +#define GL_RG_SNORM 0x8F91 +#define GL_RGB_SNORM 0x8F92 +#define GL_RGBA_SNORM 0x8F93 +#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 +/* Reuse tokens from ARB_copy_buffer */ +/* reuse GL_COPY_READ_BUFFER */ +/* reuse GL_COPY_WRITE_BUFFER */ +/* Reuse tokens from ARB_draw_instanced (none) */ +/* Reuse tokens from ARB_uniform_buffer_object */ +/* reuse GL_UNIFORM_BUFFER */ +/* reuse GL_UNIFORM_BUFFER_BINDING */ +/* reuse GL_UNIFORM_BUFFER_START */ +/* reuse GL_UNIFORM_BUFFER_SIZE */ +/* reuse GL_MAX_VERTEX_UNIFORM_BLOCKS */ +/* reuse GL_MAX_FRAGMENT_UNIFORM_BLOCKS */ +/* reuse GL_MAX_COMBINED_UNIFORM_BLOCKS */ +/* reuse GL_MAX_UNIFORM_BUFFER_BINDINGS */ +/* reuse GL_MAX_UNIFORM_BLOCK_SIZE */ +/* reuse GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS */ +/* reuse GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS */ +/* reuse GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT */ +/* reuse GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH */ +/* reuse GL_ACTIVE_UNIFORM_BLOCKS */ +/* reuse GL_UNIFORM_TYPE */ +/* reuse GL_UNIFORM_SIZE */ +/* reuse GL_UNIFORM_NAME_LENGTH */ +/* reuse GL_UNIFORM_BLOCK_INDEX */ +/* reuse GL_UNIFORM_OFFSET */ +/* reuse GL_UNIFORM_ARRAY_STRIDE */ +/* reuse GL_UNIFORM_MATRIX_STRIDE */ +/* reuse GL_UNIFORM_IS_ROW_MAJOR */ +/* reuse GL_UNIFORM_BLOCK_BINDING */ +/* reuse GL_UNIFORM_BLOCK_DATA_SIZE */ +/* reuse GL_UNIFORM_BLOCK_NAME_LENGTH */ +/* reuse GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS */ +/* reuse GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES */ +/* reuse GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER */ +/* reuse GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER */ +/* reuse GL_INVALID_INDEX */ +#endif + +#ifndef GL_VERSION_3_2 +#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 +/* reuse GL_MAX_VARYING_COMPONENTS */ +/* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER */ +/* Reuse tokens from ARB_depth_clamp */ +/* reuse GL_DEPTH_CLAMP */ +/* Reuse tokens from ARB_draw_elements_base_vertex (none) */ +/* Reuse tokens from ARB_fragment_coord_conventions (none) */ +/* Reuse tokens from ARB_provoking_vertex */ +/* reuse GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION */ +/* reuse GL_FIRST_VERTEX_CONVENTION */ +/* reuse GL_LAST_VERTEX_CONVENTION */ +/* reuse GL_PROVOKING_VERTEX */ +/* Reuse tokens from ARB_seamless_cube_map */ +/* reuse GL_TEXTURE_CUBE_MAP_SEAMLESS */ +/* Reuse tokens from ARB_sync */ +/* reuse GL_MAX_SERVER_WAIT_TIMEOUT */ +/* reuse GL_OBJECT_TYPE */ +/* reuse GL_SYNC_CONDITION */ +/* reuse GL_SYNC_STATUS */ +/* reuse GL_SYNC_FLAGS */ +/* reuse GL_SYNC_FENCE */ +/* reuse GL_SYNC_GPU_COMMANDS_COMPLETE */ +/* reuse GL_UNSIGNALED */ +/* reuse GL_SIGNALED */ +/* reuse GL_ALREADY_SIGNALED */ +/* reuse GL_TIMEOUT_EXPIRED */ +/* reuse GL_CONDITION_SATISFIED */ +/* reuse GL_WAIT_FAILED */ +/* reuse GL_TIMEOUT_IGNORED */ +/* reuse GL_SYNC_FLUSH_COMMANDS_BIT */ +/* reuse GL_TIMEOUT_IGNORED */ +/* Reuse tokens from ARB_texture_multisample */ +/* reuse GL_SAMPLE_POSITION */ +/* reuse GL_SAMPLE_MASK */ +/* reuse GL_SAMPLE_MASK_VALUE */ +/* reuse GL_MAX_SAMPLE_MASK_WORDS */ +/* reuse GL_TEXTURE_2D_MULTISAMPLE */ +/* reuse GL_PROXY_TEXTURE_2D_MULTISAMPLE */ +/* reuse GL_TEXTURE_2D_MULTISAMPLE_ARRAY */ +/* reuse GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY */ +/* reuse GL_TEXTURE_BINDING_2D_MULTISAMPLE */ +/* reuse GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY */ +/* reuse GL_TEXTURE_SAMPLES */ +/* reuse GL_TEXTURE_FIXED_SAMPLE_LOCATIONS */ +/* reuse GL_SAMPLER_2D_MULTISAMPLE */ +/* reuse GL_INT_SAMPLER_2D_MULTISAMPLE */ +/* reuse GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE */ +/* reuse GL_SAMPLER_2D_MULTISAMPLE_ARRAY */ +/* reuse GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY */ +/* reuse GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY */ +/* reuse GL_MAX_COLOR_TEXTURE_SAMPLES */ +/* reuse GL_MAX_DEPTH_TEXTURE_SAMPLES */ +/* reuse GL_MAX_INTEGER_SAMPLES */ +/* Don't need to reuse tokens from ARB_vertex_array_bgra since they're already in 1.2 core */ +#endif + +#ifndef GL_VERSION_3_3 +#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE +/* Reuse tokens from ARB_blend_func_extended */ +/* reuse GL_SRC1_COLOR */ +/* reuse GL_ONE_MINUS_SRC1_COLOR */ +/* reuse GL_ONE_MINUS_SRC1_ALPHA */ +/* reuse GL_MAX_DUAL_SOURCE_DRAW_BUFFERS */ +/* Reuse tokens from ARB_explicit_attrib_location (none) */ +/* Reuse tokens from ARB_occlusion_query2 */ +/* reuse GL_ANY_SAMPLES_PASSED */ +/* Reuse tokens from ARB_sampler_objects */ +/* reuse GL_SAMPLER_BINDING */ +/* Reuse tokens from ARB_shader_bit_encoding (none) */ +/* Reuse tokens from ARB_texture_rgb10_a2ui */ +/* reuse GL_RGB10_A2UI */ +/* Reuse tokens from ARB_texture_swizzle */ +/* reuse GL_TEXTURE_SWIZZLE_R */ +/* reuse GL_TEXTURE_SWIZZLE_G */ +/* reuse GL_TEXTURE_SWIZZLE_B */ +/* reuse GL_TEXTURE_SWIZZLE_A */ +/* reuse GL_TEXTURE_SWIZZLE_RGBA */ +/* Reuse tokens from ARB_timer_query */ +/* reuse GL_TIME_ELAPSED */ +/* reuse GL_TIMESTAMP */ +/* Reuse tokens from ARB_vertex_type_2_10_10_10_rev */ +/* reuse GL_INT_2_10_10_10_REV */ +#endif + +#ifndef GL_VERSION_4_0 +#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 +/* Reuse tokens from ARB_texture_query_lod (none) */ +/* Reuse tokens from ARB_draw_buffers_blend (none) */ +/* Reuse tokens from ARB_draw_indirect */ +/* reuse GL_DRAW_INDIRECT_BUFFER */ +/* reuse GL_DRAW_INDIRECT_BUFFER_BINDING */ +/* Reuse tokens from ARB_gpu_shader5 */ +/* reuse GL_GEOMETRY_SHADER_INVOCATIONS */ +/* reuse GL_MAX_GEOMETRY_SHADER_INVOCATIONS */ +/* reuse GL_MIN_FRAGMENT_INTERPOLATION_OFFSET */ +/* reuse GL_MAX_FRAGMENT_INTERPOLATION_OFFSET */ +/* reuse GL_FRAGMENT_INTERPOLATION_OFFSET_BITS */ +/* reuse GL_MAX_VERTEX_STREAMS */ +/* Reuse tokens from ARB_gpu_shader_fp64 */ +/* reuse GL_DOUBLE_VEC2 */ +/* reuse GL_DOUBLE_VEC3 */ +/* reuse GL_DOUBLE_VEC4 */ +/* reuse GL_DOUBLE_MAT2 */ +/* reuse GL_DOUBLE_MAT3 */ +/* reuse GL_DOUBLE_MAT4 */ +/* reuse GL_DOUBLE_MAT2x3 */ +/* reuse GL_DOUBLE_MAT2x4 */ +/* reuse GL_DOUBLE_MAT3x2 */ +/* reuse GL_DOUBLE_MAT3x4 */ +/* reuse GL_DOUBLE_MAT4x2 */ +/* reuse GL_DOUBLE_MAT4x3 */ +/* Reuse tokens from ARB_shader_subroutine */ +/* reuse GL_ACTIVE_SUBROUTINES */ +/* reuse GL_ACTIVE_SUBROUTINE_UNIFORMS */ +/* reuse GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS */ +/* reuse GL_ACTIVE_SUBROUTINE_MAX_LENGTH */ +/* reuse GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH */ +/* reuse GL_MAX_SUBROUTINES */ +/* reuse GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS */ +/* reuse GL_NUM_COMPATIBLE_SUBROUTINES */ +/* reuse GL_COMPATIBLE_SUBROUTINES */ +/* Reuse tokens from ARB_tessellation_shader */ +/* reuse GL_PATCHES */ +/* reuse GL_PATCH_VERTICES */ +/* reuse GL_PATCH_DEFAULT_INNER_LEVEL */ +/* reuse GL_PATCH_DEFAULT_OUTER_LEVEL */ +/* reuse GL_TESS_CONTROL_OUTPUT_VERTICES */ +/* reuse GL_TESS_GEN_MODE */ +/* reuse GL_TESS_GEN_SPACING */ +/* reuse GL_TESS_GEN_VERTEX_ORDER */ +/* reuse GL_TESS_GEN_POINT_MODE */ +/* reuse GL_ISOLINES */ +/* reuse GL_FRACTIONAL_ODD */ +/* reuse GL_FRACTIONAL_EVEN */ +/* reuse GL_MAX_PATCH_VERTICES */ +/* reuse GL_MAX_TESS_GEN_LEVEL */ +/* reuse GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS */ +/* reuse GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS */ +/* reuse GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS */ +/* reuse GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS */ +/* reuse GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS */ +/* reuse GL_MAX_TESS_PATCH_COMPONENTS */ +/* reuse GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS */ +/* reuse GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS */ +/* reuse GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS */ +/* reuse GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS */ +/* reuse GL_MAX_TESS_CONTROL_INPUT_COMPONENTS */ +/* reuse GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS */ +/* reuse GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS */ +/* reuse GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS */ +/* reuse GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER */ +/* reuse GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER */ +/* reuse GL_TESS_EVALUATION_SHADER */ +/* reuse GL_TESS_CONTROL_SHADER */ +/* Reuse tokens from ARB_texture_buffer_object_rgb32 (none) */ +/* Reuse tokens from ARB_transform_feedback2 */ +/* reuse GL_TRANSFORM_FEEDBACK */ +/* reuse GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED */ +/* reuse GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE */ +/* reuse GL_TRANSFORM_FEEDBACK_BINDING */ +/* Reuse tokens from ARB_transform_feedback3 */ +/* reuse GL_MAX_TRANSFORM_FEEDBACK_BUFFERS */ +/* reuse GL_MAX_VERTEX_STREAMS */ +#endif + +#ifndef GL_VERSION_4_1 +/* Reuse tokens from ARB_ES2_compatibility */ +/* reuse GL_FIXED */ +/* reuse GL_IMPLEMENTATION_COLOR_READ_TYPE */ +/* reuse GL_IMPLEMENTATION_COLOR_READ_FORMAT */ +/* reuse GL_LOW_FLOAT */ +/* reuse GL_MEDIUM_FLOAT */ +/* reuse GL_HIGH_FLOAT */ +/* reuse GL_LOW_INT */ +/* reuse GL_MEDIUM_INT */ +/* reuse GL_HIGH_INT */ +/* reuse GL_SHADER_COMPILER */ +/* reuse GL_NUM_SHADER_BINARY_FORMATS */ +/* reuse GL_MAX_VERTEX_UNIFORM_VECTORS */ +/* reuse GL_MAX_VARYING_VECTORS */ +/* reuse GL_MAX_FRAGMENT_UNIFORM_VECTORS */ +/* Reuse tokens from ARB_get_program_binary */ +/* reuse GL_PROGRAM_BINARY_RETRIEVABLE_HINT */ +/* reuse GL_PROGRAM_BINARY_LENGTH */ +/* reuse GL_NUM_PROGRAM_BINARY_FORMATS */ +/* reuse GL_PROGRAM_BINARY_FORMATS */ +/* Reuse tokens from ARB_separate_shader_objects */ +/* reuse GL_VERTEX_SHADER_BIT */ +/* reuse GL_FRAGMENT_SHADER_BIT */ +/* reuse GL_GEOMETRY_SHADER_BIT */ +/* reuse GL_TESS_CONTROL_SHADER_BIT */ +/* reuse GL_TESS_EVALUATION_SHADER_BIT */ +/* reuse GL_ALL_SHADER_BITS */ +/* reuse GL_PROGRAM_SEPARABLE */ +/* reuse GL_ACTIVE_PROGRAM */ +/* reuse GL_PROGRAM_PIPELINE_BINDING */ +/* Reuse tokens from ARB_shader_precision (none) */ +/* Reuse tokens from ARB_vertex_attrib_64bit - all are in GL 3.0 and 4.0 already */ +/* Reuse tokens from ARB_viewport_array - some are in GL 1.1 and ARB_provoking_vertex already */ +/* reuse GL_MAX_VIEWPORTS */ +/* reuse GL_VIEWPORT_SUBPIXEL_BITS */ +/* reuse GL_VIEWPORT_BOUNDS_RANGE */ +/* reuse GL_LAYER_PROVOKING_VERTEX */ +/* reuse GL_VIEWPORT_INDEX_PROVOKING_VERTEX */ +/* reuse GL_UNDEFINED_VERTEX */ +#endif + +#ifndef GL_VERSION_4_2 +/* Reuse tokens from ARB_base_instance (none) */ +/* Reuse tokens from ARB_shading_language_420pack (none) */ +/* Reuse tokens from ARB_transform_feedback_instanced (none) */ +/* Reuse tokens from ARB_compressed_texture_pixel_storage */ +/* reuse GL_UNPACK_COMPRESSED_BLOCK_WIDTH */ +/* reuse GL_UNPACK_COMPRESSED_BLOCK_HEIGHT */ +/* reuse GL_UNPACK_COMPRESSED_BLOCK_DEPTH */ +/* reuse GL_UNPACK_COMPRESSED_BLOCK_SIZE */ +/* reuse GL_PACK_COMPRESSED_BLOCK_WIDTH */ +/* reuse GL_PACK_COMPRESSED_BLOCK_HEIGHT */ +/* reuse GL_PACK_COMPRESSED_BLOCK_DEPTH */ +/* reuse GL_PACK_COMPRESSED_BLOCK_SIZE */ +/* Reuse tokens from ARB_conservative_depth (none) */ +/* Reuse tokens from ARB_internalformat_query */ +/* reuse GL_NUM_SAMPLE_COUNTS */ +/* Reuse tokens from ARB_map_buffer_alignment */ +/* reuse GL_MIN_MAP_BUFFER_ALIGNMENT */ +/* Reuse tokens from ARB_shader_atomic_counters */ +/* reuse GL_ATOMIC_COUNTER_BUFFER */ +/* reuse GL_ATOMIC_COUNTER_BUFFER_BINDING */ +/* reuse GL_ATOMIC_COUNTER_BUFFER_START */ +/* reuse GL_ATOMIC_COUNTER_BUFFER_SIZE */ +/* reuse GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE */ +/* reuse GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS */ +/* reuse GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES */ +/* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER */ +/* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER */ +/* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER */ +/* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER */ +/* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER */ +/* reuse GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS */ +/* reuse GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS */ +/* reuse GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS */ +/* reuse GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS */ +/* reuse GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS */ +/* reuse GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS */ +/* reuse GL_MAX_VERTEX_ATOMIC_COUNTERS */ +/* reuse GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS */ +/* reuse GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS */ +/* reuse GL_MAX_GEOMETRY_ATOMIC_COUNTERS */ +/* reuse GL_MAX_FRAGMENT_ATOMIC_COUNTERS */ +/* reuse GL_MAX_COMBINED_ATOMIC_COUNTERS */ +/* reuse GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE */ +/* reuse GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS */ +/* reuse GL_ACTIVE_ATOMIC_COUNTER_BUFFERS */ +/* reuse GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX */ +/* reuse GL_UNSIGNED_INT_ATOMIC_COUNTER */ +/* Reuse tokens from ARB_shader_image_load_store */ +/* reuse GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT */ +/* reuse GL_ELEMENT_ARRAY_BARRIER_BIT */ +/* reuse GL_UNIFORM_BARRIER_BIT */ +/* reuse GL_TEXTURE_FETCH_BARRIER_BIT */ +/* reuse GL_SHADER_IMAGE_ACCESS_BARRIER_BIT */ +/* reuse GL_COMMAND_BARRIER_BIT */ +/* reuse GL_PIXEL_BUFFER_BARRIER_BIT */ +/* reuse GL_TEXTURE_UPDATE_BARRIER_BIT */ +/* reuse GL_BUFFER_UPDATE_BARRIER_BIT */ +/* reuse GL_FRAMEBUFFER_BARRIER_BIT */ +/* reuse GL_TRANSFORM_FEEDBACK_BARRIER_BIT */ +/* reuse GL_ATOMIC_COUNTER_BARRIER_BIT */ +/* reuse GL_ALL_BARRIER_BITS */ +/* reuse GL_MAX_IMAGE_UNITS */ +/* reuse GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS */ +/* reuse GL_IMAGE_BINDING_NAME */ +/* reuse GL_IMAGE_BINDING_LEVEL */ +/* reuse GL_IMAGE_BINDING_LAYERED */ +/* reuse GL_IMAGE_BINDING_LAYER */ +/* reuse GL_IMAGE_BINDING_ACCESS */ +/* reuse GL_IMAGE_1D */ +/* reuse GL_IMAGE_2D */ +/* reuse GL_IMAGE_3D */ +/* reuse GL_IMAGE_2D_RECT */ +/* reuse GL_IMAGE_CUBE */ +/* reuse GL_IMAGE_BUFFER */ +/* reuse GL_IMAGE_1D_ARRAY */ +/* reuse GL_IMAGE_2D_ARRAY */ +/* reuse GL_IMAGE_CUBE_MAP_ARRAY */ +/* reuse GL_IMAGE_2D_MULTISAMPLE */ +/* reuse GL_IMAGE_2D_MULTISAMPLE_ARRAY */ +/* reuse GL_INT_IMAGE_1D */ +/* reuse GL_INT_IMAGE_2D */ +/* reuse GL_INT_IMAGE_3D */ +/* reuse GL_INT_IMAGE_2D_RECT */ +/* reuse GL_INT_IMAGE_CUBE */ +/* reuse GL_INT_IMAGE_BUFFER */ +/* reuse GL_INT_IMAGE_1D_ARRAY */ +/* reuse GL_INT_IMAGE_2D_ARRAY */ +/* reuse GL_INT_IMAGE_CUBE_MAP_ARRAY */ +/* reuse GL_INT_IMAGE_2D_MULTISAMPLE */ +/* reuse GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY */ +/* reuse GL_UNSIGNED_INT_IMAGE_1D */ +/* reuse GL_UNSIGNED_INT_IMAGE_2D */ +/* reuse GL_UNSIGNED_INT_IMAGE_3D */ +/* reuse GL_UNSIGNED_INT_IMAGE_2D_RECT */ +/* reuse GL_UNSIGNED_INT_IMAGE_CUBE */ +/* reuse GL_UNSIGNED_INT_IMAGE_BUFFER */ +/* reuse GL_UNSIGNED_INT_IMAGE_1D_ARRAY */ +/* reuse GL_UNSIGNED_INT_IMAGE_2D_ARRAY */ +/* reuse GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY */ +/* reuse GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE */ +/* reuse GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY */ +/* reuse GL_MAX_IMAGE_SAMPLES */ +/* reuse GL_IMAGE_BINDING_FORMAT */ +/* reuse GL_IMAGE_FORMAT_COMPATIBILITY_TYPE */ +/* reuse GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE */ +/* reuse GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS */ +/* reuse GL_MAX_VERTEX_IMAGE_UNIFORMS */ +/* reuse GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS */ +/* reuse GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS */ +/* reuse GL_MAX_GEOMETRY_IMAGE_UNIFORMS */ +/* reuse GL_MAX_FRAGMENT_IMAGE_UNIFORMS */ +/* reuse GL_MAX_COMBINED_IMAGE_UNIFORMS */ +/* Reuse tokens from ARB_shading_language_packing (none) */ +/* Reuse tokens from ARB_texture_storage */ +/* reuse GL_TEXTURE_IMMUTABLE_FORMAT */ #endif #ifndef GL_ARB_multitexture @@ -997,6 +1658,741 @@ extern "C" { #define GL_PIXEL_UNPACK_BUFFER_BINDING_ARB 0x88EF #endif +#ifndef GL_ARB_depth_buffer_float +#define GL_DEPTH_COMPONENT32F 0x8CAC +#define GL_DEPTH32F_STENCIL8 0x8CAD +#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD +#endif + +#ifndef GL_ARB_draw_instanced +#endif + +#ifndef GL_ARB_framebuffer_object +#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 GL_FRAMEBUFFER_BINDING +#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_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 +#endif + +#ifndef GL_ARB_framebuffer_object_DEPRECATED +#define GL_INDEX 0x8222 +#define GL_TEXTURE_LUMINANCE_TYPE 0x8C14 +#define GL_TEXTURE_INTENSITY_TYPE 0x8C15 +#endif + +#ifndef GL_ARB_framebuffer_sRGB +#define GL_FRAMEBUFFER_SRGB 0x8DB9 +#endif + +#ifndef GL_ARB_geometry_shader4 +#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 +/* reuse GL_MAX_VARYING_COMPONENTS */ +/* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER */ +#endif + +#ifndef GL_ARB_half_float_vertex +#define GL_HALF_FLOAT 0x140B +#endif + +#ifndef GL_ARB_instanced_arrays +#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ARB 0x88FE +#endif + +#ifndef GL_ARB_map_buffer_range +#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 +#endif + +#ifndef GL_ARB_texture_buffer_object +#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 +#endif + +#ifndef GL_ARB_texture_compression_rgtc +#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 +#endif + +#ifndef GL_ARB_texture_rg +#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 +#endif + +#ifndef GL_ARB_vertex_array_object +#define GL_VERTEX_ARRAY_BINDING 0x85B5 +#endif + +#ifndef GL_ARB_uniform_buffer_object +#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 +#endif + +#ifndef GL_ARB_compatibility +/* ARB_compatibility just defines tokens from core 3.0 */ +#endif + +#ifndef GL_ARB_copy_buffer +#define GL_COPY_READ_BUFFER 0x8F36 +#define GL_COPY_WRITE_BUFFER 0x8F37 +#endif + +#ifndef GL_ARB_shader_texture_lod +#endif + +#ifndef GL_ARB_depth_clamp +#define GL_DEPTH_CLAMP 0x864F +#endif + +#ifndef GL_ARB_draw_elements_base_vertex +#endif + +#ifndef GL_ARB_fragment_coord_conventions +#endif + +#ifndef GL_ARB_provoking_vertex +#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 +#endif + +#ifndef GL_ARB_seamless_cube_map +#define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F +#endif + +#ifndef GL_ARB_sync +#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_SYNC_FLUSH_COMMANDS_BIT 0x00000001 +#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull +#endif + +#ifndef GL_ARB_texture_multisample +#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 +#endif + +#ifndef GL_ARB_vertex_array_bgra +/* reuse GL_BGRA */ +#endif + +#ifndef GL_ARB_draw_buffers_blend +#endif + +#ifndef GL_ARB_sample_shading +#define GL_SAMPLE_SHADING_ARB 0x8C36 +#define GL_MIN_SAMPLE_SHADING_VALUE_ARB 0x8C37 +#endif + +#ifndef GL_ARB_texture_cube_map_array +#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 + +#ifndef GL_ARB_texture_gather +#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5E +#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5F +#endif + +#ifndef GL_ARB_texture_query_lod +#endif + +#ifndef GL_ARB_shading_language_include +#define GL_SHADER_INCLUDE_ARB 0x8DAE +#define GL_NAMED_STRING_LENGTH_ARB 0x8DE9 +#define GL_NAMED_STRING_TYPE_ARB 0x8DEA +#endif + +#ifndef GL_ARB_texture_compression_bptc +#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 + +#ifndef GL_ARB_blend_func_extended +#define GL_SRC1_COLOR 0x88F9 +/* reuse GL_SRC1_ALPHA */ +#define GL_ONE_MINUS_SRC1_COLOR 0x88FA +#define GL_ONE_MINUS_SRC1_ALPHA 0x88FB +#define GL_MAX_DUAL_SOURCE_DRAW_BUFFERS 0x88FC +#endif + +#ifndef GL_ARB_explicit_attrib_location +#endif + +#ifndef GL_ARB_occlusion_query2 +#define GL_ANY_SAMPLES_PASSED 0x8C2F +#endif + +#ifndef GL_ARB_sampler_objects +#define GL_SAMPLER_BINDING 0x8919 +#endif + +#ifndef GL_ARB_shader_bit_encoding +#endif + +#ifndef GL_ARB_texture_rgb10_a2ui +#define GL_RGB10_A2UI 0x906F +#endif + +#ifndef GL_ARB_texture_swizzle +#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 +#endif + +#ifndef GL_ARB_timer_query +#define GL_TIME_ELAPSED 0x88BF +#define GL_TIMESTAMP 0x8E28 +#endif + +#ifndef GL_ARB_vertex_type_2_10_10_10_rev +/* reuse GL_UNSIGNED_INT_2_10_10_10_REV */ +#define GL_INT_2_10_10_10_REV 0x8D9F +#endif + +#ifndef GL_ARB_draw_indirect +#define GL_DRAW_INDIRECT_BUFFER 0x8F3F +#define GL_DRAW_INDIRECT_BUFFER_BINDING 0x8F43 +#endif + +#ifndef GL_ARB_gpu_shader5 +#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 +/* reuse GL_MAX_VERTEX_STREAMS */ +#endif + +#ifndef GL_ARB_gpu_shader_fp64 +/* reuse GL_DOUBLE */ +#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 +#endif + +#ifndef GL_ARB_shader_subroutine +#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 +/* reuse GL_UNIFORM_SIZE */ +/* reuse GL_UNIFORM_NAME_LENGTH */ +#endif + +#ifndef GL_ARB_tessellation_shader +#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 +/* reuse GL_TRIANGLES */ +/* reuse GL_QUADS */ +#define GL_ISOLINES 0x8E7A +/* reuse GL_EQUAL */ +#define GL_FRACTIONAL_ODD 0x8E7B +#define GL_FRACTIONAL_EVEN 0x8E7C +/* reuse GL_CCW */ +/* reuse GL_CW */ +#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 +#endif + +#ifndef GL_ARB_texture_buffer_object_rgb32 +/* reuse GL_RGB32F */ +/* reuse GL_RGB32UI */ +/* reuse GL_RGB32I */ +#endif + +#ifndef GL_ARB_transform_feedback2 +#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 +#endif + +#ifndef GL_ARB_transform_feedback3 +#define GL_MAX_TRANSFORM_FEEDBACK_BUFFERS 0x8E70 +#define GL_MAX_VERTEX_STREAMS 0x8E71 +#endif + +#ifndef GL_ARB_ES2_compatibility +#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_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 +#endif + +#ifndef GL_ARB_get_program_binary +#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 +#endif + +#ifndef GL_ARB_separate_shader_objects +#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 +#endif + +#ifndef GL_ARB_shader_precision +#endif + +#ifndef GL_ARB_vertex_attrib_64bit +/* reuse GL_RGB32I */ +/* reuse GL_DOUBLE_VEC2 */ +/* reuse GL_DOUBLE_VEC3 */ +/* reuse GL_DOUBLE_VEC4 */ +/* reuse GL_DOUBLE_MAT2 */ +/* reuse GL_DOUBLE_MAT3 */ +/* reuse GL_DOUBLE_MAT4 */ +/* reuse GL_DOUBLE_MAT2x3 */ +/* reuse GL_DOUBLE_MAT2x4 */ +/* reuse GL_DOUBLE_MAT3x2 */ +/* reuse GL_DOUBLE_MAT3x4 */ +/* reuse GL_DOUBLE_MAT4x2 */ +/* reuse GL_DOUBLE_MAT4x3 */ +#endif + +#ifndef GL_ARB_viewport_array +/* reuse GL_SCISSOR_BOX */ +/* reuse GL_VIEWPORT */ +/* reuse GL_DEPTH_RANGE */ +/* reuse GL_SCISSOR_TEST */ +#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 +/* reuse GL_FIRST_VERTEX_CONVENTION */ +/* reuse GL_LAST_VERTEX_CONVENTION */ +/* reuse GL_PROVOKING_VERTEX */ +#endif + +#ifndef GL_ARB_cl_event +#define GL_SYNC_CL_EVENT_ARB 0x8240 +#define GL_SYNC_CL_EVENT_COMPLETE_ARB 0x8241 +#endif + +#ifndef GL_ARB_debug_output +#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 +#endif + +#ifndef GL_ARB_robustness +/* reuse GL_NO_ERROR */ +#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 +#endif + +#ifndef GL_ARB_shader_stencil_export +#endif + +#ifndef GL_ARB_base_instance +#endif + +#ifndef GL_ARB_shading_language_420pack +#endif + +#ifndef GL_ARB_transform_feedback_instanced +#endif + +#ifndef GL_ARB_compressed_texture_pixel_storage +#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 +#endif + +#ifndef GL_ARB_conservative_depth +#endif + +#ifndef GL_ARB_internalformat_query +#define GL_NUM_SAMPLE_COUNTS 0x9380 +#endif + +#ifndef GL_ARB_map_buffer_alignment +#define GL_MIN_MAP_BUFFER_ALIGNMENT 0x90BC +#endif + +#ifndef GL_ARB_shader_atomic_counters +#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 +#endif + +#ifndef GL_ARB_shader_image_load_store +#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 +#endif + +#ifndef GL_ARB_shading_language_packing +#endif + +#ifndef GL_ARB_texture_storage +#define GL_TEXTURE_IMMUTABLE_FORMAT 0x912F +#endif + #ifndef GL_EXT_abgr #define GL_ABGR_EXT 0x8000 #endif @@ -2257,13 +3653,6 @@ extern "C" { #define GL_UNSIGNED_INT_24_8_NV 0x84FA #endif -#ifndef GL_EXT_packed_depth_stencil -#define GL_DEPTH_STENCIL_EXT 0x84F9 -#define GL_DEPTH24_STENCIL8_EXT 0x88F0 -#define GL_TEXTURE_STENCIL_SIZE_EXT 0x88F1 -#define GL_UNSIGNED_INT_24_8_EXT 0x84FA -#endif - #ifndef GL_NV_register_combiners2 #define GL_PER_STAGE_CONSTANTS_NV 0x8535 #endif @@ -2825,9 +4214,9 @@ extern "C" { #endif #ifndef GL_APPLE_element_array -#define GL_ELEMENT_ARRAY_APPLE 0x8768 -#define GL_ELEMENT_ARRAY_TYPE_APPLE 0x8769 -#define GL_ELEMENT_ARRAY_POINTER_APPLE 0x876A +#define GL_ELEMENT_ARRAY_APPLE 0x8A0C +#define GL_ELEMENT_ARRAY_TYPE_APPLE 0x8A0D +#define GL_ELEMENT_ARRAY_POINTER_APPLE 0x8A0E #endif #ifndef GL_APPLE_fence @@ -2844,6 +4233,7 @@ extern "C" { #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 #define GL_STORAGE_CACHED_APPLE 0x85BE #define GL_STORAGE_SHARED_APPLE 0x85BF #endif @@ -2989,7 +4379,7 @@ extern "C" { #endif #ifndef GL_EXT_blend_equation_separate -#define GL_BLEND_EQUATION_RGB_EXT GL_BLEND_EQUATION +#define GL_BLEND_EQUATION_RGB_EXT 0x8009 #define GL_BLEND_EQUATION_ALPHA_EXT 0x883D #endif @@ -3043,7 +4433,6 @@ extern "C" { #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_DUPLICATE_ATTACHMENT_EXT 0x8CD8 #define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT 0x8CD9 #define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT 0x8CDA #define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT 0x8CDB @@ -3073,7 +4462,6 @@ extern "C" { #define GL_RENDERBUFFER_WIDTH_EXT 0x8D42 #define GL_RENDERBUFFER_HEIGHT_EXT 0x8D43 #define GL_RENDERBUFFER_INTERNAL_FORMAT_EXT 0x8D44 -#define GL_STENCIL_INDEX_EXT 0x8D45 #define GL_STENCIL_INDEX1_EXT 0x8D46 #define GL_STENCIL_INDEX4_EXT 0x8D47 #define GL_STENCIL_INDEX8_EXT 0x8D48 @@ -3089,21 +4477,126 @@ extern "C" { #ifndef GL_GREMEDY_string_marker #endif -#ifndef GL_EXT_Cg_shader -#define GL_CG_VERTEX_SHADER_EXT 0x890E -#define GL_CG_FRAGMENT_SHADER_EXT 0x890F +#ifndef GL_EXT_packed_depth_stencil +#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 + +#ifndef GL_EXT_stencil_clear_tag +#define GL_STENCIL_TAG_BITS_EXT 0x88F2 +#define GL_STENCIL_CLEAR_TAG_VALUE_EXT 0x88F3 +#endif + +#ifndef GL_EXT_texture_sRGB +#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 + +#ifndef GL_EXT_framebuffer_blit +#define GL_READ_FRAMEBUFFER_EXT 0x8CA8 +#define GL_DRAW_FRAMEBUFFER_EXT 0x8CA9 +#define GL_DRAW_FRAMEBUFFER_BINDING_EXT GL_FRAMEBUFFER_BINDING_EXT +#define GL_READ_FRAMEBUFFER_BINDING_EXT 0x8CAA +#endif + +#ifndef GL_EXT_framebuffer_multisample +#define GL_RENDERBUFFER_SAMPLES_EXT 0x8CAB +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT 0x8D56 +#define GL_MAX_SAMPLES_EXT 0x8D57 +#endif + +#ifndef GL_MESAX_texture_stack +#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 #ifndef GL_EXT_timer_query #define GL_TIME_ELAPSED_EXT 0x88BF #endif -#ifndef GL_EXT_texture_buffer_object -#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 +#ifndef GL_EXT_gpu_program_parameters +#endif + +#ifndef GL_APPLE_flush_buffer_range +#define GL_BUFFER_SERIALIZED_MODIFY_APPLE 0x8A12 +#define GL_BUFFER_FLUSHING_UNMAP_APPLE 0x8A13 +#endif + +#ifndef GL_NV_gpu_program4 +#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 +#endif + +#ifndef GL_NV_geometry_program4 +#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_GEOMETRY_PROGRAM_NV 0x8C26 +#define GL_MAX_PROGRAM_OUTPUT_VERTICES_NV 0x8C27 +#define GL_MAX_PROGRAM_TOTAL_OUTPUT_COMPONENTS_NV 0x8C28 +#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_FRAMEBUFFER_ATTACHMENT_LAYERED_EXT 0x8DA7 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_EXT 0x8DA8 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_EXT 0x8DA9 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT 0x8CD4 +#define GL_PROGRAM_POINT_SIZE_EXT 0x8642 +#endif + +#ifndef GL_EXT_geometry_shader4 +#define GL_GEOMETRY_SHADER_EXT 0x8DD9 +/* reuse GL_GEOMETRY_VERTICES_OUT_EXT */ +/* reuse GL_GEOMETRY_INPUT_TYPE_EXT */ +/* reuse GL_GEOMETRY_OUTPUT_TYPE_EXT */ +/* reuse GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_EXT */ +#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 +/* reuse GL_LINES_ADJACENCY_EXT */ +/* reuse GL_LINE_STRIP_ADJACENCY_EXT */ +/* reuse GL_TRIANGLES_ADJACENCY_EXT */ +/* reuse GL_TRIANGLE_STRIP_ADJACENCY_EXT */ +/* reuse GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_EXT */ +/* reuse GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_EXT */ +/* reuse GL_FRAMEBUFFER_ATTACHMENT_LAYERED_EXT */ +/* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT */ +/* reuse GL_PROGRAM_POINT_SIZE_EXT */ +#endif + +#ifndef GL_NV_vertex_program4 +#define GL_VERTEX_ATTRIB_ARRAY_INTEGER_NV 0x88FD #endif #ifndef GL_EXT_gpu_shader4 @@ -3132,50 +4625,9 @@ extern "C" { #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_VERTEX_ATTRIB_ARRAY_INTEGER_EXT 0x88FD #endif -#ifndef GL_EXT_geometry_shader4 -#define GL_GEOMETRY_SHADER_EXT 0x8DD9 -#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_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_LINES_ADJACENCY_EXT 0xA -#define GL_LINE_STRIP_ADJACENCY_EXT 0xB -#define GL_TRIANGLES_ADJACENCY_EXT 0xC -#define GL_TRIANGLE_STRIP_ADJACENCY_EXT 0xD -#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_EXT 0x8DA7 -#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_EXT 0x8DA8 -#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_EXT 0x8DA9 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT 0x8CD4 -#define GL_PROGRAM_POINT_SIZE_EXT 0x8642 -#endif - -#ifndef GL_EXT_bindable_uniform -#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 -#endif - -#ifndef GL_EXT_framebuffer_sRGB -#define GL_FRAMEBUFFER_SRGB_EXT 0x8DB9 -#define GL_FRAMEBUFFER_SRGB_CAPABLE_EXT 0x8DBA -#endif - -#ifndef GL_EXT_texture_shared_exponent -#define GL_RGB9_E5_EXT 0x8C3D -#define GL_UNSIGNED_INT_5_9_9_9_REV_EXT 0x8C3E -#define GL_TEXTURE_SHARED_SIZE_EXT 0x8C3F +#ifndef GL_EXT_draw_instanced #endif #ifndef GL_EXT_packed_float @@ -3193,7 +4645,114 @@ extern "C" { #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 -/* GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT */ +/* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT */ +#endif + +#ifndef GL_EXT_texture_buffer_object +#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 +#endif + +#ifndef GL_EXT_texture_compression_latc +#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 + +#ifndef GL_EXT_texture_compression_rgtc +#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 + +#ifndef GL_EXT_texture_shared_exponent +#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 + +#ifndef GL_NV_depth_buffer_float +#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 +#endif + +#ifndef GL_NV_fragment_program4 +#endif + +#ifndef GL_NV_framebuffer_multisample_coverage +#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 +#endif + +#ifndef GL_EXT_framebuffer_sRGB +#define GL_FRAMEBUFFER_SRGB_EXT 0x8DB9 +#define GL_FRAMEBUFFER_SRGB_CAPABLE_EXT 0x8DBA +#endif + +#ifndef GL_NV_geometry_shader4 +#endif + +#ifndef GL_NV_parameter_buffer_object +#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 +#endif + +#ifndef GL_EXT_draw_buffers2 +#endif + +#ifndef GL_NV_transform_feedback +#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_ATTRIBS_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 +#endif + +#ifndef GL_EXT_bindable_uniform +#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 #endif #ifndef GL_EXT_texture_integer @@ -3246,117 +4805,523 @@ extern "C" { #define GL_RGBA_INTEGER_MODE_EXT 0x8D9E #endif -#ifndef GL_NV_depth_buffer_float -#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 +#ifndef GL_GREMEDY_frame_terminator #endif -#ifndef GL_EXT_texture_compression_latc -#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 +#ifndef GL_NV_conditional_render +#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 #endif -#ifndef GL_NV_transform_feedback -#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_ATTRIBS_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 +#ifndef GL_NV_present_video +#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 #endif -#ifndef GL_NV_geometry_program4 -#define GL_GEOMETRY_PROGRAM_NV 0x8C26 -#define GL_MAX_PROGRAM_OUTPUT_VERTICES_NV 0x8C27 -#define GL_MAX_PROGRAM_TOTAL_OUTPUT_COMPONENTS_NV 0x8C28 +#ifndef GL_EXT_transform_feedback +#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 +#endif + +#ifndef GL_EXT_direct_state_access +#define GL_PROGRAM_MATRIX_EXT 0x8E2D +#define GL_TRANSPOSE_PROGRAM_MATRIX_EXT 0x8E2E +#define GL_PROGRAM_MATRIX_STACK_DEPTH_EXT 0x8E2F +#endif + +#ifndef GL_EXT_vertex_array_bgra +/* reuse GL_BGRA */ +#endif + +#ifndef GL_EXT_texture_swizzle +#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 + +#ifndef GL_NV_explicit_multisample +#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 +#endif + +#ifndef GL_NV_transform_feedback2 +#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 +#endif + +#ifndef GL_ATI_meminfo +#define GL_VBO_FREE_MEMORY_ATI 0x87FB +#define GL_TEXTURE_FREE_MEMORY_ATI 0x87FC +#define GL_RENDERBUFFER_FREE_MEMORY_ATI 0x87FD +#endif + +#ifndef GL_AMD_performance_monitor +#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 +#endif + +#ifndef GL_AMD_texture_texture4 +#endif + +#ifndef GL_AMD_vertex_shader_tesselator +#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 +#endif + +#ifndef GL_EXT_provoking_vertex +#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 +#endif + +#ifndef GL_EXT_texture_snorm +#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 +/* reuse GL_RED_SNORM */ +/* reuse GL_RG_SNORM */ +/* reuse GL_RGB_SNORM */ +/* reuse GL_RGBA_SNORM */ +/* reuse GL_R8_SNORM */ +/* reuse GL_RG8_SNORM */ +/* reuse GL_RGB8_SNORM */ +/* reuse GL_RGBA8_SNORM */ +/* reuse GL_R16_SNORM */ +/* reuse GL_RG16_SNORM */ +/* reuse GL_RGB16_SNORM */ +/* reuse GL_RGBA16_SNORM */ +/* reuse GL_SIGNED_NORMALIZED */ +#endif + +#ifndef GL_AMD_draw_buffers_blend +#endif + +#ifndef GL_APPLE_texture_range +#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 +/* reuse GL_STORAGE_CACHED_APPLE */ +/* reuse GL_STORAGE_SHARED_APPLE */ +#endif + +#ifndef GL_APPLE_float_pixels +#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 + +#ifndef GL_APPLE_vertex_program_evaluators +#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 +#endif + +#ifndef GL_APPLE_aux_depth_stencil +#define GL_AUX_DEPTH_STENCIL_APPLE 0x8A14 +#endif + +#ifndef GL_APPLE_object_purgeable +#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 +#endif + +#ifndef GL_APPLE_row_bytes +#define GL_PACK_ROW_BYTES_APPLE 0x8A15 +#define GL_UNPACK_ROW_BYTES_APPLE 0x8A16 +#endif + +#ifndef GL_APPLE_rgb_422 +#define GL_RGB_422_APPLE 0x8A1F +/* reuse GL_UNSIGNED_SHORT_8_8_APPLE */ +/* reuse GL_UNSIGNED_SHORT_8_8_REV_APPLE */ +#endif + +#ifndef GL_NV_video_capture +#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 +#endif + +#ifndef GL_NV_copy_image +#endif + +#ifndef GL_EXT_separate_shader_objects +#define GL_ACTIVE_PROGRAM_EXT 0x8B8D +#endif + +#ifndef GL_NV_parameter_buffer_object2 +#endif + +#ifndef GL_NV_shader_buffer_load +#define GL_BUFFER_GPU_ADDRESS_NV 0x8F1D +#define GL_GPU_ADDRESS_NV 0x8F34 +#define GL_MAX_SHADER_BUFFER_ADDRESS_NV 0x8F35 +#endif + +#ifndef GL_NV_vertex_buffer_unified_memory +#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 +#endif + +#ifndef GL_NV_texture_barrier +#endif + +#ifndef GL_AMD_shader_stencil_export +#endif + +#ifndef GL_AMD_seamless_cubemap_per_texture +/* reuse GL_TEXTURE_CUBE_MAP_SEAMLESS */ +#endif + +#ifndef GL_AMD_conservative_depth +#endif + +#ifndef GL_EXT_shader_image_load_store +#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 +#endif + +#ifndef GL_EXT_vertex_attrib_64bit +/* reuse GL_DOUBLE */ +#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 +#endif + +#ifndef GL_NV_gpu_program5 +#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 +#endif + +#ifndef GL_NV_gpu_shader5 +#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 +#define GL_FLOAT16_NV 0x8FF8 +#define GL_FLOAT16_VEC2_NV 0x8FF9 +#define GL_FLOAT16_VEC3_NV 0x8FFA +#define GL_FLOAT16_VEC4_NV 0x8FFB +/* reuse GL_PATCHES */ +#endif + +#ifndef GL_NV_shader_buffer_store +#define GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV 0x00000010 +/* reuse GL_READ_WRITE */ +/* reuse GL_WRITE_ONLY */ +#endif + +#ifndef GL_NV_tessellation_program5 +#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 + +#ifndef GL_NV_vertex_attrib_integer_64bit +/* reuse GL_INT64_NV */ +/* reuse GL_UNSIGNED_INT64_NV */ +#endif + +#ifndef GL_NV_multisample_coverage +#define GL_COVERAGE_SAMPLES_NV 0x80A9 +#define GL_COLOR_SAMPLES_NV 0x8E20 +#endif + +#ifndef GL_AMD_name_gen_delete +#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 #endif -#ifndef GL_NV_gpu_program4 -#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 +#ifndef GL_AMD_debug_output +#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 #endif -#ifndef NV_parameter_buffer_object -#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 +#ifndef GL_NV_vdpau_interop +#define GL_SURFACE_STATE_NV 0x86EB +#define GL_SURFACE_REGISTERED_NV 0x86FD +#define GL_SURFACE_MAPPED_NV 0x8700 +#define GL_WRITE_DISCARD_NV 0x88BE #endif -#ifndef GL_NV_framebuffer_multisample_coverage -#define GL_RENDERBUFFER_COVERAGE_SAMPLES_NV 0x8CAB -#define GL_RENDERBUFFER_COLOR_SAMPLES_NV 0x8E10 -#define GL_MAX_RENDERBUFFER_COVERAGE_SAMPLES_NV 0x8D57 -#define GL_MAX_RENDERBUFFER_COLOR_SAMPLES_NV 0x8E11 -#define GL_MAX_MULTISAMPLE_COVERAGE_MODES_NV 0x8E12 -#define GL_MULTISAMPLE_COVERAGE_MODES_NV 0x8E13 +#ifndef GL_AMD_transform_feedback3_lines_triangles #endif -#ifndef GL_EXT_framebuffer_multisample -#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT 0x8D56 -#define GL_MAX_SAMPLES_EXT 0x8D57 -#define GL_RENDERBUFFER_SAMPLES_EXT 0x8CAB +#ifndef GL_AMD_depth_clamp_separate +#define GL_DEPTH_CLAMP_NEAR_AMD 0x901E +#define GL_DEPTH_CLAMP_FAR_AMD 0x901F #endif -#ifndef GL_EXT_framebuffer_blit -#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 +#ifndef GL_EXT_texture_sRGB_decode +#define GL_TEXTURE_SRGB_DECODE_EXT 0x8A48 +#define GL_DECODE_EXT 0x8A49 +#define GL_SKIP_DECODE_EXT 0x8A4A #endif -#ifndef GL_EXT_texture_compression_rgtc -#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 +#ifndef GL_NV_texture_multisample +#define GL_TEXTURE_COVERAGE_SAMPLES_NV 0x9045 +#define GL_TEXTURE_COLOR_SAMPLES_NV 0x9046 #endif -#ifndef GL_NV_present_video -#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 +#ifndef GL_AMD_blend_minmax_factor +#define GL_FACTOR_MIN_AMD 0x901C +#define GL_FACTOR_MAX_AMD 0x901D +#endif + +#ifndef GL_AMD_sample_positions +#define GL_SUBSAMPLE_DISTANCE_AMD 0x883F +#endif + +#ifndef GL_EXT_x11_sync_object +#define GL_SYNC_X11_FENCE_EXT 0x90E1 +#endif + +#ifndef GL_AMD_multi_draw_indirect +#endif + +#ifndef GL_EXT_framebuffer_multisample_blit_scaled +#define GL_SCALED_RESOLVE_FASTEST_EXT 0x90BA +#define GL_SCALED_RESOLVE_NICEST_EXT 0x90BB +#endif + +#ifndef GL_AMD_pinned_memory +#define GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD 0x9160 #endif + /*************************************************************/ #include #ifndef GL_VERSION_2_0 /* GL type for program/shader text */ -typedef char GLchar; /* native character */ +typedef char GLchar; #endif #ifndef GL_VERSION_1_5 @@ -3372,12 +5337,12 @@ typedef ptrdiff_t GLsizeiptrARB; #endif #ifndef GL_ARB_shader_objects -/* GL types for handling shader object handles and program/shader text */ -typedef char GLcharARB; /* native character */ -typedef unsigned int GLhandleARB; /* shader object handle */ +/* GL types for program/shader text and shader object handles */ +typedef char GLcharARB; +typedef unsigned int GLhandleARB; #endif -/* GL types for "half" precision (s10e5) float data in host memory */ +/* GL type for "half" precision (s10e5) float data in host memory */ #ifndef GL_ARB_half_float_pixel typedef unsigned short GLhalfARB; #endif @@ -3386,56 +5351,127 @@ typedef unsigned short GLhalfARB; typedef unsigned short GLhalfNV; #endif +#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 + #ifndef GL_EXT_timer_query -typedef signed long long GLint64EXT; -typedef unsigned long long GLuint64EXT; +typedef int64_t GLint64EXT; +typedef uint64_t GLuint64EXT; +#endif + +#ifndef GL_ARB_sync +typedef int64_t GLint64; +typedef uint64_t GLuint64; +typedef struct __GLsync *GLsync; +#endif + +#ifndef GL_ARB_cl_event +/* These incomplete types let us declare types compatible with OpenCL's cl_context and cl_event */ +struct _cl_context; +struct _cl_event; +#endif + +#ifndef GL_ARB_debug_output +typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,GLvoid *userParam); +#endif + +#ifndef GL_AMD_debug_output +typedef void (APIENTRY *GLDEBUGPROCAMD)(GLuint id,GLenum category,GLenum severity,GLsizei length,const GLchar *message,GLvoid *userParam); +#endif + +#ifndef GL_NV_vdpau_interop +typedef GLintptr GLvdpauSurfaceNV; #endif #ifndef GL_VERSION_1_2 #define GL_VERSION_1_2 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glBlendColor (GLclampf, GLclampf, GLclampf, GLclampf); -extern void APIENTRY glBlendEquation (GLenum); -extern void APIENTRY glDrawRangeElements (GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *); -extern void APIENTRY glColorTable (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *); -extern void APIENTRY glColorTableParameterfv (GLenum, GLenum, const GLfloat *); -extern void APIENTRY glColorTableParameteriv (GLenum, GLenum, const GLint *); -extern void APIENTRY glCopyColorTable (GLenum, GLenum, GLint, GLint, GLsizei); -extern void APIENTRY glGetColorTable (GLenum, GLenum, GLenum, GLvoid *); -extern void APIENTRY glGetColorTableParameterfv (GLenum, GLenum, GLfloat *); -extern void APIENTRY glGetColorTableParameteriv (GLenum, GLenum, GLint *); -extern void APIENTRY glColorSubTable (GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); -extern void APIENTRY glCopyColorSubTable (GLenum, GLsizei, GLint, GLint, GLsizei); -extern void APIENTRY glConvolutionFilter1D (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *); -extern void APIENTRY glConvolutionFilter2D (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); -extern void APIENTRY glConvolutionParameterf (GLenum, GLenum, GLfloat); -extern void APIENTRY glConvolutionParameterfv (GLenum, GLenum, const GLfloat *); -extern void APIENTRY glConvolutionParameteri (GLenum, GLenum, GLint); -extern void APIENTRY glConvolutionParameteriv (GLenum, GLenum, const GLint *); -extern void APIENTRY glCopyConvolutionFilter1D (GLenum, GLenum, GLint, GLint, GLsizei); -extern void APIENTRY glCopyConvolutionFilter2D (GLenum, GLenum, GLint, GLint, GLsizei, GLsizei); -extern void APIENTRY glGetConvolutionFilter (GLenum, GLenum, GLenum, GLvoid *); -extern void APIENTRY glGetConvolutionParameterfv (GLenum, GLenum, GLfloat *); -extern void APIENTRY glGetConvolutionParameteriv (GLenum, GLenum, GLint *); -extern void APIENTRY glGetSeparableFilter (GLenum, GLenum, GLenum, GLvoid *, GLvoid *, GLvoid *); -extern void APIENTRY glSeparableFilter2D (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *, const GLvoid *); -extern void APIENTRY glGetHistogram (GLenum, GLboolean, GLenum, GLenum, GLvoid *); -extern void APIENTRY glGetHistogramParameterfv (GLenum, GLenum, GLfloat *); -extern void APIENTRY glGetHistogramParameteriv (GLenum, GLenum, GLint *); -extern void APIENTRY glGetMinmax (GLenum, GLboolean, GLenum, GLenum, GLvoid *); -extern void APIENTRY glGetMinmaxParameterfv (GLenum, GLenum, GLfloat *); -extern void APIENTRY glGetMinmaxParameteriv (GLenum, GLenum, GLint *); -extern void APIENTRY glHistogram (GLenum, GLsizei, GLenum, GLboolean); -extern void APIENTRY glMinmax (GLenum, GLenum, GLboolean); -extern void APIENTRY glResetHistogram (GLenum); -extern void APIENTRY glResetMinmax (GLenum); -extern void APIENTRY glTexImage3D (GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *); -extern void APIENTRY glTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); -extern void APIENTRY glCopyTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei); +GLAPI void APIENTRY glBlendColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); +GLAPI void APIENTRY glBlendEquation (GLenum mode); +GLAPI void APIENTRY glDrawRangeElements (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices); +GLAPI void APIENTRY glTexImage3D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *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 GLvoid *pixels); +GLAPI void APIENTRY glCopyTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBLENDCOLORPROC) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode); typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices); +typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *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 GLvoid *pixels); +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +#endif + +#ifndef GL_VERSION_1_2_DEPRECATED +#define GL_VERSION_1_2_DEPRECATED 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorTable (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *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, GLvoid *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 GLvoid *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 GLvoid *image); +GLAPI void APIENTRY glConvolutionFilter2D (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *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, GLvoid *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, GLvoid *row, GLvoid *column, GLvoid *span); +GLAPI void APIENTRY glSeparableFilter2D (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column); +GLAPI void APIENTRY glGetHistogram (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *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, GLvoid *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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table); typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params); typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params); @@ -3468,62 +5504,73 @@ typedef void (APIENTRYP PFNGLHISTOGRAMPROC) (GLenum target, GLsizei width, GLenu typedef void (APIENTRYP PFNGLMINMAXPROC) (GLenum target, GLenum internalformat, GLboolean sink); typedef void (APIENTRYP PFNGLRESETHISTOGRAMPROC) (GLenum target); typedef void (APIENTRYP PFNGLRESETMINMAXPROC) (GLenum target); -typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *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 GLvoid *pixels); -typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); #endif #ifndef GL_VERSION_1_3 #define GL_VERSION_1_3 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glActiveTexture (GLenum); -extern void APIENTRY glClientActiveTexture (GLenum); -extern void APIENTRY glMultiTexCoord1d (GLenum, GLdouble); -extern void APIENTRY glMultiTexCoord1dv (GLenum, const GLdouble *); -extern void APIENTRY glMultiTexCoord1f (GLenum, GLfloat); -extern void APIENTRY glMultiTexCoord1fv (GLenum, const GLfloat *); -extern void APIENTRY glMultiTexCoord1i (GLenum, GLint); -extern void APIENTRY glMultiTexCoord1iv (GLenum, const GLint *); -extern void APIENTRY glMultiTexCoord1s (GLenum, GLshort); -extern void APIENTRY glMultiTexCoord1sv (GLenum, const GLshort *); -extern void APIENTRY glMultiTexCoord2d (GLenum, GLdouble, GLdouble); -extern void APIENTRY glMultiTexCoord2dv (GLenum, const GLdouble *); -extern void APIENTRY glMultiTexCoord2f (GLenum, GLfloat, GLfloat); -extern void APIENTRY glMultiTexCoord2fv (GLenum, const GLfloat *); -extern void APIENTRY glMultiTexCoord2i (GLenum, GLint, GLint); -extern void APIENTRY glMultiTexCoord2iv (GLenum, const GLint *); -extern void APIENTRY glMultiTexCoord2s (GLenum, GLshort, GLshort); -extern void APIENTRY glMultiTexCoord2sv (GLenum, const GLshort *); -extern void APIENTRY glMultiTexCoord3d (GLenum, GLdouble, GLdouble, GLdouble); -extern void APIENTRY glMultiTexCoord3dv (GLenum, const GLdouble *); -extern void APIENTRY glMultiTexCoord3f (GLenum, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glMultiTexCoord3fv (GLenum, const GLfloat *); -extern void APIENTRY glMultiTexCoord3i (GLenum, GLint, GLint, GLint); -extern void APIENTRY glMultiTexCoord3iv (GLenum, const GLint *); -extern void APIENTRY glMultiTexCoord3s (GLenum, GLshort, GLshort, GLshort); -extern void APIENTRY glMultiTexCoord3sv (GLenum, const GLshort *); -extern void APIENTRY glMultiTexCoord4d (GLenum, GLdouble, GLdouble, GLdouble, GLdouble); -extern void APIENTRY glMultiTexCoord4dv (GLenum, const GLdouble *); -extern void APIENTRY glMultiTexCoord4f (GLenum, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glMultiTexCoord4fv (GLenum, const GLfloat *); -extern void APIENTRY glMultiTexCoord4i (GLenum, GLint, GLint, GLint, GLint); -extern void APIENTRY glMultiTexCoord4iv (GLenum, const GLint *); -extern void APIENTRY glMultiTexCoord4s (GLenum, GLshort, GLshort, GLshort, GLshort); -extern void APIENTRY glMultiTexCoord4sv (GLenum, const GLshort *); -extern void APIENTRY glLoadTransposeMatrixf (const GLfloat *); -extern void APIENTRY glLoadTransposeMatrixd (const GLdouble *); -extern void APIENTRY glMultTransposeMatrixf (const GLfloat *); -extern void APIENTRY glMultTransposeMatrixd (const GLdouble *); -extern void APIENTRY glSampleCoverage (GLclampf, GLboolean); -extern void APIENTRY glCompressedTexImage3D (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *); -extern void APIENTRY glCompressedTexImage2D (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *); -extern void APIENTRY glCompressedTexImage1D (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const GLvoid *); -extern void APIENTRY glCompressedTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *); -extern void APIENTRY glCompressedTexSubImage2D (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *); -extern void APIENTRY glCompressedTexSubImage1D (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const GLvoid *); -extern void APIENTRY glGetCompressedTexImage (GLenum, GLint, GLvoid *); +GLAPI void APIENTRY glActiveTexture (GLenum texture); +GLAPI void APIENTRY glSampleCoverage (GLclampf value, GLboolean invert); +GLAPI void APIENTRY glCompressedTexImage3D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data); +GLAPI void APIENTRY glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data); +GLAPI void APIENTRY glCompressedTexImage1D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *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 GLvoid *data); +GLAPI void APIENTRY glCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data); +GLAPI void APIENTRY glCompressedTexSubImage1D (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data); +GLAPI void APIENTRY glGetCompressedTexImage (GLenum target, GLint level, GLvoid *img); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLclampf value, GLboolean invert); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *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 GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint level, GLvoid *img); +#endif + +#ifndef GL_VERSION_1_3_DEPRECATED +#define GL_VERSION_1_3_DEPRECATED 1 +#ifdef GL_GLEXT_PROTOTYPES +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC) (GLenum texture); typedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC) (GLenum target, GLdouble s); typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC) (GLenum target, const GLdouble *v); @@ -3561,77 +5608,75 @@ 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); -typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLclampf value, GLboolean invert); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *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 GLvoid *data); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data); -typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint level, GLvoid *img); #endif #ifndef GL_VERSION_1_4 #define GL_VERSION_1_4 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glBlendFuncSeparate (GLenum, GLenum, GLenum, GLenum); -extern void APIENTRY glFogCoordf (GLfloat); -extern void APIENTRY glFogCoordfv (const GLfloat *); -extern void APIENTRY glFogCoordd (GLdouble); -extern void APIENTRY glFogCoorddv (const GLdouble *); -extern void APIENTRY glFogCoordPointer (GLenum, GLsizei, const GLvoid *); -extern void APIENTRY glMultiDrawArrays (GLenum, GLint *, GLsizei *, GLsizei); -extern void APIENTRY glMultiDrawElements (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei); -extern void APIENTRY glPointParameterf (GLenum, GLfloat); -extern void APIENTRY glPointParameterfv (GLenum, const GLfloat *); -extern void APIENTRY glPointParameteri (GLenum, GLint); -extern void APIENTRY glPointParameteriv (GLenum, const GLint *); -extern void APIENTRY glSecondaryColor3b (GLbyte, GLbyte, GLbyte); -extern void APIENTRY glSecondaryColor3bv (const GLbyte *); -extern void APIENTRY glSecondaryColor3d (GLdouble, GLdouble, GLdouble); -extern void APIENTRY glSecondaryColor3dv (const GLdouble *); -extern void APIENTRY glSecondaryColor3f (GLfloat, GLfloat, GLfloat); -extern void APIENTRY glSecondaryColor3fv (const GLfloat *); -extern void APIENTRY glSecondaryColor3i (GLint, GLint, GLint); -extern void APIENTRY glSecondaryColor3iv (const GLint *); -extern void APIENTRY glSecondaryColor3s (GLshort, GLshort, GLshort); -extern void APIENTRY glSecondaryColor3sv (const GLshort *); -extern void APIENTRY glSecondaryColor3ub (GLubyte, GLubyte, GLubyte); -extern void APIENTRY glSecondaryColor3ubv (const GLubyte *); -extern void APIENTRY glSecondaryColor3ui (GLuint, GLuint, GLuint); -extern void APIENTRY glSecondaryColor3uiv (const GLuint *); -extern void APIENTRY glSecondaryColor3us (GLushort, GLushort, GLushort); -extern void APIENTRY glSecondaryColor3usv (const GLushort *); -extern void APIENTRY glSecondaryColorPointer (GLint, GLenum, GLsizei, const GLvoid *); -extern void APIENTRY glWindowPos2d (GLdouble, GLdouble); -extern void APIENTRY glWindowPos2dv (const GLdouble *); -extern void APIENTRY glWindowPos2f (GLfloat, GLfloat); -extern void APIENTRY glWindowPos2fv (const GLfloat *); -extern void APIENTRY glWindowPos2i (GLint, GLint); -extern void APIENTRY glWindowPos2iv (const GLint *); -extern void APIENTRY glWindowPos2s (GLshort, GLshort); -extern void APIENTRY glWindowPos2sv (const GLshort *); -extern void APIENTRY glWindowPos3d (GLdouble, GLdouble, GLdouble); -extern void APIENTRY glWindowPos3dv (const GLdouble *); -extern void APIENTRY glWindowPos3f (GLfloat, GLfloat, GLfloat); -extern void APIENTRY glWindowPos3fv (const GLfloat *); -extern void APIENTRY glWindowPos3i (GLint, GLint, GLint); -extern void APIENTRY glWindowPos3iv (const GLint *); -extern void APIENTRY glWindowPos3s (GLshort, GLshort, GLshort); -extern void APIENTRY glWindowPos3sv (const GLshort *); +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 primcount); +GLAPI void APIENTRY glMultiDrawElements (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount); +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); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); -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 GLvoid *pointer); -typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount); +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount); 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); +#endif + +#ifndef GL_VERSION_1_4_DEPRECATED +#define GL_VERSION_1_4_DEPRECATED 1 +#ifdef GL_GLEXT_PROTOTYPES +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 GLvoid *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 GLvoid *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); +#endif /* GL_GLEXT_PROTOTYPES */ +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 GLvoid *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); @@ -3670,25 +5715,25 @@ typedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC) (const GLshort *v); #ifndef GL_VERSION_1_5 #define GL_VERSION_1_5 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glGenQueries (GLsizei, GLuint *); -extern void APIENTRY glDeleteQueries (GLsizei, const GLuint *); -extern GLboolean APIENTRY glIsQuery (GLuint); -extern void APIENTRY glBeginQuery (GLenum, GLuint); -extern void APIENTRY glEndQuery (GLenum); -extern void APIENTRY glGetQueryiv (GLenum, GLenum, GLint *); -extern void APIENTRY glGetQueryObjectiv (GLuint, GLenum, GLint *); -extern void APIENTRY glGetQueryObjectuiv (GLuint, GLenum, GLuint *); -extern void APIENTRY glBindBuffer (GLenum, GLuint); -extern void APIENTRY glDeleteBuffers (GLsizei, const GLuint *); -extern void APIENTRY glGenBuffers (GLsizei, GLuint *); -extern GLboolean APIENTRY glIsBuffer (GLuint); -extern void APIENTRY glBufferData (GLenum, GLsizeiptr, const GLvoid *, GLenum); -extern void APIENTRY glBufferSubData (GLenum, GLintptr, GLsizeiptr, const GLvoid *); -extern void APIENTRY glGetBufferSubData (GLenum, GLintptr, GLsizeiptr, GLvoid *); -extern GLvoid* APIENTRY glMapBuffer (GLenum, GLenum); -extern GLboolean APIENTRY glUnmapBuffer (GLenum); -extern void APIENTRY glGetBufferParameteriv (GLenum, GLenum, GLint *); -extern void APIENTRY glGetBufferPointerv (GLenum, GLenum, GLvoid* *); +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 GLvoid *data, GLenum usage); +GLAPI void APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data); +GLAPI void APIENTRY glGetBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, GLvoid *data); +GLAPI GLvoid* 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, GLvoid* *params); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLGENQUERIESPROC) (GLsizei n, GLuint *ids); typedef void (APIENTRYP PFNGLDELETEQUERIESPROC) (GLsizei n, const GLuint *ids); @@ -3714,104 +5759,104 @@ typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC) (GLenum target, GLenum pname #ifndef GL_VERSION_2_0 #define GL_VERSION_2_0 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glBlendEquationSeparate (GLenum, GLenum); -extern void APIENTRY glDrawBuffers (GLsizei, const GLenum *); -extern void APIENTRY glStencilOpSeparate (GLenum, GLenum, GLenum, GLenum); -extern void APIENTRY glStencilFuncSeparate (GLenum, GLenum, GLint, GLuint); -extern void APIENTRY glStencilMaskSeparate (GLenum, GLuint); -extern void APIENTRY glAttachShader (GLuint, GLuint); -extern void APIENTRY glBindAttribLocation (GLuint, GLuint, const GLchar *); -extern void APIENTRY glCompileShader (GLuint); -extern GLuint APIENTRY glCreateProgram (void); -extern GLuint APIENTRY glCreateShader (GLenum); -extern void APIENTRY glDeleteProgram (GLuint); -extern void APIENTRY glDeleteShader (GLuint); -extern void APIENTRY glDetachShader (GLuint, GLuint); -extern void APIENTRY glDisableVertexAttribArray (GLuint); -extern void APIENTRY glEnableVertexAttribArray (GLuint); -extern void APIENTRY glGetActiveAttrib (GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *); -extern void APIENTRY glGetActiveUniform (GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *); -extern void APIENTRY glGetAttachedShaders (GLuint, GLsizei, GLsizei *, GLuint *); -extern GLint APIENTRY glGetAttribLocation (GLuint, const GLchar *); -extern void APIENTRY glGetProgramiv (GLuint, GLenum, GLint *); -extern void APIENTRY glGetProgramInfoLog (GLuint, GLsizei, GLsizei *, GLchar *); -extern void APIENTRY glGetShaderiv (GLuint, GLenum, GLint *); -extern void APIENTRY glGetShaderInfoLog (GLuint, GLsizei, GLsizei *, GLchar *); -extern void APIENTRY glGetShaderSource (GLuint, GLsizei, GLsizei *, GLchar *); -extern GLint APIENTRY glGetUniformLocation (GLuint, const GLchar *); -extern void APIENTRY glGetUniformfv (GLuint, GLint, GLfloat *); -extern void APIENTRY glGetUniformiv (GLuint, GLint, GLint *); -extern void APIENTRY glGetVertexAttribdv (GLuint, GLenum, GLdouble *); -extern void APIENTRY glGetVertexAttribfv (GLuint, GLenum, GLfloat *); -extern void APIENTRY glGetVertexAttribiv (GLuint, GLenum, GLint *); -extern void APIENTRY glGetVertexAttribPointerv (GLuint, GLenum, GLvoid* *); -extern GLboolean APIENTRY glIsProgram (GLuint); -extern GLboolean APIENTRY glIsShader (GLuint); -extern void APIENTRY glLinkProgram (GLuint); -extern void APIENTRY glShaderSource (GLuint, GLsizei, const GLchar* *, const GLint *); -extern void APIENTRY glUseProgram (GLuint); -extern void APIENTRY glUniform1f (GLint, GLfloat); -extern void APIENTRY glUniform2f (GLint, GLfloat, GLfloat); -extern void APIENTRY glUniform3f (GLint, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glUniform4f (GLint, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glUniform1i (GLint, GLint); -extern void APIENTRY glUniform2i (GLint, GLint, GLint); -extern void APIENTRY glUniform3i (GLint, GLint, GLint, GLint); -extern void APIENTRY glUniform4i (GLint, GLint, GLint, GLint, GLint); -extern void APIENTRY glUniform1fv (GLint, GLsizei, const GLfloat *); -extern void APIENTRY glUniform2fv (GLint, GLsizei, const GLfloat *); -extern void APIENTRY glUniform3fv (GLint, GLsizei, const GLfloat *); -extern void APIENTRY glUniform4fv (GLint, GLsizei, const GLfloat *); -extern void APIENTRY glUniform1iv (GLint, GLsizei, const GLint *); -extern void APIENTRY glUniform2iv (GLint, GLsizei, const GLint *); -extern void APIENTRY glUniform3iv (GLint, GLsizei, const GLint *); -extern void APIENTRY glUniform4iv (GLint, GLsizei, const GLint *); -extern void APIENTRY glUniformMatrix2fv (GLint, GLsizei, GLboolean, const GLfloat *); -extern void APIENTRY glUniformMatrix3fv (GLint, GLsizei, GLboolean, const GLfloat *); -extern void APIENTRY glUniformMatrix4fv (GLint, GLsizei, GLboolean, const GLfloat *); -extern void APIENTRY glValidateProgram (GLuint); -extern void APIENTRY glVertexAttrib1d (GLuint, GLdouble); -extern void APIENTRY glVertexAttrib1dv (GLuint, const GLdouble *); -extern void APIENTRY glVertexAttrib1f (GLuint, GLfloat); -extern void APIENTRY glVertexAttrib1fv (GLuint, const GLfloat *); -extern void APIENTRY glVertexAttrib1s (GLuint, GLshort); -extern void APIENTRY glVertexAttrib1sv (GLuint, const GLshort *); -extern void APIENTRY glVertexAttrib2d (GLuint, GLdouble, GLdouble); -extern void APIENTRY glVertexAttrib2dv (GLuint, const GLdouble *); -extern void APIENTRY glVertexAttrib2f (GLuint, GLfloat, GLfloat); -extern void APIENTRY glVertexAttrib2fv (GLuint, const GLfloat *); -extern void APIENTRY glVertexAttrib2s (GLuint, GLshort, GLshort); -extern void APIENTRY glVertexAttrib2sv (GLuint, const GLshort *); -extern void APIENTRY glVertexAttrib3d (GLuint, GLdouble, GLdouble, GLdouble); -extern void APIENTRY glVertexAttrib3dv (GLuint, const GLdouble *); -extern void APIENTRY glVertexAttrib3f (GLuint, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glVertexAttrib3fv (GLuint, const GLfloat *); -extern void APIENTRY glVertexAttrib3s (GLuint, GLshort, GLshort, GLshort); -extern void APIENTRY glVertexAttrib3sv (GLuint, const GLshort *); -extern void APIENTRY glVertexAttrib4Nbv (GLuint, const GLbyte *); -extern void APIENTRY glVertexAttrib4Niv (GLuint, const GLint *); -extern void APIENTRY glVertexAttrib4Nsv (GLuint, const GLshort *); -extern void APIENTRY glVertexAttrib4Nub (GLuint, GLubyte, GLubyte, GLubyte, GLubyte); -extern void APIENTRY glVertexAttrib4Nubv (GLuint, const GLubyte *); -extern void APIENTRY glVertexAttrib4Nuiv (GLuint, const GLuint *); -extern void APIENTRY glVertexAttrib4Nusv (GLuint, const GLushort *); -extern void APIENTRY glVertexAttrib4bv (GLuint, const GLbyte *); -extern void APIENTRY glVertexAttrib4d (GLuint, GLdouble, GLdouble, GLdouble, GLdouble); -extern void APIENTRY glVertexAttrib4dv (GLuint, const GLdouble *); -extern void APIENTRY glVertexAttrib4f (GLuint, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glVertexAttrib4fv (GLuint, const GLfloat *); -extern void APIENTRY glVertexAttrib4iv (GLuint, const GLint *); -extern void APIENTRY glVertexAttrib4s (GLuint, GLshort, GLshort, GLshort, GLshort); -extern void APIENTRY glVertexAttrib4sv (GLuint, const GLshort *); -extern void APIENTRY glVertexAttrib4ubv (GLuint, const GLubyte *); -extern void APIENTRY glVertexAttrib4uiv (GLuint, const GLuint *); -extern void APIENTRY glVertexAttrib4usv (GLuint, const GLushort *); -extern void APIENTRY glVertexAttribPointer (GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid *); +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 *obj); +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, GLvoid* *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* *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 GLvoid *pointer); #endif /* GL_GLEXT_PROTOTYPES */ 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 frontfunc, GLenum backfunc, GLint ref, GLuint mask); +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); @@ -3906,12 +5951,12 @@ typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, #ifndef GL_VERSION_2_1 #define GL_VERSION_2_1 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glUniformMatrix2x3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -extern void APIENTRY glUniformMatrix3x2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -extern void APIENTRY glUniformMatrix2x4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -extern void APIENTRY glUniformMatrix4x2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -extern void APIENTRY glUniformMatrix3x4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -extern void APIENTRY glUniformMatrix4x3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +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 /* GL_GLEXT_PROTOTYPES */ 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); @@ -3921,43 +5966,276 @@ typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4FVPROC) (GLint location, GLsizei co typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); #endif +#ifndef GL_VERSION_3_0 +#define GL_VERSION_3_0 1 +/* OpenGL 3.0 also reuses entry points from these extensions: */ +/* ARB_framebuffer_object */ +/* ARB_map_buffer_range */ +/* ARB_vertex_array_object */ +#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* *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 GLvoid *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); +#endif /* GL_GLEXT_PROTOTYPES */ +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* *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 GLvoid *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); +#endif + +#ifndef GL_VERSION_3_1 +#define GL_VERSION_3_1 1 +/* OpenGL 3.1 also reuses entry points from these extensions: */ +/* ARB_copy_buffer */ +/* ARB_uniform_buffer_object */ +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawArraysInstanced (GLenum mode, GLint first, GLsizei count, GLsizei primcount); +GLAPI void APIENTRY glDrawElementsInstanced (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount); +GLAPI void APIENTRY glTexBuffer (GLenum target, GLenum internalformat, GLuint buffer); +GLAPI void APIENTRY glPrimitiveRestartIndex (GLuint index); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDPROC) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount); +typedef void (APIENTRYP PFNGLTEXBUFFERPROC) (GLenum target, GLenum internalformat, GLuint buffer); +typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXPROC) (GLuint index); +#endif + +#ifndef GL_VERSION_3_2 +#define GL_VERSION_3_2 1 +/* OpenGL 3.2 also reuses entry points from these extensions: */ +/* ARB_draw_elements_base_vertex */ +/* ARB_provoking_vertex */ +/* ARB_sync */ +/* ARB_texture_multisample */ +#ifdef GL_GLEXT_PROTOTYPES +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); +#endif /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_VERSION_3_3 +#define GL_VERSION_3_3 1 +/* OpenGL 3.3 also reuses entry points from these extensions: */ +/* ARB_blend_func_extended */ +/* ARB_sampler_objects */ +/* ARB_explicit_attrib_location, but it has none */ +/* ARB_occlusion_query2 (no entry points) */ +/* ARB_shader_bit_encoding (no entry points) */ +/* ARB_texture_rgb10_a2ui (no entry points) */ +/* ARB_texture_swizzle (no entry points) */ +/* ARB_timer_query */ +/* ARB_vertex_type_2_10_10_10_rev */ +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribDivisor (GLuint index, GLuint divisor); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORPROC) (GLuint index, GLuint divisor); +#endif + +#ifndef GL_VERSION_4_0 +#define GL_VERSION_4_0 1 +/* OpenGL 4.0 also reuses entry points from these extensions: */ +/* ARB_texture_query_lod (no entry points) */ +/* ARB_draw_indirect */ +/* ARB_gpu_shader5 (no entry points) */ +/* ARB_gpu_shader_fp64 */ +/* ARB_shader_subroutine */ +/* ARB_tessellation_shader */ +/* ARB_texture_buffer_object_rgb32 (no entry points) */ +/* ARB_texture_cube_map_array (no entry points) */ +/* ARB_texture_gather (no entry points) */ +/* ARB_transform_feedback2 */ +/* ARB_transform_feedback3 */ +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMinSampleShading (GLclampf 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); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLMINSAMPLESHADINGPROC) (GLclampf 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); +#endif + +#ifndef GL_VERSION_4_1 +#define GL_VERSION_4_1 1 +/* OpenGL 4.1 reuses entry points from these extensions: */ +/* ARB_ES2_compatibility */ +/* ARB_get_program_binary */ +/* ARB_separate_shader_objects */ +/* ARB_shader_precision (no entry points) */ +/* ARB_vertex_attrib_64bit */ +/* ARB_viewport_array */ +#endif + +#ifndef GL_VERSION_4_2 +#define GL_VERSION_4_2 1 +/* OpenGL 4.2 reuses entry points from these extensions: */ +/* ARB_base_instance */ +/* ARB_shading_language_420pack (no entry points) */ +/* ARB_transform_feedback_instanced */ +/* ARB_compressed_texture_pixel_storage (no entry points) */ +/* ARB_conservative_depth (no entry points) */ +/* ARB_internalformat_query */ +/* ARB_map_buffer_alignment (no entry points) */ +/* ARB_shader_atomic_counters */ +/* ARB_shader_image_load_store */ +/* ARB_shading_language_packing (no entry points) */ +/* ARB_texture_storage */ +#endif + #ifndef GL_ARB_multitexture #define GL_ARB_multitexture 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glActiveTextureARB (GLenum); -extern void APIENTRY glClientActiveTextureARB (GLenum); -extern void APIENTRY glMultiTexCoord1dARB (GLenum, GLdouble); -extern void APIENTRY glMultiTexCoord1dvARB (GLenum, const GLdouble *); -extern void APIENTRY glMultiTexCoord1fARB (GLenum, GLfloat); -extern void APIENTRY glMultiTexCoord1fvARB (GLenum, const GLfloat *); -extern void APIENTRY glMultiTexCoord1iARB (GLenum, GLint); -extern void APIENTRY glMultiTexCoord1ivARB (GLenum, const GLint *); -extern void APIENTRY glMultiTexCoord1sARB (GLenum, GLshort); -extern void APIENTRY glMultiTexCoord1svARB (GLenum, const GLshort *); -extern void APIENTRY glMultiTexCoord2dARB (GLenum, GLdouble, GLdouble); -extern void APIENTRY glMultiTexCoord2dvARB (GLenum, const GLdouble *); -extern void APIENTRY glMultiTexCoord2fARB (GLenum, GLfloat, GLfloat); -extern void APIENTRY glMultiTexCoord2fvARB (GLenum, const GLfloat *); -extern void APIENTRY glMultiTexCoord2iARB (GLenum, GLint, GLint); -extern void APIENTRY glMultiTexCoord2ivARB (GLenum, const GLint *); -extern void APIENTRY glMultiTexCoord2sARB (GLenum, GLshort, GLshort); -extern void APIENTRY glMultiTexCoord2svARB (GLenum, const GLshort *); -extern void APIENTRY glMultiTexCoord3dARB (GLenum, GLdouble, GLdouble, GLdouble); -extern void APIENTRY glMultiTexCoord3dvARB (GLenum, const GLdouble *); -extern void APIENTRY glMultiTexCoord3fARB (GLenum, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glMultiTexCoord3fvARB (GLenum, const GLfloat *); -extern void APIENTRY glMultiTexCoord3iARB (GLenum, GLint, GLint, GLint); -extern void APIENTRY glMultiTexCoord3ivARB (GLenum, const GLint *); -extern void APIENTRY glMultiTexCoord3sARB (GLenum, GLshort, GLshort, GLshort); -extern void APIENTRY glMultiTexCoord3svARB (GLenum, const GLshort *); -extern void APIENTRY glMultiTexCoord4dARB (GLenum, GLdouble, GLdouble, GLdouble, GLdouble); -extern void APIENTRY glMultiTexCoord4dvARB (GLenum, const GLdouble *); -extern void APIENTRY glMultiTexCoord4fARB (GLenum, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glMultiTexCoord4fvARB (GLenum, const GLfloat *); -extern void APIENTRY glMultiTexCoord4iARB (GLenum, GLint, GLint, GLint, GLint); -extern void APIENTRY glMultiTexCoord4ivARB (GLenum, const GLint *); -extern void APIENTRY glMultiTexCoord4sARB (GLenum, GLshort, GLshort, GLshort, GLshort); -extern void APIENTRY glMultiTexCoord4svARB (GLenum, const GLshort *); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLACTIVETEXTUREARBPROC) (GLenum texture); typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum texture); @@ -3998,10 +6276,10 @@ typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVARBPROC) (GLenum target, const GLsh #ifndef GL_ARB_transpose_matrix #define GL_ARB_transpose_matrix 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glLoadTransposeMatrixfARB (const GLfloat *); -extern void APIENTRY glLoadTransposeMatrixdARB (const GLdouble *); -extern void APIENTRY glMultTransposeMatrixfARB (const GLfloat *); -extern void APIENTRY glMultTransposeMatrixdARB (const GLdouble *); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFARBPROC) (const GLfloat *m); typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDARBPROC) (const GLdouble *m); @@ -4012,7 +6290,7 @@ typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDARBPROC) (const GLdouble *m); #ifndef GL_ARB_multisample #define GL_ARB_multisample 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glSampleCoverageARB (GLclampf, GLboolean); +GLAPI void APIENTRY glSampleCoverageARB (GLclampf value, GLboolean invert); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLSAMPLECOVERAGEARBPROC) (GLclampf value, GLboolean invert); #endif @@ -4028,13 +6306,13 @@ typedef void (APIENTRYP PFNGLSAMPLECOVERAGEARBPROC) (GLclampf value, GLboolean i #ifndef GL_ARB_texture_compression #define GL_ARB_texture_compression 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glCompressedTexImage3DARB (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *); -extern void APIENTRY glCompressedTexImage2DARB (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *); -extern void APIENTRY glCompressedTexImage1DARB (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const GLvoid *); -extern void APIENTRY glCompressedTexSubImage3DARB (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *); -extern void APIENTRY glCompressedTexSubImage2DARB (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *); -extern void APIENTRY glCompressedTexSubImage1DARB (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const GLvoid *); -extern void APIENTRY glGetCompressedTexImageARB (GLenum, GLint, GLvoid *); +GLAPI void APIENTRY glCompressedTexImage3DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data); +GLAPI void APIENTRY glCompressedTexImage2DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data); +GLAPI void APIENTRY glCompressedTexImage1DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *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 GLvoid *data); +GLAPI void APIENTRY glCompressedTexSubImage2DARB (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data); +GLAPI void APIENTRY glCompressedTexSubImage1DARB (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data); +GLAPI void APIENTRY glGetCompressedTexImageARB (GLenum target, GLint level, GLvoid *img); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data); typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data); @@ -4052,8 +6330,8 @@ typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint #ifndef GL_ARB_point_parameters #define GL_ARB_point_parameters 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glPointParameterfARB (GLenum, GLfloat); -extern void APIENTRY glPointParameterfvARB (GLenum, const GLfloat *); +GLAPI void APIENTRY glPointParameterfARB (GLenum pname, GLfloat param); +GLAPI void APIENTRY glPointParameterfvARB (GLenum pname, const GLfloat *params); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPOINTPARAMETERFARBPROC) (GLenum pname, GLfloat param); typedef void (APIENTRYP PFNGLPOINTPARAMETERFVARBPROC) (GLenum pname, const GLfloat *params); @@ -4062,16 +6340,16 @@ typedef void (APIENTRYP PFNGLPOINTPARAMETERFVARBPROC) (GLenum pname, const GLflo #ifndef GL_ARB_vertex_blend #define GL_ARB_vertex_blend 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glWeightbvARB (GLint, const GLbyte *); -extern void APIENTRY glWeightsvARB (GLint, const GLshort *); -extern void APIENTRY glWeightivARB (GLint, const GLint *); -extern void APIENTRY glWeightfvARB (GLint, const GLfloat *); -extern void APIENTRY glWeightdvARB (GLint, const GLdouble *); -extern void APIENTRY glWeightubvARB (GLint, const GLubyte *); -extern void APIENTRY glWeightusvARB (GLint, const GLushort *); -extern void APIENTRY glWeightuivARB (GLint, const GLuint *); -extern void APIENTRY glWeightPointerARB (GLint, GLenum, GLsizei, const GLvoid *); -extern void APIENTRY glVertexBlendARB (GLint); +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 GLvoid *pointer); +GLAPI void APIENTRY glVertexBlendARB (GLint count); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLWEIGHTBVARBPROC) (GLint size, const GLbyte *weights); typedef void (APIENTRYP PFNGLWEIGHTSVARBPROC) (GLint size, const GLshort *weights); @@ -4088,11 +6366,11 @@ typedef void (APIENTRYP PFNGLVERTEXBLENDARBPROC) (GLint count); #ifndef GL_ARB_matrix_palette #define GL_ARB_matrix_palette 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glCurrentPaletteMatrixARB (GLint); -extern void APIENTRY glMatrixIndexubvARB (GLint, const GLubyte *); -extern void APIENTRY glMatrixIndexusvARB (GLint, const GLushort *); -extern void APIENTRY glMatrixIndexuivARB (GLint, const GLuint *); -extern void APIENTRY glMatrixIndexPointerARB (GLint, GLenum, GLsizei, const GLvoid *); +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 GLvoid *pointer); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCURRENTPALETTEMATRIXARBPROC) (GLint index); typedef void (APIENTRYP PFNGLMATRIXINDEXUBVARBPROC) (GLint size, const GLubyte *indices); @@ -4132,22 +6410,22 @@ typedef void (APIENTRYP PFNGLMATRIXINDEXPOINTERARBPROC) (GLint size, GLenum type #ifndef GL_ARB_window_pos #define GL_ARB_window_pos 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glWindowPos2dARB (GLdouble, GLdouble); -extern void APIENTRY glWindowPos2dvARB (const GLdouble *); -extern void APIENTRY glWindowPos2fARB (GLfloat, GLfloat); -extern void APIENTRY glWindowPos2fvARB (const GLfloat *); -extern void APIENTRY glWindowPos2iARB (GLint, GLint); -extern void APIENTRY glWindowPos2ivARB (const GLint *); -extern void APIENTRY glWindowPos2sARB (GLshort, GLshort); -extern void APIENTRY glWindowPos2svARB (const GLshort *); -extern void APIENTRY glWindowPos3dARB (GLdouble, GLdouble, GLdouble); -extern void APIENTRY glWindowPos3dvARB (const GLdouble *); -extern void APIENTRY glWindowPos3fARB (GLfloat, GLfloat, GLfloat); -extern void APIENTRY glWindowPos3fvARB (const GLfloat *); -extern void APIENTRY glWindowPos3iARB (GLint, GLint, GLint); -extern void APIENTRY glWindowPos3ivARB (const GLint *); -extern void APIENTRY glWindowPos3sARB (GLshort, GLshort, GLshort); -extern void APIENTRY glWindowPos3svARB (const GLshort *); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLWINDOWPOS2DARBPROC) (GLdouble x, GLdouble y); typedef void (APIENTRYP PFNGLWINDOWPOS2DVARBPROC) (const GLdouble *v); @@ -4170,68 +6448,68 @@ typedef void (APIENTRYP PFNGLWINDOWPOS3SVARBPROC) (const GLshort *v); #ifndef GL_ARB_vertex_program #define GL_ARB_vertex_program 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glVertexAttrib1dARB (GLuint, GLdouble); -extern void APIENTRY glVertexAttrib1dvARB (GLuint, const GLdouble *); -extern void APIENTRY glVertexAttrib1fARB (GLuint, GLfloat); -extern void APIENTRY glVertexAttrib1fvARB (GLuint, const GLfloat *); -extern void APIENTRY glVertexAttrib1sARB (GLuint, GLshort); -extern void APIENTRY glVertexAttrib1svARB (GLuint, const GLshort *); -extern void APIENTRY glVertexAttrib2dARB (GLuint, GLdouble, GLdouble); -extern void APIENTRY glVertexAttrib2dvARB (GLuint, const GLdouble *); -extern void APIENTRY glVertexAttrib2fARB (GLuint, GLfloat, GLfloat); -extern void APIENTRY glVertexAttrib2fvARB (GLuint, const GLfloat *); -extern void APIENTRY glVertexAttrib2sARB (GLuint, GLshort, GLshort); -extern void APIENTRY glVertexAttrib2svARB (GLuint, const GLshort *); -extern void APIENTRY glVertexAttrib3dARB (GLuint, GLdouble, GLdouble, GLdouble); -extern void APIENTRY glVertexAttrib3dvARB (GLuint, const GLdouble *); -extern void APIENTRY glVertexAttrib3fARB (GLuint, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glVertexAttrib3fvARB (GLuint, const GLfloat *); -extern void APIENTRY glVertexAttrib3sARB (GLuint, GLshort, GLshort, GLshort); -extern void APIENTRY glVertexAttrib3svARB (GLuint, const GLshort *); -extern void APIENTRY glVertexAttrib4NbvARB (GLuint, const GLbyte *); -extern void APIENTRY glVertexAttrib4NivARB (GLuint, const GLint *); -extern void APIENTRY glVertexAttrib4NsvARB (GLuint, const GLshort *); -extern void APIENTRY glVertexAttrib4NubARB (GLuint, GLubyte, GLubyte, GLubyte, GLubyte); -extern void APIENTRY glVertexAttrib4NubvARB (GLuint, const GLubyte *); -extern void APIENTRY glVertexAttrib4NuivARB (GLuint, const GLuint *); -extern void APIENTRY glVertexAttrib4NusvARB (GLuint, const GLushort *); -extern void APIENTRY glVertexAttrib4bvARB (GLuint, const GLbyte *); -extern void APIENTRY glVertexAttrib4dARB (GLuint, GLdouble, GLdouble, GLdouble, GLdouble); -extern void APIENTRY glVertexAttrib4dvARB (GLuint, const GLdouble *); -extern void APIENTRY glVertexAttrib4fARB (GLuint, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glVertexAttrib4fvARB (GLuint, const GLfloat *); -extern void APIENTRY glVertexAttrib4ivARB (GLuint, const GLint *); -extern void APIENTRY glVertexAttrib4sARB (GLuint, GLshort, GLshort, GLshort, GLshort); -extern void APIENTRY glVertexAttrib4svARB (GLuint, const GLshort *); -extern void APIENTRY glVertexAttrib4ubvARB (GLuint, const GLubyte *); -extern void APIENTRY glVertexAttrib4uivARB (GLuint, const GLuint *); -extern void APIENTRY glVertexAttrib4usvARB (GLuint, const GLushort *); -extern void APIENTRY glVertexAttribPointerARB (GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid *); -extern void APIENTRY glEnableVertexAttribArrayARB (GLuint); -extern void APIENTRY glDisableVertexAttribArrayARB (GLuint); -extern void APIENTRY glProgramStringARB (GLenum, GLenum, GLsizei, const GLvoid *); -extern void APIENTRY glBindProgramARB (GLenum, GLuint); -extern void APIENTRY glDeleteProgramsARB (GLsizei, const GLuint *); -extern void APIENTRY glGenProgramsARB (GLsizei, GLuint *); -extern void APIENTRY glProgramEnvParameter4dARB (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble); -extern void APIENTRY glProgramEnvParameter4dvARB (GLenum, GLuint, const GLdouble *); -extern void APIENTRY glProgramEnvParameter4fARB (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glProgramEnvParameter4fvARB (GLenum, GLuint, const GLfloat *); -extern void APIENTRY glProgramLocalParameter4dARB (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble); -extern void APIENTRY glProgramLocalParameter4dvARB (GLenum, GLuint, const GLdouble *); -extern void APIENTRY glProgramLocalParameter4fARB (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glProgramLocalParameter4fvARB (GLenum, GLuint, const GLfloat *); -extern void APIENTRY glGetProgramEnvParameterdvARB (GLenum, GLuint, GLdouble *); -extern void APIENTRY glGetProgramEnvParameterfvARB (GLenum, GLuint, GLfloat *); -extern void APIENTRY glGetProgramLocalParameterdvARB (GLenum, GLuint, GLdouble *); -extern void APIENTRY glGetProgramLocalParameterfvARB (GLenum, GLuint, GLfloat *); -extern void APIENTRY glGetProgramivARB (GLenum, GLenum, GLint *); -extern void APIENTRY glGetProgramStringARB (GLenum, GLenum, GLvoid *); -extern void APIENTRY glGetVertexAttribdvARB (GLuint, GLenum, GLdouble *); -extern void APIENTRY glGetVertexAttribfvARB (GLuint, GLenum, GLfloat *); -extern void APIENTRY glGetVertexAttribivARB (GLuint, GLenum, GLint *); -extern void APIENTRY glGetVertexAttribPointervARB (GLuint, GLenum, GLvoid* *); -extern GLboolean APIENTRY glIsProgramARB (GLuint); +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 GLvoid *pointer); +GLAPI void APIENTRY glEnableVertexAttribArrayARB (GLuint index); +GLAPI void APIENTRY glDisableVertexAttribArrayARB (GLuint index); +GLAPI void APIENTRY glProgramStringARB (GLenum target, GLenum format, GLsizei len, const GLvoid *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, GLvoid *string); +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, GLvoid* *pointer); +GLAPI GLboolean APIENTRY glIsProgramARB (GLuint program); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLVERTEXATTRIB1DARBPROC) (GLuint index, GLdouble x); typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVARBPROC) (GLuint index, const GLdouble *v); @@ -4305,17 +6583,17 @@ typedef GLboolean (APIENTRYP PFNGLISPROGRAMARBPROC) (GLuint program); #ifndef GL_ARB_vertex_buffer_object #define GL_ARB_vertex_buffer_object 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glBindBufferARB (GLenum, GLuint); -extern void APIENTRY glDeleteBuffersARB (GLsizei, const GLuint *); -extern void APIENTRY glGenBuffersARB (GLsizei, GLuint *); -extern GLboolean APIENTRY glIsBufferARB (GLuint); -extern void APIENTRY glBufferDataARB (GLenum, GLsizeiptrARB, const GLvoid *, GLenum); -extern void APIENTRY glBufferSubDataARB (GLenum, GLintptrARB, GLsizeiptrARB, const GLvoid *); -extern void APIENTRY glGetBufferSubDataARB (GLenum, GLintptrARB, GLsizeiptrARB, GLvoid *); -extern GLvoid* APIENTRY glMapBufferARB (GLenum, GLenum); -extern GLboolean APIENTRY glUnmapBufferARB (GLenum); -extern void APIENTRY glGetBufferParameterivARB (GLenum, GLenum, GLint *); -extern void APIENTRY glGetBufferPointervARB (GLenum, GLenum, GLvoid* *); +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 GLvoid *data, GLenum usage); +GLAPI void APIENTRY glBufferSubDataARB (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data); +GLAPI void APIENTRY glGetBufferSubDataARB (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data); +GLAPI GLvoid* 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, GLvoid* *params); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer); typedef void (APIENTRYP PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers); @@ -4333,14 +6611,14 @@ typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVARBPROC) (GLenum target, GLenum pn #ifndef GL_ARB_occlusion_query #define GL_ARB_occlusion_query 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glGenQueriesARB (GLsizei, GLuint *); -extern void APIENTRY glDeleteQueriesARB (GLsizei, const GLuint *); -extern GLboolean APIENTRY glIsQueryARB (GLuint); -extern void APIENTRY glBeginQueryARB (GLenum, GLuint); -extern void APIENTRY glEndQueryARB (GLenum); -extern void APIENTRY glGetQueryivARB (GLenum, GLenum, GLint *); -extern void APIENTRY glGetQueryObjectivARB (GLuint, GLenum, GLint *); -extern void APIENTRY glGetQueryObjectuivARB (GLuint, GLenum, GLuint *); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLGENQUERIESARBPROC) (GLsizei n, GLuint *ids); typedef void (APIENTRYP PFNGLDELETEQUERIESARBPROC) (GLsizei n, const GLuint *ids); @@ -4355,45 +6633,45 @@ typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVARBPROC) (GLuint id, GLenum pname, #ifndef GL_ARB_shader_objects #define GL_ARB_shader_objects 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glDeleteObjectARB (GLhandleARB); -extern GLhandleARB APIENTRY glGetHandleARB (GLenum); -extern void APIENTRY glDetachObjectARB (GLhandleARB, GLhandleARB); -extern GLhandleARB APIENTRY glCreateShaderObjectARB (GLenum); -extern void APIENTRY glShaderSourceARB (GLhandleARB, GLsizei, const GLcharARB* *, const GLint *); -extern void APIENTRY glCompileShaderARB (GLhandleARB); -extern GLhandleARB APIENTRY glCreateProgramObjectARB (void); -extern void APIENTRY glAttachObjectARB (GLhandleARB, GLhandleARB); -extern void APIENTRY glLinkProgramARB (GLhandleARB); -extern void APIENTRY glUseProgramObjectARB (GLhandleARB); -extern void APIENTRY glValidateProgramARB (GLhandleARB); -extern void APIENTRY glUniform1fARB (GLint, GLfloat); -extern void APIENTRY glUniform2fARB (GLint, GLfloat, GLfloat); -extern void APIENTRY glUniform3fARB (GLint, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glUniform4fARB (GLint, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glUniform1iARB (GLint, GLint); -extern void APIENTRY glUniform2iARB (GLint, GLint, GLint); -extern void APIENTRY glUniform3iARB (GLint, GLint, GLint, GLint); -extern void APIENTRY glUniform4iARB (GLint, GLint, GLint, GLint, GLint); -extern void APIENTRY glUniform1fvARB (GLint, GLsizei, const GLfloat *); -extern void APIENTRY glUniform2fvARB (GLint, GLsizei, const GLfloat *); -extern void APIENTRY glUniform3fvARB (GLint, GLsizei, const GLfloat *); -extern void APIENTRY glUniform4fvARB (GLint, GLsizei, const GLfloat *); -extern void APIENTRY glUniform1ivARB (GLint, GLsizei, const GLint *); -extern void APIENTRY glUniform2ivARB (GLint, GLsizei, const GLint *); -extern void APIENTRY glUniform3ivARB (GLint, GLsizei, const GLint *); -extern void APIENTRY glUniform4ivARB (GLint, GLsizei, const GLint *); -extern void APIENTRY glUniformMatrix2fvARB (GLint, GLsizei, GLboolean, const GLfloat *); -extern void APIENTRY glUniformMatrix3fvARB (GLint, GLsizei, GLboolean, const GLfloat *); -extern void APIENTRY glUniformMatrix4fvARB (GLint, GLsizei, GLboolean, const GLfloat *); -extern void APIENTRY glGetObjectParameterfvARB (GLhandleARB, GLenum, GLfloat *); -extern void APIENTRY glGetObjectParameterivARB (GLhandleARB, GLenum, GLint *); -extern void APIENTRY glGetInfoLogARB (GLhandleARB, GLsizei, GLsizei *, GLcharARB *); -extern void APIENTRY glGetAttachedObjectsARB (GLhandleARB, GLsizei, GLsizei *, GLhandleARB *); -extern GLint APIENTRY glGetUniformLocationARB (GLhandleARB, const GLcharARB *); -extern void APIENTRY glGetActiveUniformARB (GLhandleARB, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLcharARB *); -extern void APIENTRY glGetUniformfvARB (GLhandleARB, GLint, GLfloat *); -extern void APIENTRY glGetUniformivARB (GLhandleARB, GLint, GLint *); -extern void APIENTRY glGetShaderSourceARB (GLhandleARB, GLsizei, GLsizei *, GLcharARB *); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLDELETEOBJECTARBPROC) (GLhandleARB obj); typedef GLhandleARB (APIENTRYP PFNGLGETHANDLEARBPROC) (GLenum pname); @@ -4439,9 +6717,9 @@ typedef void (APIENTRYP PFNGLGETSHADERSOURCEARBPROC) (GLhandleARB obj, GLsizei m #ifndef GL_ARB_vertex_shader #define GL_ARB_vertex_shader 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glBindAttribLocationARB (GLhandleARB, GLuint, const GLcharARB *); -extern void APIENTRY glGetActiveAttribARB (GLhandleARB, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLcharARB *); -extern GLint APIENTRY glGetAttribLocationARB (GLhandleARB, const GLcharARB *); +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 /* GL_GLEXT_PROTOTYPES */ 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); @@ -4471,7 +6749,7 @@ typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONARBPROC) (GLhandleARB programObj, #ifndef GL_ARB_draw_buffers #define GL_ARB_draw_buffers 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glDrawBuffersARB (GLsizei, const GLenum *); +GLAPI void APIENTRY glDrawBuffersARB (GLsizei n, const GLenum *bufs); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLDRAWBUFFERSARBPROC) (GLsizei n, const GLenum *bufs); #endif @@ -4483,7 +6761,7 @@ typedef void (APIENTRYP PFNGLDRAWBUFFERSARBPROC) (GLsizei n, const GLenum *bufs) #ifndef GL_ARB_color_buffer_float #define GL_ARB_color_buffer_float 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glClampColorARB (GLenum, GLenum); +GLAPI void APIENTRY glClampColorARB (GLenum target, GLenum clamp); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCLAMPCOLORARBPROC) (GLenum target, GLenum clamp); #endif @@ -4500,6 +6778,948 @@ typedef void (APIENTRYP PFNGLCLAMPCOLORARBPROC) (GLenum target, GLenum clamp); #define GL_ARB_pixel_buffer_object 1 #endif +#ifndef GL_ARB_depth_buffer_float +#define GL_ARB_depth_buffer_float 1 +#endif + +#ifndef GL_ARB_draw_instanced +#define GL_ARB_draw_instanced 1 +#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 GLvoid *indices, GLsizei primcount); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDARBPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDARBPROC) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount); +#endif + +#ifndef GL_ARB_framebuffer_object +#define GL_ARB_framebuffer_object 1 +#ifdef GL_GLEXT_PROTOTYPES +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); +#endif /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_ARB_framebuffer_sRGB +#define GL_ARB_framebuffer_sRGB 1 +#endif + +#ifndef GL_ARB_geometry_shader4 +#define GL_ARB_geometry_shader4 1 +#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 /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_ARB_half_float_vertex +#define GL_ARB_half_float_vertex 1 +#endif + +#ifndef GL_ARB_instanced_arrays +#define GL_ARB_instanced_arrays 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribDivisorARB (GLuint index, GLuint divisor); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORARBPROC) (GLuint index, GLuint divisor); +#endif + +#ifndef GL_ARB_map_buffer_range +#define GL_ARB_map_buffer_range 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLvoid* APIENTRY glMapBufferRange (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); +GLAPI void APIENTRY glFlushMappedBufferRange (GLenum target, GLintptr offset, GLsizeiptr length); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); +typedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length); +#endif + +#ifndef GL_ARB_texture_buffer_object +#define GL_ARB_texture_buffer_object 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexBufferARB (GLenum target, GLenum internalformat, GLuint buffer); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLTEXBUFFERARBPROC) (GLenum target, GLenum internalformat, GLuint buffer); +#endif + +#ifndef GL_ARB_texture_compression_rgtc +#define GL_ARB_texture_compression_rgtc 1 +#endif + +#ifndef GL_ARB_texture_rg +#define GL_ARB_texture_rg 1 +#endif + +#ifndef GL_ARB_vertex_array_object +#define GL_ARB_vertex_array_object 1 +#ifdef GL_GLEXT_PROTOTYPES +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 /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_ARB_uniform_buffer_object +#define GL_ARB_uniform_buffer_object 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetUniformIndices (GLuint program, GLsizei uniformCount, const GLchar* *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 /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLGETUNIFORMINDICESPROC) (GLuint program, GLsizei uniformCount, const GLchar* *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); +#endif + +#ifndef GL_ARB_compatibility +#define GL_ARB_compatibility 1 +#endif + +#ifndef GL_ARB_copy_buffer +#define GL_ARB_copy_buffer 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCopyBufferSubData (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLCOPYBUFFERSUBDATAPROC) (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +#endif + +#ifndef GL_ARB_shader_texture_lod +#define GL_ARB_shader_texture_lod 1 +#endif + +#ifndef GL_ARB_depth_clamp +#define GL_ARB_depth_clamp 1 +#endif + +#ifndef GL_ARB_draw_elements_base_vertex +#define GL_ARB_draw_elements_base_vertex 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawElementsBaseVertex (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLint basevertex); +GLAPI void APIENTRY glDrawRangeElementsBaseVertex (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices, GLint basevertex); +GLAPI void APIENTRY glDrawElementsInstancedBaseVertex (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount, GLint basevertex); +GLAPI void APIENTRY glMultiDrawElementsBaseVertex (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount, const GLint *basevertex); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLint basevertex); +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices, GLint basevertex); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount, GLint basevertex); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount, const GLint *basevertex); +#endif + +#ifndef GL_ARB_fragment_coord_conventions +#define GL_ARB_fragment_coord_conventions 1 +#endif + +#ifndef GL_ARB_provoking_vertex +#define GL_ARB_provoking_vertex 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProvokingVertex (GLenum mode); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLPROVOKINGVERTEXPROC) (GLenum mode); +#endif + +#ifndef GL_ARB_seamless_cube_map +#define GL_ARB_seamless_cube_map 1 +#endif + +#ifndef GL_ARB_sync +#define GL_ARB_sync 1 +#ifdef GL_GLEXT_PROTOTYPES +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 *params); +GLAPI void APIENTRY glGetSynciv (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); +#endif /* GL_GLEXT_PROTOTYPES */ +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 *params); +typedef void (APIENTRYP PFNGLGETSYNCIVPROC) (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); +#endif + +#ifndef GL_ARB_texture_multisample +#define GL_ARB_texture_multisample 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexImage2DMultisample (GLenum target, GLsizei samples, GLint internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTexImage3DMultisample (GLenum target, GLsizei samples, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glGetMultisamplefv (GLenum pname, GLuint index, GLfloat *val); +GLAPI void APIENTRY glSampleMaski (GLuint index, GLbitfield mask); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLint internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLGETMULTISAMPLEFVPROC) (GLenum pname, GLuint index, GLfloat *val); +typedef void (APIENTRYP PFNGLSAMPLEMASKIPROC) (GLuint index, GLbitfield mask); +#endif + +#ifndef GL_ARB_vertex_array_bgra +#define GL_ARB_vertex_array_bgra 1 +#endif + +#ifndef GL_ARB_draw_buffers_blend +#define GL_ARB_draw_buffers_blend 1 +#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 /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_ARB_sample_shading +#define GL_ARB_sample_shading 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMinSampleShadingARB (GLclampf value); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLMINSAMPLESHADINGARBPROC) (GLclampf value); +#endif + +#ifndef GL_ARB_texture_cube_map_array +#define GL_ARB_texture_cube_map_array 1 +#endif + +#ifndef GL_ARB_texture_gather +#define GL_ARB_texture_gather 1 +#endif + +#ifndef GL_ARB_texture_query_lod +#define GL_ARB_texture_query_lod 1 +#endif + +#ifndef GL_ARB_shading_language_include +#define GL_ARB_shading_language_include 1 +#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* *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 /* GL_GLEXT_PROTOTYPES */ +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* *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); +#endif + +#ifndef GL_ARB_texture_compression_bptc +#define GL_ARB_texture_compression_bptc 1 +#endif + +#ifndef GL_ARB_blend_func_extended +#define GL_ARB_blend_func_extended 1 +#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); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONINDEXEDPROC) (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name); +typedef GLint (APIENTRYP PFNGLGETFRAGDATAINDEXPROC) (GLuint program, const GLchar *name); +#endif + +#ifndef GL_ARB_explicit_attrib_location +#define GL_ARB_explicit_attrib_location 1 +#endif + +#ifndef GL_ARB_occlusion_query2 +#define GL_ARB_occlusion_query2 1 +#endif + +#ifndef GL_ARB_sampler_objects +#define GL_ARB_sampler_objects 1 +#ifdef GL_GLEXT_PROTOTYPES +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); +#endif /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_ARB_shader_bit_encoding +#define GL_ARB_shader_bit_encoding 1 +#endif + +#ifndef GL_ARB_texture_rgb10_a2ui +#define GL_ARB_texture_rgb10_a2ui 1 +#endif + +#ifndef GL_ARB_texture_swizzle +#define GL_ARB_texture_swizzle 1 +#endif + +#ifndef GL_ARB_timer_query +#define GL_ARB_timer_query 1 +#ifdef GL_GLEXT_PROTOTYPES +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); +#endif /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_ARB_vertex_type_2_10_10_10_rev +#define GL_ARB_vertex_type_2_10_10_10_rev 1 +#ifdef GL_GLEXT_PROTOTYPES +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); +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); +#endif /* GL_GLEXT_PROTOTYPES */ +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); +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); +#endif + +#ifndef GL_ARB_draw_indirect +#define GL_ARB_draw_indirect 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawArraysIndirect (GLenum mode, const GLvoid *indirect); +GLAPI void APIENTRY glDrawElementsIndirect (GLenum mode, GLenum type, const GLvoid *indirect); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLDRAWARRAYSINDIRECTPROC) (GLenum mode, const GLvoid *indirect); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINDIRECTPROC) (GLenum mode, GLenum type, const GLvoid *indirect); +#endif + +#ifndef GL_ARB_gpu_shader5 +#define GL_ARB_gpu_shader5 1 +#endif + +#ifndef GL_ARB_gpu_shader_fp64 +#define GL_ARB_gpu_shader_fp64 1 +#ifdef GL_GLEXT_PROTOTYPES +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); +#endif /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_ARB_shader_subroutine +#define GL_ARB_shader_subroutine 1 +#ifdef GL_GLEXT_PROTOTYPES +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); +#endif /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_ARB_tessellation_shader +#define GL_ARB_tessellation_shader 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPatchParameteri (GLenum pname, GLint value); +GLAPI void APIENTRY glPatchParameterfv (GLenum pname, const GLfloat *values); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLPATCHPARAMETERIPROC) (GLenum pname, GLint value); +typedef void (APIENTRYP PFNGLPATCHPARAMETERFVPROC) (GLenum pname, const GLfloat *values); +#endif + +#ifndef GL_ARB_texture_buffer_object_rgb32 +#define GL_ARB_texture_buffer_object_rgb32 1 +#endif + +#ifndef GL_ARB_transform_feedback2 +#define GL_ARB_transform_feedback2 1 +#ifdef GL_GLEXT_PROTOTYPES +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); +#endif /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_ARB_transform_feedback3 +#define GL_ARB_transform_feedback3 1 +#ifdef GL_GLEXT_PROTOTYPES +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 /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_ARB_ES2_compatibility +#define GL_ARB_ES2_compatibility 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glReleaseShaderCompiler (void); +GLAPI void APIENTRY glShaderBinary (GLsizei count, const GLuint *shaders, GLenum binaryformat, const GLvoid *binary, GLsizei length); +GLAPI void APIENTRY glGetShaderPrecisionFormat (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); +GLAPI void APIENTRY glDepthRangef (GLclampf n, GLclampf f); +GLAPI void APIENTRY glClearDepthf (GLclampf d); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLRELEASESHADERCOMPILERPROC) (void); +typedef void (APIENTRYP PFNGLSHADERBINARYPROC) (GLsizei count, const GLuint *shaders, GLenum binaryformat, const GLvoid *binary, GLsizei length); +typedef void (APIENTRYP PFNGLGETSHADERPRECISIONFORMATPROC) (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); +typedef void (APIENTRYP PFNGLDEPTHRANGEFPROC) (GLclampf n, GLclampf f); +typedef void (APIENTRYP PFNGLCLEARDEPTHFPROC) (GLclampf d); +#endif + +#ifndef GL_ARB_get_program_binary +#define GL_ARB_get_program_binary 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetProgramBinary (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, GLvoid *binary); +GLAPI void APIENTRY glProgramBinary (GLuint program, GLenum binaryFormat, const GLvoid *binary, GLsizei length); +GLAPI void APIENTRY glProgramParameteri (GLuint program, GLenum pname, GLint value); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLGETPROGRAMBINARYPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, GLvoid *binary); +typedef void (APIENTRYP PFNGLPROGRAMBINARYPROC) (GLuint program, GLenum binaryFormat, const GLvoid *binary, GLsizei length); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIPROC) (GLuint program, GLenum pname, GLint value); +#endif + +#ifndef GL_ARB_separate_shader_objects +#define GL_ARB_separate_shader_objects 1 +#ifdef GL_GLEXT_PROTOTYPES +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* *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); +#endif /* GL_GLEXT_PROTOTYPES */ +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* *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); +#endif + +#ifndef GL_ARB_vertex_attrib_64bit +#define GL_ARB_vertex_attrib_64bit 1 +#ifdef GL_GLEXT_PROTOTYPES +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 GLvoid *pointer); +GLAPI void APIENTRY glGetVertexAttribLdv (GLuint index, GLenum pname, GLdouble *params); +#endif /* GL_GLEXT_PROTOTYPES */ +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 GLvoid *pointer); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLDVPROC) (GLuint index, GLenum pname, GLdouble *params); +#endif + +#ifndef GL_ARB_viewport_array +#define GL_ARB_viewport_array 1 +#ifdef GL_GLEXT_PROTOTYPES +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 GLclampd *v); +GLAPI void APIENTRY glDepthRangeIndexed (GLuint index, GLclampd n, GLclampd f); +GLAPI void APIENTRY glGetFloati_v (GLenum target, GLuint index, GLfloat *data); +GLAPI void APIENTRY glGetDoublei_v (GLenum target, GLuint index, GLdouble *data); +#endif /* GL_GLEXT_PROTOTYPES */ +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 GLclampd *v); +typedef void (APIENTRYP PFNGLDEPTHRANGEINDEXEDPROC) (GLuint index, GLclampd n, GLclampd f); +typedef void (APIENTRYP PFNGLGETFLOATI_VPROC) (GLenum target, GLuint index, GLfloat *data); +typedef void (APIENTRYP PFNGLGETDOUBLEI_VPROC) (GLenum target, GLuint index, GLdouble *data); +#endif + +#ifndef GL_ARB_cl_event +#define GL_ARB_cl_event 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLsync APIENTRY glCreateSyncFromCLeventARB (struct _cl_context * context, struct _cl_event * event, GLbitfield flags); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef GLsync (APIENTRYP PFNGLCREATESYNCFROMCLEVENTARBPROC) (struct _cl_context * context, struct _cl_event * event, GLbitfield flags); +#endif + +#ifndef GL_ARB_debug_output +#define GL_ARB_debug_output 1 +#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 GLvoid *userParam); +GLAPI GLuint APIENTRY glGetDebugMessageLogARB (GLuint count, GLsizei bufsize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); +#endif /* GL_GLEXT_PROTOTYPES */ +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 GLvoid *userParam); +typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGARBPROC) (GLuint count, GLsizei bufsize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); +#endif + +#ifndef GL_ARB_robustness +#define GL_ARB_robustness 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLenum APIENTRY glGetGraphicsResetStatusARB (void); +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, GLvoid *table); +GLAPI void APIENTRY glGetnConvolutionFilterARB (GLenum target, GLenum format, GLenum type, GLsizei bufSize, GLvoid *image); +GLAPI void APIENTRY glGetnSeparableFilterARB (GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, GLvoid *row, GLsizei columnBufSize, GLvoid *column, GLvoid *span); +GLAPI void APIENTRY glGetnHistogramARB (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, GLvoid *values); +GLAPI void APIENTRY glGetnMinmaxARB (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, GLvoid *values); +GLAPI void APIENTRY glGetnTexImageARB (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, GLvoid *img); +GLAPI void APIENTRY glReadnPixelsARB (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, GLvoid *data); +GLAPI void APIENTRY glGetnCompressedTexImageARB (GLenum target, GLint lod, GLsizei bufSize, GLvoid *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); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef GLenum (APIENTRYP PFNGLGETGRAPHICSRESETSTATUSARBPROC) (void); +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, GLvoid *table); +typedef void (APIENTRYP PFNGLGETNCONVOLUTIONFILTERARBPROC) (GLenum target, GLenum format, GLenum type, GLsizei bufSize, GLvoid *image); +typedef void (APIENTRYP PFNGLGETNSEPARABLEFILTERARBPROC) (GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, GLvoid *row, GLsizei columnBufSize, GLvoid *column, GLvoid *span); +typedef void (APIENTRYP PFNGLGETNHISTOGRAMARBPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, GLvoid *values); +typedef void (APIENTRYP PFNGLGETNMINMAXARBPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, GLvoid *values); +typedef void (APIENTRYP PFNGLGETNTEXIMAGEARBPROC) (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, GLvoid *img); +typedef void (APIENTRYP PFNGLREADNPIXELSARBPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, GLvoid *data); +typedef void (APIENTRYP PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint lod, GLsizei bufSize, GLvoid *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); +#endif + +#ifndef GL_ARB_shader_stencil_export +#define GL_ARB_shader_stencil_export 1 +#endif + +#ifndef GL_ARB_base_instance +#define GL_ARB_base_instance 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawArraysInstancedBaseInstance (GLenum mode, GLint first, GLsizei count, GLsizei primcount, GLuint baseinstance); +GLAPI void APIENTRY glDrawElementsInstancedBaseInstance (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount, GLuint baseinstance); +GLAPI void APIENTRY glDrawElementsInstancedBaseVertexBaseInstance (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount, GLint basevertex, GLuint baseinstance); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount, GLuint baseinstance); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount, GLuint baseinstance); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount, GLint basevertex, GLuint baseinstance); +#endif + +#ifndef GL_ARB_shading_language_420pack +#define GL_ARB_shading_language_420pack 1 +#endif + +#ifndef GL_ARB_transform_feedback_instanced +#define GL_ARB_transform_feedback_instanced 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawTransformFeedbackInstanced (GLenum mode, GLuint id, GLsizei primcount); +GLAPI void APIENTRY glDrawTransformFeedbackStreamInstanced (GLenum mode, GLuint id, GLuint stream, GLsizei primcount); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC) (GLenum mode, GLuint id, GLsizei primcount); +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC) (GLenum mode, GLuint id, GLuint stream, GLsizei primcount); +#endif + +#ifndef GL_ARB_compressed_texture_pixel_storage +#define GL_ARB_compressed_texture_pixel_storage 1 +#endif + +#ifndef GL_ARB_conservative_depth +#define GL_ARB_conservative_depth 1 +#endif + +#ifndef GL_ARB_internalformat_query +#define GL_ARB_internalformat_query 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetInternalformativ (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLGETINTERNALFORMATIVPROC) (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params); +#endif + +#ifndef GL_ARB_map_buffer_alignment +#define GL_ARB_map_buffer_alignment 1 +#endif + +#ifndef GL_ARB_shader_atomic_counters +#define GL_ARB_shader_atomic_counters 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetActiveAtomicCounterBufferiv (GLuint program, GLuint bufferIndex, GLenum pname, GLint *params); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC) (GLuint program, GLuint bufferIndex, GLenum pname, GLint *params); +#endif + +#ifndef GL_ARB_shader_image_load_store +#define GL_ARB_shader_image_load_store 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindImageTexture (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format); +GLAPI void APIENTRY glMemoryBarrier (GLbitfield barriers); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLBINDIMAGETEXTUREPROC) (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format); +typedef void (APIENTRYP PFNGLMEMORYBARRIERPROC) (GLbitfield barriers); +#endif + +#ifndef GL_ARB_shading_language_packing +#define GL_ARB_shading_language_packing 1 +#endif + +#ifndef GL_ARB_texture_storage +#define GL_ARB_texture_storage 1 +#ifdef GL_GLEXT_PROTOTYPES +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 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); +#endif /* GL_GLEXT_PROTOTYPES */ +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 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); +#endif + #ifndef GL_EXT_abgr #define GL_EXT_abgr 1 #endif @@ -4507,7 +7727,7 @@ typedef void (APIENTRYP PFNGLCLAMPCOLORARBPROC) (GLenum target, GLenum clamp); #ifndef GL_EXT_blend_color #define GL_EXT_blend_color 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glBlendColorEXT (GLclampf, GLclampf, GLclampf, GLclampf); +GLAPI void APIENTRY glBlendColorEXT (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBLENDCOLOREXTPROC) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); #endif @@ -4515,7 +7735,7 @@ typedef void (APIENTRYP PFNGLBLENDCOLOREXTPROC) (GLclampf red, GLclampf green, G #ifndef GL_EXT_polygon_offset #define GL_EXT_polygon_offset 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glPolygonOffsetEXT (GLfloat, GLfloat); +GLAPI void APIENTRY glPolygonOffsetEXT (GLfloat factor, GLfloat bias); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPOLYGONOFFSETEXTPROC) (GLfloat factor, GLfloat bias); #endif @@ -4527,8 +7747,8 @@ typedef void (APIENTRYP PFNGLPOLYGONOFFSETEXTPROC) (GLfloat factor, GLfloat bias #ifndef GL_EXT_texture3D #define GL_EXT_texture3D 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glTexImage3DEXT (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *); -extern void APIENTRY glTexSubImage3DEXT (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); +GLAPI void APIENTRY glTexImage3DEXT (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *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 GLvoid *pixels); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLTEXIMAGE3DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *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 GLvoid *pixels); @@ -4537,8 +7757,8 @@ typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, #ifndef GL_SGIS_texture_filter4 #define GL_SGIS_texture_filter4 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glGetTexFilterFuncSGIS (GLenum, GLenum, GLfloat *); -extern void APIENTRY glTexFilterFuncSGIS (GLenum, GLenum, GLsizei, const GLfloat *); +GLAPI void APIENTRY glGetTexFilterFuncSGIS (GLenum target, GLenum filter, GLfloat *weights); +GLAPI void APIENTRY glTexFilterFuncSGIS (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLGETTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLfloat *weights); typedef void (APIENTRYP PFNGLTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights); @@ -4547,8 +7767,8 @@ typedef void (APIENTRYP PFNGLTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filte #ifndef GL_EXT_subtexture #define GL_EXT_subtexture 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glTexSubImage1DEXT (GLenum, GLint, GLint, GLsizei, GLenum, GLenum, const GLvoid *); -extern void APIENTRY glTexSubImage2DEXT (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); +GLAPI void APIENTRY glTexSubImage1DEXT (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels); +GLAPI void APIENTRY glTexSubImage2DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels); typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels); @@ -4557,11 +7777,11 @@ typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, #ifndef GL_EXT_copy_texture #define GL_EXT_copy_texture 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glCopyTexImage1DEXT (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLint); -extern void APIENTRY glCopyTexImage2DEXT (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint); -extern void APIENTRY glCopyTexSubImage1DEXT (GLenum, GLint, GLint, GLint, GLint, GLsizei); -extern void APIENTRY glCopyTexSubImage2DEXT (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei); -extern void APIENTRY glCopyTexSubImage3DEXT (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei); +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 /* GL_GLEXT_PROTOTYPES */ 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); @@ -4573,16 +7793,16 @@ typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint lev #ifndef GL_EXT_histogram #define GL_EXT_histogram 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glGetHistogramEXT (GLenum, GLboolean, GLenum, GLenum, GLvoid *); -extern void APIENTRY glGetHistogramParameterfvEXT (GLenum, GLenum, GLfloat *); -extern void APIENTRY glGetHistogramParameterivEXT (GLenum, GLenum, GLint *); -extern void APIENTRY glGetMinmaxEXT (GLenum, GLboolean, GLenum, GLenum, GLvoid *); -extern void APIENTRY glGetMinmaxParameterfvEXT (GLenum, GLenum, GLfloat *); -extern void APIENTRY glGetMinmaxParameterivEXT (GLenum, GLenum, GLint *); -extern void APIENTRY glHistogramEXT (GLenum, GLsizei, GLenum, GLboolean); -extern void APIENTRY glMinmaxEXT (GLenum, GLenum, GLboolean); -extern void APIENTRY glResetHistogramEXT (GLenum); -extern void APIENTRY glResetMinmaxEXT (GLenum); +GLAPI void APIENTRY glGetHistogramEXT (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *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, GLvoid *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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLGETHISTOGRAMEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values); typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); @@ -4599,19 +7819,19 @@ typedef void (APIENTRYP PFNGLRESETMINMAXEXTPROC) (GLenum target); #ifndef GL_EXT_convolution #define GL_EXT_convolution 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glConvolutionFilter1DEXT (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *); -extern void APIENTRY glConvolutionFilter2DEXT (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); -extern void APIENTRY glConvolutionParameterfEXT (GLenum, GLenum, GLfloat); -extern void APIENTRY glConvolutionParameterfvEXT (GLenum, GLenum, const GLfloat *); -extern void APIENTRY glConvolutionParameteriEXT (GLenum, GLenum, GLint); -extern void APIENTRY glConvolutionParameterivEXT (GLenum, GLenum, const GLint *); -extern void APIENTRY glCopyConvolutionFilter1DEXT (GLenum, GLenum, GLint, GLint, GLsizei); -extern void APIENTRY glCopyConvolutionFilter2DEXT (GLenum, GLenum, GLint, GLint, GLsizei, GLsizei); -extern void APIENTRY glGetConvolutionFilterEXT (GLenum, GLenum, GLenum, GLvoid *); -extern void APIENTRY glGetConvolutionParameterfvEXT (GLenum, GLenum, GLfloat *); -extern void APIENTRY glGetConvolutionParameterivEXT (GLenum, GLenum, GLint *); -extern void APIENTRY glGetSeparableFilterEXT (GLenum, GLenum, GLenum, GLvoid *, GLvoid *, GLvoid *); -extern void APIENTRY glSeparableFilter2DEXT (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *, const GLvoid *); +GLAPI void APIENTRY glConvolutionFilter1DEXT (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image); +GLAPI void APIENTRY glConvolutionFilter2DEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *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, GLvoid *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, GLvoid *row, GLvoid *column, GLvoid *span); +GLAPI void APIENTRY glSeparableFilter2DEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image); typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image); @@ -4628,20 +7848,20 @@ typedef void (APIENTRYP PFNGLGETSEPARABLEFILTEREXTPROC) (GLenum target, GLenum f typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column); #endif -#ifndef GL_EXT_color_matrix -#define GL_EXT_color_matrix 1 +#ifndef GL_SGI_color_matrix +#define GL_SGI_color_matrix 1 #endif #ifndef GL_SGI_color_table #define GL_SGI_color_table 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glColorTableSGI (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *); -extern void APIENTRY glColorTableParameterfvSGI (GLenum, GLenum, const GLfloat *); -extern void APIENTRY glColorTableParameterivSGI (GLenum, GLenum, const GLint *); -extern void APIENTRY glCopyColorTableSGI (GLenum, GLenum, GLint, GLint, GLsizei); -extern void APIENTRY glGetColorTableSGI (GLenum, GLenum, GLenum, GLvoid *); -extern void APIENTRY glGetColorTableParameterfvSGI (GLenum, GLenum, GLfloat *); -extern void APIENTRY glGetColorTableParameterivSGI (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glColorTableSGI (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *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, GLvoid *table); +GLAPI void APIENTRY glGetColorTableParameterfvSGI (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetColorTableParameterivSGI (GLenum target, GLenum pname, GLint *params); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table); typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, const GLfloat *params); @@ -4655,7 +7875,7 @@ typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GL #ifndef GL_SGIX_pixel_texture #define GL_SGIX_pixel_texture 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glPixelTexGenSGIX (GLenum); +GLAPI void APIENTRY glPixelTexGenSGIX (GLenum mode); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPIXELTEXGENSGIXPROC) (GLenum mode); #endif @@ -4663,12 +7883,12 @@ typedef void (APIENTRYP PFNGLPIXELTEXGENSGIXPROC) (GLenum mode); #ifndef GL_SGIS_pixel_texture #define GL_SGIS_pixel_texture 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glPixelTexGenParameteriSGIS (GLenum, GLint); -extern void APIENTRY glPixelTexGenParameterivSGIS (GLenum, const GLint *); -extern void APIENTRY glPixelTexGenParameterfSGIS (GLenum, GLfloat); -extern void APIENTRY glPixelTexGenParameterfvSGIS (GLenum, const GLfloat *); -extern void APIENTRY glGetPixelTexGenParameterivSGIS (GLenum, GLint *); -extern void APIENTRY glGetPixelTexGenParameterfvSGIS (GLenum, GLfloat *); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERISGISPROC) (GLenum pname, GLint param); typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, const GLint *params); @@ -4681,8 +7901,8 @@ typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, G #ifndef GL_SGIS_texture4D #define GL_SGIS_texture4D 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glTexImage4DSGIS (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *); -extern void APIENTRY glTexSubImage4DSGIS (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); +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 GLvoid *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 GLvoid *pixels); #endif /* GL_GLEXT_PROTOTYPES */ 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 GLvoid *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 GLvoid *pixels); @@ -4699,12 +7919,12 @@ typedef void (APIENTRYP PFNGLTEXSUBIMAGE4DSGISPROC) (GLenum target, GLint level, #ifndef GL_EXT_texture_object #define GL_EXT_texture_object 1 #ifdef GL_GLEXT_PROTOTYPES -extern GLboolean APIENTRY glAreTexturesResidentEXT (GLsizei, const GLuint *, GLboolean *); -extern void APIENTRY glBindTextureEXT (GLenum, GLuint); -extern void APIENTRY glDeleteTexturesEXT (GLsizei, const GLuint *); -extern void APIENTRY glGenTexturesEXT (GLsizei, GLuint *); -extern GLboolean APIENTRY glIsTextureEXT (GLuint); -extern void APIENTRY glPrioritizeTexturesEXT (GLsizei, const GLuint *, const GLclampf *); +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 /* GL_GLEXT_PROTOTYPES */ typedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTEXTPROC) (GLsizei n, const GLuint *textures, GLboolean *residences); typedef void (APIENTRYP PFNGLBINDTEXTUREEXTPROC) (GLenum target, GLuint texture); @@ -4717,8 +7937,8 @@ typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESEXTPROC) (GLsizei n, const GLuint #ifndef GL_SGIS_detail_texture #define GL_SGIS_detail_texture 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glDetailTexFuncSGIS (GLenum, GLsizei, const GLfloat *); -extern void APIENTRY glGetDetailTexFuncSGIS (GLenum, GLfloat *); +GLAPI void APIENTRY glDetailTexFuncSGIS (GLenum target, GLsizei n, const GLfloat *points); +GLAPI void APIENTRY glGetDetailTexFuncSGIS (GLenum target, GLfloat *points); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLDETAILTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points); typedef void (APIENTRYP PFNGLGETDETAILTEXFUNCSGISPROC) (GLenum target, GLfloat *points); @@ -4727,8 +7947,8 @@ typedef void (APIENTRYP PFNGLGETDETAILTEXFUNCSGISPROC) (GLenum target, GLfloat * #ifndef GL_SGIS_sharpen_texture #define GL_SGIS_sharpen_texture 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glSharpenTexFuncSGIS (GLenum, GLsizei, const GLfloat *); -extern void APIENTRY glGetSharpenTexFuncSGIS (GLenum, GLfloat *); +GLAPI void APIENTRY glSharpenTexFuncSGIS (GLenum target, GLsizei n, const GLfloat *points); +GLAPI void APIENTRY glGetSharpenTexFuncSGIS (GLenum target, GLfloat *points); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLSHARPENTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points); typedef void (APIENTRYP PFNGLGETSHARPENTEXFUNCSGISPROC) (GLenum target, GLfloat *points); @@ -4745,8 +7965,8 @@ typedef void (APIENTRYP PFNGLGETSHARPENTEXFUNCSGISPROC) (GLenum target, GLfloat #ifndef GL_SGIS_multisample #define GL_SGIS_multisample 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glSampleMaskSGIS (GLclampf, GLboolean); -extern void APIENTRY glSamplePatternSGIS (GLenum); +GLAPI void APIENTRY glSampleMaskSGIS (GLclampf value, GLboolean invert); +GLAPI void APIENTRY glSamplePatternSGIS (GLenum pattern); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLSAMPLEMASKSGISPROC) (GLclampf value, GLboolean invert); typedef void (APIENTRYP PFNGLSAMPLEPATTERNSGISPROC) (GLenum pattern); @@ -4759,15 +7979,15 @@ typedef void (APIENTRYP PFNGLSAMPLEPATTERNSGISPROC) (GLenum pattern); #ifndef GL_EXT_vertex_array #define GL_EXT_vertex_array 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glArrayElementEXT (GLint); -extern void APIENTRY glColorPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *); -extern void APIENTRY glDrawArraysEXT (GLenum, GLint, GLsizei); -extern void APIENTRY glEdgeFlagPointerEXT (GLsizei, GLsizei, const GLboolean *); -extern void APIENTRY glGetPointervEXT (GLenum, GLvoid* *); -extern void APIENTRY glIndexPointerEXT (GLenum, GLsizei, GLsizei, const GLvoid *); -extern void APIENTRY glNormalPointerEXT (GLenum, GLsizei, GLsizei, const GLvoid *); -extern void APIENTRY glTexCoordPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *); -extern void APIENTRY glVertexPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *); +GLAPI void APIENTRY glArrayElementEXT (GLint i); +GLAPI void APIENTRY glColorPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *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, GLvoid* *params); +GLAPI void APIENTRY glIndexPointerEXT (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer); +GLAPI void APIENTRY glNormalPointerEXT (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer); +GLAPI void APIENTRY glTexCoordPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer); +GLAPI void APIENTRY glVertexPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLARRAYELEMENTEXTPROC) (GLint i); typedef void (APIENTRYP PFNGLCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer); @@ -4807,7 +8027,7 @@ typedef void (APIENTRYP PFNGLVERTEXPOINTEREXTPROC) (GLint size, GLenum type, GLs #ifndef GL_EXT_blend_minmax #define GL_EXT_blend_minmax 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glBlendEquationEXT (GLenum); +GLAPI void APIENTRY glBlendEquationEXT (GLenum mode); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBLENDEQUATIONEXTPROC) (GLenum mode); #endif @@ -4835,10 +8055,10 @@ typedef void (APIENTRYP PFNGLBLENDEQUATIONEXTPROC) (GLenum mode); #ifndef GL_SGIX_sprite #define GL_SGIX_sprite 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glSpriteParameterfSGIX (GLenum, GLfloat); -extern void APIENTRY glSpriteParameterfvSGIX (GLenum, const GLfloat *); -extern void APIENTRY glSpriteParameteriSGIX (GLenum, GLint); -extern void APIENTRY glSpriteParameterivSGIX (GLenum, const GLint *); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLSPRITEPARAMETERFSGIXPROC) (GLenum pname, GLfloat param); typedef void (APIENTRYP PFNGLSPRITEPARAMETERFVSGIXPROC) (GLenum pname, const GLfloat *params); @@ -4853,8 +8073,8 @@ typedef void (APIENTRYP PFNGLSPRITEPARAMETERIVSGIXPROC) (GLenum pname, const GLi #ifndef GL_EXT_point_parameters #define GL_EXT_point_parameters 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glPointParameterfEXT (GLenum, GLfloat); -extern void APIENTRY glPointParameterfvEXT (GLenum, const GLfloat *); +GLAPI void APIENTRY glPointParameterfEXT (GLenum pname, GLfloat param); +GLAPI void APIENTRY glPointParameterfvEXT (GLenum pname, const GLfloat *params); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPOINTPARAMETERFEXTPROC) (GLenum pname, GLfloat param); typedef void (APIENTRYP PFNGLPOINTPARAMETERFVEXTPROC) (GLenum pname, const GLfloat *params); @@ -4863,8 +8083,8 @@ typedef void (APIENTRYP PFNGLPOINTPARAMETERFVEXTPROC) (GLenum pname, const GLflo #ifndef GL_SGIS_point_parameters #define GL_SGIS_point_parameters 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glPointParameterfSGIS (GLenum, GLfloat); -extern void APIENTRY glPointParameterfvSGIS (GLenum, const GLfloat *); +GLAPI void APIENTRY glPointParameterfSGIS (GLenum pname, GLfloat param); +GLAPI void APIENTRY glPointParameterfvSGIS (GLenum pname, const GLfloat *params); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPOINTPARAMETERFSGISPROC) (GLenum pname, GLfloat param); typedef void (APIENTRYP PFNGLPOINTPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params); @@ -4873,12 +8093,12 @@ typedef void (APIENTRYP PFNGLPOINTPARAMETERFVSGISPROC) (GLenum pname, const GLfl #ifndef GL_SGIX_instruments #define GL_SGIX_instruments 1 #ifdef GL_GLEXT_PROTOTYPES -extern GLint APIENTRY glGetInstrumentsSGIX (void); -extern void APIENTRY glInstrumentsBufferSGIX (GLsizei, GLint *); -extern GLint APIENTRY glPollInstrumentsSGIX (GLint *); -extern void APIENTRY glReadInstrumentsSGIX (GLint); -extern void APIENTRY glStartInstrumentsSGIX (void); -extern void APIENTRY glStopInstrumentsSGIX (GLint); +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 /* GL_GLEXT_PROTOTYPES */ typedef GLint (APIENTRYP PFNGLGETINSTRUMENTSSGIXPROC) (void); typedef void (APIENTRYP PFNGLINSTRUMENTSBUFFERSGIXPROC) (GLsizei size, GLint *buffer); @@ -4895,7 +8115,7 @@ typedef void (APIENTRYP PFNGLSTOPINSTRUMENTSSGIXPROC) (GLint marker); #ifndef GL_SGIX_framezoom #define GL_SGIX_framezoom 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glFrameZoomSGIX (GLint); +GLAPI void APIENTRY glFrameZoomSGIX (GLint factor); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLFRAMEZOOMSGIXPROC) (GLint factor); #endif @@ -4903,7 +8123,7 @@ typedef void (APIENTRYP PFNGLFRAMEZOOMSGIXPROC) (GLint factor); #ifndef GL_SGIX_tag_sample_buffer #define GL_SGIX_tag_sample_buffer 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glTagSampleBufferSGIX (void); +GLAPI void APIENTRY glTagSampleBufferSGIX (void); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLTAGSAMPLEBUFFERSGIXPROC) (void); #endif @@ -4911,10 +8131,10 @@ typedef void (APIENTRYP PFNGLTAGSAMPLEBUFFERSGIXPROC) (void); #ifndef GL_SGIX_polynomial_ffd #define GL_SGIX_polynomial_ffd 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glDeformationMap3dSGIX (GLenum, GLdouble, GLdouble, GLint, GLint, GLdouble, GLdouble, GLint, GLint, GLdouble, GLdouble, GLint, GLint, const GLdouble *); -extern void APIENTRY glDeformationMap3fSGIX (GLenum, GLfloat, GLfloat, GLint, GLint, GLfloat, GLfloat, GLint, GLint, GLfloat, GLfloat, GLint, GLint, const GLfloat *); -extern void APIENTRY glDeformSGIX (GLbitfield); -extern void APIENTRY glLoadIdentityDeformationMapSGIX (GLbitfield); +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 /* GL_GLEXT_PROTOTYPES */ 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); @@ -4925,7 +8145,7 @@ typedef void (APIENTRYP PFNGLLOADIDENTITYDEFORMATIONMAPSGIXPROC) (GLbitfield mas #ifndef GL_SGIX_reference_plane #define GL_SGIX_reference_plane 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glReferencePlaneSGIX (const GLdouble *); +GLAPI void APIENTRY glReferencePlaneSGIX (const GLdouble *equation); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLREFERENCEPLANESGIXPROC) (const GLdouble *equation); #endif @@ -4933,7 +8153,7 @@ typedef void (APIENTRYP PFNGLREFERENCEPLANESGIXPROC) (const GLdouble *equation); #ifndef GL_SGIX_flush_raster #define GL_SGIX_flush_raster 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glFlushRasterSGIX (void); +GLAPI void APIENTRY glFlushRasterSGIX (void); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLFLUSHRASTERSGIXPROC) (void); #endif @@ -4945,8 +8165,8 @@ typedef void (APIENTRYP PFNGLFLUSHRASTERSGIXPROC) (void); #ifndef GL_SGIS_fog_function #define GL_SGIS_fog_function 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glFogFuncSGIS (GLsizei, const GLfloat *); -extern void APIENTRY glGetFogFuncSGIS (GLfloat *); +GLAPI void APIENTRY glFogFuncSGIS (GLsizei n, const GLfloat *points); +GLAPI void APIENTRY glGetFogFuncSGIS (GLfloat *points); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLFOGFUNCSGISPROC) (GLsizei n, const GLfloat *points); typedef void (APIENTRYP PFNGLGETFOGFUNCSGISPROC) (GLfloat *points); @@ -4959,12 +8179,12 @@ typedef void (APIENTRYP PFNGLGETFOGFUNCSGISPROC) (GLfloat *points); #ifndef GL_HP_image_transform #define GL_HP_image_transform 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glImageTransformParameteriHP (GLenum, GLenum, GLint); -extern void APIENTRY glImageTransformParameterfHP (GLenum, GLenum, GLfloat); -extern void APIENTRY glImageTransformParameterivHP (GLenum, GLenum, const GLint *); -extern void APIENTRY glImageTransformParameterfvHP (GLenum, GLenum, const GLfloat *); -extern void APIENTRY glGetImageTransformParameterivHP (GLenum, GLenum, GLint *); -extern void APIENTRY glGetImageTransformParameterfvHP (GLenum, GLenum, GLfloat *); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIHPPROC) (GLenum target, GLenum pname, GLint param); typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFHPPROC) (GLenum target, GLenum pname, GLfloat param); @@ -4985,8 +8205,8 @@ typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, #ifndef GL_EXT_color_subtable #define GL_EXT_color_subtable 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glColorSubTableEXT (GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); -extern void APIENTRY glCopyColorSubTableEXT (GLenum, GLsizei, GLint, GLint, GLsizei); +GLAPI void APIENTRY glColorSubTableEXT (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data); +GLAPI void APIENTRY glCopyColorSubTableEXT (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data); typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width); @@ -4999,7 +8219,7 @@ typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei s #ifndef GL_PGI_misc_hints #define GL_PGI_misc_hints 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glHintPGI (GLenum, GLint); +GLAPI void APIENTRY glHintPGI (GLenum target, GLint mode); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLHINTPGIPROC) (GLenum target, GLint mode); #endif @@ -5007,10 +8227,10 @@ typedef void (APIENTRYP PFNGLHINTPGIPROC) (GLenum target, GLint mode); #ifndef GL_EXT_paletted_texture #define GL_EXT_paletted_texture 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glColorTableEXT (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *); -extern void APIENTRY glGetColorTableEXT (GLenum, GLenum, GLenum, GLvoid *); -extern void APIENTRY glGetColorTableParameterivEXT (GLenum, GLenum, GLint *); -extern void APIENTRY glGetColorTableParameterfvEXT (GLenum, GLenum, GLfloat *); +GLAPI void APIENTRY glColorTableEXT (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const GLvoid *table); +GLAPI void APIENTRY glGetColorTableEXT (GLenum target, GLenum format, GLenum type, GLvoid *data); +GLAPI void APIENTRY glGetColorTableParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetColorTableParameterfvEXT (GLenum target, GLenum pname, GLfloat *params); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCOLORTABLEEXTPROC) (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const GLvoid *table); typedef void (APIENTRYP PFNGLGETCOLORTABLEEXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *data); @@ -5025,12 +8245,12 @@ typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVEXTPROC) (GLenum target, GL #ifndef GL_SGIX_list_priority #define GL_SGIX_list_priority 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glGetListParameterfvSGIX (GLuint, GLenum, GLfloat *); -extern void APIENTRY glGetListParameterivSGIX (GLuint, GLenum, GLint *); -extern void APIENTRY glListParameterfSGIX (GLuint, GLenum, GLfloat); -extern void APIENTRY glListParameterfvSGIX (GLuint, GLenum, const GLfloat *); -extern void APIENTRY glListParameteriSGIX (GLuint, GLenum, GLint); -extern void APIENTRY glListParameterivSGIX (GLuint, GLenum, const GLint *); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLGETLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, GLint *params); @@ -5063,7 +8283,7 @@ typedef void (APIENTRYP PFNGLLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname #ifndef GL_EXT_index_material #define GL_EXT_index_material 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glIndexMaterialEXT (GLenum, GLenum); +GLAPI void APIENTRY glIndexMaterialEXT (GLenum face, GLenum mode); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLINDEXMATERIALEXTPROC) (GLenum face, GLenum mode); #endif @@ -5071,7 +8291,7 @@ typedef void (APIENTRYP PFNGLINDEXMATERIALEXTPROC) (GLenum face, GLenum mode); #ifndef GL_EXT_index_func #define GL_EXT_index_func 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glIndexFuncEXT (GLenum, GLclampf); +GLAPI void APIENTRY glIndexFuncEXT (GLenum func, GLclampf ref); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLINDEXFUNCEXTPROC) (GLenum func, GLclampf ref); #endif @@ -5083,8 +8303,8 @@ typedef void (APIENTRYP PFNGLINDEXFUNCEXTPROC) (GLenum func, GLclampf ref); #ifndef GL_EXT_compiled_vertex_array #define GL_EXT_compiled_vertex_array 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glLockArraysEXT (GLint, GLsizei); -extern void APIENTRY glUnlockArraysEXT (void); +GLAPI void APIENTRY glLockArraysEXT (GLint first, GLsizei count); +GLAPI void APIENTRY glUnlockArraysEXT (void); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLLOCKARRAYSEXTPROC) (GLint first, GLsizei count); typedef void (APIENTRYP PFNGLUNLOCKARRAYSEXTPROC) (void); @@ -5093,8 +8313,8 @@ typedef void (APIENTRYP PFNGLUNLOCKARRAYSEXTPROC) (void); #ifndef GL_EXT_cull_vertex #define GL_EXT_cull_vertex 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glCullParameterdvEXT (GLenum, GLdouble *); -extern void APIENTRY glCullParameterfvEXT (GLenum, GLfloat *); +GLAPI void APIENTRY glCullParameterdvEXT (GLenum pname, GLdouble *params); +GLAPI void APIENTRY glCullParameterfvEXT (GLenum pname, GLfloat *params); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCULLPARAMETERDVEXTPROC) (GLenum pname, GLdouble *params); typedef void (APIENTRYP PFNGLCULLPARAMETERFVEXTPROC) (GLenum pname, GLfloat *params); @@ -5107,24 +8327,24 @@ typedef void (APIENTRYP PFNGLCULLPARAMETERFVEXTPROC) (GLenum pname, GLfloat *par #ifndef GL_SGIX_fragment_lighting #define GL_SGIX_fragment_lighting 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glFragmentColorMaterialSGIX (GLenum, GLenum); -extern void APIENTRY glFragmentLightfSGIX (GLenum, GLenum, GLfloat); -extern void APIENTRY glFragmentLightfvSGIX (GLenum, GLenum, const GLfloat *); -extern void APIENTRY glFragmentLightiSGIX (GLenum, GLenum, GLint); -extern void APIENTRY glFragmentLightivSGIX (GLenum, GLenum, const GLint *); -extern void APIENTRY glFragmentLightModelfSGIX (GLenum, GLfloat); -extern void APIENTRY glFragmentLightModelfvSGIX (GLenum, const GLfloat *); -extern void APIENTRY glFragmentLightModeliSGIX (GLenum, GLint); -extern void APIENTRY glFragmentLightModelivSGIX (GLenum, const GLint *); -extern void APIENTRY glFragmentMaterialfSGIX (GLenum, GLenum, GLfloat); -extern void APIENTRY glFragmentMaterialfvSGIX (GLenum, GLenum, const GLfloat *); -extern void APIENTRY glFragmentMaterialiSGIX (GLenum, GLenum, GLint); -extern void APIENTRY glFragmentMaterialivSGIX (GLenum, GLenum, const GLint *); -extern void APIENTRY glGetFragmentLightfvSGIX (GLenum, GLenum, GLfloat *); -extern void APIENTRY glGetFragmentLightivSGIX (GLenum, GLenum, GLint *); -extern void APIENTRY glGetFragmentMaterialfvSGIX (GLenum, GLenum, GLfloat *); -extern void APIENTRY glGetFragmentMaterialivSGIX (GLenum, GLenum, GLint *); -extern void APIENTRY glLightEnviSGIX (GLenum, GLint); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLFRAGMENTCOLORMATERIALSGIXPROC) (GLenum face, GLenum mode); typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFSGIXPROC) (GLenum light, GLenum pname, GLfloat param); @@ -5157,7 +8377,7 @@ typedef void (APIENTRYP PFNGLLIGHTENVISGIXPROC) (GLenum pname, GLint param); #ifndef GL_EXT_draw_range_elements #define GL_EXT_draw_range_elements 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glDrawRangeElementsEXT (GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *); +GLAPI void APIENTRY glDrawRangeElementsEXT (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSEXTPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices); #endif @@ -5173,9 +8393,9 @@ typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSEXTPROC) (GLenum mode, GLuint star #ifndef GL_EXT_light_texture #define GL_EXT_light_texture 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glApplyTextureEXT (GLenum); -extern void APIENTRY glTextureLightEXT (GLenum); -extern void APIENTRY glTextureMaterialEXT (GLenum, GLenum); +GLAPI void APIENTRY glApplyTextureEXT (GLenum mode); +GLAPI void APIENTRY glTextureLightEXT (GLenum pname); +GLAPI void APIENTRY glTextureMaterialEXT (GLenum face, GLenum mode); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLAPPLYTEXTUREEXTPROC) (GLenum mode); typedef void (APIENTRYP PFNGLTEXTURELIGHTEXTPROC) (GLenum pname); @@ -5193,12 +8413,12 @@ typedef void (APIENTRYP PFNGLTEXTUREMATERIALEXTPROC) (GLenum face, GLenum mode); #ifndef GL_SGIX_async #define GL_SGIX_async 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glAsyncMarkerSGIX (GLuint); -extern GLint APIENTRY glFinishAsyncSGIX (GLuint *); -extern GLint APIENTRY glPollAsyncSGIX (GLuint *); -extern GLuint APIENTRY glGenAsyncMarkersSGIX (GLsizei); -extern void APIENTRY glDeleteAsyncMarkersSGIX (GLuint, GLsizei); -extern GLboolean APIENTRY glIsAsyncMarkerSGIX (GLuint); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLASYNCMARKERSGIXPROC) (GLuint marker); typedef GLint (APIENTRYP PFNGLFINISHASYNCSGIXPROC) (GLuint *markerp); @@ -5219,10 +8439,10 @@ typedef GLboolean (APIENTRYP PFNGLISASYNCMARKERSGIXPROC) (GLuint marker); #ifndef GL_INTEL_parallel_arrays #define GL_INTEL_parallel_arrays 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glVertexPointervINTEL (GLint, GLenum, const GLvoid* *); -extern void APIENTRY glNormalPointervINTEL (GLenum, const GLvoid* *); -extern void APIENTRY glColorPointervINTEL (GLint, GLenum, const GLvoid* *); -extern void APIENTRY glTexCoordPointervINTEL (GLint, GLenum, const GLvoid* *); +GLAPI void APIENTRY glVertexPointervINTEL (GLint size, GLenum type, const GLvoid* *pointer); +GLAPI void APIENTRY glNormalPointervINTEL (GLenum type, const GLvoid* *pointer); +GLAPI void APIENTRY glColorPointervINTEL (GLint size, GLenum type, const GLvoid* *pointer); +GLAPI void APIENTRY glTexCoordPointervINTEL (GLint size, GLenum type, const GLvoid* *pointer); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLVERTEXPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer); typedef void (APIENTRYP PFNGLNORMALPOINTERVINTELPROC) (GLenum type, const GLvoid* *pointer); @@ -5237,10 +8457,10 @@ typedef void (APIENTRYP PFNGLTEXCOORDPOINTERVINTELPROC) (GLint size, GLenum type #ifndef GL_EXT_pixel_transform #define GL_EXT_pixel_transform 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glPixelTransformParameteriEXT (GLenum, GLenum, GLint); -extern void APIENTRY glPixelTransformParameterfEXT (GLenum, GLenum, GLfloat); -extern void APIENTRY glPixelTransformParameterivEXT (GLenum, GLenum, const GLint *); -extern void APIENTRY glPixelTransformParameterfvEXT (GLenum, GLenum, const GLfloat *); +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); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint param); typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat param); @@ -5263,23 +8483,23 @@ typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFVEXTPROC) (GLenum target, G #ifndef GL_EXT_secondary_color #define GL_EXT_secondary_color 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glSecondaryColor3bEXT (GLbyte, GLbyte, GLbyte); -extern void APIENTRY glSecondaryColor3bvEXT (const GLbyte *); -extern void APIENTRY glSecondaryColor3dEXT (GLdouble, GLdouble, GLdouble); -extern void APIENTRY glSecondaryColor3dvEXT (const GLdouble *); -extern void APIENTRY glSecondaryColor3fEXT (GLfloat, GLfloat, GLfloat); -extern void APIENTRY glSecondaryColor3fvEXT (const GLfloat *); -extern void APIENTRY glSecondaryColor3iEXT (GLint, GLint, GLint); -extern void APIENTRY glSecondaryColor3ivEXT (const GLint *); -extern void APIENTRY glSecondaryColor3sEXT (GLshort, GLshort, GLshort); -extern void APIENTRY glSecondaryColor3svEXT (const GLshort *); -extern void APIENTRY glSecondaryColor3ubEXT (GLubyte, GLubyte, GLubyte); -extern void APIENTRY glSecondaryColor3ubvEXT (const GLubyte *); -extern void APIENTRY glSecondaryColor3uiEXT (GLuint, GLuint, GLuint); -extern void APIENTRY glSecondaryColor3uivEXT (const GLuint *); -extern void APIENTRY glSecondaryColor3usEXT (GLushort, GLushort, GLushort); -extern void APIENTRY glSecondaryColor3usvEXT (const GLushort *); -extern void APIENTRY glSecondaryColorPointerEXT (GLint, GLenum, GLsizei, const GLvoid *); +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 GLvoid *pointer); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BEXTPROC) (GLbyte red, GLbyte green, GLbyte blue); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVEXTPROC) (const GLbyte *v); @@ -5303,7 +8523,7 @@ typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTEREXTPROC) (GLint size, GLenum t #ifndef GL_EXT_texture_perturb_normal #define GL_EXT_texture_perturb_normal 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glTextureNormalEXT (GLenum); +GLAPI void APIENTRY glTextureNormalEXT (GLenum mode); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLTEXTURENORMALEXTPROC) (GLenum mode); #endif @@ -5311,21 +8531,21 @@ typedef void (APIENTRYP PFNGLTEXTURENORMALEXTPROC) (GLenum mode); #ifndef GL_EXT_multi_draw_arrays #define GL_EXT_multi_draw_arrays 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glMultiDrawArraysEXT (GLenum, GLint *, GLsizei *, GLsizei); -extern void APIENTRY glMultiDrawElementsEXT (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei); +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 GLvoid* *indices, GLsizei primcount); #endif /* GL_GLEXT_PROTOTYPES */ -typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount); +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 GLvoid* *indices, GLsizei primcount); #endif #ifndef GL_EXT_fog_coord #define GL_EXT_fog_coord 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glFogCoordfEXT (GLfloat); -extern void APIENTRY glFogCoordfvEXT (const GLfloat *); -extern void APIENTRY glFogCoorddEXT (GLdouble); -extern void APIENTRY glFogCoorddvEXT (const GLdouble *); -extern void APIENTRY glFogCoordPointerEXT (GLenum, GLsizei, const GLvoid *); +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 GLvoid *pointer); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLFOGCOORDFEXTPROC) (GLfloat coord); typedef void (APIENTRYP PFNGLFOGCOORDFVEXTPROC) (const GLfloat *coord); @@ -5341,28 +8561,28 @@ typedef void (APIENTRYP PFNGLFOGCOORDPOINTEREXTPROC) (GLenum type, GLsizei strid #ifndef GL_EXT_coordinate_frame #define GL_EXT_coordinate_frame 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glTangent3bEXT (GLbyte, GLbyte, GLbyte); -extern void APIENTRY glTangent3bvEXT (const GLbyte *); -extern void APIENTRY glTangent3dEXT (GLdouble, GLdouble, GLdouble); -extern void APIENTRY glTangent3dvEXT (const GLdouble *); -extern void APIENTRY glTangent3fEXT (GLfloat, GLfloat, GLfloat); -extern void APIENTRY glTangent3fvEXT (const GLfloat *); -extern void APIENTRY glTangent3iEXT (GLint, GLint, GLint); -extern void APIENTRY glTangent3ivEXT (const GLint *); -extern void APIENTRY glTangent3sEXT (GLshort, GLshort, GLshort); -extern void APIENTRY glTangent3svEXT (const GLshort *); -extern void APIENTRY glBinormal3bEXT (GLbyte, GLbyte, GLbyte); -extern void APIENTRY glBinormal3bvEXT (const GLbyte *); -extern void APIENTRY glBinormal3dEXT (GLdouble, GLdouble, GLdouble); -extern void APIENTRY glBinormal3dvEXT (const GLdouble *); -extern void APIENTRY glBinormal3fEXT (GLfloat, GLfloat, GLfloat); -extern void APIENTRY glBinormal3fvEXT (const GLfloat *); -extern void APIENTRY glBinormal3iEXT (GLint, GLint, GLint); -extern void APIENTRY glBinormal3ivEXT (const GLint *); -extern void APIENTRY glBinormal3sEXT (GLshort, GLshort, GLshort); -extern void APIENTRY glBinormal3svEXT (const GLshort *); -extern void APIENTRY glTangentPointerEXT (GLenum, GLsizei, const GLvoid *); -extern void APIENTRY glBinormalPointerEXT (GLenum, GLsizei, const GLvoid *); +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 GLvoid *pointer); +GLAPI void APIENTRY glBinormalPointerEXT (GLenum type, GLsizei stride, const GLvoid *pointer); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLTANGENT3BEXTPROC) (GLbyte tx, GLbyte ty, GLbyte tz); typedef void (APIENTRYP PFNGLTANGENT3BVEXTPROC) (const GLbyte *v); @@ -5407,7 +8627,7 @@ typedef void (APIENTRYP PFNGLBINORMALPOINTEREXTPROC) (GLenum type, GLsizei strid #ifndef GL_SUNX_constant_data #define GL_SUNX_constant_data 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glFinishTextureSUNX (void); +GLAPI void APIENTRY glFinishTextureSUNX (void); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLFINISHTEXTURESUNXPROC) (void); #endif @@ -5415,14 +8635,14 @@ typedef void (APIENTRYP PFNGLFINISHTEXTURESUNXPROC) (void); #ifndef GL_SUN_global_alpha #define GL_SUN_global_alpha 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glGlobalAlphaFactorbSUN (GLbyte); -extern void APIENTRY glGlobalAlphaFactorsSUN (GLshort); -extern void APIENTRY glGlobalAlphaFactoriSUN (GLint); -extern void APIENTRY glGlobalAlphaFactorfSUN (GLfloat); -extern void APIENTRY glGlobalAlphaFactordSUN (GLdouble); -extern void APIENTRY glGlobalAlphaFactorubSUN (GLubyte); -extern void APIENTRY glGlobalAlphaFactorusSUN (GLushort); -extern void APIENTRY glGlobalAlphaFactoruiSUN (GLuint); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORBSUNPROC) (GLbyte factor); typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORSSUNPROC) (GLshort factor); @@ -5437,13 +8657,13 @@ typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUISUNPROC) (GLuint factor); #ifndef GL_SUN_triangle_list #define GL_SUN_triangle_list 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glReplacementCodeuiSUN (GLuint); -extern void APIENTRY glReplacementCodeusSUN (GLushort); -extern void APIENTRY glReplacementCodeubSUN (GLubyte); -extern void APIENTRY glReplacementCodeuivSUN (const GLuint *); -extern void APIENTRY glReplacementCodeusvSUN (const GLushort *); -extern void APIENTRY glReplacementCodeubvSUN (const GLubyte *); -extern void APIENTRY glReplacementCodePointerSUN (GLenum, GLsizei, const GLvoid* *); +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 GLvoid* *pointer); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLREPLACEMENTCODEUISUNPROC) (GLuint code); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSSUNPROC) (GLushort code); @@ -5457,46 +8677,46 @@ typedef void (APIENTRYP PFNGLREPLACEMENTCODEPOINTERSUNPROC) (GLenum type, GLsize #ifndef GL_SUN_vertex #define GL_SUN_vertex 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glColor4ubVertex2fSUN (GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat); -extern void APIENTRY glColor4ubVertex2fvSUN (const GLubyte *, const GLfloat *); -extern void APIENTRY glColor4ubVertex3fSUN (GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glColor4ubVertex3fvSUN (const GLubyte *, const GLfloat *); -extern void APIENTRY glColor3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glColor3fVertex3fvSUN (const GLfloat *, const GLfloat *); -extern void APIENTRY glNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *); -extern void APIENTRY glColor4fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glColor4fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *); -extern void APIENTRY glTexCoord2fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glTexCoord2fVertex3fvSUN (const GLfloat *, const GLfloat *); -extern void APIENTRY glTexCoord4fVertex4fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glTexCoord4fVertex4fvSUN (const GLfloat *, const GLfloat *); -extern void APIENTRY glTexCoord2fColor4ubVertex3fSUN (GLfloat, GLfloat, GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glTexCoord2fColor4ubVertex3fvSUN (const GLfloat *, const GLubyte *, const GLfloat *); -extern void APIENTRY glTexCoord2fColor3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glTexCoord2fColor3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *); -extern void APIENTRY glTexCoord2fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glTexCoord2fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *); -extern void APIENTRY glTexCoord2fColor4fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glTexCoord2fColor4fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *); -extern void APIENTRY glTexCoord4fColor4fNormal3fVertex4fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glTexCoord4fColor4fNormal3fVertex4fvSUN (const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *); -extern void APIENTRY glReplacementCodeuiVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glReplacementCodeuiVertex3fvSUN (const GLuint *, const GLfloat *); -extern void APIENTRY glReplacementCodeuiColor4ubVertex3fSUN (GLuint, GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glReplacementCodeuiColor4ubVertex3fvSUN (const GLuint *, const GLubyte *, const GLfloat *); -extern void APIENTRY glReplacementCodeuiColor3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glReplacementCodeuiColor3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *); -extern void APIENTRY glReplacementCodeuiNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glReplacementCodeuiNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *); -extern void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *); -extern void APIENTRY glReplacementCodeuiTexCoord2fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glReplacementCodeuiTexCoord2fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *); -extern void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *); -extern void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *); +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 /* GL_GLEXT_PROTOTYPES */ 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); @@ -5543,7 +8763,7 @@ typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FV #ifndef GL_EXT_blend_func_separate #define GL_EXT_blend_func_separate 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glBlendFuncSeparateEXT (GLenum, GLenum, GLenum, GLenum); +GLAPI void APIENTRY glBlendFuncSeparateEXT (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEEXTPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); #endif @@ -5551,7 +8771,7 @@ typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEEXTPROC) (GLenum sfactorRGB, GLenu #ifndef GL_INGR_blend_func_separate #define GL_INGR_blend_func_separate 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glBlendFuncSeparateINGR (GLenum, GLenum, GLenum, GLenum); +GLAPI void APIENTRY glBlendFuncSeparateINGR (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINGRPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); #endif @@ -5595,9 +8815,9 @@ typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINGRPROC) (GLenum sfactorRGB, GLen #ifndef GL_EXT_vertex_weighting #define GL_EXT_vertex_weighting 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glVertexWeightfEXT (GLfloat); -extern void APIENTRY glVertexWeightfvEXT (const GLfloat *); -extern void APIENTRY glVertexWeightPointerEXT (GLsizei, GLenum, GLsizei, const GLvoid *); +GLAPI void APIENTRY glVertexWeightfEXT (GLfloat weight); +GLAPI void APIENTRY glVertexWeightfvEXT (const GLfloat *weight); +GLAPI void APIENTRY glVertexWeightPointerEXT (GLsizei size, GLenum type, GLsizei stride, const GLvoid *pointer); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLVERTEXWEIGHTFEXTPROC) (GLfloat weight); typedef void (APIENTRYP PFNGLVERTEXWEIGHTFVEXTPROC) (const GLfloat *weight); @@ -5611,8 +8831,8 @@ typedef void (APIENTRYP PFNGLVERTEXWEIGHTPOINTEREXTPROC) (GLsizei size, GLenum t #ifndef GL_NV_vertex_array_range #define GL_NV_vertex_array_range 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glFlushVertexArrayRangeNV (void); -extern void APIENTRY glVertexArrayRangeNV (GLsizei, const GLvoid *); +GLAPI void APIENTRY glFlushVertexArrayRangeNV (void); +GLAPI void APIENTRY glVertexArrayRangeNV (GLsizei length, const GLvoid *pointer); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGENVPROC) (void); typedef void (APIENTRYP PFNGLVERTEXARRAYRANGENVPROC) (GLsizei length, const GLvoid *pointer); @@ -5621,19 +8841,19 @@ typedef void (APIENTRYP PFNGLVERTEXARRAYRANGENVPROC) (GLsizei length, const GLvo #ifndef GL_NV_register_combiners #define GL_NV_register_combiners 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glCombinerParameterfvNV (GLenum, const GLfloat *); -extern void APIENTRY glCombinerParameterfNV (GLenum, GLfloat); -extern void APIENTRY glCombinerParameterivNV (GLenum, const GLint *); -extern void APIENTRY glCombinerParameteriNV (GLenum, GLint); -extern void APIENTRY glCombinerInputNV (GLenum, GLenum, GLenum, GLenum, GLenum, GLenum); -extern void APIENTRY glCombinerOutputNV (GLenum, GLenum, GLenum, GLenum, GLenum, GLenum, GLenum, GLboolean, GLboolean, GLboolean); -extern void APIENTRY glFinalCombinerInputNV (GLenum, GLenum, GLenum, GLenum); -extern void APIENTRY glGetCombinerInputParameterfvNV (GLenum, GLenum, GLenum, GLenum, GLfloat *); -extern void APIENTRY glGetCombinerInputParameterivNV (GLenum, GLenum, GLenum, GLenum, GLint *); -extern void APIENTRY glGetCombinerOutputParameterfvNV (GLenum, GLenum, GLenum, GLfloat *); -extern void APIENTRY glGetCombinerOutputParameterivNV (GLenum, GLenum, GLenum, GLint *); -extern void APIENTRY glGetFinalCombinerInputParameterfvNV (GLenum, GLenum, GLfloat *); -extern void APIENTRY glGetFinalCombinerInputParameterivNV (GLenum, GLenum, GLint *); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFVNVPROC) (GLenum pname, const GLfloat *params); typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFNVPROC) (GLenum pname, GLfloat param); @@ -5669,7 +8889,7 @@ typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC) (GLenum var #ifndef GL_MESA_resize_buffers #define GL_MESA_resize_buffers 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glResizeBuffersMESA (void); +GLAPI void APIENTRY glResizeBuffersMESA (void); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLRESIZEBUFFERSMESAPROC) (void); #endif @@ -5677,30 +8897,30 @@ typedef void (APIENTRYP PFNGLRESIZEBUFFERSMESAPROC) (void); #ifndef GL_MESA_window_pos #define GL_MESA_window_pos 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glWindowPos2dMESA (GLdouble, GLdouble); -extern void APIENTRY glWindowPos2dvMESA (const GLdouble *); -extern void APIENTRY glWindowPos2fMESA (GLfloat, GLfloat); -extern void APIENTRY glWindowPos2fvMESA (const GLfloat *); -extern void APIENTRY glWindowPos2iMESA (GLint, GLint); -extern void APIENTRY glWindowPos2ivMESA (const GLint *); -extern void APIENTRY glWindowPos2sMESA (GLshort, GLshort); -extern void APIENTRY glWindowPos2svMESA (const GLshort *); -extern void APIENTRY glWindowPos3dMESA (GLdouble, GLdouble, GLdouble); -extern void APIENTRY glWindowPos3dvMESA (const GLdouble *); -extern void APIENTRY glWindowPos3fMESA (GLfloat, GLfloat, GLfloat); -extern void APIENTRY glWindowPos3fvMESA (const GLfloat *); -extern void APIENTRY glWindowPos3iMESA (GLint, GLint, GLint); -extern void APIENTRY glWindowPos3ivMESA (const GLint *); -extern void APIENTRY glWindowPos3sMESA (GLshort, GLshort, GLshort); -extern void APIENTRY glWindowPos3svMESA (const GLshort *); -extern void APIENTRY glWindowPos4dMESA (GLdouble, GLdouble, GLdouble, GLdouble); -extern void APIENTRY glWindowPos4dvMESA (const GLdouble *); -extern void APIENTRY glWindowPos4fMESA (GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glWindowPos4fvMESA (const GLfloat *); -extern void APIENTRY glWindowPos4iMESA (GLint, GLint, GLint, GLint); -extern void APIENTRY glWindowPos4ivMESA (const GLint *); -extern void APIENTRY glWindowPos4sMESA (GLshort, GLshort, GLshort, GLshort); -extern void APIENTRY glWindowPos4svMESA (const GLshort *); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLWINDOWPOS2DMESAPROC) (GLdouble x, GLdouble y); typedef void (APIENTRYP PFNGLWINDOWPOS2DVMESAPROC) (const GLdouble *v); @@ -5728,10 +8948,6 @@ typedef void (APIENTRYP PFNGLWINDOWPOS4SMESAPROC) (GLshort x, GLshort y, GLshort typedef void (APIENTRYP PFNGLWINDOWPOS4SVMESAPROC) (const GLshort *v); #endif -#ifndef GL_EXT_texture_compression_s3tc -#define GL_EXT_texture_compression_s3tc 1 -#endif - #ifndef GL_IBM_cull_vertex #define GL_IBM_cull_vertex 1 #endif @@ -5739,8 +8955,8 @@ typedef void (APIENTRYP PFNGLWINDOWPOS4SVMESAPROC) (const GLshort *v); #ifndef GL_IBM_multimode_draw_arrays #define GL_IBM_multimode_draw_arrays 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glMultiModeDrawArraysIBM (const GLenum *, const GLint *, const GLsizei *, GLsizei, GLint); -extern void APIENTRY glMultiModeDrawElementsIBM (const GLenum *, const GLsizei *, GLenum, const GLvoid* const *, GLsizei, GLint); +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 GLvoid* const *indices, GLsizei primcount, GLint modestride); #endif /* GL_GLEXT_PROTOTYPES */ 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 GLvoid* const *indices, GLsizei primcount, GLint modestride); @@ -5749,14 +8965,14 @@ typedef void (APIENTRYP PFNGLMULTIMODEDRAWELEMENTSIBMPROC) (const GLenum *mode, #ifndef GL_IBM_vertex_array_lists #define GL_IBM_vertex_array_lists 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glColorPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint); -extern void APIENTRY glSecondaryColorPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint); -extern void APIENTRY glEdgeFlagPointerListIBM (GLint, const GLboolean* *, GLint); -extern void APIENTRY glFogCoordPointerListIBM (GLenum, GLint, const GLvoid* *, GLint); -extern void APIENTRY glIndexPointerListIBM (GLenum, GLint, const GLvoid* *, GLint); -extern void APIENTRY glNormalPointerListIBM (GLenum, GLint, const GLvoid* *, GLint); -extern void APIENTRY glTexCoordPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint); -extern void APIENTRY glVertexPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint); +GLAPI void APIENTRY glColorPointerListIBM (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); +GLAPI void APIENTRY glSecondaryColorPointerListIBM (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); +GLAPI void APIENTRY glEdgeFlagPointerListIBM (GLint stride, const GLboolean* *pointer, GLint ptrstride); +GLAPI void APIENTRY glFogCoordPointerListIBM (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); +GLAPI void APIENTRY glIndexPointerListIBM (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); +GLAPI void APIENTRY glNormalPointerListIBM (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); +GLAPI void APIENTRY glTexCoordPointerListIBM (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); +GLAPI void APIENTRY glVertexPointerListIBM (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); @@ -5795,7 +9011,7 @@ typedef void (APIENTRYP PFNGLVERTEXPOINTERLISTIBMPROC) (GLint size, GLenum type, #ifndef GL_3DFX_tbuffer #define GL_3DFX_tbuffer 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glTbufferMask3DFX (GLuint); +GLAPI void APIENTRY glTbufferMask3DFX (GLuint mask); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLTBUFFERMASK3DFXPROC) (GLuint mask); #endif @@ -5803,8 +9019,8 @@ typedef void (APIENTRYP PFNGLTBUFFERMASK3DFXPROC) (GLuint mask); #ifndef GL_EXT_multisample #define GL_EXT_multisample 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glSampleMaskEXT (GLclampf, GLboolean); -extern void APIENTRY glSamplePatternEXT (GLenum); +GLAPI void APIENTRY glSampleMaskEXT (GLclampf value, GLboolean invert); +GLAPI void APIENTRY glSamplePatternEXT (GLenum pattern); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLSAMPLEMASKEXTPROC) (GLclampf value, GLboolean invert); typedef void (APIENTRYP PFNGLSAMPLEPATTERNEXTPROC) (GLenum pattern); @@ -5829,7 +9045,7 @@ typedef void (APIENTRYP PFNGLSAMPLEPATTERNEXTPROC) (GLenum pattern); #ifndef GL_SGIS_texture_color_mask #define GL_SGIS_texture_color_mask 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glTextureColorMaskSGIS (GLboolean, GLboolean, GLboolean, GLboolean); +GLAPI void APIENTRY glTextureColorMaskSGIS (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLTEXTURECOLORMASKSGISPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); #endif @@ -5837,7 +9053,7 @@ typedef void (APIENTRYP PFNGLTEXTURECOLORMASKSGISPROC) (GLboolean red, GLboolean #ifndef GL_SGIX_igloo_interface #define GL_SGIX_igloo_interface 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glIglooInterfaceSGIX (GLenum, const GLvoid *); +GLAPI void APIENTRY glIglooInterfaceSGIX (GLenum pname, const GLvoid *params); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLIGLOOINTERFACESGIXPROC) (GLenum pname, const GLvoid *params); #endif @@ -5853,13 +9069,13 @@ typedef void (APIENTRYP PFNGLIGLOOINTERFACESGIXPROC) (GLenum pname, const GLvoid #ifndef GL_NV_fence #define GL_NV_fence 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glDeleteFencesNV (GLsizei, const GLuint *); -extern void APIENTRY glGenFencesNV (GLsizei, GLuint *); -extern GLboolean APIENTRY glIsFenceNV (GLuint); -extern GLboolean APIENTRY glTestFenceNV (GLuint); -extern void APIENTRY glGetFenceivNV (GLuint, GLenum, GLint *); -extern void APIENTRY glFinishFenceNV (GLuint); -extern void APIENTRY glSetFenceNV (GLuint, GLenum); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences); typedef void (APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences); @@ -5873,15 +9089,15 @@ typedef void (APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition); #ifndef GL_NV_evaluators #define GL_NV_evaluators 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glMapControlPointsNV (GLenum, GLuint, GLenum, GLsizei, GLsizei, GLint, GLint, GLboolean, const GLvoid *); -extern void APIENTRY glMapParameterivNV (GLenum, GLenum, const GLint *); -extern void APIENTRY glMapParameterfvNV (GLenum, GLenum, const GLfloat *); -extern void APIENTRY glGetMapControlPointsNV (GLenum, GLuint, GLenum, GLsizei, GLsizei, GLboolean, GLvoid *); -extern void APIENTRY glGetMapParameterivNV (GLenum, GLenum, GLint *); -extern void APIENTRY glGetMapParameterfvNV (GLenum, GLenum, GLfloat *); -extern void APIENTRY glGetMapAttribParameterivNV (GLenum, GLuint, GLenum, GLint *); -extern void APIENTRY glGetMapAttribParameterfvNV (GLenum, GLuint, GLenum, GLfloat *); -extern void APIENTRY glEvalMapsNV (GLenum, GLenum); +GLAPI void APIENTRY glMapControlPointsNV (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const GLvoid *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, GLvoid *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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const GLvoid *points); typedef void (APIENTRYP PFNGLMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, const GLint *params); @@ -5898,15 +9114,11 @@ typedef void (APIENTRYP PFNGLEVALMAPSNVPROC) (GLenum target, GLenum mode); #define GL_NV_packed_depth_stencil 1 #endif -#ifndef GL_EXT_packed_depth_stencil -#define GL_EXT_packed_depth_stencil 1 -#endif - #ifndef GL_NV_register_combiners2 #define GL_NV_register_combiners2 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glCombinerStageParameterfvNV (GLenum, GLenum, const GLfloat *); -extern void APIENTRY glGetCombinerStageParameterfvNV (GLenum, GLenum, GLfloat *); +GLAPI void APIENTRY glCombinerStageParameterfvNV (GLenum stage, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glGetCombinerStageParameterfvNV (GLenum stage, GLenum pname, GLfloat *params); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, const GLfloat *params); typedef void (APIENTRYP PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, GLfloat *params); @@ -5935,70 +9147,70 @@ typedef void (APIENTRYP PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, G #ifndef GL_NV_vertex_program #define GL_NV_vertex_program 1 #ifdef GL_GLEXT_PROTOTYPES -extern GLboolean APIENTRY glAreProgramsResidentNV (GLsizei, const GLuint *, GLboolean *); -extern void APIENTRY glBindProgramNV (GLenum, GLuint); -extern void APIENTRY glDeleteProgramsNV (GLsizei, const GLuint *); -extern void APIENTRY glExecuteProgramNV (GLenum, GLuint, const GLfloat *); -extern void APIENTRY glGenProgramsNV (GLsizei, GLuint *); -extern void APIENTRY glGetProgramParameterdvNV (GLenum, GLuint, GLenum, GLdouble *); -extern void APIENTRY glGetProgramParameterfvNV (GLenum, GLuint, GLenum, GLfloat *); -extern void APIENTRY glGetProgramivNV (GLuint, GLenum, GLint *); -extern void APIENTRY glGetProgramStringNV (GLuint, GLenum, GLubyte *); -extern void APIENTRY glGetTrackMatrixivNV (GLenum, GLuint, GLenum, GLint *); -extern void APIENTRY glGetVertexAttribdvNV (GLuint, GLenum, GLdouble *); -extern void APIENTRY glGetVertexAttribfvNV (GLuint, GLenum, GLfloat *); -extern void APIENTRY glGetVertexAttribivNV (GLuint, GLenum, GLint *); -extern void APIENTRY glGetVertexAttribPointervNV (GLuint, GLenum, GLvoid* *); -extern GLboolean APIENTRY glIsProgramNV (GLuint); -extern void APIENTRY glLoadProgramNV (GLenum, GLuint, GLsizei, const GLubyte *); -extern void APIENTRY glProgramParameter4dNV (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble); -extern void APIENTRY glProgramParameter4dvNV (GLenum, GLuint, const GLdouble *); -extern void APIENTRY glProgramParameter4fNV (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glProgramParameter4fvNV (GLenum, GLuint, const GLfloat *); -extern void APIENTRY glProgramParameters4dvNV (GLenum, GLuint, GLuint, const GLdouble *); -extern void APIENTRY glProgramParameters4fvNV (GLenum, GLuint, GLuint, const GLfloat *); -extern void APIENTRY glRequestResidentProgramsNV (GLsizei, const GLuint *); -extern void APIENTRY glTrackMatrixNV (GLenum, GLuint, GLenum, GLenum); -extern void APIENTRY glVertexAttribPointerNV (GLuint, GLint, GLenum, GLsizei, const GLvoid *); -extern void APIENTRY glVertexAttrib1dNV (GLuint, GLdouble); -extern void APIENTRY glVertexAttrib1dvNV (GLuint, const GLdouble *); -extern void APIENTRY glVertexAttrib1fNV (GLuint, GLfloat); -extern void APIENTRY glVertexAttrib1fvNV (GLuint, const GLfloat *); -extern void APIENTRY glVertexAttrib1sNV (GLuint, GLshort); -extern void APIENTRY glVertexAttrib1svNV (GLuint, const GLshort *); -extern void APIENTRY glVertexAttrib2dNV (GLuint, GLdouble, GLdouble); -extern void APIENTRY glVertexAttrib2dvNV (GLuint, const GLdouble *); -extern void APIENTRY glVertexAttrib2fNV (GLuint, GLfloat, GLfloat); -extern void APIENTRY glVertexAttrib2fvNV (GLuint, const GLfloat *); -extern void APIENTRY glVertexAttrib2sNV (GLuint, GLshort, GLshort); -extern void APIENTRY glVertexAttrib2svNV (GLuint, const GLshort *); -extern void APIENTRY glVertexAttrib3dNV (GLuint, GLdouble, GLdouble, GLdouble); -extern void APIENTRY glVertexAttrib3dvNV (GLuint, const GLdouble *); -extern void APIENTRY glVertexAttrib3fNV (GLuint, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glVertexAttrib3fvNV (GLuint, const GLfloat *); -extern void APIENTRY glVertexAttrib3sNV (GLuint, GLshort, GLshort, GLshort); -extern void APIENTRY glVertexAttrib3svNV (GLuint, const GLshort *); -extern void APIENTRY glVertexAttrib4dNV (GLuint, GLdouble, GLdouble, GLdouble, GLdouble); -extern void APIENTRY glVertexAttrib4dvNV (GLuint, const GLdouble *); -extern void APIENTRY glVertexAttrib4fNV (GLuint, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glVertexAttrib4fvNV (GLuint, const GLfloat *); -extern void APIENTRY glVertexAttrib4sNV (GLuint, GLshort, GLshort, GLshort, GLshort); -extern void APIENTRY glVertexAttrib4svNV (GLuint, const GLshort *); -extern void APIENTRY glVertexAttrib4ubNV (GLuint, GLubyte, GLubyte, GLubyte, GLubyte); -extern void APIENTRY glVertexAttrib4ubvNV (GLuint, const GLubyte *); -extern void APIENTRY glVertexAttribs1dvNV (GLuint, GLsizei, const GLdouble *); -extern void APIENTRY glVertexAttribs1fvNV (GLuint, GLsizei, const GLfloat *); -extern void APIENTRY glVertexAttribs1svNV (GLuint, GLsizei, const GLshort *); -extern void APIENTRY glVertexAttribs2dvNV (GLuint, GLsizei, const GLdouble *); -extern void APIENTRY glVertexAttribs2fvNV (GLuint, GLsizei, const GLfloat *); -extern void APIENTRY glVertexAttribs2svNV (GLuint, GLsizei, const GLshort *); -extern void APIENTRY glVertexAttribs3dvNV (GLuint, GLsizei, const GLdouble *); -extern void APIENTRY glVertexAttribs3fvNV (GLuint, GLsizei, const GLfloat *); -extern void APIENTRY glVertexAttribs3svNV (GLuint, GLsizei, const GLshort *); -extern void APIENTRY glVertexAttribs4dvNV (GLuint, GLsizei, const GLdouble *); -extern void APIENTRY glVertexAttribs4fvNV (GLuint, GLsizei, const GLfloat *); -extern void APIENTRY glVertexAttribs4svNV (GLuint, GLsizei, const GLshort *); -extern void APIENTRY glVertexAttribs4ubvNV (GLuint, GLsizei, const GLubyte *); +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, GLvoid* *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 GLvoid *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 /* GL_GLEXT_PROTOTYPES */ typedef GLboolean (APIENTRYP PFNGLAREPROGRAMSRESIDENTNVPROC) (GLsizei n, const GLuint *programs, GLboolean *residences); typedef void (APIENTRYP PFNGLBINDPROGRAMNVPROC) (GLenum target, GLuint id); @@ -6020,8 +9232,8 @@ typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DNVPROC) (GLenum target, GLuint in 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, GLuint count, const GLdouble *v); -typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4FVNVPROC) (GLenum target, GLuint index, GLuint count, 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 GLvoid *pointer); @@ -6093,10 +9305,10 @@ typedef void (APIENTRYP PFNGLVERTEXATTRIBS4UBVNVPROC) (GLuint index, GLsizei cou #ifndef GL_ATI_envmap_bumpmap #define GL_ATI_envmap_bumpmap 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glTexBumpParameterivATI (GLenum, const GLint *); -extern void APIENTRY glTexBumpParameterfvATI (GLenum, const GLfloat *); -extern void APIENTRY glGetTexBumpParameterivATI (GLenum, GLint *); -extern void APIENTRY glGetTexBumpParameterfvATI (GLenum, GLfloat *); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERIVATIPROC) (GLenum pname, const GLint *param); typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERFVATIPROC) (GLenum pname, const GLfloat *param); @@ -6107,20 +9319,20 @@ typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERFVATIPROC) (GLenum pname, GLfloa #ifndef GL_ATI_fragment_shader #define GL_ATI_fragment_shader 1 #ifdef GL_GLEXT_PROTOTYPES -extern GLuint APIENTRY glGenFragmentShadersATI (GLuint); -extern void APIENTRY glBindFragmentShaderATI (GLuint); -extern void APIENTRY glDeleteFragmentShaderATI (GLuint); -extern void APIENTRY glBeginFragmentShaderATI (void); -extern void APIENTRY glEndFragmentShaderATI (void); -extern void APIENTRY glPassTexCoordATI (GLuint, GLuint, GLenum); -extern void APIENTRY glSampleMapATI (GLuint, GLuint, GLenum); -extern void APIENTRY glColorFragmentOp1ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint); -extern void APIENTRY glColorFragmentOp2ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint); -extern void APIENTRY glColorFragmentOp3ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint); -extern void APIENTRY glAlphaFragmentOp1ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint); -extern void APIENTRY glAlphaFragmentOp2ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint); -extern void APIENTRY glAlphaFragmentOp3ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint); -extern void APIENTRY glSetFragmentShaderConstantATI (GLuint, const GLfloat *); +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 /* GL_GLEXT_PROTOTYPES */ typedef GLuint (APIENTRYP PFNGLGENFRAGMENTSHADERSATIPROC) (GLuint range); typedef void (APIENTRYP PFNGLBINDFRAGMENTSHADERATIPROC) (GLuint id); @@ -6141,8 +9353,8 @@ typedef void (APIENTRYP PFNGLSETFRAGMENTSHADERCONSTANTATIPROC) (GLuint dst, cons #ifndef GL_ATI_pn_triangles #define GL_ATI_pn_triangles 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glPNTrianglesiATI (GLenum, GLint); -extern void APIENTRY glPNTrianglesfATI (GLenum, GLfloat); +GLAPI void APIENTRY glPNTrianglesiATI (GLenum pname, GLint param); +GLAPI void APIENTRY glPNTrianglesfATI (GLenum pname, GLfloat param); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPNTRIANGLESIATIPROC) (GLenum pname, GLint param); typedef void (APIENTRYP PFNGLPNTRIANGLESFATIPROC) (GLenum pname, GLfloat param); @@ -6151,18 +9363,18 @@ typedef void (APIENTRYP PFNGLPNTRIANGLESFATIPROC) (GLenum pname, GLfloat param); #ifndef GL_ATI_vertex_array_object #define GL_ATI_vertex_array_object 1 #ifdef GL_GLEXT_PROTOTYPES -extern GLuint APIENTRY glNewObjectBufferATI (GLsizei, const GLvoid *, GLenum); -extern GLboolean APIENTRY glIsObjectBufferATI (GLuint); -extern void APIENTRY glUpdateObjectBufferATI (GLuint, GLuint, GLsizei, const GLvoid *, GLenum); -extern void APIENTRY glGetObjectBufferfvATI (GLuint, GLenum, GLfloat *); -extern void APIENTRY glGetObjectBufferivATI (GLuint, GLenum, GLint *); -extern void APIENTRY glFreeObjectBufferATI (GLuint); -extern void APIENTRY glArrayObjectATI (GLenum, GLint, GLenum, GLsizei, GLuint, GLuint); -extern void APIENTRY glGetArrayObjectfvATI (GLenum, GLenum, GLfloat *); -extern void APIENTRY glGetArrayObjectivATI (GLenum, GLenum, GLint *); -extern void APIENTRY glVariantArrayObjectATI (GLuint, GLenum, GLsizei, GLuint, GLuint); -extern void APIENTRY glGetVariantArrayObjectfvATI (GLuint, GLenum, GLfloat *); -extern void APIENTRY glGetVariantArrayObjectivATI (GLuint, GLenum, GLint *); +GLAPI GLuint APIENTRY glNewObjectBufferATI (GLsizei size, const GLvoid *pointer, GLenum usage); +GLAPI GLboolean APIENTRY glIsObjectBufferATI (GLuint buffer); +GLAPI void APIENTRY glUpdateObjectBufferATI (GLuint buffer, GLuint offset, GLsizei size, const GLvoid *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 /* GL_GLEXT_PROTOTYPES */ typedef GLuint (APIENTRYP PFNGLNEWOBJECTBUFFERATIPROC) (GLsizei size, const GLvoid *pointer, GLenum usage); typedef GLboolean (APIENTRYP PFNGLISOBJECTBUFFERATIPROC) (GLuint buffer); @@ -6181,48 +9393,48 @@ typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTIVATIPROC) (GLuint id, GLenum #ifndef GL_EXT_vertex_shader #define GL_EXT_vertex_shader 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glBeginVertexShaderEXT (void); -extern void APIENTRY glEndVertexShaderEXT (void); -extern void APIENTRY glBindVertexShaderEXT (GLuint); -extern GLuint APIENTRY glGenVertexShadersEXT (GLuint); -extern void APIENTRY glDeleteVertexShaderEXT (GLuint); -extern void APIENTRY glShaderOp1EXT (GLenum, GLuint, GLuint); -extern void APIENTRY glShaderOp2EXT (GLenum, GLuint, GLuint, GLuint); -extern void APIENTRY glShaderOp3EXT (GLenum, GLuint, GLuint, GLuint, GLuint); -extern void APIENTRY glSwizzleEXT (GLuint, GLuint, GLenum, GLenum, GLenum, GLenum); -extern void APIENTRY glWriteMaskEXT (GLuint, GLuint, GLenum, GLenum, GLenum, GLenum); -extern void APIENTRY glInsertComponentEXT (GLuint, GLuint, GLuint); -extern void APIENTRY glExtractComponentEXT (GLuint, GLuint, GLuint); -extern GLuint APIENTRY glGenSymbolsEXT (GLenum, GLenum, GLenum, GLuint); -extern void APIENTRY glSetInvariantEXT (GLuint, GLenum, const GLvoid *); -extern void APIENTRY glSetLocalConstantEXT (GLuint, GLenum, const GLvoid *); -extern void APIENTRY glVariantbvEXT (GLuint, const GLbyte *); -extern void APIENTRY glVariantsvEXT (GLuint, const GLshort *); -extern void APIENTRY glVariantivEXT (GLuint, const GLint *); -extern void APIENTRY glVariantfvEXT (GLuint, const GLfloat *); -extern void APIENTRY glVariantdvEXT (GLuint, const GLdouble *); -extern void APIENTRY glVariantubvEXT (GLuint, const GLubyte *); -extern void APIENTRY glVariantusvEXT (GLuint, const GLushort *); -extern void APIENTRY glVariantuivEXT (GLuint, const GLuint *); -extern void APIENTRY glVariantPointerEXT (GLuint, GLenum, GLuint, const GLvoid *); -extern void APIENTRY glEnableVariantClientStateEXT (GLuint); -extern void APIENTRY glDisableVariantClientStateEXT (GLuint); -extern GLuint APIENTRY glBindLightParameterEXT (GLenum, GLenum); -extern GLuint APIENTRY glBindMaterialParameterEXT (GLenum, GLenum); -extern GLuint APIENTRY glBindTexGenParameterEXT (GLenum, GLenum, GLenum); -extern GLuint APIENTRY glBindTextureUnitParameterEXT (GLenum, GLenum); -extern GLuint APIENTRY glBindParameterEXT (GLenum); -extern GLboolean APIENTRY glIsVariantEnabledEXT (GLuint, GLenum); -extern void APIENTRY glGetVariantBooleanvEXT (GLuint, GLenum, GLboolean *); -extern void APIENTRY glGetVariantIntegervEXT (GLuint, GLenum, GLint *); -extern void APIENTRY glGetVariantFloatvEXT (GLuint, GLenum, GLfloat *); -extern void APIENTRY glGetVariantPointervEXT (GLuint, GLenum, GLvoid* *); -extern void APIENTRY glGetInvariantBooleanvEXT (GLuint, GLenum, GLboolean *); -extern void APIENTRY glGetInvariantIntegervEXT (GLuint, GLenum, GLint *); -extern void APIENTRY glGetInvariantFloatvEXT (GLuint, GLenum, GLfloat *); -extern void APIENTRY glGetLocalConstantBooleanvEXT (GLuint, GLenum, GLboolean *); -extern void APIENTRY glGetLocalConstantIntegervEXT (GLuint, GLenum, GLint *); -extern void APIENTRY glGetLocalConstantFloatvEXT (GLuint, GLenum, GLfloat *); +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 GLvoid *addr); +GLAPI void APIENTRY glSetLocalConstantEXT (GLuint id, GLenum type, const GLvoid *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 GLvoid *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, GLvoid* *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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBEGINVERTEXSHADEREXTPROC) (void); typedef void (APIENTRYP PFNGLENDVERTEXSHADEREXTPROC) (void); @@ -6271,51 +9483,51 @@ typedef void (APIENTRYP PFNGLGETLOCALCONSTANTFLOATVEXTPROC) (GLuint id, GLenum v #ifndef GL_ATI_vertex_streams #define GL_ATI_vertex_streams 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glVertexStream1sATI (GLenum, GLshort); -extern void APIENTRY glVertexStream1svATI (GLenum, const GLshort *); -extern void APIENTRY glVertexStream1iATI (GLenum, GLint); -extern void APIENTRY glVertexStream1ivATI (GLenum, const GLint *); -extern void APIENTRY glVertexStream1fATI (GLenum, GLfloat); -extern void APIENTRY glVertexStream1fvATI (GLenum, const GLfloat *); -extern void APIENTRY glVertexStream1dATI (GLenum, GLdouble); -extern void APIENTRY glVertexStream1dvATI (GLenum, const GLdouble *); -extern void APIENTRY glVertexStream2sATI (GLenum, GLshort, GLshort); -extern void APIENTRY glVertexStream2svATI (GLenum, const GLshort *); -extern void APIENTRY glVertexStream2iATI (GLenum, GLint, GLint); -extern void APIENTRY glVertexStream2ivATI (GLenum, const GLint *); -extern void APIENTRY glVertexStream2fATI (GLenum, GLfloat, GLfloat); -extern void APIENTRY glVertexStream2fvATI (GLenum, const GLfloat *); -extern void APIENTRY glVertexStream2dATI (GLenum, GLdouble, GLdouble); -extern void APIENTRY glVertexStream2dvATI (GLenum, const GLdouble *); -extern void APIENTRY glVertexStream3sATI (GLenum, GLshort, GLshort, GLshort); -extern void APIENTRY glVertexStream3svATI (GLenum, const GLshort *); -extern void APIENTRY glVertexStream3iATI (GLenum, GLint, GLint, GLint); -extern void APIENTRY glVertexStream3ivATI (GLenum, const GLint *); -extern void APIENTRY glVertexStream3fATI (GLenum, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glVertexStream3fvATI (GLenum, const GLfloat *); -extern void APIENTRY glVertexStream3dATI (GLenum, GLdouble, GLdouble, GLdouble); -extern void APIENTRY glVertexStream3dvATI (GLenum, const GLdouble *); -extern void APIENTRY glVertexStream4sATI (GLenum, GLshort, GLshort, GLshort, GLshort); -extern void APIENTRY glVertexStream4svATI (GLenum, const GLshort *); -extern void APIENTRY glVertexStream4iATI (GLenum, GLint, GLint, GLint, GLint); -extern void APIENTRY glVertexStream4ivATI (GLenum, const GLint *); -extern void APIENTRY glVertexStream4fATI (GLenum, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glVertexStream4fvATI (GLenum, const GLfloat *); -extern void APIENTRY glVertexStream4dATI (GLenum, GLdouble, GLdouble, GLdouble, GLdouble); -extern void APIENTRY glVertexStream4dvATI (GLenum, const GLdouble *); -extern void APIENTRY glNormalStream3bATI (GLenum, GLbyte, GLbyte, GLbyte); -extern void APIENTRY glNormalStream3bvATI (GLenum, const GLbyte *); -extern void APIENTRY glNormalStream3sATI (GLenum, GLshort, GLshort, GLshort); -extern void APIENTRY glNormalStream3svATI (GLenum, const GLshort *); -extern void APIENTRY glNormalStream3iATI (GLenum, GLint, GLint, GLint); -extern void APIENTRY glNormalStream3ivATI (GLenum, const GLint *); -extern void APIENTRY glNormalStream3fATI (GLenum, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glNormalStream3fvATI (GLenum, const GLfloat *); -extern void APIENTRY glNormalStream3dATI (GLenum, GLdouble, GLdouble, GLdouble); -extern void APIENTRY glNormalStream3dvATI (GLenum, const GLdouble *); -extern void APIENTRY glClientActiveVertexStreamATI (GLenum); -extern void APIENTRY glVertexBlendEnviATI (GLenum, GLint); -extern void APIENTRY glVertexBlendEnvfATI (GLenum, GLfloat); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLVERTEXSTREAM1SATIPROC) (GLenum stream, GLshort x); typedef void (APIENTRYP PFNGLVERTEXSTREAM1SVATIPROC) (GLenum stream, const GLshort *coords); @@ -6367,9 +9579,9 @@ typedef void (APIENTRYP PFNGLVERTEXBLENDENVFATIPROC) (GLenum pname, GLfloat para #ifndef GL_ATI_element_array #define GL_ATI_element_array 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glElementPointerATI (GLenum, const GLvoid *); -extern void APIENTRY glDrawElementArrayATI (GLenum, GLsizei); -extern void APIENTRY glDrawRangeElementArrayATI (GLenum, GLuint, GLuint, GLsizei); +GLAPI void APIENTRY glElementPointerATI (GLenum type, const GLvoid *pointer); +GLAPI void APIENTRY glDrawElementArrayATI (GLenum mode, GLsizei count); +GLAPI void APIENTRY glDrawRangeElementArrayATI (GLenum mode, GLuint start, GLuint end, GLsizei count); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLELEMENTPOINTERATIPROC) (GLenum type, const GLvoid *pointer); typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYATIPROC) (GLenum mode, GLsizei count); @@ -6379,7 +9591,7 @@ typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYATIPROC) (GLenum mode, GLuint #ifndef GL_SUN_mesh_array #define GL_SUN_mesh_array 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glDrawMeshArraysSUN (GLenum, GLint, GLsizei, GLsizei); +GLAPI void APIENTRY glDrawMeshArraysSUN (GLenum mode, GLint first, GLsizei count, GLsizei width); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLDRAWMESHARRAYSSUNPROC) (GLenum mode, GLint first, GLsizei count, GLsizei width); #endif @@ -6399,13 +9611,13 @@ typedef void (APIENTRYP PFNGLDRAWMESHARRAYSSUNPROC) (GLenum mode, GLint first, G #ifndef GL_NV_occlusion_query #define GL_NV_occlusion_query 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glGenOcclusionQueriesNV (GLsizei, GLuint *); -extern void APIENTRY glDeleteOcclusionQueriesNV (GLsizei, const GLuint *); -extern GLboolean APIENTRY glIsOcclusionQueryNV (GLuint); -extern void APIENTRY glBeginOcclusionQueryNV (GLuint); -extern void APIENTRY glEndOcclusionQueryNV (void); -extern void APIENTRY glGetOcclusionQueryivNV (GLuint, GLenum, GLint *); -extern void APIENTRY glGetOcclusionQueryuivNV (GLuint, GLenum, GLuint *); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLGENOCCLUSIONQUERIESNVPROC) (GLsizei n, GLuint *ids); typedef void (APIENTRYP PFNGLDELETEOCCLUSIONQUERIESNVPROC) (GLsizei n, const GLuint *ids); @@ -6419,8 +9631,8 @@ typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYUIVNVPROC) (GLuint id, GLenum pnam #ifndef GL_NV_point_sprite #define GL_NV_point_sprite 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glPointParameteriNV (GLenum, GLint); -extern void APIENTRY glPointParameterivNV (GLenum, const GLint *); +GLAPI void APIENTRY glPointParameteriNV (GLenum pname, GLint param); +GLAPI void APIENTRY glPointParameterivNV (GLenum pname, const GLint *params); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPOINTPARAMETERINVPROC) (GLenum pname, GLint param); typedef void (APIENTRYP PFNGLPOINTPARAMETERIVNVPROC) (GLenum pname, const GLint *params); @@ -6441,7 +9653,7 @@ typedef void (APIENTRYP PFNGLPOINTPARAMETERIVNVPROC) (GLenum pname, const GLint #ifndef GL_EXT_stencil_two_side #define GL_EXT_stencil_two_side 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glActiveStencilFaceEXT (GLenum); +GLAPI void APIENTRY glActiveStencilFaceEXT (GLenum face); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLACTIVESTENCILFACEEXTPROC) (GLenum face); #endif @@ -6457,11 +9669,11 @@ typedef void (APIENTRYP PFNGLACTIVESTENCILFACEEXTPROC) (GLenum face); #ifndef GL_APPLE_element_array #define GL_APPLE_element_array 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glElementPointerAPPLE (GLenum, const GLvoid *); -extern void APIENTRY glDrawElementArrayAPPLE (GLenum, GLint, GLsizei); -extern void APIENTRY glDrawRangeElementArrayAPPLE (GLenum, GLuint, GLuint, GLint, GLsizei); -extern void APIENTRY glMultiDrawElementArrayAPPLE (GLenum, const GLint *, const GLsizei *, GLsizei); -extern void APIENTRY glMultiDrawRangeElementArrayAPPLE (GLenum, GLuint, GLuint, const GLint *, const GLsizei *, GLsizei); +GLAPI void APIENTRY glElementPointerAPPLE (GLenum type, const GLvoid *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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLELEMENTPOINTERAPPLEPROC) (GLenum type, const GLvoid *pointer); typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, GLint first, GLsizei count); @@ -6473,14 +9685,14 @@ typedef void (APIENTRYP PFNGLMULTIDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, #ifndef GL_APPLE_fence #define GL_APPLE_fence 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glGenFencesAPPLE (GLsizei, GLuint *); -extern void APIENTRY glDeleteFencesAPPLE (GLsizei, const GLuint *); -extern void APIENTRY glSetFenceAPPLE (GLuint); -extern GLboolean APIENTRY glIsFenceAPPLE (GLuint); -extern GLboolean APIENTRY glTestFenceAPPLE (GLuint); -extern void APIENTRY glFinishFenceAPPLE (GLuint); -extern GLboolean APIENTRY glTestObjectAPPLE (GLenum, GLuint); -extern void APIENTRY glFinishObjectAPPLE (GLenum, GLint); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLGENFENCESAPPLEPROC) (GLsizei n, GLuint *fences); typedef void (APIENTRYP PFNGLDELETEFENCESAPPLEPROC) (GLsizei n, const GLuint *fences); @@ -6495,23 +9707,23 @@ typedef void (APIENTRYP PFNGLFINISHOBJECTAPPLEPROC) (GLenum object, GLint name); #ifndef GL_APPLE_vertex_array_object #define GL_APPLE_vertex_array_object 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glBindVertexArrayAPPLE (GLuint); -extern void APIENTRY glDeleteVertexArraysAPPLE (GLsizei, const GLuint *); -extern void APIENTRY glGenVertexArraysAPPLE (GLsizei, const GLuint *); -extern GLboolean APIENTRY glIsVertexArrayAPPLE (GLuint); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBINDVERTEXARRAYAPPLEPROC) (GLuint array); typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays); -typedef void (APIENTRYP PFNGLGENVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays); +typedef void (APIENTRYP PFNGLGENVERTEXARRAYSAPPLEPROC) (GLsizei n, GLuint *arrays); typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYAPPLEPROC) (GLuint array); #endif #ifndef GL_APPLE_vertex_array_range #define GL_APPLE_vertex_array_range 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glVertexArrayRangeAPPLE (GLsizei, GLvoid *); -extern void APIENTRY glFlushVertexArrayRangeAPPLE (GLsizei, GLvoid *); -extern void APIENTRY glVertexArrayParameteriAPPLE (GLenum, GLint); +GLAPI void APIENTRY glVertexArrayRangeAPPLE (GLsizei length, GLvoid *pointer); +GLAPI void APIENTRY glFlushVertexArrayRangeAPPLE (GLsizei length, GLvoid *pointer); +GLAPI void APIENTRY glVertexArrayParameteriAPPLE (GLenum pname, GLint param); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, GLvoid *pointer); typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, GLvoid *pointer); @@ -6529,7 +9741,7 @@ typedef void (APIENTRYP PFNGLVERTEXARRAYPARAMETERIAPPLEPROC) (GLenum pname, GLin #ifndef GL_ATI_draw_buffers #define GL_ATI_draw_buffers 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glDrawBuffersATI (GLsizei, const GLenum *); +GLAPI void APIENTRY glDrawBuffersATI (GLsizei n, const GLenum *bufs); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLDRAWBUFFERSATIPROC) (GLsizei n, const GLenum *bufs); #endif @@ -6557,12 +9769,12 @@ typedef void (APIENTRYP PFNGLDRAWBUFFERSATIPROC) (GLsizei n, const GLenum *bufs) #define GL_NV_fragment_program 1 /* Some NV_fragment_program entry points are shared with ARB_vertex_program. */ #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glProgramNamedParameter4fNV (GLuint, GLsizei, const GLubyte *, GLfloat, GLfloat, GLfloat, GLfloat); -extern void APIENTRY glProgramNamedParameter4dNV (GLuint, GLsizei, const GLubyte *, GLdouble, GLdouble, GLdouble, GLdouble); -extern void APIENTRY glProgramNamedParameter4fvNV (GLuint, GLsizei, const GLubyte *, const GLfloat *); -extern void APIENTRY glProgramNamedParameter4dvNV (GLuint, GLsizei, const GLubyte *, const GLdouble *); -extern void APIENTRY glGetProgramNamedParameterfvNV (GLuint, GLsizei, const GLubyte *, GLfloat *); -extern void APIENTRY glGetProgramNamedParameterdvNV (GLuint, GLsizei, const GLubyte *, GLdouble *); +GLAPI void APIENTRY glProgramNamedParameter4fNV (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glProgramNamedParameter4dNV (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glProgramNamedParameter4fvNV (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w); typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w); @@ -6575,52 +9787,52 @@ typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERDVNVPROC) (GLuint id, GLsiz #ifndef GL_NV_half_float #define GL_NV_half_float 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glVertex2hNV (GLhalfNV, GLhalfNV); -extern void APIENTRY glVertex2hvNV (const GLhalfNV *); -extern void APIENTRY glVertex3hNV (GLhalfNV, GLhalfNV, GLhalfNV); -extern void APIENTRY glVertex3hvNV (const GLhalfNV *); -extern void APIENTRY glVertex4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV); -extern void APIENTRY glVertex4hvNV (const GLhalfNV *); -extern void APIENTRY glNormal3hNV (GLhalfNV, GLhalfNV, GLhalfNV); -extern void APIENTRY glNormal3hvNV (const GLhalfNV *); -extern void APIENTRY glColor3hNV (GLhalfNV, GLhalfNV, GLhalfNV); -extern void APIENTRY glColor3hvNV (const GLhalfNV *); -extern void APIENTRY glColor4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV); -extern void APIENTRY glColor4hvNV (const GLhalfNV *); -extern void APIENTRY glTexCoord1hNV (GLhalfNV); -extern void APIENTRY glTexCoord1hvNV (const GLhalfNV *); -extern void APIENTRY glTexCoord2hNV (GLhalfNV, GLhalfNV); -extern void APIENTRY glTexCoord2hvNV (const GLhalfNV *); -extern void APIENTRY glTexCoord3hNV (GLhalfNV, GLhalfNV, GLhalfNV); -extern void APIENTRY glTexCoord3hvNV (const GLhalfNV *); -extern void APIENTRY glTexCoord4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV); -extern void APIENTRY glTexCoord4hvNV (const GLhalfNV *); -extern void APIENTRY glMultiTexCoord1hNV (GLenum, GLhalfNV); -extern void APIENTRY glMultiTexCoord1hvNV (GLenum, const GLhalfNV *); -extern void APIENTRY glMultiTexCoord2hNV (GLenum, GLhalfNV, GLhalfNV); -extern void APIENTRY glMultiTexCoord2hvNV (GLenum, const GLhalfNV *); -extern void APIENTRY glMultiTexCoord3hNV (GLenum, GLhalfNV, GLhalfNV, GLhalfNV); -extern void APIENTRY glMultiTexCoord3hvNV (GLenum, const GLhalfNV *); -extern void APIENTRY glMultiTexCoord4hNV (GLenum, GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV); -extern void APIENTRY glMultiTexCoord4hvNV (GLenum, const GLhalfNV *); -extern void APIENTRY glFogCoordhNV (GLhalfNV); -extern void APIENTRY glFogCoordhvNV (const GLhalfNV *); -extern void APIENTRY glSecondaryColor3hNV (GLhalfNV, GLhalfNV, GLhalfNV); -extern void APIENTRY glSecondaryColor3hvNV (const GLhalfNV *); -extern void APIENTRY glVertexWeighthNV (GLhalfNV); -extern void APIENTRY glVertexWeighthvNV (const GLhalfNV *); -extern void APIENTRY glVertexAttrib1hNV (GLuint, GLhalfNV); -extern void APIENTRY glVertexAttrib1hvNV (GLuint, const GLhalfNV *); -extern void APIENTRY glVertexAttrib2hNV (GLuint, GLhalfNV, GLhalfNV); -extern void APIENTRY glVertexAttrib2hvNV (GLuint, const GLhalfNV *); -extern void APIENTRY glVertexAttrib3hNV (GLuint, GLhalfNV, GLhalfNV, GLhalfNV); -extern void APIENTRY glVertexAttrib3hvNV (GLuint, const GLhalfNV *); -extern void APIENTRY glVertexAttrib4hNV (GLuint, GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV); -extern void APIENTRY glVertexAttrib4hvNV (GLuint, const GLhalfNV *); -extern void APIENTRY glVertexAttribs1hvNV (GLuint, GLsizei, const GLhalfNV *); -extern void APIENTRY glVertexAttribs2hvNV (GLuint, GLsizei, const GLhalfNV *); -extern void APIENTRY glVertexAttribs3hvNV (GLuint, GLsizei, const GLhalfNV *); -extern void APIENTRY glVertexAttribs4hvNV (GLuint, GLsizei, const GLhalfNV *); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLVERTEX2HNVPROC) (GLhalfNV x, GLhalfNV y); typedef void (APIENTRYP PFNGLVERTEX2HVNVPROC) (const GLhalfNV *v); @@ -6673,8 +9885,8 @@ typedef void (APIENTRYP PFNGLVERTEXATTRIBS4HVNVPROC) (GLuint index, GLsizei n, c #ifndef GL_NV_pixel_data_range #define GL_NV_pixel_data_range 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glPixelDataRangeNV (GLenum, GLsizei, GLvoid *); -extern void APIENTRY glFlushPixelDataRangeNV (GLenum); +GLAPI void APIENTRY glPixelDataRangeNV (GLenum target, GLsizei length, GLvoid *pointer); +GLAPI void APIENTRY glFlushPixelDataRangeNV (GLenum target); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPIXELDATARANGENVPROC) (GLenum target, GLsizei length, GLvoid *pointer); typedef void (APIENTRYP PFNGLFLUSHPIXELDATARANGENVPROC) (GLenum target); @@ -6683,8 +9895,8 @@ typedef void (APIENTRYP PFNGLFLUSHPIXELDATARANGENVPROC) (GLenum target); #ifndef GL_NV_primitive_restart #define GL_NV_primitive_restart 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glPrimitiveRestartNV (void); -extern void APIENTRY glPrimitiveRestartIndexNV (GLuint); +GLAPI void APIENTRY glPrimitiveRestartNV (void); +GLAPI void APIENTRY glPrimitiveRestartIndexNV (GLuint index); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPRIMITIVERESTARTNVPROC) (void); typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXNVPROC) (GLuint index); @@ -6701,8 +9913,8 @@ typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXNVPROC) (GLuint index); #ifndef GL_ATI_map_object_buffer #define GL_ATI_map_object_buffer 1 #ifdef GL_GLEXT_PROTOTYPES -extern GLvoid* APIENTRY glMapObjectBufferATI (GLuint); -extern void APIENTRY glUnmapObjectBufferATI (GLuint); +GLAPI GLvoid* APIENTRY glMapObjectBufferATI (GLuint buffer); +GLAPI void APIENTRY glUnmapObjectBufferATI (GLuint buffer); #endif /* GL_GLEXT_PROTOTYPES */ typedef GLvoid* (APIENTRYP PFNGLMAPOBJECTBUFFERATIPROC) (GLuint buffer); typedef void (APIENTRYP PFNGLUNMAPOBJECTBUFFERATIPROC) (GLuint buffer); @@ -6711,8 +9923,8 @@ typedef void (APIENTRYP PFNGLUNMAPOBJECTBUFFERATIPROC) (GLuint buffer); #ifndef GL_ATI_separate_stencil #define GL_ATI_separate_stencil 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glStencilOpSeparateATI (GLenum, GLenum, GLenum, GLenum); -extern void APIENTRY glStencilFuncSeparateATI (GLenum, GLenum, GLint, GLuint); +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 /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEATIPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEATIPROC) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask); @@ -6721,9 +9933,9 @@ typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEATIPROC) (GLenum frontfunc, GLen #ifndef GL_ATI_vertex_attrib_array_object #define GL_ATI_vertex_attrib_array_object 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glVertexAttribArrayObjectATI (GLuint, GLint, GLenum, GLboolean, GLsizei, GLuint, GLuint); -extern void APIENTRY glGetVertexAttribArrayObjectfvATI (GLuint, GLenum, GLfloat *); -extern void APIENTRY glGetVertexAttribArrayObjectivATI (GLuint, GLenum, GLint *); +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 /* GL_GLEXT_PROTOTYPES */ 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); @@ -6737,7 +9949,7 @@ typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTIVATIPROC) (GLuint index, #ifndef GL_EXT_depth_bounds_test #define GL_EXT_depth_bounds_test 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glDepthBoundsEXT (GLclampd, GLclampd); +GLAPI void APIENTRY glDepthBoundsEXT (GLclampd zmin, GLclampd zmax); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLDEPTHBOUNDSEXTPROC) (GLclampd zmin, GLclampd zmax); #endif @@ -6749,7 +9961,7 @@ typedef void (APIENTRYP PFNGLDEPTHBOUNDSEXTPROC) (GLclampd zmin, GLclampd zmax); #ifndef GL_EXT_blend_equation_separate #define GL_EXT_blend_equation_separate 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glBlendEquationSeparateEXT (GLenum, GLenum); +GLAPI void APIENTRY glBlendEquationSeparateEXT (GLenum modeRGB, GLenum modeAlpha); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEEXTPROC) (GLenum modeRGB, GLenum modeAlpha); #endif @@ -6785,23 +9997,23 @@ typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEEXTPROC) (GLenum modeRGB, GLen #ifndef GL_EXT_framebuffer_object #define GL_EXT_framebuffer_object 1 #ifdef GL_GLEXT_PROTOTYPES -extern GLboolean APIENTRY glIsRenderbufferEXT (GLuint); -extern void APIENTRY glBindRenderbufferEXT (GLenum, GLuint); -extern void APIENTRY glDeleteRenderbuffersEXT (GLsizei, const GLuint *); -extern void APIENTRY glGenRenderbuffersEXT (GLsizei, GLuint *); -extern void APIENTRY glRenderbufferStorageEXT (GLenum, GLenum, GLsizei, GLsizei); -extern void APIENTRY glGetRenderbufferParameterivEXT (GLenum, GLenum, GLint *); -extern GLboolean APIENTRY glIsFramebufferEXT (GLuint); -extern void APIENTRY glBindFramebufferEXT (GLenum, GLuint); -extern void APIENTRY glDeleteFramebuffersEXT (GLsizei, const GLuint *); -extern void APIENTRY glGenFramebuffersEXT (GLsizei, GLuint *); -extern GLenum APIENTRY glCheckFramebufferStatusEXT (GLenum); -extern void APIENTRY glFramebufferTexture1DEXT (GLenum, GLenum, GLenum, GLuint, GLint); -extern void APIENTRY glFramebufferTexture2DEXT (GLenum, GLenum, GLenum, GLuint, GLint); -extern void APIENTRY glFramebufferTexture3DEXT (GLenum, GLenum, GLenum, GLuint, GLint, GLint); -extern void APIENTRY glFramebufferRenderbufferEXT (GLenum, GLenum, GLenum, GLuint); -extern void APIENTRY glGetFramebufferAttachmentParameterivEXT (GLenum, GLenum, GLenum, GLint *); -extern void APIENTRY glGenerateMipmapEXT (GLenum); +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 /* GL_GLEXT_PROTOTYPES */ typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFEREXTPROC) (GLuint renderbuffer); typedef void (APIENTRYP PFNGLBINDRENDERBUFFEREXTPROC) (GLenum target, GLuint renderbuffer); @@ -6825,193 +10037,166 @@ typedef void (APIENTRYP PFNGLGENERATEMIPMAPEXTPROC) (GLenum target); #ifndef GL_GREMEDY_string_marker #define GL_GREMEDY_string_marker 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glStringMarkerGREMEDY (GLsizei, const GLvoid *); +GLAPI void APIENTRY glStringMarkerGREMEDY (GLsizei len, const GLvoid *string); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLSTRINGMARKERGREMEDYPROC) (GLsizei len, const GLvoid *string); #endif -#ifndef GL_EXT_Cg_shader -#define GL_EXT_Cg_shader 1 +#ifndef GL_EXT_packed_depth_stencil +#define GL_EXT_packed_depth_stencil 1 #endif -#ifndef GL_EXT_timer_query -#define GL_EXT_timer_query 1 +#ifndef GL_EXT_stencil_clear_tag +#define GL_EXT_stencil_clear_tag 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glGetQueryObjecti64vEXT (GLuint id, GLenum pname, GLint64EXT *params); -extern void APIENTRY glGetQueryObjectui64vEXT (GLuint id, GLenum pname, GLuint64EXT *params); +GLAPI void APIENTRY glStencilClearTagEXT (GLsizei stencilTagBits, GLuint stencilClearTag); #endif /* GL_GLEXT_PROTOTYPES */ -typedef void (APIENTRYP PFNGLGETQUERYOBJECTI64VEXTPROC) (GLuint id, GLenum pname, GLint64EXT *params); -typedef void (APIENTRYP PFNGLGETQUERYOBJECTUI64VEXTPROC) (GLuint id, GLenum pname, GLuint64EXT *params); +typedef void (APIENTRYP PFNGLSTENCILCLEARTAGEXTPROC) (GLsizei stencilTagBits, GLuint stencilClearTag); #endif -#ifndef GL_EXT_texture_buffer_object -#define GL_EXT_texture_buffer_object 1 -#ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glTexBufferEXT (GLenum target, GLenum internalformat, GLuint buffer); -#endif /* GL_GLEXT_PROTOTYPES */ -typedef void (APIENTRYP PFNGLTEXBUFFEREXTPROC) (GLenum target, GLenum internalformat, GLuint buffer); +#ifndef GL_EXT_texture_sRGB +#define GL_EXT_texture_sRGB 1 #endif -#ifndef GL_NV_transform_feedback -#define GL_NV_transform_feedback 1 +#ifndef GL_EXT_framebuffer_blit +#define GL_EXT_framebuffer_blit 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glBeginTransformFeedbackNV (GLenum primitiveMode); -extern void APIENTRY glEndTransformFeedbackNV (void); -extern void APIENTRY glTransformFeedbackAttribsNV (GLuint count, const GLint *attribs, GLenum bufferMode); -extern void APIENTRY glBindBufferRangeNV (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); -extern void APIENTRY glBindBufferOffsetNV (GLenum target, GLuint index, GLuint buffer, GLintptr offset); -extern void APIENTRY glBindBufferBaseNV (GLenum target, GLuint index, GLuint buffer); -extern void APIENTRY glTransformFeedbackVaryingsNV (GLuint program, GLsizei count, const GLint *locations, GLenum bufferMode); -extern void APIENTRY glActiveVaryingNV (GLuint program, const GLchar *name); -extern GLint APIENTRY glGetVaryingLocationNV (GLuint program, const GLchar *name); -extern void APIENTRY glGetActiveVaryingNV (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); -extern void APIENTRY glGetTransformFeedbackVaryingNV (GLuint program, GLuint index, GLint *location); +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 /* GL_GLEXT_PROTOTYPES */ -typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKNVPROC) (GLenum primitiveMode); -typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKNVPROC) (void); -typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKATTRIBSNVPROC) (GLuint 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 PFNGLBLITFRAMEBUFFEREXTPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); #endif - -#ifndef GL_NV_depth_buffer_float -#define GL_NV_depth_buffer_float 1 +#ifndef GL_EXT_framebuffer_multisample +#define GL_EXT_framebuffer_multisample 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glDepthRangedNV (GLdouble zNear, GLdouble zFar); -extern void APIENTRY glClearDepthdNV (GLdouble depth); -extern void APIENTRY glDepthBoundsdNV (GLdouble zmin, GLdouble zmax); +GLAPI void APIENTRY glRenderbufferStorageMultisampleEXT (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); #endif /* GL_GLEXT_PROTOTYPES */ -typedef void (APIENTRYP PFNGLDEPTHRANGEDNVPROC) (GLdouble zNear, GLdouble zFar); -typedef void (APIENTRYP PFNGLCLEARDEPTHDNVPROC) (GLdouble depth); -typedef void (APIENTRYP PFNGLDEPTHBOUNDSDNVPROC) (GLdouble zmin, GLdouble zmax); -#endif - -#ifndef GL_EXT_texture_compression_latc -#define GL_EXT_texture_compression_latc 1 -#endif - -#ifndef GL_EXT_framebuffer_sRGB -#define GL_EXT_framebuffer_sRGB 1 -#endif - -#ifndef GL_EXT_texture_shared_exponent -#define GL_EXT_texture_shared_exponent 1 -#endif - -#ifndef GL_EXT_packed_float -#define GL_EXT_packed_float 1 +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); #endif -#ifndef GL_EXT_texture_array -#define GL_EXT_texture_array 1 +#ifndef GL_MESAX_texture_stack +#define GL_MESAX_texture_stack 1 #endif -#ifndef GL_EXT_draw_buffers2 -#define GL_EXT_draw_buffers2 1 +#ifndef GL_EXT_timer_query +#define GL_EXT_timer_query 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glColorMaskIndexedEXT (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); -extern void APIENTRY glGetBooleanIndexedvEXT (GLenum target, GLuint index, GLboolean *data); -extern void APIENTRY glGetIntegerIndexedvEXT (GLenum target, GLuint index, GLint *data); -extern void APIENTRY glEnableIndexedEXT (GLenum target, GLuint index); -extern void APIENTRY glDisableIndexedEXT (GLenum target, GLuint index); -extern GLboolean APIENTRY glIsEnabledIndexedEXT (GLenum target, GLuint index); +GLAPI void APIENTRY glGetQueryObjecti64vEXT (GLuint id, GLenum pname, GLint64EXT *params); +GLAPI void APIENTRY glGetQueryObjectui64vEXT (GLuint id, GLenum pname, GLuint64EXT *params); #endif /* GL_GLEXT_PROTOTYPES */ -typedef void (APIENTRYP PFNGLCOLORMASKINDEXEDEXTPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); -typedef void (APIENTRYP PFNGLGETBOOLEANINDEXEDVEXTPROC) (GLenum target, GLuint index, GLboolean *data); -typedef void (APIENTRYP PFNGLGETINTEGERINDEXEDVEXTPROC) (GLenum target, GLuint index, GLint *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 PFNGLGETQUERYOBJECTI64VEXTPROC) (GLuint id, GLenum pname, GLint64EXT *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUI64VEXTPROC) (GLuint id, GLenum pname, GLuint64EXT *params); #endif -#ifndef GL_EXT_texture_integer -#define GL_EXT_texture_integer 1 +#ifndef GL_EXT_gpu_program_parameters +#define GL_EXT_gpu_program_parameters 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glTexParameterIivEXT (GLenum target, GLenum pname, const GLint *params); -extern void APIENTRY glTexParameterIuivEXT (GLenum target, GLenum pname, const GLuint *params); -extern void APIENTRY glGetTexParameterIivEXT (GLenum target, GLenum pname, GLint *params); -extern void APIENTRY glGetTexParameterIuivEXT (GLenum target, GLenum pname, GLuint *params); -extern void APIENTRY glClearColorIiEXT (GLint red, GLint green, GLint blue, GLint alpha); -extern void APIENTRY glClearColorIuiEXT (GLuint red, GLuint green, GLuint blue, GLuint alpha); +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 /* GL_GLEXT_PROTOTYPES */ -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); +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); #endif -#ifndef GL_EXT_bindable_uniform -#define GL_EXT_bindable_uniform 1 +#ifndef GL_APPLE_flush_buffer_range +#define GL_APPLE_flush_buffer_range 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glUniformBufferEXT (GLuint program, GLint location, GLuint buffer); -extern GLint APIENTRY glGetUniformBufferSizeEXT (GLuint program, GLint location); -extern GLintptr APIENTRY glGetUniformOffsetEXT (GLuint program, GLint location); +GLAPI void APIENTRY glBufferParameteriAPPLE (GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glFlushMappedBufferRangeAPPLE (GLenum target, GLintptr offset, GLsizeiptr size); #endif /* GL_GLEXT_PROTOTYPES */ -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); +typedef void (APIENTRYP PFNGLBUFFERPARAMETERIAPPLEPROC) (GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEAPPLEPROC) (GLenum target, GLintptr offset, GLsizeiptr size); #endif -#ifndef GL_EXT_gpu_shader4 -#define GL_EXT_gpu_shader4 1 +#ifndef GL_NV_gpu_program4 +#define GL_NV_gpu_program4 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glGetUniformuivEXT (GLuint program, GLint location, GLuint *params); -extern void APIENTRY glBindFragDataLocationEXT (GLuint program, GLuint color, const GLchar *name); -extern GLint APIENTRY glGetFragDataLocationEXT (GLuint program, const GLchar *name); -extern void APIENTRY glUniform1uiEXT (GLint location, GLuint v0); -extern void APIENTRY glUniform2uiEXT (GLint location, GLuint v0, GLuint v1); -extern void APIENTRY glUniform3uiEXT (GLint location, GLuint v0, GLuint v1, GLuint v2); -extern void APIENTRY glUniform4uiEXT (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); -extern void APIENTRY glUniform1uivEXT (GLint location, GLsizei count, const GLuint *value); -extern void APIENTRY glUniform2uivEXT (GLint location, GLsizei count, const GLuint *value); -extern void APIENTRY glUniform3uivEXT (GLint location, GLsizei count, const GLuint *value); -extern void APIENTRY glUniform4uivEXT (GLint location, GLsizei count, const GLuint *value); -extern void APIENTRY glVertexAttribI1iEXT (GLuint index, GLint x); -extern void APIENTRY glVertexAttribI2iEXT (GLuint index, GLint x, GLint y); -extern void APIENTRY glVertexAttribI3iEXT (GLuint index, GLint x, GLint y, GLint z); -extern void APIENTRY glVertexAttribI4iEXT (GLuint index, GLint x, GLint y, GLint z, GLint w); -extern void APIENTRY glVertexAttribI1uiEXT (GLuint index, GLuint x); -extern void APIENTRY glVertexAttribI2uiEXT (GLuint index, GLuint x, GLuint y); -extern void APIENTRY glVertexAttribI3uiEXT (GLuint index, GLuint x, GLuint y, GLuint z); -extern void APIENTRY glVertexAttribI4uiEXT (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); -extern void APIENTRY glVertexAttribI1ivEXT (GLuint index, const GLint *v); -extern void APIENTRY glVertexAttribI2ivEXT (GLuint index, const GLint *v); -extern void APIENTRY glVertexAttribI3ivEXT (GLuint index, const GLint *v); -extern void APIENTRY glVertexAttribI4ivEXT (GLuint index, const GLint *v); -extern void APIENTRY glVertexAttribI1uivEXT (GLuint index, const GLuint *v); -extern void APIENTRY glVertexAttribI2uivEXT (GLuint index, const GLuint *v); -extern void APIENTRY glVertexAttribI3uivEXT (GLuint index, const GLuint *v); -extern void APIENTRY glVertexAttribI4uivEXT (GLuint index, const GLuint *v); -extern void APIENTRY glVertexAttribI4bvEXT (GLuint index, const GLbyte *v); -extern void APIENTRY glVertexAttribI4svEXT (GLuint index, const GLshort *v); -extern void APIENTRY glVertexAttribI4ubvEXT (GLuint index, const GLubyte *v); -extern void APIENTRY glVertexAttribI4usvEXT (GLuint index, const GLushort *v); -extern void APIENTRY glVertexAttribIPointerEXT (GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); -extern void APIENTRY glGetVertexAttribIivEXT (GLuint index, GLenum pname, GLint *params); -extern void APIENTRY glGetVertexAttribIuivEXT (GLuint index, GLenum pname, GLuint *params); +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 /* GL_GLEXT_PROTOTYPES */ -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); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IEXTPROC) (GLuint index, GLint x); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IEXTPROC) (GLuint index, GLint x, GLint y); +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); +#endif + +#ifndef GL_NV_geometry_program4 +#define GL_NV_geometry_program4 1 +#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 glFramebufferTextureLayerEXT (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +GLAPI void APIENTRY glFramebufferTextureFaceEXT (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLPROGRAMVERTEXLIMITNVPROC) (GLenum target, GLint limit); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREEXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYEREXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREFACEEXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); +#endif + +#ifndef GL_EXT_geometry_shader4 +#define GL_EXT_geometry_shader4 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramParameteriEXT (GLuint program, GLenum pname, GLint value); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIEXTPROC) (GLuint program, GLenum pname, GLint value); +#endif + +#ifndef GL_NV_vertex_program4 +#define GL_NV_vertex_program4 1 +#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 GLvoid *pointer); +GLAPI void APIENTRY glGetVertexAttribIivEXT (GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribIuivEXT (GLuint index, GLenum pname, GLuint *params); +#endif /* GL_GLEXT_PROTOTYPES */ +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); @@ -7035,163 +10220,1273 @@ typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIIVEXTPROC) (GLuint index, GLenum pn typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIUIVEXTPROC) (GLuint index, GLenum pname, GLuint *params); #endif +#ifndef GL_EXT_gpu_shader4 +#define GL_EXT_gpu_shader4 1 +#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 /* GL_GLEXT_PROTOTYPES */ +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); +#endif -#ifndef GL_EXT_geometry_shader4 -#define GL_EXT_geometry_shader4 1 +#ifndef GL_EXT_draw_instanced +#define GL_EXT_draw_instanced 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glProgramParameteriEXT (GLuint program, GLenum pname, GLint value); -extern void APIENTRY glFramebufferTextureEXT (GLenum target, GLenum attachment, GLuint texture, GLint level); -extern void APIENTRY glFramebufferTextureLayerEXT (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); -extern void APIENTRY glFramebufferTextureFaceEXT (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); +GLAPI void APIENTRY glDrawArraysInstancedEXT (GLenum mode, GLint start, GLsizei count, GLsizei primcount); +GLAPI void APIENTRY glDrawElementsInstancedEXT (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount); #endif /* GL_GLEXT_PROTOTYPES */ -typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIEXTPROC) (GLuint program, GLenum pname, GLint value); -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREEXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level); -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYEREXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREFACEEXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDEXTPROC) (GLenum mode, GLint start, GLsizei count, GLsizei primcount); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDEXTPROC) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount); #endif -#ifndef GL_NV_geometry_program4 -#define GL_NV_geometry_program4 1 +#ifndef GL_EXT_packed_float +#define GL_EXT_packed_float 1 +#endif + +#ifndef GL_EXT_texture_array +#define GL_EXT_texture_array 1 +#endif + +#ifndef GL_EXT_texture_buffer_object +#define GL_EXT_texture_buffer_object 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glProgramVertexLimitNV (GLenum target, GLint limit); +GLAPI void APIENTRY glTexBufferEXT (GLenum target, GLenum internalformat, GLuint buffer); #endif /* GL_GLEXT_PROTOTYPES */ -typedef void (APIENTRYP PFNGLPROGRAMVERTEXLIMITNVPROC) (GLenum target, GLint limit); +typedef void (APIENTRYP PFNGLTEXBUFFEREXTPROC) (GLenum target, GLenum internalformat, GLuint buffer); #endif -#ifndef GL_NV_gpu_program4 -#define GL_NV_gpu_program4 1 +#ifndef GL_EXT_texture_compression_latc +#define GL_EXT_texture_compression_latc 1 +#endif + +#ifndef GL_EXT_texture_compression_rgtc +#define GL_EXT_texture_compression_rgtc 1 +#endif + +#ifndef GL_EXT_texture_shared_exponent +#define GL_EXT_texture_shared_exponent 1 +#endif + +#ifndef GL_NV_depth_buffer_float +#define GL_NV_depth_buffer_float 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glProgramLocalParameterI4iNV (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); -extern void APIENTRY glProgramLocalParameterI4ivNV (GLenum target, GLuint index, const GLint *params); -extern void APIENTRY glProgramLocalParametersI4ivNV (GLenum target, GLuint index, GLsizei count, const GLint *params); -extern void APIENTRY glProgramLocalParameterI4uiNV (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); -extern void APIENTRY glProgramLocalParameterI4uivNV (GLenum target, GLuint index, const GLuint *params); -extern void APIENTRY glProgramLocalParametersI4uivNV (GLenum target, GLuint index, GLsizei count, const GLuint *params); -extern void APIENTRY glProgramEnvParameterI4iNV (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); -extern void APIENTRY glProgramEnvParameterI4ivNV (GLenum target, GLuint index, const GLint *params); -extern void APIENTRY glProgramEnvParametersI4ivNV (GLenum target, GLuint index, GLsizei count, const GLint *params); -extern void APIENTRY glProgramEnvParameterI4uiNV (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); -extern void APIENTRY glProgramEnvParameterI4uivNV (GLenum target, GLuint index, const GLuint *params); -extern void APIENTRY glProgramEnvParametersI4uivNV (GLenum target, GLuint index, GLsizei count, const GLuint *params); -extern void APIENTRY glGetProgramLocalParameterIivNV (GLenum target, GLuint index, GLint *params); -extern void APIENTRY glGetProgramLocalParameterIuivNV (GLenum target, GLuint index, GLuint *params); -extern void APIENTRY glGetProgramEnvParameterIivNV (GLenum target, GLuint index, GLint *params); -extern void APIENTRY glGetProgramEnvParameterIuivNV (GLenum target, GLuint index, GLuint *params); +GLAPI void APIENTRY glDepthRangedNV (GLdouble zNear, GLdouble zFar); +GLAPI void APIENTRY glClearDepthdNV (GLdouble depth); +GLAPI void APIENTRY glDepthBoundsdNV (GLdouble zmin, GLdouble zmax); #endif /* GL_GLEXT_PROTOTYPES */ -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); +typedef void (APIENTRYP PFNGLDEPTHRANGEDNVPROC) (GLdouble zNear, GLdouble zFar); +typedef void (APIENTRYP PFNGLCLEARDEPTHDNVPROC) (GLdouble depth); +typedef void (APIENTRYP PFNGLDEPTHBOUNDSDNVPROC) (GLdouble zmin, GLdouble zmax); +#endif + +#ifndef GL_NV_fragment_program4 +#define GL_NV_fragment_program4 1 +#endif + +#ifndef GL_NV_framebuffer_multisample_coverage +#define GL_NV_framebuffer_multisample_coverage 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glRenderbufferStorageMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLECOVERAGENVPROC) (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); +#endif + +#ifndef GL_EXT_framebuffer_sRGB +#define GL_EXT_framebuffer_sRGB 1 +#endif + +#ifndef GL_NV_geometry_shader4 +#define GL_NV_geometry_shader4 1 #endif #ifndef GL_NV_parameter_buffer_object #define GL_NV_parameter_buffer_object 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glProgramBufferParametersfvNV (GLenum target, GLuint buffer, GLuint index, GLsizei count, const GLfloat *params); -extern void APIENTRY glProgramBufferParametersIivNV (GLenum target, GLuint buffer, GLuint index, GLsizei count, const GLint *params); -extern void APIENTRY glProgramBufferParametersIuivNV (GLenum target, GLuint buffer, GLuint index, GLsizei count, const GLuint *params); +GLAPI void APIENTRY glProgramBufferParametersfvNV (GLenum target, GLuint buffer, GLuint index, GLsizei count, const GLfloat *params); +GLAPI void APIENTRY glProgramBufferParametersIivNV (GLenum target, GLuint buffer, GLuint index, GLsizei count, const GLint *params); +GLAPI void APIENTRY glProgramBufferParametersIuivNV (GLenum target, GLuint buffer, GLuint index, GLsizei count, const GLuint *params); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPROGRAMBUFFERPARAMETERSFVNVPROC) (GLenum target, GLuint buffer, GLuint index, GLsizei count, const GLfloat *params); typedef void (APIENTRYP PFNGLPROGRAMBUFFERPARAMETERSIIVNVPROC) (GLenum target, GLuint buffer, GLuint index, GLsizei count, const GLint *params); typedef void (APIENTRYP PFNGLPROGRAMBUFFERPARAMETERSIUIVNVPROC) (GLenum target, GLuint buffer, GLuint index, GLsizei count, const GLuint *params); #endif -#ifndef GL_EXT_framebuffer_multisample -#define GL_EXT_framebuffer_multisample 1 +#ifndef GL_EXT_draw_buffers2 +#define GL_EXT_draw_buffers2 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glRenderbufferStorageMultisampleEXT (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glColorMaskIndexedEXT (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +GLAPI void APIENTRY glGetBooleanIndexedvEXT (GLenum target, GLuint index, GLboolean *data); +GLAPI void APIENTRY glGetIntegerIndexedvEXT (GLenum target, GLuint index, GLint *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); #endif /* GL_GLEXT_PROTOTYPES */ -typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLCOLORMASKINDEXEDEXTPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +typedef void (APIENTRYP PFNGLGETBOOLEANINDEXEDVEXTPROC) (GLenum target, GLuint index, GLboolean *data); +typedef void (APIENTRYP PFNGLGETINTEGERINDEXEDVEXTPROC) (GLenum target, GLuint index, GLint *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); #endif -#ifndef GL_NV_framebuffer_multisample_coverage -#define GL_NV_framebuffer_multisample_coverage 1 +#ifndef GL_NV_transform_feedback +#define GL_NV_transform_feedback 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glRenderbufferStorageMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glBeginTransformFeedbackNV (GLenum primitiveMode); +GLAPI void APIENTRY glEndTransformFeedbackNV (void); +GLAPI void APIENTRY glTransformFeedbackAttribsNV (GLuint 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 /* GL_GLEXT_PROTOTYPES */ -typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLECOVERAGENVPROC) (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKNVPROC) (GLenum primitiveMode); +typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKNVPROC) (void); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKATTRIBSNVPROC) (GLuint 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); #endif -#ifndef GL_EXT_framebuffer_blit -#define GL_EXT_framebuffer_blit 1 +#ifndef GL_EXT_bindable_uniform +#define GL_EXT_bindable_uniform 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glBlitFramebufferEXT (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +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 /* GL_GLEXT_PROTOTYPES */ -typedef void (APIENTRYP PFNGLBLITFRAMEBUFFEREXTPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +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); #endif -#ifndef GL_EXT_draw_instanced -#define GL_EXT_draw_instanced 1 +#ifndef GL_EXT_texture_integer +#define GL_EXT_texture_integer 1 #ifdef GL_GLEXT_PROTOTYPES -extern void APIENTRY glDrawArraysInstancedEXT (GLenum mode, GLint start, GLsizei count, GLsizei primcount); -extern void APIENTRY glDrawElementsInstancedEXT (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount); +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 /* GL_GLEXT_PROTOTYPES */ -typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDEXTPROC) (GLenum mode, GLint start, GLsizei count, GLsizei primcount); -typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDEXTPROC) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount); +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); #endif -#ifndef GL_EXT_texture_compression_rgtc -#define GL_EXT_texture_compression_rgtc 1 +#ifndef GL_GREMEDY_frame_terminator +#define GL_GREMEDY_frame_terminator 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFrameTerminatorGREMEDY (void); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLFRAMETERMINATORGREMEDYPROC) (void); +#endif + +#ifndef GL_NV_conditional_render +#define GL_NV_conditional_render 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginConditionalRenderNV (GLuint id, GLenum mode); +GLAPI void APIENTRY glEndConditionalRenderNV (void); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERNVPROC) (GLuint id, GLenum mode); +typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERNVPROC) (void); #endif #ifndef GL_NV_present_video #define GL_NV_present_video 1 #ifdef GL_GLEXT_PROTOTYPES -extern 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); -extern 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); -extern void APIENTRY glGetVideoivNV (GLuint video_slot, GLenum pname, GLint *params); -extern void APIENTRY glGetVideouivNV (GLuint video_slot, GLenum pname, GLuint *params); -extern void APIENTRY glGetVideoi64vNV (GLuint video_slot, GLenum pname, GLint64EXT *params); -extern void APIENTRY glGetVideoui64vNV (GLuint video_slot, GLenum pname, GLuint64EXT *params); -#endif /* GL_GLEXT_PROTOTYPES */ -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); +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 /* GL_GLEXT_PROTOTYPES */ +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); #endif +#ifndef GL_EXT_transform_feedback +#define GL_EXT_transform_feedback 1 +#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* *varyings, GLenum bufferMode); +GLAPI void APIENTRY glGetTransformFeedbackVaryingEXT (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +#endif /* GL_GLEXT_PROTOTYPES */ +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* *varyings, GLenum bufferMode); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGEXTPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +#endif + +#ifndef GL_EXT_direct_state_access +#define GL_EXT_direct_state_access 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glClientAttribDefaultEXT (GLbitfield mask); +GLAPI void APIENTRY glPushClientAttribDefaultEXT (GLbitfield mask); +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 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 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, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels); +GLAPI void APIENTRY glTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels); +GLAPI void APIENTRY glTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels); +GLAPI void APIENTRY glTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *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, GLvoid *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, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *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 GLvoid *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 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 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 glMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels); +GLAPI void APIENTRY glMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels); +GLAPI void APIENTRY glMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels); +GLAPI void APIENTRY glMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *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, GLvoid *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, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *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 GLvoid *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 glBindMultiTextureEXT (GLenum texunit, GLenum target, GLuint texture); +GLAPI void APIENTRY glEnableClientStateIndexedEXT (GLenum array, GLuint index); +GLAPI void APIENTRY glDisableClientStateIndexedEXT (GLenum array, GLuint index); +GLAPI void APIENTRY glMultiTexCoordPointerEXT (GLenum texunit, GLint size, GLenum type, GLsizei stride, const GLvoid *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 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, GLvoid* *data); +GLAPI void APIENTRY glCompressedTextureImage3DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *bits); +GLAPI void APIENTRY glCompressedTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *bits); +GLAPI void APIENTRY glCompressedTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *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 GLvoid *bits); +GLAPI void APIENTRY glCompressedTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *bits); +GLAPI void APIENTRY glCompressedTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *bits); +GLAPI void APIENTRY glGetCompressedTextureImageEXT (GLuint texture, GLenum target, GLint lod, GLvoid *img); +GLAPI void APIENTRY glCompressedMultiTexImage3DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *bits); +GLAPI void APIENTRY glCompressedMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *bits); +GLAPI void APIENTRY glCompressedMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *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 GLvoid *bits); +GLAPI void APIENTRY glCompressedMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *bits); +GLAPI void APIENTRY glCompressedMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *bits); +GLAPI void APIENTRY glGetCompressedMultiTexImageEXT (GLenum texunit, GLenum target, GLint lod, GLvoid *img); +GLAPI void APIENTRY glNamedProgramStringEXT (GLuint program, GLenum target, GLenum format, GLsizei len, const GLvoid *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, GLvoid *string); +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 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 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 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 glNamedBufferDataEXT (GLuint buffer, GLsizeiptr size, const GLvoid *data, GLenum usage); +GLAPI void APIENTRY glNamedBufferSubDataEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, const GLvoid *data); +GLAPI GLvoid* APIENTRY glMapNamedBufferEXT (GLuint buffer, GLenum access); +GLAPI GLboolean APIENTRY glUnmapNamedBufferEXT (GLuint buffer); +GLAPI GLvoid* APIENTRY glMapNamedBufferRangeEXT (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access); +GLAPI void APIENTRY glFlushMappedNamedBufferRangeEXT (GLuint buffer, GLintptr offset, GLsizeiptr length); +GLAPI void APIENTRY glNamedCopyBufferSubDataEXT (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +GLAPI void APIENTRY glGetNamedBufferParameterivEXT (GLuint buffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetNamedBufferPointervEXT (GLuint buffer, GLenum pname, GLvoid* *params); +GLAPI void APIENTRY glGetNamedBufferSubDataEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, GLvoid *data); +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 glNamedRenderbufferStorageEXT (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetNamedRenderbufferParameterivEXT (GLuint renderbuffer, GLenum pname, GLint *params); +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 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 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 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); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLCLIENTATTRIBDEFAULTEXTPROC) (GLbitfield mask); +typedef void (APIENTRYP PFNGLPUSHCLIENTATTRIBDEFAULTEXTPROC) (GLbitfield mask); +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 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 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, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *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, GLvoid *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, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *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 GLvoid *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 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 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 PFNGLMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels); +typedef void (APIENTRYP PFNGLMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels); +typedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels); +typedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *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, GLvoid *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, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *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 GLvoid *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 PFNGLBINDMULTITEXTUREEXTPROC) (GLenum texunit, GLenum target, GLuint texture); +typedef void (APIENTRYP PFNGLENABLECLIENTSTATEINDEXEDEXTPROC) (GLenum array, GLuint index); +typedef void (APIENTRYP PFNGLDISABLECLIENTSTATEINDEXEDEXTPROC) (GLenum array, GLuint index); +typedef void (APIENTRYP PFNGLMULTITEXCOORDPOINTEREXTPROC) (GLenum texunit, GLint size, GLenum type, GLsizei stride, const GLvoid *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 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, GLvoid* *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *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 GLvoid *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *bits); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTUREIMAGEEXTPROC) (GLuint texture, GLenum target, GLint lod, GLvoid *img); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *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 GLvoid *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *bits); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDMULTITEXIMAGEEXTPROC) (GLenum texunit, GLenum target, GLint lod, GLvoid *img); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMSTRINGEXTPROC) (GLuint program, GLenum target, GLenum format, GLsizei len, const GLvoid *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, GLvoid *string); +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 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 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 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 PFNGLNAMEDBUFFERDATAEXTPROC) (GLuint buffer, GLsizeiptr size, const GLvoid *data, GLenum usage); +typedef void (APIENTRYP PFNGLNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, const GLvoid *data); +typedef GLvoid* (APIENTRYP PFNGLMAPNAMEDBUFFEREXTPROC) (GLuint buffer, GLenum access); +typedef GLboolean (APIENTRYP PFNGLUNMAPNAMEDBUFFEREXTPROC) (GLuint buffer); +typedef GLvoid* (APIENTRYP PFNGLMAPNAMEDBUFFERRANGEEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access); +typedef void (APIENTRYP PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length); +typedef void (APIENTRYP PFNGLNAMEDCOPYBUFFERSUBDATAEXTPROC) (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERIVEXTPROC) (GLuint buffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPOINTERVEXTPROC) (GLuint buffer, GLenum pname, GLvoid* *params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, GLvoid *data); +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 PFNGLNAMEDRENDERBUFFERSTORAGEEXTPROC) (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETNAMEDRENDERBUFFERPARAMETERIVEXTPROC) (GLuint renderbuffer, GLenum pname, GLint *params); +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 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 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 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); +#endif + +#ifndef GL_EXT_vertex_array_bgra +#define GL_EXT_vertex_array_bgra 1 +#endif + +#ifndef GL_EXT_texture_swizzle +#define GL_EXT_texture_swizzle 1 +#endif + +#ifndef GL_NV_explicit_multisample +#define GL_NV_explicit_multisample 1 +#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 /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_NV_transform_feedback2 +#define GL_NV_transform_feedback2 1 +#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 /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_ATI_meminfo +#define GL_ATI_meminfo 1 +#endif + +#ifndef GL_AMD_performance_monitor +#define GL_AMD_performance_monitor 1 +#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, GLvoid *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 /* GL_GLEXT_PROTOTYPES */ +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, GLvoid *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); +#endif + +#ifndef GL_AMD_texture_texture4 +#define GL_AMD_texture_texture4 1 +#endif + +#ifndef GL_AMD_vertex_shader_tesselator +#define GL_AMD_vertex_shader_tesselator 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTessellationFactorAMD (GLfloat factor); +GLAPI void APIENTRY glTessellationModeAMD (GLenum mode); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLTESSELLATIONFACTORAMDPROC) (GLfloat factor); +typedef void (APIENTRYP PFNGLTESSELLATIONMODEAMDPROC) (GLenum mode); +#endif + +#ifndef GL_EXT_provoking_vertex +#define GL_EXT_provoking_vertex 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProvokingVertexEXT (GLenum mode); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLPROVOKINGVERTEXEXTPROC) (GLenum mode); +#endif + +#ifndef GL_EXT_texture_snorm +#define GL_EXT_texture_snorm 1 +#endif + +#ifndef GL_AMD_draw_buffers_blend +#define GL_AMD_draw_buffers_blend 1 +#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 /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_APPLE_texture_range +#define GL_APPLE_texture_range 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTextureRangeAPPLE (GLenum target, GLsizei length, const GLvoid *pointer); +GLAPI void APIENTRY glGetTexParameterPointervAPPLE (GLenum target, GLenum pname, GLvoid* *params); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLTEXTURERANGEAPPLEPROC) (GLenum target, GLsizei length, const GLvoid *pointer); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERPOINTERVAPPLEPROC) (GLenum target, GLenum pname, GLvoid* *params); +#endif + +#ifndef GL_APPLE_float_pixels +#define GL_APPLE_float_pixels 1 +#endif + +#ifndef GL_APPLE_vertex_program_evaluators +#define GL_APPLE_vertex_program_evaluators 1 +#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 /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_APPLE_aux_depth_stencil +#define GL_APPLE_aux_depth_stencil 1 +#endif + +#ifndef GL_APPLE_object_purgeable +#define GL_APPLE_object_purgeable 1 +#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 /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_APPLE_row_bytes +#define GL_APPLE_row_bytes 1 +#endif + +#ifndef GL_APPLE_rgb_422 +#define GL_APPLE_rgb_422 1 +#endif + +#ifndef GL_NV_video_capture +#define GL_NV_video_capture 1 +#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 /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_NV_copy_image +#define GL_NV_copy_image 1 +#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 /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_EXT_separate_shader_objects +#define GL_EXT_separate_shader_objects 1 +#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 /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLUSESHADERPROGRAMEXTPROC) (GLenum type, GLuint program); +typedef void (APIENTRYP PFNGLACTIVEPROGRAMEXTPROC) (GLuint program); +typedef GLuint (APIENTRYP PFNGLCREATESHADERPROGRAMEXTPROC) (GLenum type, const GLchar *string); +#endif + +#ifndef GL_NV_parameter_buffer_object2 +#define GL_NV_parameter_buffer_object2 1 +#endif + +#ifndef GL_NV_shader_buffer_load +#define GL_NV_shader_buffer_load 1 +#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 glGetUniformui64vNV (GLuint program, GLint location, GLuint64EXT *params); +GLAPI void APIENTRY glProgramUniformui64NV (GLuint program, GLint location, GLuint64EXT value); +GLAPI void APIENTRY glProgramUniformui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +#endif /* GL_GLEXT_PROTOTYPES */ +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 PFNGLGETUNIFORMUI64VNVPROC) (GLuint program, GLint location, GLuint64EXT *params); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMUI64NVPROC) (GLuint program, GLint location, GLuint64EXT value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMUI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +#endif + +#ifndef GL_NV_vertex_buffer_unified_memory +#define GL_NV_vertex_buffer_unified_memory 1 +#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 /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_NV_texture_barrier +#define GL_NV_texture_barrier 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTextureBarrierNV (void); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLTEXTUREBARRIERNVPROC) (void); +#endif + +#ifndef GL_AMD_shader_stencil_export +#define GL_AMD_shader_stencil_export 1 +#endif + +#ifndef GL_AMD_seamless_cubemap_per_texture +#define GL_AMD_seamless_cubemap_per_texture 1 +#endif + +#ifndef GL_AMD_conservative_depth +#define GL_AMD_conservative_depth 1 +#endif + +#ifndef GL_EXT_shader_image_load_store +#define GL_EXT_shader_image_load_store 1 +#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 /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLBINDIMAGETEXTUREEXTPROC) (GLuint index, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLint format); +typedef void (APIENTRYP PFNGLMEMORYBARRIEREXTPROC) (GLbitfield barriers); +#endif + +#ifndef GL_EXT_vertex_attrib_64bit +#define GL_EXT_vertex_attrib_64bit 1 +#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 GLvoid *pointer); +GLAPI void APIENTRY glGetVertexAttribLdvEXT (GLuint index, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glVertexArrayVertexAttribLOffsetEXT (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); +#endif /* GL_GLEXT_PROTOTYPES */ +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 GLvoid *pointer); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLDVEXTPROC) (GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBLOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); +#endif + +#ifndef GL_NV_gpu_program5 +#define GL_NV_gpu_program5 1 +#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 /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLPROGRAMSUBROUTINEPARAMETERSUIVNVPROC) (GLenum target, GLsizei count, const GLuint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMSUBROUTINEPARAMETERUIVNVPROC) (GLenum target, GLuint index, GLuint *param); +#endif + +#ifndef GL_NV_gpu_shader5 +#define GL_NV_gpu_shader5 1 +#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 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 /* GL_GLEXT_PROTOTYPES */ +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 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); +#endif + +#ifndef GL_NV_shader_buffer_store +#define GL_NV_shader_buffer_store 1 +#endif + +#ifndef GL_NV_tessellation_program5 +#define GL_NV_tessellation_program5 1 +#endif + +#ifndef GL_NV_vertex_attrib_integer_64bit +#define GL_NV_vertex_attrib_integer_64bit 1 +#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 /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_NV_multisample_coverage +#define GL_NV_multisample_coverage 1 +#endif + +#ifndef GL_AMD_name_gen_delete +#define GL_AMD_name_gen_delete 1 +#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 /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_AMD_debug_output +#define GL_AMD_debug_output 1 +#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, GLvoid *userParam); +GLAPI GLuint APIENTRY glGetDebugMessageLogAMD (GLuint count, GLsizei bufsize, GLenum *categories, GLuint *severities, GLuint *ids, GLsizei *lengths, GLchar *message); +#endif /* GL_GLEXT_PROTOTYPES */ +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, GLvoid *userParam); +typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGAMDPROC) (GLuint count, GLsizei bufsize, GLenum *categories, GLuint *severities, GLuint *ids, GLsizei *lengths, GLchar *message); +#endif + +#ifndef GL_NV_vdpau_interop +#define GL_NV_vdpau_interop 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVDPAUInitNV (const GLvoid *vdpDevice, const GLvoid *getProcAddress); +GLAPI void APIENTRY glVDPAUFiniNV (void); +GLAPI GLvdpauSurfaceNV APIENTRY glVDPAURegisterVideoSurfaceNV (GLvoid *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames); +GLAPI GLvdpauSurfaceNV APIENTRY glVDPAURegisterOutputSurfaceNV (GLvoid *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames); +GLAPI void 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 /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLVDPAUINITNVPROC) (const GLvoid *vdpDevice, const GLvoid *getProcAddress); +typedef void (APIENTRYP PFNGLVDPAUFININVPROC) (void); +typedef GLvdpauSurfaceNV (APIENTRYP PFNGLVDPAUREGISTERVIDEOSURFACENVPROC) (GLvoid *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames); +typedef GLvdpauSurfaceNV (APIENTRYP PFNGLVDPAUREGISTEROUTPUTSURFACENVPROC) (GLvoid *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames); +typedef void (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); +#endif + +#ifndef GL_AMD_transform_feedback3_lines_triangles +#define GL_AMD_transform_feedback3_lines_triangles 1 +#endif + +#ifndef GL_AMD_depth_clamp_separate +#define GL_AMD_depth_clamp_separate 1 +#endif + +#ifndef GL_EXT_texture_sRGB_decode +#define GL_EXT_texture_sRGB_decode 1 +#endif + +#ifndef GL_NV_texture_multisample +#define GL_NV_texture_multisample 1 +#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 /* GL_GLEXT_PROTOTYPES */ +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); +#endif + +#ifndef GL_AMD_blend_minmax_factor +#define GL_AMD_blend_minmax_factor 1 +#endif + +#ifndef GL_AMD_sample_positions +#define GL_AMD_sample_positions 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSetMultisamplefvAMD (GLenum pname, GLuint index, const GLfloat *val); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLSETMULTISAMPLEFVAMDPROC) (GLenum pname, GLuint index, const GLfloat *val); +#endif + +#ifndef GL_EXT_x11_sync_object +#define GL_EXT_x11_sync_object 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLsync APIENTRY glImportSyncEXT (GLenum external_sync_type, GLintptr external_sync, GLbitfield flags); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef GLsync (APIENTRYP PFNGLIMPORTSYNCEXTPROC) (GLenum external_sync_type, GLintptr external_sync, GLbitfield flags); +#endif + +#ifndef GL_AMD_multi_draw_indirect +#define GL_AMD_multi_draw_indirect 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiDrawArraysIndirectAMD (GLenum mode, const GLvoid *indirect, GLsizei primcount, GLsizei stride); +GLAPI void APIENTRY glMultiDrawElementsIndirectAMD (GLenum mode, GLenum type, const GLvoid *indirect, GLsizei primcount, GLsizei stride); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTAMDPROC) (GLenum mode, const GLvoid *indirect, GLsizei primcount, GLsizei stride); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTAMDPROC) (GLenum mode, GLenum type, const GLvoid *indirect, GLsizei primcount, GLsizei stride); +#endif + +#ifndef GL_EXT_framebuffer_multisample_blit_scaled +#define GL_EXT_framebuffer_multisample_blit_scaled 1 +#endif + +#ifndef GL_AMD_pinned_memory +#define GL_AMD_pinned_memory 1 +#endif + + #ifdef __cplusplus } #endif diff --git a/mojoshader/LICENSE.txt b/mojoshader/LICENSE.txt index be1cf32..baa29ef 100644 --- a/mojoshader/LICENSE.txt +++ b/mojoshader/LICENSE.txt @@ -1,22 +1,17 @@ +Copyright (c) 2008-2025 Ryan C. Gordon + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. - Copyright (c) 2008-2011 Ryan C. Gordon. - - This software is provided 'as-is', without any express or implied warranty. - In no event will the authors be held liable for any damages arising from - the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software in a - product, an acknowledgment in the product documentation would be - appreciated but is not required. - - 2. Altered source versions must be plainly marked as such, and must not be +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. - - 3. This notice may not be removed or altered from any source distribution. - - Ryan C. Gordon +3. This notice may not be removed or altered from any source distribution. diff --git a/mojoshader/README.txt b/mojoshader/README.txt deleted file mode 100644 index a147282..0000000 --- a/mojoshader/README.txt +++ /dev/null @@ -1,29 +0,0 @@ -To use this in your project: - -- Add mojoshader*.c and mojoshader*.h to your project. -- Compile mojoshader*.c -- If you don't have a C99-compliant compiler, like Microsoft Visual Studio, - you'll need to compile the .c files as C++ to get them to build. -- If you don't have cmake to generate mojoshader_version.h, you can either - add a blank file with that name, or add MOJOSHADER_NO_VERSION_INCLUDE to - your preprocessor definitions. - -// end of README.txt ... - - - -MonoGame Build Instructions ---------------------------- - -Windows: - - - You need CMake to generate the projects. - - First run `cmake -G "Visual Studio 11"` to generate projects for 32bit. - - Open the solution and unload the finderrors, test, testoutput, and testparse projects. - - Select and build the lemon and mojoshader projects under the MinSizeRel config. - - Copy the 32bit lemon.exe parser generator from the MinSizeRel folder to a safe place. - - Clean and run `cmake -G "Visual Studio 11 Win64"` to generate 64bit projects. - - Open the solution and unload the finderrors, test, testoutput, testparse, and lemon projects. - - Copy the 32bit lemon.exe to the MinSizeRel folder. - - Select and build the mojoshader project under the MinSizeRel config. - diff --git a/mojoshader/misc/lemon.c b/mojoshader/misc/lemon.c deleted file mode 100644 index c0054bd..0000000 --- a/mojoshader/misc/lemon.c +++ /dev/null @@ -1,4980 +0,0 @@ -/* - * My changes over the original lemon.c from SQLite are encased in - * #if __MOJOSHADER__ blocks. --ryan. - */ -#define __MOJOSHADER__ 1 - -/* -** This file contains all sources (including headers) to the LEMON -** LALR(1) parser generator. The sources have been combined into a -** single file to make it easy to include LEMON in the source tree -** and Makefile of another program. -** -** The author of this program disclaims copyright. -*/ -#include -#include -#include -#include -#include -#include - -#ifndef __WIN32__ -# if defined(_WIN32) || defined(WIN32) -# define __WIN32__ -# endif -#endif - -#ifdef __WIN32__ -#ifdef __cplusplus -extern "C" { -#endif -extern int access(const char *path, int mode); -#ifdef __cplusplus -} -#endif -#else -#include -#endif - -/* #define PRIVATE static */ -#define PRIVATE - -#ifdef TEST -#define MAXRHS 5 /* Set low to exercise exception code */ -#else -#define MAXRHS 1000 -#endif - -static const char **made_files = NULL; -static int made_files_count = 0; -static int successful_exit = 0; -static void LemonAtExit(void) -{ - /* if we failed, delete (most) files we made, to unconfuse build tools. */ - int i; - for (i = 0; i < made_files_count; i++) { - if (!successful_exit) { - remove(made_files[i]); - } - } - free(made_files); - made_files_count = 0; - made_files = NULL; -} - -static char *msort(char*,char**,int(*)(const char*,const char*)); - -/* -** Compilers are getting increasingly pedantic about type conversions -** as C evolves ever closer to Ada.... To work around the latest problems -** we have to define the following variant of strlen(). -*/ -#define lemonStrlen(X) ((int)strlen(X)) - -/* a few forward declarations... */ -struct rule; -struct lemon; -struct action; - -static struct action *Action_new(void); -static struct action *Action_sort(struct action *); - -/********** From the file "build.h" ************************************/ -void FindRulePrecedences(); -void FindFirstSets(); -void FindStates(); -void FindLinks(); -void FindFollowSets(); -void FindActions(); - -/********* From the file "configlist.h" *********************************/ -void Configlist_init(void); -struct config *Configlist_add(struct rule *, int); -struct config *Configlist_addbasis(struct rule *, int); -void Configlist_closure(struct lemon *); -void Configlist_sort(void); -void Configlist_sortbasis(void); -struct config *Configlist_return(void); -struct config *Configlist_basis(void); -void Configlist_eat(struct config *); -void Configlist_reset(void); - -/********* From the file "error.h" ***************************************/ -void ErrorMsg(const char *, int,const char *, ...); - -/****** From the file "option.h" ******************************************/ -enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR, - OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR}; -struct s_options { - enum option_type type; - const char *label; - char *arg; - const char *message; -}; -int OptInit(char**,struct s_options*,FILE*); -int OptNArgs(void); -char *OptArg(int); -void OptErr(int); -void OptPrint(void); - -/******** From the file "parse.h" *****************************************/ -void Parse(struct lemon *lemp); - -/********* From the file "plink.h" ***************************************/ -struct plink *Plink_new(void); -void Plink_add(struct plink **, struct config *); -void Plink_copy(struct plink **, struct plink *); -void Plink_delete(struct plink *); - -/********** From the file "report.h" *************************************/ -void Reprint(struct lemon *); -void ReportOutput(struct lemon *); -void ReportTable(struct lemon *, int); -void ReportHeader(struct lemon *); -void CompressTables(struct lemon *); -void ResortStates(struct lemon *); - -/********** From the file "set.h" ****************************************/ -void SetSize(int); /* All sets will be of size N */ -char *SetNew(void); /* A new set for element 0..N */ -void SetFree(char*); /* Deallocate a set */ - -char *SetNew(void); /* A new set for element 0..N */ -int SetAdd(char*,int); /* Add element to a set */ -int SetUnion(char *,char *); /* A <- A U B, thru element N */ -#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */ - -/********** From the file "struct.h" *************************************/ -/* -** Principal data structures for the LEMON parser generator. -*/ - -typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean; - -/* Symbols (terminals and nonterminals) of the grammar are stored -** in the following: */ -enum symbol_type { - TERMINAL, - NONTERMINAL, - MULTITERMINAL -}; -enum e_assoc { - LEFT, - RIGHT, - NONE, - UNK -}; -struct symbol { - const char *name; /* Name of the symbol */ - int index; /* Index number for this symbol */ - enum symbol_type type; /* Symbols are all either TERMINALS or NTs */ - struct rule *rule; /* Linked list of rules of this (if an NT) */ - struct symbol *fallback; /* fallback token in case this token doesn't parse */ - int prec; /* Precedence if defined (-1 otherwise) */ - enum e_assoc assoc; /* Associativity if precedence is defined */ - char *firstset; /* First-set for all rules of this symbol */ - Boolean lambda; /* True if NT and can generate an empty string */ - int useCnt; /* Number of times used */ - char *destructor; /* Code which executes whenever this symbol is - ** popped from the stack during error processing */ - int destLineno; /* Line number for start of destructor */ - char *datatype; /* The data type of information held by this - ** object. Only used if type==NONTERMINAL */ - int dtnum; /* The data type number. In the parser, the value - ** stack is a union. The .yy%d element of this - ** union is the correct data type for this object */ - /* The following fields are used by MULTITERMINALs only */ - int nsubsym; /* Number of constituent symbols in the MULTI */ - struct symbol **subsym; /* Array of constituent symbols */ -}; - -/* Each production rule in the grammar is stored in the following -** structure. */ -struct rule { - struct symbol *lhs; /* Left-hand side of the rule */ - const char *lhsalias; /* Alias for the LHS (NULL if none) */ - int lhsStart; /* True if left-hand side is the start symbol */ - int ruleline; /* Line number for the rule */ - int nrhs; /* Number of RHS symbols */ - struct symbol **rhs; /* The RHS symbols */ - const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */ - int line; /* Line number at which code begins */ - const char *code; /* The code executed when this rule is reduced */ - struct symbol *precsym; /* Precedence symbol for this rule */ - int index; /* An index number for this rule */ - Boolean canReduce; /* True if this rule is ever reduced */ - struct rule *nextlhs; /* Next rule with the same LHS */ - struct rule *next; /* Next rule in the global list */ -}; - -/* A configuration is a production rule of the grammar together with -** a mark (dot) showing how much of that rule has been processed so far. -** Configurations also contain a follow-set which is a list of terminal -** symbols which are allowed to immediately follow the end of the rule. -** Every configuration is recorded as an instance of the following: */ -enum cfgstatus { - COMPLETE, - INCOMPLETE -}; -struct config { - struct rule *rp; /* The rule upon which the configuration is based */ - int dot; /* The parse point */ - char *fws; /* Follow-set for this configuration only */ - struct plink *fplp; /* Follow-set forward propagation links */ - struct plink *bplp; /* Follow-set backwards propagation links */ - struct state *stp; /* Pointer to state which contains this */ - enum cfgstatus status; /* used during followset and shift computations */ - struct config *next; /* Next configuration in the state */ - struct config *bp; /* The next basis configuration */ -}; - -enum e_action { - SHIFT, - ACCEPT, - REDUCE, - ERROR, - SSCONFLICT, /* A shift/shift conflict */ - SRCONFLICT, /* Was a reduce, but part of a conflict */ - RRCONFLICT, /* Was a reduce, but part of a conflict */ - SH_RESOLVED, /* Was a shift. Precedence resolved conflict */ - RD_RESOLVED, /* Was reduce. Precedence resolved conflict */ - NOT_USED /* Deleted by compression */ -}; - -/* Every shift or reduce operation is stored as one of the following */ -struct action { - struct symbol *sp; /* The look-ahead symbol */ - enum e_action type; - union { - struct state *stp; /* The new state, if a shift */ - struct rule *rp; /* The rule, if a reduce */ - } x; - struct action *next; /* Next action for this state */ - struct action *collide; /* Next action with the same hash */ -}; - -/* Each state of the generated parser's finite state machine -** is encoded as an instance of the following structure. */ -struct state { - struct config *bp; /* The basis configurations for this state */ - struct config *cfp; /* All configurations in this set */ - int statenum; /* Sequential number for this state */ - struct action *ap; /* Array of actions for this state */ - int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */ - int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */ - int iDflt; /* Default action */ -}; -#define NO_OFFSET (-2147483647) - -/* A followset propagation link indicates that the contents of one -** configuration followset should be propagated to another whenever -** the first changes. */ -struct plink { - struct config *cfp; /* The configuration to which linked */ - struct plink *next; /* The next propagate link */ -}; - -/* The state vector for the entire parser generator is recorded as -** follows. (LEMON uses no global variables and makes little use of -** static variables. Fields in the following structure can be thought -** of as begin global variables in the program.) */ -struct lemon { - struct state **sorted; /* Table of states sorted by state number */ - struct rule *rule; /* List of all rules */ - int nstate; /* Number of states */ - int nrule; /* Number of rules */ - int nsymbol; /* Number of terminal and nonterminal symbols */ - int nterminal; /* Number of terminal symbols */ - struct symbol **symbols; /* Sorted array of pointers to symbols */ - int errorcnt; /* Number of errors */ - struct symbol *errsym; /* The error symbol */ - struct symbol *wildcard; /* Token that matches anything */ - char *name; /* Name of the generated parser */ - char *arg; /* Declaration of the 3th argument to parser */ - char *tokentype; /* Type of terminal symbols in the parser stack */ - char *vartype; /* The default type of non-terminal symbols */ - char *start; /* Name of the start symbol for the grammar */ - char *stacksize; /* Size of the parser stack */ - char *include; /* Code to put at the start of the C file */ - char *error; /* Code to execute when an error is seen */ - char *overflow; /* Code to execute on a stack overflow */ - char *failure; /* Code to execute on parser failure */ - char *accept; /* Code to execute when the parser excepts */ - char *extracode; /* Code appended to the generated file */ - char *tokendest; /* Code to execute to destroy token data */ - char *vardest; /* Code for the default non-terminal destructor */ - char *filename; /* Name of the input file */ - char *outname; /* Name of the current output file */ - char *tokenprefix; /* A prefix added to token names in the .h file */ - int nconflict; /* Number of parsing conflicts */ -#if __MOJOSHADER__ - int nexpected; /* Number of expected parsing conflicts */ -#endif - int tablesize; /* Size of the parse tables */ - int basisflag; /* Print only basis configurations */ - int has_fallback; /* True if any %fallback is seen in the grammar */ - int nolinenosflag; /* True if #line statements should not be printed */ - char *argv0; /* Name of the program */ -}; - -#define MemoryCheck(X) if((X)==0){ \ - extern void memory_error(); \ - memory_error(); \ -} - -/**************** From the file "table.h" *********************************/ -/* -** All code in this file has been automatically generated -** from a specification in the file -** "table.q" -** by the associative array code building program "aagen". -** Do not edit this file! Instead, edit the specification -** file, then rerun aagen. -*/ -/* -** Code for processing tables in the LEMON parser generator. -*/ -/* Routines for handling a strings */ - -const char *Strsafe(const char *); - -void Strsafe_init(void); -int Strsafe_insert(const char *); -const char *Strsafe_find(const char *); - -/* Routines for handling symbols of the grammar */ - -struct symbol *Symbol_new(const char *); -int Symbolcmpp(const void *, const void *); -void Symbol_init(void); -int Symbol_insert(struct symbol *, const char *); -struct symbol *Symbol_find(const char *); -struct symbol *Symbol_Nth(int); -int Symbol_count(void); -struct symbol **Symbol_arrayof(void); - -/* Routines to manage the state table */ - -int Configcmp(const char *, const char *); -struct state *State_new(void); -void State_init(void); -int State_insert(struct state *, struct config *); -struct state *State_find(struct config *); -struct state **State_arrayof(/* */); - -/* Routines used for efficiency in Configlist_add */ - -void Configtable_init(void); -int Configtable_insert(struct config *); -struct config *Configtable_find(struct config *); -void Configtable_clear(int(*)(struct config *)); - -/****************** From the file "action.c" *******************************/ -/* -** Routines processing parser actions in the LEMON parser generator. -*/ - -/* Allocate a new parser action */ -static struct action *Action_new(void){ - static struct action *freelist = 0; - struct action *newaction; - - if( freelist==0 ){ - int i; - int amt = 100; - freelist = (struct action *)calloc(amt, sizeof(struct action)); - if( freelist==0 ){ - fprintf(stderr,"Unable to allocate memory for a new parser action."); - exit(1); - } - for(i=0; inext; - return newaction; -} - -/* Compare two actions for sorting purposes. Return negative, zero, or -** positive if the first action is less than, equal to, or greater than -** the first -*/ -static int actioncmp( - struct action *ap1, - struct action *ap2 -){ - int rc; - rc = ap1->sp->index - ap2->sp->index; - if( rc==0 ){ - rc = (int)ap1->type - (int)ap2->type; - } - if( rc==0 && ap1->type==REDUCE ){ - rc = ap1->x.rp->index - ap2->x.rp->index; - } - if( rc==0 ){ - rc = (int) (ap2 - ap1); - } - return rc; -} - -/* Sort parser actions */ -static struct action *Action_sort( - struct action *ap -){ - ap = (struct action *)msort((char *)ap,(char **)&ap->next, - (int(*)(const char*,const char*))actioncmp); - return ap; -} - -void Action_add( - struct action **app, - enum e_action type, - struct symbol *sp, - char *arg -){ - struct action *newaction; - newaction = Action_new(); - newaction->next = *app; - *app = newaction; - newaction->type = type; - newaction->sp = sp; - if( type==SHIFT ){ - newaction->x.stp = (struct state *)arg; - }else{ - newaction->x.rp = (struct rule *)arg; - } -} -/********************** New code to implement the "acttab" module ***********/ -/* -** This module implements routines use to construct the yy_action[] table. -*/ - -/* -** The state of the yy_action table under construction is an instance of -** the following structure. -** -** The yy_action table maps the pair (state_number, lookahead) into an -** action_number. The table is an array of integers pairs. The state_number -** determines an initial offset into the yy_action array. The lookahead -** value is then added to this initial offset to get an index X into the -** yy_action array. If the aAction[X].lookahead equals the value of the -** of the lookahead input, then the value of the action_number output is -** aAction[X].action. If the lookaheads do not match then the -** default action for the state_number is returned. -** -** All actions associated with a single state_number are first entered -** into aLookahead[] using multiple calls to acttab_action(). Then the -** actions for that single state_number are placed into the aAction[] -** array with a single call to acttab_insert(). The acttab_insert() call -** also resets the aLookahead[] array in preparation for the next -** state number. -*/ -struct lookahead_action { - int lookahead; /* Value of the lookahead token */ - int action; /* Action to take on the given lookahead */ -}; -typedef struct acttab acttab; -struct acttab { - int nAction; /* Number of used slots in aAction[] */ - int nActionAlloc; /* Slots allocated for aAction[] */ - struct lookahead_action - *aAction, /* The yy_action[] table under construction */ - *aLookahead; /* A single new transaction set */ - int mnLookahead; /* Minimum aLookahead[].lookahead */ - int mnAction; /* Action associated with mnLookahead */ - int mxLookahead; /* Maximum aLookahead[].lookahead */ - int nLookahead; /* Used slots in aLookahead[] */ - int nLookaheadAlloc; /* Slots allocated in aLookahead[] */ -}; - -/* Return the number of entries in the yy_action table */ -#define acttab_size(X) ((X)->nAction) - -/* The value for the N-th entry in yy_action */ -#define acttab_yyaction(X,N) ((X)->aAction[N].action) - -/* The value for the N-th entry in yy_lookahead */ -#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead) - -/* Free all memory associated with the given acttab */ -void acttab_free(acttab *p){ - free( p->aAction ); - free( p->aLookahead ); - free( p ); -} - -/* Allocate a new acttab structure */ -acttab *acttab_alloc(void){ - acttab *p = (acttab *) calloc( 1, sizeof(*p) ); - if( p==0 ){ - fprintf(stderr,"Unable to allocate memory for a new acttab."); - exit(1); - } - memset(p, 0, sizeof(*p)); - return p; -} - -/* Add a new action to the current transaction set. -** -** This routine is called once for each lookahead for a particular -** state. -*/ -void acttab_action(acttab *p, int lookahead, int action){ - if( p->nLookahead>=p->nLookaheadAlloc ){ - p->nLookaheadAlloc += 25; - p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead, - sizeof(p->aLookahead[0])*p->nLookaheadAlloc ); - if( p->aLookahead==0 ){ - fprintf(stderr,"malloc failed\n"); - exit(1); - } - } - if( p->nLookahead==0 ){ - p->mxLookahead = lookahead; - p->mnLookahead = lookahead; - p->mnAction = action; - }else{ - if( p->mxLookaheadmxLookahead = lookahead; - if( p->mnLookahead>lookahead ){ - p->mnLookahead = lookahead; - p->mnAction = action; - } - } - p->aLookahead[p->nLookahead].lookahead = lookahead; - p->aLookahead[p->nLookahead].action = action; - p->nLookahead++; -} - -/* -** Add the transaction set built up with prior calls to acttab_action() -** into the current action table. Then reset the transaction set back -** to an empty set in preparation for a new round of acttab_action() calls. -** -** Return the offset into the action table of the new transaction. -*/ -int acttab_insert(acttab *p){ - int i, j, k, n; - assert( p->nLookahead>0 ); - - /* Make sure we have enough space to hold the expanded action table - ** in the worst case. The worst case occurs if the transaction set - ** must be appended to the current action table - */ - n = p->mxLookahead + 1; - if( p->nAction + n >= p->nActionAlloc ){ - int oldAlloc = p->nActionAlloc; - p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20; - p->aAction = (struct lookahead_action *) realloc( p->aAction, - sizeof(p->aAction[0])*p->nActionAlloc); - if( p->aAction==0 ){ - fprintf(stderr,"malloc failed\n"); - exit(1); - } - for(i=oldAlloc; inActionAlloc; i++){ - p->aAction[i].lookahead = -1; - p->aAction[i].action = -1; - } - } - - /* Scan the existing action table looking for an offset that is a - ** duplicate of the current transaction set. Fall out of the loop - ** if and when the duplicate is found. - ** - ** i is the index in p->aAction[] where p->mnLookahead is inserted. - */ - for(i=p->nAction-1; i>=0; i--){ - if( p->aAction[i].lookahead==p->mnLookahead ){ - /* All lookaheads and actions in the aLookahead[] transaction - ** must match against the candidate aAction[i] entry. */ - if( p->aAction[i].action!=p->mnAction ) continue; - for(j=0; jnLookahead; j++){ - k = p->aLookahead[j].lookahead - p->mnLookahead + i; - if( k<0 || k>=p->nAction ) break; - if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break; - if( p->aLookahead[j].action!=p->aAction[k].action ) break; - } - if( jnLookahead ) continue; - - /* No possible lookahead value that is not in the aLookahead[] - ** transaction is allowed to match aAction[i] */ - n = 0; - for(j=0; jnAction; j++){ - if( p->aAction[j].lookahead<0 ) continue; - if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++; - } - if( n==p->nLookahead ){ - break; /* An exact match is found at offset i */ - } - } - } - - /* If no existing offsets exactly match the current transaction, find an - ** an empty offset in the aAction[] table in which we can add the - ** aLookahead[] transaction. - */ - if( i<0 ){ - /* Look for holes in the aAction[] table that fit the current - ** aLookahead[] transaction. Leave i set to the offset of the hole. - ** If no holes are found, i is left at p->nAction, which means the - ** transaction will be appended. */ - for(i=0; inActionAlloc - p->mxLookahead; i++){ - if( p->aAction[i].lookahead<0 ){ - for(j=0; jnLookahead; j++){ - k = p->aLookahead[j].lookahead - p->mnLookahead + i; - if( k<0 ) break; - if( p->aAction[k].lookahead>=0 ) break; - } - if( jnLookahead ) continue; - for(j=0; jnAction; j++){ - if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break; - } - if( j==p->nAction ){ - break; /* Fits in empty slots */ - } - } - } - } - /* Insert transaction set at index i. */ - for(j=0; jnLookahead; j++){ - k = p->aLookahead[j].lookahead - p->mnLookahead + i; - p->aAction[k] = p->aLookahead[j]; - if( k>=p->nAction ) p->nAction = k+1; - } - p->nLookahead = 0; - - /* Return the offset that is added to the lookahead in order to get the - ** index into yy_action of the action */ - return i - p->mnLookahead; -} - -/********************** From the file "build.c" *****************************/ -/* -** Routines to construction the finite state machine for the LEMON -** parser generator. -*/ - -/* Find a precedence symbol of every rule in the grammar. -** -** Those rules which have a precedence symbol coded in the input -** grammar using the "[symbol]" construct will already have the -** rp->precsym field filled. Other rules take as their precedence -** symbol the first RHS symbol with a defined precedence. If there -** are not RHS symbols with a defined precedence, the precedence -** symbol field is left blank. -*/ -void FindRulePrecedences(struct lemon *xp) -{ - struct rule *rp; - for(rp=xp->rule; rp; rp=rp->next){ - if( rp->precsym==0 ){ - int i, j; - for(i=0; inrhs && rp->precsym==0; i++){ - struct symbol *sp = rp->rhs[i]; - if( sp->type==MULTITERMINAL ){ - for(j=0; jnsubsym; j++){ - if( sp->subsym[j]->prec>=0 ){ - rp->precsym = sp->subsym[j]; - break; - } - } - }else if( sp->prec>=0 ){ - rp->precsym = rp->rhs[i]; - } - } - } - } - return; -} - -/* Find all nonterminals which will generate the empty string. -** Then go back and compute the first sets of every nonterminal. -** The first set is the set of all terminal symbols which can begin -** a string generated by that nonterminal. -*/ -void FindFirstSets(struct lemon *lemp) -{ - int i, j; - struct rule *rp; - int progress; - - for(i=0; insymbol; i++){ - lemp->symbols[i]->lambda = LEMON_FALSE; - } - for(i=lemp->nterminal; insymbol; i++){ - lemp->symbols[i]->firstset = SetNew(); - } - - /* First compute all lambdas */ - do{ - progress = 0; - for(rp=lemp->rule; rp; rp=rp->next){ - if( rp->lhs->lambda ) continue; - for(i=0; inrhs; i++){ - struct symbol *sp = rp->rhs[i]; - if( sp->type!=TERMINAL || sp->lambda==LEMON_FALSE ) break; - } - if( i==rp->nrhs ){ - rp->lhs->lambda = LEMON_TRUE; - progress = 1; - } - } - }while( progress ); - - /* Now compute all first sets */ - do{ - struct symbol *s1, *s2; - progress = 0; - for(rp=lemp->rule; rp; rp=rp->next){ - s1 = rp->lhs; - for(i=0; inrhs; i++){ - s2 = rp->rhs[i]; - if( s2->type==TERMINAL ){ - progress += SetAdd(s1->firstset,s2->index); - break; - }else if( s2->type==MULTITERMINAL ){ - for(j=0; jnsubsym; j++){ - progress += SetAdd(s1->firstset,s2->subsym[j]->index); - } - break; - }else if( s1==s2 ){ - if( s1->lambda==LEMON_FALSE ) break; - }else{ - progress += SetUnion(s1->firstset,s2->firstset); - if( s2->lambda==LEMON_FALSE ) break; - } - } - } - }while( progress ); - return; -} - -/* Compute all LR(0) states for the grammar. Links -** are added to between some states so that the LR(1) follow sets -** can be computed later. -*/ -PRIVATE struct state *getstate(struct lemon *); /* forward reference */ -void FindStates(struct lemon *lemp) -{ - struct symbol *sp; - struct rule *rp; - - Configlist_init(); - - /* Find the start symbol */ - if( lemp->start ){ - sp = Symbol_find(lemp->start); - if( sp==0 ){ - ErrorMsg(lemp->filename,0, -"The specified start symbol \"%s\" is not \ -in a nonterminal of the grammar. \"%s\" will be used as the start \ -symbol instead.",lemp->start,lemp->rule->lhs->name); - lemp->errorcnt++; - sp = lemp->rule->lhs; - } - }else{ - sp = lemp->rule->lhs; - } - - /* Make sure the start symbol doesn't occur on the right-hand side of - ** any rule. Report an error if it does. (YACC would generate a new - ** start symbol in this case.) */ - for(rp=lemp->rule; rp; rp=rp->next){ - int i; - for(i=0; inrhs; i++){ - if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */ - ErrorMsg(lemp->filename,0, -"The start symbol \"%s\" occurs on the \ -right-hand side of a rule. This will result in a parser which \ -does not work properly.",sp->name); - lemp->errorcnt++; - } - } - } - - /* The basis configuration set for the first state - ** is all rules which have the start symbol as their - ** left-hand side */ - for(rp=sp->rule; rp; rp=rp->nextlhs){ - struct config *newcfp; - rp->lhsStart = 1; - newcfp = Configlist_addbasis(rp,0); - SetAdd(newcfp->fws,0); - } - - /* Compute the first state. All other states will be - ** computed automatically during the computation of the first one. - ** The returned pointer to the first state is not used. */ - (void)getstate(lemp); - return; -} - -/* Return a pointer to a state which is described by the configuration -** list which has been built from calls to Configlist_add. -*/ -PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */ -PRIVATE struct state *getstate(struct lemon *lemp) -{ - struct config *cfp, *bp; - struct state *stp; - - /* Extract the sorted basis of the new state. The basis was constructed - ** by prior calls to "Configlist_addbasis()". */ - Configlist_sortbasis(); - bp = Configlist_basis(); - - /* Get a state with the same basis */ - stp = State_find(bp); - if( stp ){ - /* A state with the same basis already exists! Copy all the follow-set - ** propagation links from the state under construction into the - ** preexisting state, then return a pointer to the preexisting state */ - struct config *x, *y; - for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){ - Plink_copy(&y->bplp,x->bplp); - Plink_delete(x->fplp); - x->fplp = x->bplp = 0; - } - cfp = Configlist_return(); - Configlist_eat(cfp); - }else{ - /* This really is a new state. Construct all the details */ - Configlist_closure(lemp); /* Compute the configuration closure */ - Configlist_sort(); /* Sort the configuration closure */ - cfp = Configlist_return(); /* Get a pointer to the config list */ - stp = State_new(); /* A new state structure */ - MemoryCheck(stp); - stp->bp = bp; /* Remember the configuration basis */ - stp->cfp = cfp; /* Remember the configuration closure */ - stp->statenum = lemp->nstate++; /* Every state gets a sequence number */ - stp->ap = 0; /* No actions, yet. */ - State_insert(stp,stp->bp); /* Add to the state table */ - buildshifts(lemp,stp); /* Recursively compute successor states */ - } - return stp; -} - -/* -** Return true if two symbols are the same. -*/ -int same_symbol(struct symbol *a, struct symbol *b) -{ - int i; - if( a==b ) return 1; - if( a->type!=MULTITERMINAL ) return 0; - if( b->type!=MULTITERMINAL ) return 0; - if( a->nsubsym!=b->nsubsym ) return 0; - for(i=0; insubsym; i++){ - if( a->subsym[i]!=b->subsym[i] ) return 0; - } - return 1; -} - -/* Construct all successor states to the given state. A "successor" -** state is any state which can be reached by a shift action. -*/ -PRIVATE void buildshifts(struct lemon *lemp, struct state *stp) -{ - struct config *cfp; /* For looping thru the config closure of "stp" */ - struct config *bcfp; /* For the inner loop on config closure of "stp" */ - struct config *newcfg; /* */ - struct symbol *sp; /* Symbol following the dot in configuration "cfp" */ - struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */ - struct state *newstp; /* A pointer to a successor state */ - - /* Each configuration becomes complete after it contibutes to a successor - ** state. Initially, all configurations are incomplete */ - for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE; - - /* Loop through all configurations of the state "stp" */ - for(cfp=stp->cfp; cfp; cfp=cfp->next){ - if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */ - if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */ - Configlist_reset(); /* Reset the new config set */ - sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */ - - /* For every configuration in the state "stp" which has the symbol "sp" - ** following its dot, add the same configuration to the basis set under - ** construction but with the dot shifted one symbol to the right. */ - for(bcfp=cfp; bcfp; bcfp=bcfp->next){ - if( bcfp->status==COMPLETE ) continue; /* Already used */ - if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */ - bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */ - if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */ - bcfp->status = COMPLETE; /* Mark this config as used */ - newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1); - Plink_add(&newcfg->bplp,bcfp); - } - - /* Get a pointer to the state described by the basis configuration set - ** constructed in the preceding loop */ - newstp = getstate(lemp); - - /* The state "newstp" is reached from the state "stp" by a shift action - ** on the symbol "sp" */ - if( sp->type==MULTITERMINAL ){ - int i; - for(i=0; insubsym; i++){ - Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp); - } - }else{ - Action_add(&stp->ap,SHIFT,sp,(char *)newstp); - } - } -} - -/* -** Construct the propagation links -*/ -void FindLinks(struct lemon *lemp) -{ - int i; - struct config *cfp, *other; - struct state *stp; - struct plink *plp; - - /* Housekeeping detail: - ** Add to every propagate link a pointer back to the state to - ** which the link is attached. */ - for(i=0; instate; i++){ - stp = lemp->sorted[i]; - for(cfp=stp->cfp; cfp; cfp=cfp->next){ - cfp->stp = stp; - } - } - - /* Convert all backlinks into forward links. Only the forward - ** links are used in the follow-set computation. */ - for(i=0; instate; i++){ - stp = lemp->sorted[i]; - for(cfp=stp->cfp; cfp; cfp=cfp->next){ - for(plp=cfp->bplp; plp; plp=plp->next){ - other = plp->cfp; - Plink_add(&other->fplp,cfp); - } - } - } -} - -/* Compute all followsets. -** -** A followset is the set of all symbols which can come immediately -** after a configuration. -*/ -void FindFollowSets(struct lemon *lemp) -{ - int i; - struct config *cfp; - struct plink *plp; - int progress; - int change; - - for(i=0; instate; i++){ - for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){ - cfp->status = INCOMPLETE; - } - } - - do{ - progress = 0; - for(i=0; instate; i++){ - for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){ - if( cfp->status==COMPLETE ) continue; - for(plp=cfp->fplp; plp; plp=plp->next){ - change = SetUnion(plp->cfp->fws,cfp->fws); - if( change ){ - plp->cfp->status = INCOMPLETE; - progress = 1; - } - } - cfp->status = COMPLETE; - } - } - }while( progress ); -} - -static int resolve_conflict(struct action *,struct action *, struct symbol *); - -/* Compute the reduce actions, and resolve conflicts. -*/ -void FindActions(struct lemon *lemp) -{ - int i,j; - struct config *cfp; - struct state *stp; - struct symbol *sp; - struct rule *rp; - - /* Add all of the reduce actions - ** A reduce action is added for each element of the followset of - ** a configuration which has its dot at the extreme right. - */ - for(i=0; instate; i++){ /* Loop over all states */ - stp = lemp->sorted[i]; - for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */ - if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */ - for(j=0; jnterminal; j++){ - if( SetFind(cfp->fws,j) ){ - /* Add a reduce action to the state "stp" which will reduce by the - ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */ - Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp); - } - } - } - } - } - - /* Add the accepting token */ - if( lemp->start ){ - sp = Symbol_find(lemp->start); - if( sp==0 ) sp = lemp->rule->lhs; - }else{ - sp = lemp->rule->lhs; - } - /* Add to the first state (which is always the starting state of the - ** finite state machine) an action to ACCEPT if the lookahead is the - ** start nonterminal. */ - Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0); - - /* Resolve conflicts */ - for(i=0; instate; i++){ - struct action *ap, *nap; - struct state *stp; - stp = lemp->sorted[i]; - /* assert( stp->ap ); */ - stp->ap = Action_sort(stp->ap); - for(ap=stp->ap; ap && ap->next; ap=ap->next){ - for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){ - /* The two actions "ap" and "nap" have the same lookahead. - ** Figure out which one should be used */ - lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym); - } - } - } - - /* Report an error for each rule that can never be reduced. */ - for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE; - for(i=0; instate; i++){ - struct action *ap; - for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){ - if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE; - } - } - for(rp=lemp->rule; rp; rp=rp->next){ - if( rp->canReduce ) continue; - ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n"); - lemp->errorcnt++; - } -} - -/* Resolve a conflict between the two given actions. If the -** conflict can't be resolved, return non-zero. -** -** NO LONGER TRUE: -** To resolve a conflict, first look to see if either action -** is on an error rule. In that case, take the action which -** is not associated with the error rule. If neither or both -** actions are associated with an error rule, then try to -** use precedence to resolve the conflict. -** -** If either action is a SHIFT, then it must be apx. This -** function won't work if apx->type==REDUCE and apy->type==SHIFT. -*/ -static int resolve_conflict( - struct action *apx, - struct action *apy, - struct symbol *errsym /* The error symbol (if defined. NULL otherwise) */ -){ - struct symbol *spx, *spy; - int errcnt = 0; - assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */ - if( apx->type==SHIFT && apy->type==SHIFT ){ - apy->type = SSCONFLICT; - errcnt++; - } - if( apx->type==SHIFT && apy->type==REDUCE ){ - spx = apx->sp; - spy = apy->x.rp->precsym; - if( spy==0 || spx->prec<0 || spy->prec<0 ){ - /* Not enough precedence information. */ - apy->type = SRCONFLICT; - errcnt++; - }else if( spx->prec>spy->prec ){ /* Lower precedence wins */ - apy->type = RD_RESOLVED; - }else if( spx->precprec ){ - apx->type = SH_RESOLVED; - }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */ - apy->type = RD_RESOLVED; /* associativity */ - }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */ - apx->type = SH_RESOLVED; - }else{ - assert( spx->prec==spy->prec && spx->assoc==NONE ); - apy->type = SRCONFLICT; - errcnt++; - } - }else if( apx->type==REDUCE && apy->type==REDUCE ){ - spx = apx->x.rp->precsym; - spy = apy->x.rp->precsym; - if( spx==0 || spy==0 || spx->prec<0 || - spy->prec<0 || spx->prec==spy->prec ){ - apy->type = RRCONFLICT; - errcnt++; - }else if( spx->prec>spy->prec ){ - apy->type = RD_RESOLVED; - }else if( spx->precprec ){ - apx->type = RD_RESOLVED; - } - }else{ - assert( - apx->type==SH_RESOLVED || - apx->type==RD_RESOLVED || - apx->type==SSCONFLICT || - apx->type==SRCONFLICT || - apx->type==RRCONFLICT || - apy->type==SH_RESOLVED || - apy->type==RD_RESOLVED || - apy->type==SSCONFLICT || - apy->type==SRCONFLICT || - apy->type==RRCONFLICT - ); - /* The REDUCE/SHIFT case cannot happen because SHIFTs come before - ** REDUCEs on the list. If we reach this point it must be because - ** the parser conflict had already been resolved. */ - } - return errcnt; -} -/********************* From the file "configlist.c" *************************/ -/* -** Routines to processing a configuration list and building a state -** in the LEMON parser generator. -*/ - -static struct config *freelist = 0; /* List of free configurations */ -static struct config *current = 0; /* Top of list of configurations */ -static struct config **currentend = 0; /* Last on list of configs */ -static struct config *basis = 0; /* Top of list of basis configs */ -static struct config **basisend = 0; /* End of list of basis configs */ - -/* Return a pointer to a new configuration */ -PRIVATE struct config *newconfig(){ - struct config *newcfg; - if( freelist==0 ){ - int i; - int amt = 3; - freelist = (struct config *)calloc( amt, sizeof(struct config) ); - if( freelist==0 ){ - fprintf(stderr,"Unable to allocate memory for a new configuration."); - exit(1); - } - for(i=0; inext; - return newcfg; -} - -/* The configuration "old" is no longer used */ -PRIVATE void deleteconfig(struct config *old) -{ - old->next = freelist; - freelist = old; -} - -/* Initialized the configuration list builder */ -void Configlist_init(){ - current = 0; - currentend = ¤t; - basis = 0; - basisend = &basis; - Configtable_init(); - return; -} - -/* Initialized the configuration list builder */ -void Configlist_reset(){ - current = 0; - currentend = ¤t; - basis = 0; - basisend = &basis; - Configtable_clear(0); - return; -} - -/* Add another configuration to the configuration list */ -struct config *Configlist_add( - struct rule *rp, /* The rule */ - int dot /* Index into the RHS of the rule where the dot goes */ -){ - struct config *cfp, model; - - assert( currentend!=0 ); - model.rp = rp; - model.dot = dot; - cfp = Configtable_find(&model); - if( cfp==0 ){ - cfp = newconfig(); - cfp->rp = rp; - cfp->dot = dot; - cfp->fws = SetNew(); - cfp->stp = 0; - cfp->fplp = cfp->bplp = 0; - cfp->next = 0; - cfp->bp = 0; - *currentend = cfp; - currentend = &cfp->next; - Configtable_insert(cfp); - } - return cfp; -} - -/* Add a basis configuration to the configuration list */ -struct config *Configlist_addbasis(struct rule *rp, int dot) -{ - struct config *cfp, model; - - assert( basisend!=0 ); - assert( currentend!=0 ); - model.rp = rp; - model.dot = dot; - cfp = Configtable_find(&model); - if( cfp==0 ){ - cfp = newconfig(); - cfp->rp = rp; - cfp->dot = dot; - cfp->fws = SetNew(); - cfp->stp = 0; - cfp->fplp = cfp->bplp = 0; - cfp->next = 0; - cfp->bp = 0; - *currentend = cfp; - currentend = &cfp->next; - *basisend = cfp; - basisend = &cfp->bp; - Configtable_insert(cfp); - } - return cfp; -} - -/* Compute the closure of the configuration list */ -void Configlist_closure(struct lemon *lemp) -{ - struct config *cfp, *newcfp; - struct rule *rp, *newrp; - struct symbol *sp, *xsp; - int i, dot; - - assert( currentend!=0 ); - for(cfp=current; cfp; cfp=cfp->next){ - rp = cfp->rp; - dot = cfp->dot; - if( dot>=rp->nrhs ) continue; - sp = rp->rhs[dot]; - if( sp->type==NONTERMINAL ){ - if( sp->rule==0 && sp!=lemp->errsym ){ - ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.", - sp->name); - lemp->errorcnt++; - } - for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){ - newcfp = Configlist_add(newrp,0); - for(i=dot+1; inrhs; i++){ - xsp = rp->rhs[i]; - if( xsp->type==TERMINAL ){ - SetAdd(newcfp->fws,xsp->index); - break; - }else if( xsp->type==MULTITERMINAL ){ - int k; - for(k=0; knsubsym; k++){ - SetAdd(newcfp->fws, xsp->subsym[k]->index); - } - break; - }else{ - SetUnion(newcfp->fws,xsp->firstset); - if( xsp->lambda==LEMON_FALSE ) break; - } - } - if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp); - } - } - } - return; -} - -/* Sort the configuration list */ -void Configlist_sort(){ - current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp); - currentend = 0; - return; -} - -/* Sort the basis configuration list */ -void Configlist_sortbasis(){ - basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp); - basisend = 0; - return; -} - -/* Return a pointer to the head of the configuration list and -** reset the list */ -struct config *Configlist_return(){ - struct config *old; - old = current; - current = 0; - currentend = 0; - return old; -} - -/* Return a pointer to the head of the configuration list and -** reset the list */ -struct config *Configlist_basis(){ - struct config *old; - old = basis; - basis = 0; - basisend = 0; - return old; -} - -/* Free all elements of the given configuration list */ -void Configlist_eat(struct config *cfp) -{ - struct config *nextcfp; - for(; cfp; cfp=nextcfp){ - nextcfp = cfp->next; - assert( cfp->fplp==0 ); - assert( cfp->bplp==0 ); - if( cfp->fws ) SetFree(cfp->fws); - deleteconfig(cfp); - } - return; -} -/***************** From the file "error.c" *********************************/ -/* -** Code for printing error message. -*/ - -void ErrorMsg(const char *filename, int lineno, const char *format, ...){ - va_list ap; - fprintf(stderr, "%s:%d: ", filename, lineno); - va_start(ap, format); - vfprintf(stderr,format,ap); - va_end(ap); - fprintf(stderr, "\n"); -} -/**************** From the file "main.c" ************************************/ -/* -** Main program file for the LEMON parser generator. -*/ - -/* Report an out-of-memory condition and abort. This function -** is used mostly by the "MemoryCheck" macro in struct.h -*/ -void memory_error(){ - fprintf(stderr,"Out of memory. Aborting...\n"); - exit(1); -} - -static int nDefine = 0; /* Number of -D options on the command line */ -static char **azDefine = 0; /* Name of the -D macros */ - -/* This routine is called with the argument to each -D command-line option. -** Add the macro defined to the azDefine array. -*/ -static void handle_D_option(char *z){ - char **paz; - nDefine++; - azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine); - if( azDefine==0 ){ - fprintf(stderr,"out of memory\n"); - exit(1); - } - paz = &azDefine[nDefine-1]; - *paz = (char *) malloc( lemonStrlen(z)+1 ); - if( *paz==0 ){ - fprintf(stderr,"out of memory\n"); - exit(1); - } - strcpy(*paz, z); - for(z=*paz; *z && *z!='='; z++){} - *z = 0; -} - -static char *user_templatename = NULL; -static void handle_T_option(char *z){ - user_templatename = (char *) malloc( lemonStrlen(z)+1 ); - if( user_templatename==0 ){ - memory_error(); - } - strcpy(user_templatename, z); -} - -/* The main program. Parse the command line and do it... */ -int main(int argc, char **argv) -{ - static int version = 0; - static int rpflag = 0; - static int basisflag = 0; - static int compress = 0; - static int quiet = 0; - static int statistics = 0; - static int mhflag = 0; - static int nolinenosflag = 0; - static struct s_options options[] = { - {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."}, - {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."}, - {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."}, - {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."}, - {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."}, - {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."}, - {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."}, - {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."}, - {OPT_FLAG, "s", (char*)&statistics, - "Print parser stats to standard output."}, - {OPT_FLAG, "x", (char*)&version, "Print the version number."}, - {OPT_FLAG,0,0,0} - }; - int i; - int exitcode; - struct lemon lem; - - atexit(LemonAtExit); - - OptInit(argv,options,stderr); - if( version ){ - printf("Lemon version 1.0\n"); -#if __MOJOSHADER__ - printf(" (...with MojoShader hacks.)\n"); -#endif - exit(0); - } - if( OptNArgs()!=1 ){ - fprintf(stderr,"Exactly one filename argument is required.\n"); - exit(1); - } - memset(&lem, 0, sizeof(lem)); - lem.errorcnt = 0; -#if __MOJOSHADER__ - lem.nexpected = -1; -#endif - - /* Initialize the machine */ - Strsafe_init(); - Symbol_init(); - State_init(); - lem.argv0 = argv[0]; - lem.filename = OptArg(0); - lem.basisflag = basisflag; - lem.nolinenosflag = nolinenosflag; - Symbol_new("$"); - lem.errsym = Symbol_new("error"); - lem.errsym->useCnt = 0; - - /* Parse the input file */ - Parse(&lem); - if( lem.errorcnt ) exit(lem.errorcnt); - if( lem.nrule==0 ){ - fprintf(stderr,"Empty grammar.\n"); - exit(1); - } - - /* Count and index the symbols of the grammar */ - lem.nsymbol = Symbol_count(); - Symbol_new("{default}"); - lem.symbols = Symbol_arrayof(); - for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i; - qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*), Symbolcmpp); - for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i; - for(i=1; isupper(lem.symbols[i]->name[0]); i++); - lem.nterminal = i; - - /* Generate a reprint of the grammar, if requested on the command line */ - if( rpflag ){ - Reprint(&lem); - }else{ - /* Initialize the size for all follow and first sets */ - SetSize(lem.nterminal+1); - - /* Find the precedence for every production rule (that has one) */ - FindRulePrecedences(&lem); - - /* Compute the lambda-nonterminals and the first-sets for every - ** nonterminal */ - FindFirstSets(&lem); - - /* Compute all LR(0) states. Also record follow-set propagation - ** links so that the follow-set can be computed later */ - lem.nstate = 0; - FindStates(&lem); - lem.sorted = State_arrayof(); - - /* Tie up loose ends on the propagation links */ - FindLinks(&lem); - - /* Compute the follow set of every reducible configuration */ - FindFollowSets(&lem); - - /* Compute the action tables */ - FindActions(&lem); - - /* Compress the action tables */ - if( compress==0 ) CompressTables(&lem); - - /* Reorder and renumber the states so that states with fewer choices - ** occur at the end. */ - ResortStates(&lem); - - /* Generate a report of the parser generated. (the "y.output" file) */ - if( !quiet ) ReportOutput(&lem); - - /* Generate the source code for the parser */ - ReportTable(&lem, mhflag); - - /* Produce a header file for use by the scanner. (This step is - ** omitted if the "-m" option is used because makeheaders will - ** generate the file for us.) */ -#if !__MOJOSHADER__ - if( !mhflag ) ReportHeader(&lem); -#endif - } - if( statistics ){ - printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n", - lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule); - printf(" %d states, %d parser table entries, %d conflicts\n", - lem.nstate, lem.tablesize, lem.nconflict); - } - -#if __MOJOSHADER__ - if( lem.nexpected < 0 ) { - lem.nexpected = 0; /* grammar didn't have an %expect declaration. */ - } - if( lem.nconflict != lem.nexpected ){ - fprintf(stderr,"%d parsing conflicts (%d expected).\n",lem.nconflict,lem.nexpected); - } - /* return 0 on success, 1 on failure. */ - exitcode = ((lem.errorcnt > 0) || (lem.nconflict != lem.nexpected)) ? 1 : 0; -#else - if( lem.nconflict > 0 ){ - fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict); - } - - /* return 0 on success, 1 on failure. */ - exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0; -#endif - successful_exit = (exitcode == 0); - exit(exitcode); - return (exitcode); -} -/******************** From the file "msort.c" *******************************/ -/* -** A generic merge-sort program. -** -** USAGE: -** Let "ptr" be a pointer to some structure which is at the head of -** a null-terminated list. Then to sort the list call: -** -** ptr = msort(ptr,&(ptr->next),cmpfnc); -** -** In the above, "cmpfnc" is a pointer to a function which compares -** two instances of the structure and returns an integer, as in -** strcmp. The second argument is a pointer to the pointer to the -** second element of the linked list. This address is used to compute -** the offset to the "next" field within the structure. The offset to -** the "next" field must be constant for all structures in the list. -** -** The function returns a new pointer which is the head of the list -** after sorting. -** -** ALGORITHM: -** Merge-sort. -*/ - -/* -** Return a pointer to the next structure in the linked list. -*/ -#define NEXT(A) (*(char**)(((unsigned long)A)+offset)) - -/* -** Inputs: -** a: A sorted, null-terminated linked list. (May be null). -** b: A sorted, null-terminated linked list. (May be null). -** cmp: A pointer to the comparison function. -** offset: Offset in the structure to the "next" field. -** -** Return Value: -** A pointer to the head of a sorted list containing the elements -** of both a and b. -** -** Side effects: -** The "next" pointers for elements in the lists a and b are -** changed. -*/ -static char *merge( - char *a, - char *b, - int (*cmp)(const char*,const char*), - int offset -){ - char *ptr, *head; - - if( a==0 ){ - head = b; - }else if( b==0 ){ - head = a; - }else{ - if( (*cmp)(a,b)<=0 ){ - ptr = a; - a = NEXT(a); - }else{ - ptr = b; - b = NEXT(b); - } - head = ptr; - while( a && b ){ - if( (*cmp)(a,b)<=0 ){ - NEXT(ptr) = a; - ptr = a; - a = NEXT(a); - }else{ - NEXT(ptr) = b; - ptr = b; - b = NEXT(b); - } - } - if( a ) NEXT(ptr) = a; - else NEXT(ptr) = b; - } - return head; -} - -/* -** Inputs: -** list: Pointer to a singly-linked list of structures. -** next: Pointer to pointer to the second element of the list. -** cmp: A comparison function. -** -** Return Value: -** A pointer to the head of a sorted list containing the elements -** orginally in list. -** -** Side effects: -** The "next" pointers for elements in list are changed. -*/ -#define LISTSIZE 30 -static char *msort( - char *list, - char **next, - int (*cmp)(const char*,const char*) -){ - unsigned long offset; - char *ep; - char *set[LISTSIZE]; - int i; - offset = (unsigned long)next - (unsigned long)list; - for(i=0; istate = WAITING_FOR_DECL_KEYWORD; - }else if( islower(x[0]) ){ - psp->lhs = Symbol_new(x); - psp->nrhs = 0; - psp->lhsalias = 0; - psp->state = WAITING_FOR_ARROW; - }else if( x[0]=='{' ){ - if( psp->prevrule==0 ){ - ErrorMsg(psp->filename,psp->tokenlineno, -"There is no prior rule opon which to attach the code \ -fragment which begins on this line."); - psp->errorcnt++; - }else if( psp->prevrule->code!=0 ){ - ErrorMsg(psp->filename,psp->tokenlineno, -"Code fragment beginning on this line is not the first \ -to follow the previous rule."); - psp->errorcnt++; - }else{ - psp->prevrule->line = psp->tokenlineno; - psp->prevrule->code = &x[1]; - } - }else if( x[0]=='[' ){ - psp->state = PRECEDENCE_MARK_1; - }else{ - ErrorMsg(psp->filename,psp->tokenlineno, - "Token \"%s\" should be either \"%%\" or a nonterminal name.", - x); - psp->errorcnt++; - } - break; - case PRECEDENCE_MARK_1: - if( !isupper(x[0]) ){ - ErrorMsg(psp->filename,psp->tokenlineno, - "The precedence symbol must be a terminal."); - psp->errorcnt++; - }else if( psp->prevrule==0 ){ - ErrorMsg(psp->filename,psp->tokenlineno, - "There is no prior rule to assign precedence \"[%s]\".",x); - psp->errorcnt++; - }else if( psp->prevrule->precsym!=0 ){ - ErrorMsg(psp->filename,psp->tokenlineno, -"Precedence mark on this line is not the first \ -to follow the previous rule."); - psp->errorcnt++; - }else{ - psp->prevrule->precsym = Symbol_new(x); - } - psp->state = PRECEDENCE_MARK_2; - break; - case PRECEDENCE_MARK_2: - if( x[0]!=']' ){ - ErrorMsg(psp->filename,psp->tokenlineno, - "Missing \"]\" on precedence mark."); - psp->errorcnt++; - } - psp->state = WAITING_FOR_DECL_OR_RULE; - break; - case WAITING_FOR_ARROW: - if( x[0]==':' && x[1]==':' && x[2]=='=' ){ - psp->state = IN_RHS; - }else if( x[0]=='(' ){ - psp->state = LHS_ALIAS_1; - }else{ - ErrorMsg(psp->filename,psp->tokenlineno, - "Expected to see a \":\" following the LHS symbol \"%s\".", - psp->lhs->name); - psp->errorcnt++; - psp->state = RESYNC_AFTER_RULE_ERROR; - } - break; - case LHS_ALIAS_1: - if( isalpha(x[0]) ){ - psp->lhsalias = x; - psp->state = LHS_ALIAS_2; - }else{ - ErrorMsg(psp->filename,psp->tokenlineno, - "\"%s\" is not a valid alias for the LHS \"%s\"\n", - x,psp->lhs->name); - psp->errorcnt++; - psp->state = RESYNC_AFTER_RULE_ERROR; - } - break; - case LHS_ALIAS_2: - if( x[0]==')' ){ - psp->state = LHS_ALIAS_3; - }else{ - ErrorMsg(psp->filename,psp->tokenlineno, - "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias); - psp->errorcnt++; - psp->state = RESYNC_AFTER_RULE_ERROR; - } - break; - case LHS_ALIAS_3: - if( x[0]==':' && x[1]==':' && x[2]=='=' ){ - psp->state = IN_RHS; - }else{ - ErrorMsg(psp->filename,psp->tokenlineno, - "Missing \"->\" following: \"%s(%s)\".", - psp->lhs->name,psp->lhsalias); - psp->errorcnt++; - psp->state = RESYNC_AFTER_RULE_ERROR; - } - break; - case IN_RHS: - if( x[0]=='.' ){ - struct rule *rp; - rp = (struct rule *)calloc( sizeof(struct rule) + - sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1); - if( rp==0 ){ - ErrorMsg(psp->filename,psp->tokenlineno, - "Can't allocate enough memory for this rule."); - psp->errorcnt++; - psp->prevrule = 0; - }else{ - int i; - rp->ruleline = psp->tokenlineno; - rp->rhs = (struct symbol**)&rp[1]; - rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]); - for(i=0; inrhs; i++){ - rp->rhs[i] = psp->rhs[i]; - rp->rhsalias[i] = psp->alias[i]; - } - rp->lhs = psp->lhs; - rp->lhsalias = psp->lhsalias; - rp->nrhs = psp->nrhs; - rp->code = 0; - rp->precsym = 0; - rp->index = psp->gp->nrule++; - rp->nextlhs = rp->lhs->rule; - rp->lhs->rule = rp; - rp->next = 0; - if( psp->firstrule==0 ){ - psp->firstrule = psp->lastrule = rp; - }else{ - psp->lastrule->next = rp; - psp->lastrule = rp; - } - psp->prevrule = rp; - } - psp->state = WAITING_FOR_DECL_OR_RULE; - }else if( isalpha(x[0]) ){ - if( psp->nrhs>=MAXRHS ){ - ErrorMsg(psp->filename,psp->tokenlineno, - "Too many symbols on RHS of rule beginning at \"%s\".", - x); - psp->errorcnt++; - psp->state = RESYNC_AFTER_RULE_ERROR; - }else{ - psp->rhs[psp->nrhs] = Symbol_new(x); - psp->alias[psp->nrhs] = 0; - psp->nrhs++; - } - }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){ - struct symbol *msp = psp->rhs[psp->nrhs-1]; - if( msp->type!=MULTITERMINAL ){ - struct symbol *origsp = msp; - msp = (struct symbol *) calloc(1,sizeof(*msp)); - memset(msp, 0, sizeof(*msp)); - msp->type = MULTITERMINAL; - msp->nsubsym = 1; - msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*)); - msp->subsym[0] = origsp; - msp->name = origsp->name; - psp->rhs[psp->nrhs-1] = msp; - } - msp->nsubsym++; - msp->subsym = (struct symbol **) realloc(msp->subsym, - sizeof(struct symbol*)*msp->nsubsym); - msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]); - if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){ - ErrorMsg(psp->filename,psp->tokenlineno, - "Cannot form a compound containing a non-terminal"); - psp->errorcnt++; - } - }else if( x[0]=='(' && psp->nrhs>0 ){ - psp->state = RHS_ALIAS_1; - }else{ - ErrorMsg(psp->filename,psp->tokenlineno, - "Illegal character on RHS of rule: \"%s\".",x); - psp->errorcnt++; - psp->state = RESYNC_AFTER_RULE_ERROR; - } - break; - case RHS_ALIAS_1: - if( isalpha(x[0]) ){ - psp->alias[psp->nrhs-1] = x; - psp->state = RHS_ALIAS_2; - }else{ - ErrorMsg(psp->filename,psp->tokenlineno, - "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n", - x,psp->rhs[psp->nrhs-1]->name); - psp->errorcnt++; - psp->state = RESYNC_AFTER_RULE_ERROR; - } - break; - case RHS_ALIAS_2: - if( x[0]==')' ){ - psp->state = IN_RHS; - }else{ - ErrorMsg(psp->filename,psp->tokenlineno, - "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias); - psp->errorcnt++; - psp->state = RESYNC_AFTER_RULE_ERROR; - } - break; - case WAITING_FOR_DECL_KEYWORD: - if( isalpha(x[0]) ){ - psp->declkeyword = x; - psp->declargslot = 0; - psp->decllinenoslot = 0; - psp->insertLineMacro = 1; - psp->state = WAITING_FOR_DECL_ARG; - if( strcmp(x,"name")==0 ){ - psp->declargslot = &(psp->gp->name); - psp->insertLineMacro = 0; - }else if( strcmp(x,"include")==0 ){ - psp->declargslot = &(psp->gp->include); - }else if( strcmp(x,"code")==0 ){ - psp->declargslot = &(psp->gp->extracode); - }else if( strcmp(x,"token_destructor")==0 ){ - psp->declargslot = &psp->gp->tokendest; - }else if( strcmp(x,"default_destructor")==0 ){ - psp->declargslot = &psp->gp->vardest; - }else if( strcmp(x,"token_prefix")==0 ){ - psp->declargslot = &psp->gp->tokenprefix; - psp->insertLineMacro = 0; - }else if( strcmp(x,"syntax_error")==0 ){ - psp->declargslot = &(psp->gp->error); - }else if( strcmp(x,"parse_accept")==0 ){ - psp->declargslot = &(psp->gp->accept); - }else if( strcmp(x,"parse_failure")==0 ){ - psp->declargslot = &(psp->gp->failure); - }else if( strcmp(x,"stack_overflow")==0 ){ - psp->declargslot = &(psp->gp->overflow); - }else if( strcmp(x,"extra_argument")==0 ){ - psp->declargslot = &(psp->gp->arg); - psp->insertLineMacro = 0; - }else if( strcmp(x,"token_type")==0 ){ - psp->declargslot = &(psp->gp->tokentype); - psp->insertLineMacro = 0; - }else if( strcmp(x,"default_type")==0 ){ - psp->declargslot = &(psp->gp->vartype); - psp->insertLineMacro = 0; - }else if( strcmp(x,"stack_size")==0 ){ - psp->declargslot = &(psp->gp->stacksize); - psp->insertLineMacro = 0; - }else if( strcmp(x,"start_symbol")==0 ){ - psp->declargslot = &(psp->gp->start); - psp->insertLineMacro = 0; - }else if( strcmp(x,"left")==0 ){ - psp->preccounter++; - psp->declassoc = LEFT; - psp->state = WAITING_FOR_PRECEDENCE_SYMBOL; - }else if( strcmp(x,"right")==0 ){ - psp->preccounter++; - psp->declassoc = RIGHT; - psp->state = WAITING_FOR_PRECEDENCE_SYMBOL; - }else if( strcmp(x,"nonassoc")==0 ){ - psp->preccounter++; - psp->declassoc = NONE; - psp->state = WAITING_FOR_PRECEDENCE_SYMBOL; - }else if( strcmp(x,"destructor")==0 ){ - psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL; - }else if( strcmp(x,"type")==0 ){ - psp->state = WAITING_FOR_DATATYPE_SYMBOL; - }else if( strcmp(x,"fallback")==0 ){ - psp->fallback = 0; - psp->state = WAITING_FOR_FALLBACK_ID; - }else if( strcmp(x,"wildcard")==0 ){ - psp->state = WAITING_FOR_WILDCARD_ID; -#if __MOJOSHADER__ - }else if( strcmp(x,"expect")==0 ){ - if (psp->gp->nexpected >= 0) { - ErrorMsg(psp->filename,psp->tokenlineno, "Multiple %expect declarations."); - psp->errorcnt++; - psp->state = RESYNC_AFTER_DECL_ERROR; - } else { - psp->state = WAITING_FOR_EXPECT_VALUE; - } -#endif - }else{ - ErrorMsg(psp->filename,psp->tokenlineno, - "Unknown declaration keyword: \"%%%s\".",x); - psp->errorcnt++; - psp->state = RESYNC_AFTER_DECL_ERROR; - } - }else{ - ErrorMsg(psp->filename,psp->tokenlineno, - "Illegal declaration keyword: \"%s\".",x); - psp->errorcnt++; - psp->state = RESYNC_AFTER_DECL_ERROR; - } - break; - case WAITING_FOR_DESTRUCTOR_SYMBOL: - if( !isalpha(x[0]) ){ - ErrorMsg(psp->filename,psp->tokenlineno, - "Symbol name missing after %%destructor keyword"); - psp->errorcnt++; - psp->state = RESYNC_AFTER_DECL_ERROR; - }else{ - struct symbol *sp = Symbol_new(x); - psp->declargslot = &sp->destructor; - psp->decllinenoslot = &sp->destLineno; - psp->insertLineMacro = 1; - psp->state = WAITING_FOR_DECL_ARG; - } - break; -#if __MOJOSHADER__ - case WAITING_FOR_EXPECT_VALUE: - psp->gp->nexpected = (int) strtol(x, &endptr, 10); - if( (*endptr != '\0') || (endptr == x) ) { - ErrorMsg(psp->filename,psp->tokenlineno, - "Integer expected after %%expect keyword"); - psp->errorcnt++; - } else if (psp->gp->nexpected < 0) { - ErrorMsg(psp->filename,psp->tokenlineno, - "Integer can't be negative after %%expect keyword"); - psp->errorcnt++; - } - psp->state = WAITING_FOR_DECL_OR_RULE; - break; -#endif - case WAITING_FOR_DATATYPE_SYMBOL: - if( !isalpha(x[0]) ){ - ErrorMsg(psp->filename,psp->tokenlineno, - "Symbol name missing after %%type keyword"); - psp->errorcnt++; - psp->state = RESYNC_AFTER_DECL_ERROR; - }else{ - struct symbol *sp = Symbol_find(x); - if((sp) && (sp->datatype)){ - ErrorMsg(psp->filename,psp->tokenlineno, - "Symbol %%type \"%s\" already defined", x); - psp->errorcnt++; - psp->state = RESYNC_AFTER_DECL_ERROR; - }else{ - if (!sp){ - sp = Symbol_new(x); - } - psp->declargslot = &sp->datatype; - psp->insertLineMacro = 0; - psp->state = WAITING_FOR_DECL_ARG; - } - } - break; - case WAITING_FOR_PRECEDENCE_SYMBOL: - if( x[0]=='.' ){ - psp->state = WAITING_FOR_DECL_OR_RULE; - }else if( isupper(x[0]) ){ - struct symbol *sp; - sp = Symbol_new(x); - if( sp->prec>=0 ){ - ErrorMsg(psp->filename,psp->tokenlineno, - "Symbol \"%s\" has already be given a precedence.",x); - psp->errorcnt++; - }else{ - sp->prec = psp->preccounter; - sp->assoc = psp->declassoc; - } - }else{ - ErrorMsg(psp->filename,psp->tokenlineno, - "Can't assign a precedence to \"%s\".",x); - psp->errorcnt++; - } - break; - case WAITING_FOR_DECL_ARG: - if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){ - const char *zOld, *zNew; - char *zBuf, *z; - int nOld, n, nLine, nNew, nBack; - int addLineMacro; - char zLine[50]; - zNew = x; - if( zNew[0]=='"' || zNew[0]=='{' ) zNew++; - nNew = lemonStrlen(zNew); - if( *psp->declargslot ){ - zOld = *psp->declargslot; - }else{ - zOld = ""; - } - nOld = lemonStrlen(zOld); - n = nOld + nNew + 20; - addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro && - (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0); - if( addLineMacro ){ - for(z=psp->filename, nBack=0; *z; z++){ - if( *z=='\\' ) nBack++; - } - sprintf(zLine, "#line %d ", psp->tokenlineno); - nLine = lemonStrlen(zLine); - n += nLine + lemonStrlen(psp->filename) + nBack; - } - *psp->declargslot = (char *) realloc(*psp->declargslot, n); - zBuf = *psp->declargslot + nOld; - if( addLineMacro ){ - if( nOld && zBuf[-1]!='\n' ){ - *(zBuf++) = '\n'; - } - memcpy(zBuf, zLine, nLine); - zBuf += nLine; - *(zBuf++) = '"'; - for(z=psp->filename; *z; z++){ - if( *z=='\\' ){ - *(zBuf++) = '\\'; - } - *(zBuf++) = *z; - } - *(zBuf++) = '"'; - *(zBuf++) = '\n'; - } - if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){ - psp->decllinenoslot[0] = psp->tokenlineno; - } - memcpy(zBuf, zNew, nNew); - zBuf += nNew; - *zBuf = 0; - psp->state = WAITING_FOR_DECL_OR_RULE; - }else{ - ErrorMsg(psp->filename,psp->tokenlineno, - "Illegal argument to %%%s: %s",psp->declkeyword,x); - psp->errorcnt++; - psp->state = RESYNC_AFTER_DECL_ERROR; - } - break; - case WAITING_FOR_FALLBACK_ID: - if( x[0]=='.' ){ - psp->state = WAITING_FOR_DECL_OR_RULE; - }else if( !isupper(x[0]) ){ - ErrorMsg(psp->filename, psp->tokenlineno, - "%%fallback argument \"%s\" should be a token", x); - psp->errorcnt++; - }else{ - struct symbol *sp = Symbol_new(x); - if( psp->fallback==0 ){ - psp->fallback = sp; - }else if( sp->fallback ){ - ErrorMsg(psp->filename, psp->tokenlineno, - "More than one fallback assigned to token %s", x); - psp->errorcnt++; - }else{ - sp->fallback = psp->fallback; - psp->gp->has_fallback = 1; - } - } - break; - case WAITING_FOR_WILDCARD_ID: - if( x[0]=='.' ){ - psp->state = WAITING_FOR_DECL_OR_RULE; - }else if( !isupper(x[0]) ){ - ErrorMsg(psp->filename, psp->tokenlineno, - "%%wildcard argument \"%s\" should be a token", x); - psp->errorcnt++; - }else{ - struct symbol *sp = Symbol_new(x); - if( psp->gp->wildcard==0 ){ - psp->gp->wildcard = sp; - }else{ - ErrorMsg(psp->filename, psp->tokenlineno, - "Extra wildcard to token: %s", x); - psp->errorcnt++; - } - } - break; - case RESYNC_AFTER_RULE_ERROR: -/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE; -** break; */ - case RESYNC_AFTER_DECL_ERROR: - if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE; - if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD; - break; - } -} - -/* Run the preprocessor over the input file text. The global variables -** azDefine[0] through azDefine[nDefine-1] contains the names of all defined -** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and -** comments them out. Text in between is also commented out as appropriate. -*/ -static void preprocess_input(char *z){ - int i, j, k, n; - int exclude = 0; - int start = 0; - int lineno = 1; - int start_lineno = 1; - for(i=0; z[i]; i++){ - if( z[i]=='\n' ) lineno++; - if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue; - if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){ - if( exclude ){ - exclude--; - if( exclude==0 ){ - for(j=start; jfilename; - ps.errorcnt = 0; - ps.state = INITIALIZE; - - /* Begin by reading the input file */ - fp = fopen(ps.filename,"rb"); - if( fp==0 ){ - ErrorMsg(ps.filename,0,"Can't open this file for reading."); - gp->errorcnt++; - return; - } - fseek(fp,0,2); - filesize = ftell(fp); - rewind(fp); - filebuf = (char *)malloc( filesize+1 ); - if( filebuf==0 ){ - ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.", - filesize+1); - gp->errorcnt++; - return; - } - if( fread(filebuf,1,filesize,fp)!=filesize ){ - ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.", - filesize); - free(filebuf); - gp->errorcnt++; - return; - } - fclose(fp); - filebuf[filesize] = 0; - - /* Make an initial pass through the file to handle %ifdef and %ifndef */ - preprocess_input(filebuf); - - /* Now scan the text of the input file */ - lineno = 1; - for(cp=filebuf; (c= *cp)!=0; ){ - if( c=='\n' ) lineno++; /* Keep track of the line number */ - if( isspace(c) ){ cp++; continue; } /* Skip all white space */ - if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */ - cp+=2; - while( (c= *cp)!=0 && c!='\n' ) cp++; - continue; - } - if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */ - cp+=2; - while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){ - if( c=='\n' ) lineno++; - cp++; - } - if( c ) cp++; - continue; - } - ps.tokenstart = cp; /* Mark the beginning of the token */ - ps.tokenlineno = lineno; /* Linenumber on which token begins */ - if( c=='\"' ){ /* String literals */ - cp++; - while( (c= *cp)!=0 && c!='\"' ){ - if( c=='\n' ) lineno++; - cp++; - } - if( c==0 ){ - ErrorMsg(ps.filename,startline, -"String starting on this line is not terminated before the end of the file."); - ps.errorcnt++; - nextcp = cp; - }else{ - nextcp = cp+1; - } - }else if( c=='{' ){ /* A block of C code */ - int level; - cp++; - for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){ - if( c=='\n' ) lineno++; - else if( c=='{' ) level++; - else if( c=='}' ) level--; - else if( c=='/' && cp[1]=='*' ){ /* Skip comments */ - int prevc; - cp = &cp[2]; - prevc = 0; - while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){ - if( c=='\n' ) lineno++; - prevc = c; - cp++; - } - }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */ - cp = &cp[2]; - while( (c= *cp)!=0 && c!='\n' ) cp++; - if( c ) lineno++; - }else if( c=='\'' || c=='\"' ){ /* String a character literals */ - int startchar, prevc; - startchar = c; - prevc = 0; - for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){ - if( c=='\n' ) lineno++; - if( prevc=='\\' ) prevc = 0; - else prevc = c; - } - } - } - if( c==0 ){ - ErrorMsg(ps.filename,ps.tokenlineno, -"C code starting on this line is not terminated before the end of the file."); - ps.errorcnt++; - nextcp = cp; - }else{ - nextcp = cp+1; - } - }else if( isalnum(c) ){ /* Identifiers */ - while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++; - nextcp = cp; - }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */ - cp += 3; - nextcp = cp; - }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){ - cp += 2; - while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++; - nextcp = cp; - }else{ /* All other (one character) operators */ - cp++; - nextcp = cp; - } - c = *cp; - *cp = 0; /* Null terminate the token */ - parseonetoken(&ps); /* Parse the token */ - *cp = c; /* Restore the buffer */ - cp = nextcp; - } - free(filebuf); /* Release the buffer after parsing */ - gp->rule = ps.firstrule; - gp->errorcnt = ps.errorcnt; -} -/*************************** From the file "plink.c" *********************/ -/* -** Routines processing configuration follow-set propagation links -** in the LEMON parser generator. -*/ -static struct plink *plink_freelist = 0; - -/* Allocate a new plink */ -struct plink *Plink_new(){ - struct plink *newlink; - - if( plink_freelist==0 ){ - int i; - int amt = 100; - plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) ); - if( plink_freelist==0 ){ - fprintf(stderr, - "Unable to allocate memory for a new follow-set propagation link.\n"); - exit(1); - } - for(i=0; inext; - return newlink; -} - -/* Add a plink to a plink list */ -void Plink_add(struct plink **plpp, struct config *cfp) -{ - struct plink *newlink; - newlink = Plink_new(); - newlink->next = *plpp; - *plpp = newlink; - newlink->cfp = cfp; -} - -/* Transfer every plink on the list "from" to the list "to" */ -void Plink_copy(struct plink **to, struct plink *from) -{ - struct plink *nextpl; - while( from ){ - nextpl = from->next; - from->next = *to; - *to = from; - from = nextpl; - } -} - -/* Delete every plink on the list */ -void Plink_delete(struct plink *plp) -{ - struct plink *nextpl; - - while( plp ){ - nextpl = plp->next; - plp->next = plink_freelist; - plink_freelist = plp; - plp = nextpl; - } -} -/*********************** From the file "report.c" **************************/ -/* -** Procedures for generating reports and tables in the LEMON parser generator. -*/ - -/* Generate a filename with the given suffix. Space to hold the -** name comes from malloc() and must be freed by the calling -** function. -*/ -PRIVATE char *file_makename(struct lemon *lemp, const char *suffix) -{ - char *name; - char *cp; - - name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 ); - if( name==0 ){ - fprintf(stderr,"Can't allocate space for a filename.\n"); - exit(1); - } - strcpy(name,lemp->filename); - cp = strrchr(name,'.'); - if( cp ) *cp = 0; - strcat(name,suffix); - return name; -} - -/* Open a file with a name based on the name of the input file, -** but with a different (specified) suffix, and return a pointer -** to the stream */ -PRIVATE FILE *file_open( - struct lemon *lemp, - const char *suffix, - const char *mode -){ - FILE *fp; - - if( lemp->outname ) free(lemp->outname); - lemp->outname = file_makename(lemp, suffix); - fp = fopen(lemp->outname,mode); - if( fp==0 && *mode=='w' ){ - fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname); - lemp->errorcnt++; - return 0; - } - - /* Add files we create to a list, so we can delete them if we fail. This - ** is to keep makefiles from getting confused. We don't include .out files, - ** though: this is debug information, and you don't want it deleted if there - ** was an error you need to track down. - */ - if(( *mode=='w' ) && (strcmp(suffix, ".out") != 0)){ - const char **ptr = (const char **) - realloc(made_files, sizeof (const char *) * (made_files_count + 1)); - const char *fname = Strsafe(lemp->outname); - if ((ptr == NULL) || (fname == NULL)) { - free(ptr); - memory_error(); - } - made_files = ptr; - made_files[made_files_count++] = fname; - } - return fp; -} - -/* Duplicate the input file without comments and without actions -** on rules */ -void Reprint(struct lemon *lemp) -{ - struct rule *rp; - struct symbol *sp; - int i, j, maxlen, len, ncolumns, skip; - printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename); - maxlen = 10; - for(i=0; insymbol; i++){ - sp = lemp->symbols[i]; - len = lemonStrlen(sp->name); - if( len>maxlen ) maxlen = len; - } - ncolumns = 76/(maxlen+5); - if( ncolumns<1 ) ncolumns = 1; - skip = (lemp->nsymbol + ncolumns - 1)/ncolumns; - for(i=0; insymbol; j+=skip){ - sp = lemp->symbols[j]; - assert( sp->index==j ); - printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name); - } - printf("\n"); - } - for(rp=lemp->rule; rp; rp=rp->next){ - printf("%s",rp->lhs->name); - /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */ - printf(" ::="); - for(i=0; inrhs; i++){ - sp = rp->rhs[i]; - printf(" %s", sp->name); - if( sp->type==MULTITERMINAL ){ - for(j=1; jnsubsym; j++){ - printf("|%s", sp->subsym[j]->name); - } - } - /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */ - } - printf("."); - if( rp->precsym ) printf(" [%s]",rp->precsym->name); - /* if( rp->code ) printf("\n %s",rp->code); */ - printf("\n"); - } -} - -void ConfigPrint(FILE *fp, struct config *cfp) -{ - struct rule *rp; - struct symbol *sp; - int i, j; - rp = cfp->rp; - fprintf(fp,"%s ::=",rp->lhs->name); - for(i=0; i<=rp->nrhs; i++){ - if( i==cfp->dot ) fprintf(fp," *"); - if( i==rp->nrhs ) break; - sp = rp->rhs[i]; - fprintf(fp," %s", sp->name); - if( sp->type==MULTITERMINAL ){ - for(j=1; jnsubsym; j++){ - fprintf(fp,"|%s",sp->subsym[j]->name); - } - } - } -} - -/* #define TEST */ -#if 0 -/* Print a set */ -PRIVATE void SetPrint(out,set,lemp) -FILE *out; -char *set; -struct lemon *lemp; -{ - int i; - char *spacer; - spacer = ""; - fprintf(out,"%12s[",""); - for(i=0; interminal; i++){ - if( SetFind(set,i) ){ - fprintf(out,"%s%s",spacer,lemp->symbols[i]->name); - spacer = " "; - } - } - fprintf(out,"]\n"); -} - -/* Print a plink chain */ -PRIVATE void PlinkPrint(out,plp,tag) -FILE *out; -struct plink *plp; -char *tag; -{ - while( plp ){ - fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum); - ConfigPrint(out,plp->cfp); - fprintf(out,"\n"); - plp = plp->next; - } -} -#endif - -/* Print an action to the given file descriptor. Return FALSE if -** nothing was actually printed. -*/ -int PrintAction(struct action *ap, FILE *fp, int indent){ - int result = 1; - switch( ap->type ){ - case SHIFT: - fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum); - break; - case REDUCE: - fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index); - break; - case ACCEPT: - fprintf(fp,"%*s accept",indent,ap->sp->name); - break; - case ERROR: - fprintf(fp,"%*s error",indent,ap->sp->name); - break; - case SRCONFLICT: - case RRCONFLICT: - fprintf(fp,"%*s reduce %-3d ** Parsing conflict **", - indent,ap->sp->name,ap->x.rp->index); - break; - case SSCONFLICT: - fprintf(fp,"%*s shift %d ** Parsing conflict **", - indent,ap->sp->name,ap->x.stp->statenum); - break; - case SH_RESOLVED: - case RD_RESOLVED: - case NOT_USED: - result = 0; - break; - } - return result; -} - -/* Generate the "y.output" log file */ -void ReportOutput(struct lemon *lemp) -{ - int i; - struct state *stp; - struct config *cfp; - struct action *ap; - FILE *fp; - - fp = file_open(lemp,".out","wb"); - if( fp==0 ) return; - for(i=0; instate; i++){ - stp = lemp->sorted[i]; - fprintf(fp,"State %d:\n",stp->statenum); - if( lemp->basisflag ) cfp=stp->bp; - else cfp=stp->cfp; - while( cfp ){ - char buf[20]; - if( cfp->dot==cfp->rp->nrhs ){ - sprintf(buf,"(%d)",cfp->rp->index); - fprintf(fp," %5s ",buf); - }else{ - fprintf(fp," "); - } - ConfigPrint(fp,cfp); - fprintf(fp,"\n"); -#if 0 - SetPrint(fp,cfp->fws,lemp); - PlinkPrint(fp,cfp->fplp,"To "); - PlinkPrint(fp,cfp->bplp,"From"); -#endif - if( lemp->basisflag ) cfp=cfp->bp; - else cfp=cfp->next; - } - fprintf(fp,"\n"); - for(ap=stp->ap; ap; ap=ap->next){ - if( PrintAction(ap,fp,30) ) fprintf(fp,"\n"); - } - fprintf(fp,"\n"); - } - fprintf(fp, "----------------------------------------------------\n"); - fprintf(fp, "Symbols:\n"); - for(i=0; insymbol; i++){ - int j; - struct symbol *sp; - - sp = lemp->symbols[i]; - fprintf(fp, " %3d: %s", i, sp->name); - if( sp->type==NONTERMINAL ){ - fprintf(fp, ":"); - if( sp->lambda ){ - fprintf(fp, " "); - } - for(j=0; jnterminal; j++){ - if( sp->firstset && SetFind(sp->firstset, j) ){ - fprintf(fp, " %s", lemp->symbols[j]->name); - } - } - } - fprintf(fp, "\n"); - } - fclose(fp); - return; -} - -/* Search for the file "name" which is in the same directory as -** the exacutable */ -PRIVATE char *pathsearch(char *argv0, char *name, int modemask) -{ - const char *pathlist; - char *pathbufptr; - char *pathbuf; - char *path,*cp; - char c; - -#ifdef __WIN32__ - cp = strrchr(argv0,'\\'); -#else - cp = strrchr(argv0,'/'); -#endif - if( cp ){ - c = *cp; - *cp = 0; - path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 ); - if( path ) sprintf(path,"%s/%s",argv0,name); - *cp = c; - }else{ - pathlist = getenv("PATH"); - if( pathlist==0 ) pathlist = ".:/bin:/usr/bin"; - pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 ); - path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 ); - if( (pathbuf != 0) && (path!=0) ){ - pathbufptr = pathbuf; - strcpy(pathbuf, pathlist); - while( *pathbuf ){ - cp = strchr(pathbuf,':'); - if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)]; - c = *cp; - *cp = 0; - sprintf(path,"%s/%s",pathbuf,name); - *cp = c; - if( c==0 ) pathbuf[0] = 0; - else pathbuf = &cp[1]; - if( access(path,modemask)==0 ) break; - } - free(pathbufptr); - } - } - return path; -} - -/* Given an action, compute the integer value for that action -** which is to be put in the action table of the generated machine. -** Return negative if no action should be generated. -*/ -PRIVATE int compute_action(struct lemon *lemp, struct action *ap) -{ - int act; - switch( ap->type ){ - case SHIFT: act = ap->x.stp->statenum; break; - case REDUCE: act = ap->x.rp->index + lemp->nstate; break; - case ERROR: act = lemp->nstate + lemp->nrule; break; - case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break; - default: act = -1; break; - } - return act; -} - -#define LINESIZE 1000 -/* The next cluster of routines are for reading the template file -** and writing the results to the generated parser */ -/* The first function transfers data from "in" to "out" until -** a line is seen which begins with "%%". The line number is -** tracked. -** -** if name!=0, then any word that begin with "Parse" is changed to -** begin with *name instead. -*/ -PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno) -{ - int i, iStart; - char line[LINESIZE]; - while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){ - (*lineno)++; - iStart = 0; - if( name ){ - for(i=0; line[i]; i++){ - if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0 - && (i==0 || !isalpha(line[i-1])) - ){ - if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]); - fprintf(out,"%s",name); - i += 4; - iStart = i+1; - } - } - } - fprintf(out,"%s",&line[iStart]); - } -} - -/* The next function finds the template file and opens it, returning -** a pointer to the opened file. */ -PRIVATE FILE *tplt_open(struct lemon *lemp) -{ - static char templatename[] = "lempar.c"; - char buf[1000]; - FILE *in; - char *tpltname; - char *cp; - - /* first, see if user specified a template filename on the command line. */ - if (user_templatename != 0) { - if( access(user_templatename,004)==-1 ){ - fprintf(stderr,"Can't find the parser driver template file \"%s\".\n", - user_templatename); - lemp->errorcnt++; - return 0; - } - in = fopen(user_templatename,"rb"); - if( in==0 ){ - fprintf(stderr,"Can't open the template file \"%s\".\n",user_templatename); - lemp->errorcnt++; - return 0; - } - return in; - } - - cp = strrchr(lemp->filename,'.'); - if( cp ){ - sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename); - }else{ - sprintf(buf,"%s.lt",lemp->filename); - } - if( access(buf,004)==0 ){ - tpltname = buf; - }else if( access(templatename,004)==0 ){ - tpltname = templatename; - }else{ - tpltname = pathsearch(lemp->argv0,templatename,0); - } - if( tpltname==0 ){ - fprintf(stderr,"Can't find the parser driver template file \"%s\".\n", - templatename); - lemp->errorcnt++; - return 0; - } - in = fopen(tpltname,"rb"); - if( in==0 ){ - fprintf(stderr,"Can't open the template file \"%s\".\n",templatename); - lemp->errorcnt++; - return 0; - } - return in; -} - -/* Print a #line directive line to the output file. */ -PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename) -{ - fprintf(out,"#line %d \"",lineno); - while( *filename ){ - if( *filename == '\\' ) putc('\\',out); - putc(*filename,out); - filename++; - } - fprintf(out,"\"\n"); -} - -/* Print a string to the file and keep the linenumber up to date */ -PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno) -{ - if( str==0 ) return; - while( *str ){ - putc(*str,out); - if( *str=='\n' ) (*lineno)++; - str++; - } - if( str[-1]!='\n' ){ - putc('\n',out); - (*lineno)++; - } - if (!lemp->nolinenosflag) { - (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); - } - return; -} - -/* -** The following routine emits code for the destructor for the -** symbol sp -*/ -void emit_destructor_code( - FILE *out, - struct symbol *sp, - struct lemon *lemp, - int *lineno -){ - char *cp = 0; - - if( sp->type==TERMINAL ){ - cp = lemp->tokendest; - if( cp==0 ) return; - fprintf(out,"{\n"); (*lineno)++; - }else if( sp->destructor ){ - cp = sp->destructor; - fprintf(out,"{\n"); (*lineno)++; - if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); } - }else if( lemp->vardest ){ - cp = lemp->vardest; - if( cp==0 ) return; - fprintf(out,"{\n"); (*lineno)++; - }else{ - assert( 0 ); /* Cannot happen */ - } - for(; *cp; cp++){ - if( *cp=='$' && cp[1]=='$' ){ - fprintf(out,"(yypminor->yy%d)",sp->dtnum); - cp++; - continue; - } - if( *cp=='\n' ) (*lineno)++; - fputc(*cp,out); - } - fprintf(out,"\n"); (*lineno)++; - if (!lemp->nolinenosflag) { - (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); - } - fprintf(out,"}\n"); (*lineno)++; - return; -} - -/* -** Return TRUE (non-zero) if the given symbol has a destructor. -*/ -int has_destructor(struct symbol *sp, struct lemon *lemp) -{ - int ret; - if( sp->type==TERMINAL ){ - ret = lemp->tokendest!=0; - }else{ - ret = lemp->vardest!=0 || sp->destructor!=0; - } - return ret; -} - -/* -** Append text to a dynamically allocated string. If zText is 0 then -** reset the string to be empty again. Always return the complete text -** of the string (which is overwritten with each call). -** -** n bytes of zText are stored. If n==0 then all of zText up to the first -** \000 terminator is stored. zText can contain up to two instances of -** %d. The values of p1 and p2 are written into the first and second -** %d. -** -** If n==-1, then the previous character is overwritten. -*/ -PRIVATE char *append_str(const char *zText, int n, int p1, int p2){ - static char empty[1] = { 0 }; - static char *z = 0; - static int alloced = 0; - static int used = 0; - int c; - char zInt[40]; - if( zText==0 ){ - used = 0; - return z; - } - if( n<=0 ){ - if( n<0 ){ - used += n; - assert( used>=0 ); - } - n = lemonStrlen(zText); - } - if( (int) (n+sizeof(zInt)*2+used) >= alloced ){ - alloced = n + sizeof(zInt)*2 + used + 200; - z = (char *) realloc(z, alloced); - } - if( z==0 ) return empty; - while( n-- > 0 ){ - c = *(zText++); - if( c=='%' && n>0 && zText[0]=='d' ){ - sprintf(zInt, "%d", p1); - p1 = p2; - strcpy(&z[used], zInt); - used += lemonStrlen(&z[used]); - zText++; - n--; - }else{ - z[used++] = c; - } - } - z[used] = 0; - return z; -} - -/* -** zCode is a string that is the action associated with a rule. Expand -** the symbols in this string so that the refer to elements of the parser -** stack. -*/ -PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){ - char *cp, *xp; - int i; - char lhsused = 0; /* True if the LHS element has been used */ - char used[MAXRHS]; /* True for each RHS element which is used */ - - for(i=0; inrhs; i++) used[i] = 0; - lhsused = 0; - - if( rp->code==0 ){ - static char newlinestr[2] = { '\n', '\0' }; - rp->code = newlinestr; - rp->line = rp->ruleline; - } - - append_str(0,0,0,0); - - /* This const cast is wrong but harmless, if we're careful. */ - for(cp=(char *)rp->code; *cp; cp++){ - if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){ - char saved; - for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++); - saved = *xp; - *xp = 0; - if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){ - append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0); - cp = xp; - lhsused = 1; - }else{ - for(i=0; inrhs; i++){ - if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){ - if( cp!=rp->code && cp[-1]=='@' ){ - /* If the argument is of the form @X then substituted - ** the token number of X, not the value of X */ - append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0); - }else{ - struct symbol *sp = rp->rhs[i]; - int dtnum; - if( sp->type==MULTITERMINAL ){ - dtnum = sp->subsym[0]->dtnum; - }else{ - dtnum = sp->dtnum; - } - append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum); - } - cp = xp; - used[i] = 1; - break; - } - } - } - *xp = saved; - } - append_str(cp, 1, 0, 0); - } /* End loop */ - - /* Check to make sure the LHS has been used */ - if( rp->lhsalias && !lhsused ){ - ErrorMsg(lemp->filename,rp->ruleline, - "Label \"%s\" for \"%s(%s)\" is never used.", - rp->lhsalias,rp->lhs->name,rp->lhsalias); - lemp->errorcnt++; - } - - /* Generate destructor code for RHS symbols which are not used in the - ** reduce code */ - for(i=0; inrhs; i++){ - if( rp->rhsalias[i] && !used[i] ){ - ErrorMsg(lemp->filename,rp->ruleline, - "Label %s for \"%s(%s)\" is never used.", - rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]); - lemp->errorcnt++; - }else if( rp->rhsalias[i]==0 ){ - if( has_destructor(rp->rhs[i],lemp) ){ - append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0, - rp->rhs[i]->index,i-rp->nrhs+1); - }else{ - /* No destructor defined for this term */ - } - } - } - if( rp->code ){ - cp = append_str(0,0,0,0); - rp->code = Strsafe(cp?cp:""); - } -} - -/* -** Generate code which executes when the rule "rp" is reduced. Write -** the code to "out". Make sure lineno stays up-to-date. -*/ -PRIVATE void emit_code( - FILE *out, - struct rule *rp, - struct lemon *lemp, - int *lineno -){ - const char *cp; - - /* Generate code to do the reduce action */ - if( rp->code ){ - if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); } - fprintf(out,"{%s",rp->code); - for(cp=rp->code; *cp; cp++){ - if( *cp=='\n' ) (*lineno)++; - } /* End loop */ - fprintf(out,"}\n"); (*lineno)++; - if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); } - } /* End if( rp->code ) */ - - return; -} - -/* -** Print the definition of the union used for the parser's data stack. -** This union contains fields for every possible data type for tokens -** and nonterminals. In the process of computing and printing this -** union, also set the ".dtnum" field of every terminal and nonterminal -** symbol. -*/ -void print_stack_union( - FILE *out, /* The output stream */ - struct lemon *lemp, /* The main info structure for this parser */ - int *plineno, /* Pointer to the line number */ - int mhflag /* True if generating makeheaders output */ -){ - int lineno = 0; /* The line number of the output */ - char **types; /* A hash table of datatypes */ - int arraysize; /* Size of the "types" array */ - int maxdtlength; /* Maximum length of any ".datatype" field. */ - char *stddt; /* Standardized name for a datatype */ - int i,j; /* Loop counters */ - int hash; /* For hashing the name of a type */ - const char *name; /* Name of the parser */ - - /* Allocate and initialize types[] and allocate stddt[] */ - arraysize = lemp->nsymbol * 2; - types = (char**)calloc( arraysize, sizeof(char*) ); - for(i=0; ivartype ){ - maxdtlength = lemonStrlen(lemp->vartype); - } - for(i=0; insymbol; i++){ - int len; - struct symbol *sp = lemp->symbols[i]; - if( sp->datatype==0 ) continue; - len = lemonStrlen(sp->datatype); - if( len>maxdtlength ) maxdtlength = len; - } - stddt = (char*)malloc( maxdtlength*2 + 1 ); - if( types==0 || stddt==0 ){ - fprintf(stderr,"Out of memory.\n"); - exit(1); - } - - /* Build a hash table of datatypes. The ".dtnum" field of each symbol - ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is - ** used for terminal symbols. If there is no %default_type defined then - ** 0 is also used as the .dtnum value for nonterminals which do not specify - ** a datatype using the %type directive. - */ - for(i=0; insymbol; i++){ - struct symbol *sp = lemp->symbols[i]; - char *cp; - if( sp==lemp->errsym ){ - sp->dtnum = arraysize+1; - continue; - } - if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){ - sp->dtnum = 0; - continue; - } - cp = sp->datatype; - if( cp==0 ) cp = lemp->vartype; - j = 0; - while( isspace(*cp) ) cp++; - while( *cp ) stddt[j++] = *cp++; - while( j>0 && isspace(stddt[j-1]) ) j--; - stddt[j] = 0; - if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){ - sp->dtnum = 0; - continue; - } - hash = 0; - for(j=0; stddt[j]; j++){ - hash = hash*53 + stddt[j]; - } - hash = (hash & 0x7fffffff)%arraysize; - while( types[hash] ){ - if( strcmp(types[hash],stddt)==0 ){ - sp->dtnum = hash + 1; - break; - } - hash++; - if( hash>=arraysize ) hash = 0; - } - if( types[hash]==0 ){ - sp->dtnum = hash + 1; - types[hash] = (char*)malloc( lemonStrlen(stddt)+1 ); - if( types[hash]==0 ){ - fprintf(stderr,"Out of memory.\n"); - exit(1); - } - strcpy(types[hash],stddt); - } - } - - /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */ - name = lemp->name ? lemp->name : "Parse"; - lineno = *plineno; - if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; } - fprintf(out,"#define %sTOKENTYPE %s\n",name, - lemp->tokentype?lemp->tokentype:"void*"); lineno++; - if( mhflag ){ fprintf(out,"#endif\n"); lineno++; } - fprintf(out,"typedef union {\n"); lineno++; - fprintf(out," int yyinit;\n"); lineno++; - fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++; - for(i=0; ierrsym->useCnt ){ - fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++; - } - free(stddt); - free(types); - fprintf(out,"} YYMINORTYPE;\n"); lineno++; - *plineno = lineno; -} - -/* -** Return the name of a C datatype able to represent values between -** lwr and upr, inclusive. -*/ -static const char *minimum_size_type(int lwr, int upr){ - if( lwr>=0 ){ - if( upr<=255 ){ - return "unsigned char"; - }else if( upr<65535 ){ - return "unsigned short int"; - }else{ - return "unsigned int"; - } - }else if( lwr>=-127 && upr<=127 ){ - return "signed char"; - }else if( lwr>=-32767 && upr<32767 ){ - return "short"; - }else{ - return "int"; - } -} - -/* -** Each state contains a set of token transaction and a set of -** nonterminal transactions. Each of these sets makes an instance -** of the following structure. An array of these structures is used -** to order the creation of entries in the yy_action[] table. -*/ -struct axset { - struct state *stp; /* A pointer to a state */ - int isTkn; /* True to use tokens. False for non-terminals */ - int nAction; /* Number of actions */ - int iOrder; /* Original order of action sets */ -}; - -/* -** Compare to axset structures for sorting purposes -*/ -static int axset_compare(const void *a, const void *b){ - struct axset *p1 = (struct axset*)a; - struct axset *p2 = (struct axset*)b; - int c; - c = p2->nAction - p1->nAction; - if( c==0 ){ - c = p2->iOrder - p1->iOrder; - } - assert( c!=0 || p1==p2 ); - return c; -} - -/* -** Write text on "out" that describes the rule "rp". -*/ -static void writeRuleText(FILE *out, struct rule *rp){ - int j; - fprintf(out,"%s ::=", rp->lhs->name); - for(j=0; jnrhs; j++){ - struct symbol *sp = rp->rhs[j]; - fprintf(out," %s", sp->name); - if( sp->type==MULTITERMINAL ){ - int k; - for(k=1; knsubsym; k++){ - fprintf(out,"|%s",sp->subsym[k]->name); - } - } - } -} - - -/* Generate C source code for the parser */ -void ReportTable( - struct lemon *lemp, - int mhflag /* Output in makeheaders format if true */ -){ - FILE *out, *in; - char line[LINESIZE]; - int lineno; - struct state *stp; - struct action *ap; - struct rule *rp; - struct acttab *pActtab; - int i, j, n; - const char *name; - int mnTknOfst, mxTknOfst; - int mnNtOfst, mxNtOfst; - struct axset *ax; - - in = tplt_open(lemp); - if( in==0 ) return; -#if __MOJOSHADER__ - out = file_open(lemp,".h","wb"); -#else - out = file_open(lemp,".c","wb"); -#endif - if( out==0 ){ - fclose(in); - return; - } - lineno = 1; - tplt_xfer(lemp->name,in,out,&lineno); - - /* Generate the include code, if any */ - tplt_print(out,lemp,lemp->include,&lineno); -#if !__MOJOSHADER__ - if( mhflag ){ - char *name = file_makename(lemp, ".h"); - fprintf(out,"#include \"%s\"\n", name); lineno++; - free(name); - } -#endif - tplt_xfer(lemp->name,in,out,&lineno); - - /* Generate #defines for all tokens */ -#if __MOJOSHADER__ - if( 1 ){ -#else - if( mhflag ){ -#endif - char *prefix; -#if !__MOJOSHADER__ - fprintf(out,"#if INTERFACE\n"); lineno++; -#endif - if( lemp->tokenprefix ) prefix = lemp->tokenprefix; - else prefix = ""; - for(i=1; interminal; i++){ - fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i); - lineno++; - } -#if !__MOJOSHADER__ - fprintf(out,"#endif\n"); lineno++; -#endif - } - tplt_xfer(lemp->name,in,out,&lineno); - - /* Generate the defines */ - fprintf(out,"#define YYCODETYPE %s\n", - minimum_size_type(0, lemp->nsymbol+1)); lineno++; - fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++; - fprintf(out,"#define YYACTIONTYPE %s\n", - minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++; - if( lemp->wildcard ){ - fprintf(out,"#define YYWILDCARD %d\n", - lemp->wildcard->index); lineno++; - } - print_stack_union(out,lemp,&lineno,mhflag); - fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++; - if( lemp->stacksize ){ - fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++; - }else{ - fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++; - } - fprintf(out, "#endif\n"); lineno++; - if( mhflag ){ - fprintf(out,"#if INTERFACE\n"); lineno++; - } - name = lemp->name ? lemp->name : "Parse"; - if( lemp->arg && lemp->arg[0] ){ - int i; - i = lemonStrlen(lemp->arg); - while( i>=1 && isspace(lemp->arg[i-1]) ) i--; - while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--; - fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++; - fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++; - fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n", - name,lemp->arg,&lemp->arg[i]); lineno++; - fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n", - name,&lemp->arg[i],&lemp->arg[i]); lineno++; - }else{ - fprintf(out,"#define %sARG_SDECL\n",name); lineno++; - fprintf(out,"#define %sARG_PDECL\n",name); lineno++; - fprintf(out,"#define %sARG_FETCH\n",name); lineno++; - fprintf(out,"#define %sARG_STORE\n",name); lineno++; - } - if( mhflag ){ - fprintf(out,"#endif\n"); lineno++; - } - fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++; - fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++; - if( lemp->errsym->useCnt ){ - fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++; - fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++; - } - if( lemp->has_fallback ){ - fprintf(out,"#define YYFALLBACK 1\n"); lineno++; - } - tplt_xfer(lemp->name,in,out,&lineno); - - /* Generate the action table and its associates: - ** - ** yy_action[] A single table containing all actions. - ** yy_lookahead[] A table containing the lookahead for each entry in - ** yy_action. Used to detect hash collisions. - ** yy_shift_ofst[] For each state, the offset into yy_action for - ** shifting terminals. - ** yy_reduce_ofst[] For each state, the offset into yy_action for - ** shifting non-terminals after a reduce. - ** yy_default[] Default action for each state. - */ - - /* Compute the actions on all states and count them up */ - ax = (struct axset *) calloc(lemp->nstate*2, sizeof(ax[0])); - if( ax==0 ){ - fprintf(stderr,"malloc failed\n"); - exit(1); - } - for(i=0; instate; i++){ - stp = lemp->sorted[i]; - ax[i*2].stp = stp; - ax[i*2].isTkn = 1; - ax[i*2].nAction = stp->nTknAct; - ax[i*2+1].stp = stp; - ax[i*2+1].isTkn = 0; - ax[i*2+1].nAction = stp->nNtAct; - } - mxTknOfst = mnTknOfst = 0; - mxNtOfst = mnNtOfst = 0; - - /* Compute the action table. In order to try to keep the size of the - ** action table to a minimum, the heuristic of placing the largest action - ** sets first is used. - */ - for(i=0; instate*2; i++) ax[i].iOrder = i; - qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare); - pActtab = acttab_alloc(); - for(i=0; instate*2 && ax[i].nAction>0; i++){ - stp = ax[i].stp; - if( ax[i].isTkn ){ - for(ap=stp->ap; ap; ap=ap->next){ - int action; - if( ap->sp->index>=lemp->nterminal ) continue; - action = compute_action(lemp, ap); - if( action<0 ) continue; - acttab_action(pActtab, ap->sp->index, action); - } - stp->iTknOfst = acttab_insert(pActtab); - if( stp->iTknOfstiTknOfst; - if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst; - }else{ - for(ap=stp->ap; ap; ap=ap->next){ - int action; - if( ap->sp->indexnterminal ) continue; - if( ap->sp->index==lemp->nsymbol ) continue; - action = compute_action(lemp, ap); - if( action<0 ) continue; - acttab_action(pActtab, ap->sp->index, action); - } - stp->iNtOfst = acttab_insert(pActtab); - if( stp->iNtOfstiNtOfst; - if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst; - } - } - free(ax); - - /* Output the yy_action table */ - n = acttab_size(pActtab); - fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++; - fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++; - for(i=j=0; instate + lemp->nrule + 2; - if( j==0 ) fprintf(out," /* %5d */ ", i); - fprintf(out, " %4d,", action); - if( j==9 || i==n-1 ){ - fprintf(out, "\n"); lineno++; - j = 0; - }else{ - j++; - } - } - fprintf(out, "};\n"); lineno++; - - /* Output the yy_lookahead table */ - fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++; - for(i=j=0; insymbol; - if( j==0 ) fprintf(out," /* %5d */ ", i); - fprintf(out, " %4d,", la); - if( j==9 || i==n-1 ){ - fprintf(out, "\n"); lineno++; - j = 0; - }else{ - j++; - } - } - fprintf(out, "};\n"); lineno++; - - /* Output the yy_shift_ofst[] table */ - fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++; - n = lemp->nstate; - while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--; - fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++; - fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++; - fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++; - fprintf(out, "static const %s yy_shift_ofst[] = {\n", - minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++; - for(i=j=0; isorted[i]; - ofst = stp->iTknOfst; - if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1; - if( j==0 ) fprintf(out," /* %5d */ ", i); - fprintf(out, " %4d,", ofst); - if( j==9 || i==n-1 ){ - fprintf(out, "\n"); lineno++; - j = 0; - }else{ - j++; - } - } - fprintf(out, "};\n"); lineno++; - - /* Output the yy_reduce_ofst[] table */ - fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++; - n = lemp->nstate; - while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--; - fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++; - fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++; - fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++; - fprintf(out, "static const %s yy_reduce_ofst[] = {\n", - minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++; - for(i=j=0; isorted[i]; - ofst = stp->iNtOfst; - if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1; - if( j==0 ) fprintf(out," /* %5d */ ", i); - fprintf(out, " %4d,", ofst); - if( j==9 || i==n-1 ){ - fprintf(out, "\n"); lineno++; - j = 0; - }else{ - j++; - } - } - fprintf(out, "};\n"); lineno++; - - /* Output the default action table */ - fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++; - n = lemp->nstate; - for(i=j=0; isorted[i]; - if( j==0 ) fprintf(out," /* %5d */ ", i); - fprintf(out, " %4d,", stp->iDflt); - if( j==9 || i==n-1 ){ - fprintf(out, "\n"); lineno++; - j = 0; - }else{ - j++; - } - } - fprintf(out, "};\n"); lineno++; - tplt_xfer(lemp->name,in,out,&lineno); - - /* Generate the table of fallback tokens. - */ - if( lemp->has_fallback ){ - int mx = lemp->nterminal - 1; - while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; } - for(i=0; i<=mx; i++){ - struct symbol *p = lemp->symbols[i]; - if( p->fallback==0 ){ - fprintf(out, " 0, /* %10s => nothing */\n", p->name); - }else{ - fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index, - p->name, p->fallback->name); - } - lineno++; - } - } - tplt_xfer(lemp->name, in, out, &lineno); - - /* Generate a table containing the symbolic name of every symbol - */ - for(i=0; insymbol; i++){ - sprintf(line,"\"%s\",",lemp->symbols[i]->name); - fprintf(out," %-15s",line); - if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; } - } - if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; } - tplt_xfer(lemp->name,in,out,&lineno); - - /* Generate a table containing a text string that describes every - ** rule in the rule set of the grammar. This information is used - ** when tracing REDUCE actions. - */ - for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){ - assert( rp->index==i ); - fprintf(out," /* %3d */ \"", i); - writeRuleText(out, rp); - fprintf(out,"\",\n"); lineno++; - } - tplt_xfer(lemp->name,in,out,&lineno); - - /* Generate code which executes every time a symbol is popped from - ** the stack while processing errors or while destroying the parser. - ** (In other words, generate the %destructor actions) - */ - if( lemp->tokendest ){ - int once = 1; - for(i=0; insymbol; i++){ - struct symbol *sp = lemp->symbols[i]; - if( sp==0 || sp->type!=TERMINAL ) continue; - if( once ){ - fprintf(out, " /* TERMINAL Destructor */\n"); lineno++; - once = 0; - } - fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++; - } - for(i=0; insymbol && lemp->symbols[i]->type!=TERMINAL; i++); - if( insymbol ){ - emit_destructor_code(out,lemp->symbols[i],lemp,&lineno); - fprintf(out," break;\n"); lineno++; - } - } - if( lemp->vardest ){ - struct symbol *dflt_sp = 0; - int once = 1; - for(i=0; insymbol; i++){ - struct symbol *sp = lemp->symbols[i]; - if( sp==0 || sp->type==TERMINAL || - sp->index<=0 || sp->destructor!=0 ) continue; - if( once ){ - fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++; - once = 0; - } - fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++; - dflt_sp = sp; - } - if( dflt_sp!=0 ){ - emit_destructor_code(out,dflt_sp,lemp,&lineno); - } - fprintf(out," break;\n"); lineno++; - } - for(i=0; insymbol; i++){ - struct symbol *sp = lemp->symbols[i]; - if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue; - fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++; - - /* Combine duplicate destructors into a single case */ - for(j=i+1; jnsymbol; j++){ - struct symbol *sp2 = lemp->symbols[j]; - if( sp2 && sp2->type!=TERMINAL && sp2->destructor - && sp2->dtnum==sp->dtnum - && strcmp(sp->destructor,sp2->destructor)==0 ){ - fprintf(out," case %d: /* %s */\n", - sp2->index, sp2->name); lineno++; - sp2->destructor = 0; - } - } - - emit_destructor_code(out,lemp->symbols[i],lemp,&lineno); - fprintf(out," break;\n"); lineno++; - } - tplt_xfer(lemp->name,in,out,&lineno); - - /* Generate code which executes whenever the parser stack overflows */ - tplt_print(out,lemp,lemp->overflow,&lineno); - tplt_xfer(lemp->name,in,out,&lineno); - - /* Generate the table of rule information - ** - ** Note: This code depends on the fact that rules are number - ** sequentually beginning with 0. - */ - for(rp=lemp->rule; rp; rp=rp->next){ - fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++; - } - tplt_xfer(lemp->name,in,out,&lineno); - - /* Generate code which execution during each REDUCE action */ - for(rp=lemp->rule; rp; rp=rp->next){ - translate_code(lemp, rp); - } - /* First output rules other than the default: rule */ - for(rp=lemp->rule; rp; rp=rp->next){ - struct rule *rp2; /* Other rules with the same action */ - if( rp->code==0 ) continue; - if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */ - fprintf(out," case %d: /* ", rp->index); - writeRuleText(out, rp); - fprintf(out, " */\n"); lineno++; - for(rp2=rp->next; rp2; rp2=rp2->next){ - if( rp2->code==rp->code ){ - fprintf(out," case %d: /* ", rp2->index); - writeRuleText(out, rp2); - fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++; - rp2->code = 0; - } - } - emit_code(out,rp,lemp,&lineno); - fprintf(out," break;\n"); lineno++; - rp->code = 0; - } - /* Finally, output the default: rule. We choose as the default: all - ** empty actions. */ - fprintf(out," default:\n"); lineno++; - for(rp=lemp->rule; rp; rp=rp->next){ - if( rp->code==0 ) continue; - assert( rp->code[0]=='\n' && rp->code[1]==0 ); - fprintf(out," /* (%d) ", rp->index); - writeRuleText(out, rp); - fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++; - } - fprintf(out," break;\n"); lineno++; - tplt_xfer(lemp->name,in,out,&lineno); - - /* Generate code which executes if a parse fails */ - tplt_print(out,lemp,lemp->failure,&lineno); - tplt_xfer(lemp->name,in,out,&lineno); - - /* Generate code which executes when a syntax error occurs */ - tplt_print(out,lemp,lemp->error,&lineno); - tplt_xfer(lemp->name,in,out,&lineno); - - /* Generate code which executes when the parser accepts its input */ - tplt_print(out,lemp,lemp->accept,&lineno); - tplt_xfer(lemp->name,in,out,&lineno); - - /* Append any addition code the user desires */ - tplt_print(out,lemp,lemp->extracode,&lineno); - - fclose(in); - fclose(out); - return; -} - -/* Generate a header file for the parser */ -void ReportHeader(struct lemon *lemp) -{ - FILE *out, *in; - const char *prefix; - char line[LINESIZE]; - char pattern[LINESIZE]; - int i; - - if( lemp->tokenprefix ) prefix = lemp->tokenprefix; - else prefix = ""; - in = file_open(lemp,".h","rb"); - if( in ){ - for(i=1; interminal && fgets(line,LINESIZE,in); i++){ - sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i); - if( strcmp(line,pattern) ) break; - } - fclose(in); - if( i==lemp->nterminal ){ - /* No change in the file. Don't rewrite it. */ - return; - } - } - out = file_open(lemp,".h","wb"); - if( out ){ - for(i=1; interminal; i++){ - fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i); - } - fclose(out); - } - return; -} - -/* Reduce the size of the action tables, if possible, by making use -** of defaults. -** -** In this version, we take the most frequent REDUCE action and make -** it the default. Except, there is no default if the wildcard token -** is a possible look-ahead. -*/ -void CompressTables(struct lemon *lemp) -{ - struct state *stp; - struct action *ap, *ap2; - struct rule *rp, *rp2, *rbest; - int nbest, n; - int i; - int usesWildcard; - - for(i=0; instate; i++){ - stp = lemp->sorted[i]; - nbest = 0; - rbest = 0; - usesWildcard = 0; - - for(ap=stp->ap; ap; ap=ap->next){ - if( ap->type==SHIFT && ap->sp==lemp->wildcard ){ - usesWildcard = 1; - } - if( ap->type!=REDUCE ) continue; - rp = ap->x.rp; - if( rp->lhsStart ) continue; - if( rp==rbest ) continue; - n = 1; - for(ap2=ap->next; ap2; ap2=ap2->next){ - if( ap2->type!=REDUCE ) continue; - rp2 = ap2->x.rp; - if( rp2==rbest ) continue; - if( rp2==rp ) n++; - } - if( n>nbest ){ - nbest = n; - rbest = rp; - } - } - - /* Do not make a default if the number of rules to default - ** is not at least 1 or if the wildcard token is a possible - ** lookahead. - */ - if( nbest<1 || usesWildcard ) continue; - - - /* Combine matching REDUCE actions into a single default */ - for(ap=stp->ap; ap; ap=ap->next){ - if( ap->type==REDUCE && ap->x.rp==rbest ) break; - } - assert( ap ); - ap->sp = Symbol_new("{default}"); - for(ap=ap->next; ap; ap=ap->next){ - if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED; - } - stp->ap = Action_sort(stp->ap); - } -} - - -/* -** Compare two states for sorting purposes. The smaller state is the -** one with the most non-terminal actions. If they have the same number -** of non-terminal actions, then the smaller is the one with the most -** token actions. -*/ -static int stateResortCompare(const void *a, const void *b){ - const struct state *pA = *(const struct state**)a; - const struct state *pB = *(const struct state**)b; - int n; - - n = pB->nNtAct - pA->nNtAct; - if( n==0 ){ - n = pB->nTknAct - pA->nTknAct; - if( n==0 ){ - n = pB->statenum - pA->statenum; - } - } - assert( n!=0 ); - return n; -} - - -/* -** Renumber and resort states so that states with fewer choices -** occur at the end. Except, keep state 0 as the first state. -*/ -void ResortStates(struct lemon *lemp) -{ - int i; - struct state *stp; - struct action *ap; - - for(i=0; instate; i++){ - stp = lemp->sorted[i]; - stp->nTknAct = stp->nNtAct = 0; - stp->iDflt = lemp->nstate + lemp->nrule; - stp->iTknOfst = NO_OFFSET; - stp->iNtOfst = NO_OFFSET; - for(ap=stp->ap; ap; ap=ap->next){ - if( compute_action(lemp,ap)>=0 ){ - if( ap->sp->indexnterminal ){ - stp->nTknAct++; - }else if( ap->sp->indexnsymbol ){ - stp->nNtAct++; - }else{ - stp->iDflt = compute_action(lemp, ap); - } - } - } - } - qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]), - stateResortCompare); - for(i=0; instate; i++){ - lemp->sorted[i]->statenum = i; - } -} - - -/***************** From the file "set.c" ************************************/ -/* -** Set manipulation routines for the LEMON parser generator. -*/ - -static int size = 0; - -/* Set the set size */ -void SetSize(int n) -{ - size = n+1; -} - -/* Allocate a new set */ -char *SetNew(){ - char *s; - s = (char*)calloc( size, 1); - if( s==0 ){ - extern void memory_error(); - memory_error(); - } - return s; -} - -/* Deallocate a set */ -void SetFree(char *s) -{ - free(s); -} - -/* Add a new element to the set. Return TRUE if the element was added -** and FALSE if it was already there. */ -int SetAdd(char *s, int e) -{ - int rv; - assert( e>=0 && esize = 1024; - x1a->count = 0; - x1a->tbl = (x1node*)malloc( - (sizeof(x1node) + sizeof(x1node*))*1024 ); - if( x1a->tbl==0 ){ - free(x1a); - x1a = 0; - }else{ - int i; - x1a->ht = (x1node**)&(x1a->tbl[1024]); - for(i=0; i<1024; i++) x1a->ht[i] = 0; - } - } -} -/* Insert a new record into the array. Return TRUE if successful. -** Prior data with the same key is NOT overwritten */ -int Strsafe_insert(const char *data) -{ - x1node *np; - int h; - int ph; - - if( x1a==0 ) return 0; - ph = strhash(data); - h = ph & (x1a->size-1); - np = x1a->ht[h]; - while( np ){ - if( strcmp(np->data,data)==0 ){ - /* An existing entry with the same key is found. */ - /* Fail because overwrite is not allows. */ - return 0; - } - np = np->next; - } - if( x1a->count>=x1a->size ){ - /* Need to make the hash table bigger */ - int i,size; - struct s_x1 array; - array.size = size = x1a->size*2; - array.count = x1a->count; - array.tbl = (x1node*)malloc( - (sizeof(x1node) + sizeof(x1node*))*size ); - if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ - array.ht = (x1node**)&(array.tbl[size]); - for(i=0; icount; i++){ - x1node *oldnp, *newnp; - oldnp = &(x1a->tbl[i]); - h = strhash(oldnp->data) & (size-1); - newnp = &(array.tbl[i]); - if( array.ht[h] ) array.ht[h]->from = &(newnp->next); - newnp->next = array.ht[h]; - newnp->data = oldnp->data; - newnp->from = &(array.ht[h]); - array.ht[h] = newnp; - } - free(x1a->tbl); - *x1a = array; - } - /* Insert the new data */ - h = ph & (x1a->size-1); - np = &(x1a->tbl[x1a->count++]); - np->data = data; - if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next); - np->next = x1a->ht[h]; - x1a->ht[h] = np; - np->from = &(x1a->ht[h]); - return 1; -} - -/* Return a pointer to data assigned to the given key. Return NULL -** if no such key. */ -const char *Strsafe_find(const char *key) -{ - int h; - x1node *np; - - if( x1a==0 ) return 0; - h = strhash(key) & (x1a->size-1); - np = x1a->ht[h]; - while( np ){ - if( strcmp(np->data,key)==0 ) break; - np = np->next; - } - return np ? np->data : 0; -} - -/* Return a pointer to the (terminal or nonterminal) symbol "x". -** Create a new symbol if this is the first time "x" has been seen. -*/ -struct symbol *Symbol_new(const char *x) -{ - struct symbol *sp; - - sp = Symbol_find(x); - if( sp==0 ){ - sp = (struct symbol *)calloc(1, sizeof(struct symbol) ); - MemoryCheck(sp); - sp->name = Strsafe(x); - sp->type = isupper(*x) ? TERMINAL : NONTERMINAL; - sp->rule = 0; - sp->fallback = 0; - sp->prec = -1; - sp->assoc = UNK; - sp->firstset = 0; - sp->lambda = LEMON_FALSE; - sp->destructor = 0; - sp->destLineno = 0; - sp->datatype = 0; - sp->useCnt = 0; - Symbol_insert(sp,sp->name); - } - sp->useCnt++; - return sp; -} - -/* Compare two symbols for working purposes -** -** Symbols that begin with upper case letters (terminals or tokens) -** must sort before symbols that begin with lower case letters -** (non-terminals). Other than that, the order does not matter. -** -** We find experimentally that leaving the symbols in their original -** order (the order they appeared in the grammar file) gives the -** smallest parser tables in SQLite. -*/ -int Symbolcmpp(const void *_a, const void *_b) -{ - const struct symbol **a = (const struct symbol **) _a; - const struct symbol **b = (const struct symbol **) _b; - int i1 = (**a).index + 10000000*((**a).name[0]>'Z'); - int i2 = (**b).index + 10000000*((**b).name[0]>'Z'); - assert( i1!=i2 || strcmp((**a).name,(**b).name)==0 ); - return i1-i2; -} - -/* There is one instance of the following structure for each -** associative array of type "x2". -*/ -struct s_x2 { - int size; /* The number of available slots. */ - /* Must be a power of 2 greater than or */ - /* equal to 1 */ - int count; /* Number of currently slots filled */ - struct s_x2node *tbl; /* The data stored here */ - struct s_x2node **ht; /* Hash table for lookups */ -}; - -/* There is one instance of this structure for every data element -** in an associative array of type "x2". -*/ -typedef struct s_x2node { - struct symbol *data; /* The data */ - const char *key; /* The key */ - struct s_x2node *next; /* Next entry with the same hash */ - struct s_x2node **from; /* Previous link */ -} x2node; - -/* There is only one instance of the array, which is the following */ -static struct s_x2 *x2a; - -/* Allocate a new associative array */ -void Symbol_init(){ - if( x2a ) return; - x2a = (struct s_x2*)malloc( sizeof(struct s_x2) ); - if( x2a ){ - x2a->size = 128; - x2a->count = 0; - x2a->tbl = (x2node*)malloc( - (sizeof(x2node) + sizeof(x2node*))*128 ); - if( x2a->tbl==0 ){ - free(x2a); - x2a = 0; - }else{ - int i; - x2a->ht = (x2node**)&(x2a->tbl[128]); - for(i=0; i<128; i++) x2a->ht[i] = 0; - } - } -} -/* Insert a new record into the array. Return TRUE if successful. -** Prior data with the same key is NOT overwritten */ -int Symbol_insert(struct symbol *data, const char *key) -{ - x2node *np; - int h; - int ph; - - if( x2a==0 ) return 0; - ph = strhash(key); - h = ph & (x2a->size-1); - np = x2a->ht[h]; - while( np ){ - if( strcmp(np->key,key)==0 ){ - /* An existing entry with the same key is found. */ - /* Fail because overwrite is not allows. */ - return 0; - } - np = np->next; - } - if( x2a->count>=x2a->size ){ - /* Need to make the hash table bigger */ - int i,size; - struct s_x2 array; - array.size = size = x2a->size*2; - array.count = x2a->count; - array.tbl = (x2node*)malloc( - (sizeof(x2node) + sizeof(x2node*))*size ); - if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ - array.ht = (x2node**)&(array.tbl[size]); - for(i=0; icount; i++){ - x2node *oldnp, *newnp; - oldnp = &(x2a->tbl[i]); - h = strhash(oldnp->key) & (size-1); - newnp = &(array.tbl[i]); - if( array.ht[h] ) array.ht[h]->from = &(newnp->next); - newnp->next = array.ht[h]; - newnp->key = oldnp->key; - newnp->data = oldnp->data; - newnp->from = &(array.ht[h]); - array.ht[h] = newnp; - } - free(x2a->tbl); - *x2a = array; - } - /* Insert the new data */ - h = ph & (x2a->size-1); - np = &(x2a->tbl[x2a->count++]); - np->key = key; - np->data = data; - if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next); - np->next = x2a->ht[h]; - x2a->ht[h] = np; - np->from = &(x2a->ht[h]); - return 1; -} - -/* Return a pointer to data assigned to the given key. Return NULL -** if no such key. */ -struct symbol *Symbol_find(const char *key) -{ - int h; - x2node *np; - - if( x2a==0 ) return 0; - h = strhash(key) & (x2a->size-1); - np = x2a->ht[h]; - while( np ){ - if( strcmp(np->key,key)==0 ) break; - np = np->next; - } - return np ? np->data : 0; -} - -/* Return the n-th data. Return NULL if n is out of range. */ -struct symbol *Symbol_Nth(int n) -{ - struct symbol *data; - if( x2a && n>0 && n<=x2a->count ){ - data = x2a->tbl[n-1].data; - }else{ - data = 0; - } - return data; -} - -/* Return the size of the array */ -int Symbol_count() -{ - return x2a ? x2a->count : 0; -} - -/* Return an array of pointers to all data in the table. -** The array is obtained from malloc. Return NULL if memory allocation -** problems, or if the array is empty. */ -struct symbol **Symbol_arrayof() -{ - struct symbol **array; - int i,size; - if( x2a==0 ) return 0; - size = x2a->count; - array = (struct symbol **)calloc(size, sizeof(struct symbol *)); - if( array ){ - for(i=0; itbl[i].data; - } - return array; -} - -/* Compare two configurations */ -int Configcmp(const char *_a,const char *_b) -{ - const struct config *a = (struct config *) _a; - const struct config *b = (struct config *) _b; - int x; - x = a->rp->index - b->rp->index; - if( x==0 ) x = a->dot - b->dot; - return x; -} - -/* Compare two states */ -PRIVATE int statecmp(struct config *a, struct config *b) -{ - int rc; - for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){ - rc = a->rp->index - b->rp->index; - if( rc==0 ) rc = a->dot - b->dot; - } - if( rc==0 ){ - if( a ) rc = 1; - if( b ) rc = -1; - } - return rc; -} - -/* Hash a state */ -PRIVATE int statehash(struct config *a) -{ - int h=0; - while( a ){ - h = h*571 + a->rp->index*37 + a->dot; - a = a->bp; - } - return h; -} - -/* Allocate a new state structure */ -struct state *State_new() -{ - struct state *newstate; - newstate = (struct state *)calloc(1, sizeof(struct state) ); - MemoryCheck(newstate); - return newstate; -} - -/* There is one instance of the following structure for each -** associative array of type "x3". -*/ -struct s_x3 { - int size; /* The number of available slots. */ - /* Must be a power of 2 greater than or */ - /* equal to 1 */ - int count; /* Number of currently slots filled */ - struct s_x3node *tbl; /* The data stored here */ - struct s_x3node **ht; /* Hash table for lookups */ -}; - -/* There is one instance of this structure for every data element -** in an associative array of type "x3". -*/ -typedef struct s_x3node { - struct state *data; /* The data */ - struct config *key; /* The key */ - struct s_x3node *next; /* Next entry with the same hash */ - struct s_x3node **from; /* Previous link */ -} x3node; - -/* There is only one instance of the array, which is the following */ -static struct s_x3 *x3a; - -/* Allocate a new associative array */ -void State_init(){ - if( x3a ) return; - x3a = (struct s_x3*)malloc( sizeof(struct s_x3) ); - if( x3a ){ - x3a->size = 128; - x3a->count = 0; - x3a->tbl = (x3node*)malloc( - (sizeof(x3node) + sizeof(x3node*))*128 ); - if( x3a->tbl==0 ){ - free(x3a); - x3a = 0; - }else{ - int i; - x3a->ht = (x3node**)&(x3a->tbl[128]); - for(i=0; i<128; i++) x3a->ht[i] = 0; - } - } -} -/* Insert a new record into the array. Return TRUE if successful. -** Prior data with the same key is NOT overwritten */ -int State_insert(struct state *data, struct config *key) -{ - x3node *np; - int h; - int ph; - - if( x3a==0 ) return 0; - ph = statehash(key); - h = ph & (x3a->size-1); - np = x3a->ht[h]; - while( np ){ - if( statecmp(np->key,key)==0 ){ - /* An existing entry with the same key is found. */ - /* Fail because overwrite is not allows. */ - return 0; - } - np = np->next; - } - if( x3a->count>=x3a->size ){ - /* Need to make the hash table bigger */ - int i,size; - struct s_x3 array; - array.size = size = x3a->size*2; - array.count = x3a->count; - array.tbl = (x3node*)malloc( - (sizeof(x3node) + sizeof(x3node*))*size ); - if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ - array.ht = (x3node**)&(array.tbl[size]); - for(i=0; icount; i++){ - x3node *oldnp, *newnp; - oldnp = &(x3a->tbl[i]); - h = statehash(oldnp->key) & (size-1); - newnp = &(array.tbl[i]); - if( array.ht[h] ) array.ht[h]->from = &(newnp->next); - newnp->next = array.ht[h]; - newnp->key = oldnp->key; - newnp->data = oldnp->data; - newnp->from = &(array.ht[h]); - array.ht[h] = newnp; - } - free(x3a->tbl); - *x3a = array; - } - /* Insert the new data */ - h = ph & (x3a->size-1); - np = &(x3a->tbl[x3a->count++]); - np->key = key; - np->data = data; - if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next); - np->next = x3a->ht[h]; - x3a->ht[h] = np; - np->from = &(x3a->ht[h]); - return 1; -} - -/* Return a pointer to data assigned to the given key. Return NULL -** if no such key. */ -struct state *State_find(struct config *key) -{ - int h; - x3node *np; - - if( x3a==0 ) return 0; - h = statehash(key) & (x3a->size-1); - np = x3a->ht[h]; - while( np ){ - if( statecmp(np->key,key)==0 ) break; - np = np->next; - } - return np ? np->data : 0; -} - -/* Return an array of pointers to all data in the table. -** The array is obtained from malloc. Return NULL if memory allocation -** problems, or if the array is empty. */ -struct state **State_arrayof() -{ - struct state **array; - int i,size; - if( x3a==0 ) return 0; - size = x3a->count; - array = (struct state **)malloc( sizeof(struct state *)*size ); - if( array ){ - for(i=0; itbl[i].data; - } - return array; -} - -/* Hash a configuration */ -PRIVATE int confighash(struct config *a) -{ - int h=0; - h = h*571 + a->rp->index*37 + a->dot; - return h; -} - -/* There is one instance of the following structure for each -** associative array of type "x4". -*/ -struct s_x4 { - int size; /* The number of available slots. */ - /* Must be a power of 2 greater than or */ - /* equal to 1 */ - int count; /* Number of currently slots filled */ - struct s_x4node *tbl; /* The data stored here */ - struct s_x4node **ht; /* Hash table for lookups */ -}; - -/* There is one instance of this structure for every data element -** in an associative array of type "x4". -*/ -typedef struct s_x4node { - struct config *data; /* The data */ - struct s_x4node *next; /* Next entry with the same hash */ - struct s_x4node **from; /* Previous link */ -} x4node; - -/* There is only one instance of the array, which is the following */ -static struct s_x4 *x4a; - -/* Allocate a new associative array */ -void Configtable_init(){ - if( x4a ) return; - x4a = (struct s_x4*)malloc( sizeof(struct s_x4) ); - if( x4a ){ - x4a->size = 64; - x4a->count = 0; - x4a->tbl = (x4node*)malloc( - (sizeof(x4node) + sizeof(x4node*))*64 ); - if( x4a->tbl==0 ){ - free(x4a); - x4a = 0; - }else{ - int i; - x4a->ht = (x4node**)&(x4a->tbl[64]); - for(i=0; i<64; i++) x4a->ht[i] = 0; - } - } -} -/* Insert a new record into the array. Return TRUE if successful. -** Prior data with the same key is NOT overwritten */ -int Configtable_insert(struct config *data) -{ - x4node *np; - int h; - int ph; - - if( x4a==0 ) return 0; - ph = confighash(data); - h = ph & (x4a->size-1); - np = x4a->ht[h]; - while( np ){ - if( Configcmp((const char *) np->data,(const char *) data)==0 ){ - /* An existing entry with the same key is found. */ - /* Fail because overwrite is not allows. */ - return 0; - } - np = np->next; - } - if( x4a->count>=x4a->size ){ - /* Need to make the hash table bigger */ - int i,size; - struct s_x4 array; - array.size = size = x4a->size*2; - array.count = x4a->count; - array.tbl = (x4node*)malloc( - (sizeof(x4node) + sizeof(x4node*))*size ); - if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ - array.ht = (x4node**)&(array.tbl[size]); - for(i=0; icount; i++){ - x4node *oldnp, *newnp; - oldnp = &(x4a->tbl[i]); - h = confighash(oldnp->data) & (size-1); - newnp = &(array.tbl[i]); - if( array.ht[h] ) array.ht[h]->from = &(newnp->next); - newnp->next = array.ht[h]; - newnp->data = oldnp->data; - newnp->from = &(array.ht[h]); - array.ht[h] = newnp; - } - free(x4a->tbl); - *x4a = array; - } - /* Insert the new data */ - h = ph & (x4a->size-1); - np = &(x4a->tbl[x4a->count++]); - np->data = data; - if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next); - np->next = x4a->ht[h]; - x4a->ht[h] = np; - np->from = &(x4a->ht[h]); - return 1; -} - -/* Return a pointer to data assigned to the given key. Return NULL -** if no such key. */ -struct config *Configtable_find(struct config *key) -{ - int h; - x4node *np; - - if( x4a==0 ) return 0; - h = confighash(key) & (x4a->size-1); - np = x4a->ht[h]; - while( np ){ - if( Configcmp((const char *) np->data,(const char *) key)==0 ) break; - np = np->next; - } - return np ? np->data : 0; -} - -/* Remove all data from the table. Pass each data to the function "f" -** as it is removed. ("f" may be null to avoid this step.) */ -void Configtable_clear(int(*f)(struct config *)) -{ - int i; - if( x4a==0 || x4a->count==0 ) return; - if( f ) for(i=0; icount; i++) (*f)(x4a->tbl[i].data); - for(i=0; isize; i++) x4a->ht[i] = 0; - x4a->count = 0; - return; -} diff --git a/mojoshader/misc/lempar.c b/mojoshader/misc/lempar.c deleted file mode 100644 index e684681..0000000 --- a/mojoshader/misc/lempar.c +++ /dev/null @@ -1,889 +0,0 @@ -/* - * My changes over the original lempar.c from SQLite are encased in - * #if __MOJOSHADER__ blocks. --ryan. - */ -#ifndef __MOJOSHADER__ -#define __MOJOSHADER__ 1 -#endif - -#if !__MOJOSHADER__ -#define LEMON_SUPPORT_TRACING (!defined(NDEBUG)) -#endif - -/* Driver template for the LEMON parser generator. -** The original author(s) of lempar.c disclaim copyright to this source code. -** However, changes made for MojoShader fall under the same license as the -** rest of MojoShader. Please see the file LICENSE.txt in the source's root -** directory. -*/ -/* First off, code is included that follows the "include" declaration -** in the input grammar file. */ -#include -%% -/* Next is all token values, in a form suitable for use by makeheaders. -** This section will be null unless lemon is run with the -m switch. -*/ -/* -** These constants (all generated automatically by the parser generator) -** specify the various kinds of tokens (terminals) that the parser -** understands. -** -** Each symbol here is a terminal symbol in the grammar. -*/ -%% -/* Make sure the INTERFACE macro is defined. -*/ -#ifndef INTERFACE -# define INTERFACE 1 -#endif -/* The next thing included is series of defines which control -** various aspects of the generated parser. -** YYCODETYPE is the data type used for storing terminal -** and nonterminal numbers. "unsigned char" is -** used if there are fewer than 250 terminals -** and nonterminals. "int" is used otherwise. -** YYNOCODE is a number of type YYCODETYPE which corresponds -** to no legal terminal or nonterminal number. This -** number is used to fill in empty slots of the hash -** table. -** YYFALLBACK If defined, this indicates that one or more tokens -** have fall-back values which should be used if the -** original value of the token will not parse. -** YYACTIONTYPE is the data type used for storing terminal -** and nonterminal numbers. "unsigned char" is -** used if there are fewer than 250 rules and -** states combined. "int" is used otherwise. -** ParseTOKENTYPE is the data type used for minor tokens given -** directly to the parser from the tokenizer. -** YYMINORTYPE is the data type used for all minor tokens. -** This is typically a union of many types, one of -** which is ParseTOKENTYPE. The entry in the union -** for base tokens is called "yy0". -** YYSTACKDEPTH is the maximum depth of the parser's stack. If -** zero the stack is dynamically sized using realloc() -** ParseARG_SDECL A static variable declaration for the %extra_argument -** ParseARG_PDECL A parameter declaration for the %extra_argument -** ParseARG_STORE Code to store %extra_argument into yypParser -** ParseARG_FETCH Code to extract %extra_argument from yypParser -** YYNSTATE the combined number of states. -** YYNRULE the number of rules in the grammar -** YYERRORSYMBOL is the code number of the error symbol. If not -** defined, then do no error processing. -*/ -%% -#define YY_NO_ACTION (YYNSTATE+YYNRULE+2) -#define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1) -#define YY_ERROR_ACTION (YYNSTATE+YYNRULE) - -/* The yyzerominor constant is used to initialize instances of -** YYMINORTYPE objects to zero. */ -static const YYMINORTYPE yyzerominor = { 0 }; - -/* Define the yytestcase() macro to be a no-op if is not already defined -** otherwise. -** -** Applications can choose to define yytestcase() in the %include section -** to a macro that can assist in verifying code coverage. For production -** code the yytestcase() macro should be turned off. But it is useful -** for testing. -*/ -#ifndef yytestcase -# define yytestcase(X) -#endif - - -/* Next are the tables used to determine what action to take based on the -** current state and lookahead token. These tables are used to implement -** functions that take a state number and lookahead value and return an -** action integer. -** -** Suppose the action integer is N. Then the action is determined as -** follows -** -** 0 <= N < YYNSTATE Shift N. That is, push the lookahead -** token onto the stack and goto state N. -** -** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE. -** -** N == YYNSTATE+YYNRULE A syntax error has occurred. -** -** N == YYNSTATE+YYNRULE+1 The parser accepts its input. -** -** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused -** slots in the yy_action[] table. -** -** The action table is constructed as a single large table named yy_action[]. -** Given state S and lookahead X, the action is computed as -** -** yy_action[ yy_shift_ofst[S] + X ] -** -** If the index value yy_shift_ofst[S]+X is out of range or if the value -** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S] -** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table -** and that yy_default[S] should be used instead. -** -** The formula above is for computing the action when the lookahead is -** a terminal symbol. If the lookahead is a non-terminal (as occurs after -** a reduce action) then the yy_reduce_ofst[] array is used in place of -** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of -** YY_SHIFT_USE_DFLT. -** -** The following are the tables generated in this section: -** -** yy_action[] A single table containing all actions. -** yy_lookahead[] A table containing the lookahead for each entry in -** yy_action. Used to detect hash collisions. -** yy_shift_ofst[] For each state, the offset into yy_action for -** shifting terminals. -** yy_reduce_ofst[] For each state, the offset into yy_action for -** shifting non-terminals after a reduce. -** yy_default[] Default action for each state. -*/ -%% - -/* The next table maps tokens into fallback tokens. If a construct -** like the following: -** -** %fallback ID X Y Z. -** -** appears in the grammar, then ID becomes a fallback token for X, Y, -** and Z. Whenever one of the tokens X, Y, or Z is input to the parser -** but it does not parse, the type of the token is changed to ID and -** the parse is retried before an error is thrown. -*/ -#ifdef YYFALLBACK -static const YYCODETYPE yyFallback[] = { -%% -}; -#endif /* YYFALLBACK */ - -/* The following structure represents a single element of the -** parser's stack. Information stored includes: -** -** + The state number for the parser at this level of the stack. -** -** + The value of the token stored at this level of the stack. -** (In other words, the "major" token.) -** -** + The semantic value stored at this level of the stack. This is -** the information used by the action routines in the grammar. -** It is sometimes called the "minor" token. -*/ -struct yyStackEntry { - YYACTIONTYPE stateno; /* The state-number */ - YYCODETYPE major; /* The major token value. This is the code - ** number for the token at this stack level */ - YYMINORTYPE minor; /* The user-supplied minor token value. This - ** is the value of the token */ -}; -typedef struct yyStackEntry yyStackEntry; - -/* The state of the parser is completely contained in an instance of -** the following structure */ -struct yyParser { - int yyidx; /* Index of top element in stack */ -#ifdef YYTRACKMAXSTACKDEPTH - int yyidxMax; /* Maximum value of yyidx */ -#endif - int yyerrcnt; /* Shifts left before out of the error */ - ParseARG_SDECL /* A place to hold %extra_argument */ -#if YYSTACKDEPTH<=0 - int yystksz; /* Current side of the stack */ - yyStackEntry *yystack; /* The parser's stack */ -#else - yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */ -#endif -}; -typedef struct yyParser yyParser; - -#if LEMON_SUPPORT_TRACING /* __MOJOSHADER__ */ -#include -static FILE *yyTraceFILE = 0; -static char *yyTracePrompt = 0; -#endif /* NDEBUG */ - -#if LEMON_SUPPORT_TRACING /* __MOJOSHADER__ */ -/* -** Turn parser tracing on by giving a stream to which to write the trace -** and a prompt to preface each trace message. Tracing is turned off -** by making either argument NULL -** -** Inputs: -**
    -**
  • A FILE* to which trace output should be written. -** If NULL, then tracing is turned off. -**
  • A prefix string written at the beginning of every -** line of trace output. If NULL, then tracing is -** turned off. -**
-** -** Outputs: -** None. -*/ -#if __MOJOSHADER__ -static -#endif -void ParseTrace(FILE *TraceFILE, char *zTracePrompt){ - yyTraceFILE = TraceFILE; - yyTracePrompt = zTracePrompt; - if( yyTraceFILE==0 ) yyTracePrompt = 0; - else if( yyTracePrompt==0 ) yyTraceFILE = 0; -} -#endif /* NDEBUG */ - -#if LEMON_SUPPORT_TRACING /* __MOJOSHADER__ */ -/* For tracing shifts, the names of all terminals and nonterminals -** are required. The following table supplies these names */ -static const char *const yyTokenName[] = { -%% -}; -#endif /* NDEBUG */ - -#if LEMON_SUPPORT_TRACING /* __MOJOSHADER__ */ -/* For tracing reduce actions, the names of all rules are required. -*/ -static const char *const yyRuleName[] = { -%% -}; -#endif /* NDEBUG */ - - -#if YYSTACKDEPTH<=0 -/* -** Try to increase the size of the parser stack. -*/ -static void yyGrowStack(yyParser *p){ - int newSize; - yyStackEntry *pNew; - - newSize = p->yystksz*2 + 100; - pNew = realloc(p->yystack, newSize*sizeof(pNew[0])); - if( pNew ){ - p->yystack = pNew; - p->yystksz = newSize; -#if LEMON_SUPPORT_TRACING /* __MOJOSHADER__ */ - if( yyTraceFILE ){ - fprintf(yyTraceFILE,"%sStack grows to %d entries!\n", - yyTracePrompt, p->yystksz); - } -#endif - } -} -#endif - -/* -** This function allocates a new parser. -** The only argument is a pointer to a function which works like -** malloc. -** -** Inputs: -** A pointer to the function used to allocate memory. -** -** Outputs: -** A pointer to a parser. This pointer is used in subsequent calls -** to Parse and ParseFree. -*/ -#if __MOJOSHADER__ -static void *ParseAlloc(void *(*mallocProc)(int,void *), void *malloc_data){ - yyParser *pParser; - pParser = (yyParser*)(*mallocProc)( (int)sizeof(yyParser), malloc_data ); -#else -void *ParseAlloc(void *(*mallocProc)(size_t)){ - yyParser *pParser; - pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) ); -#endif - if( pParser ){ - pParser->yyidx = -1; -#ifdef YYTRACKMAXSTACKDEPTH - pParser->yyidxMax = 0; -#endif -#if YYSTACKDEPTH<=0 - pParser->yystack = NULL; - pParser->yystksz = 0; - yyGrowStack(pParser); -#endif - } - return pParser; -} - -/* The following function deletes the value associated with a -** symbol. The symbol can be either a terminal or nonterminal. -** "yymajor" is the symbol code, and "yypminor" is a pointer to -** the value. -*/ -static void yy_destructor( - yyParser *yypParser, /* The parser */ - YYCODETYPE yymajor, /* Type code for object to destroy */ - YYMINORTYPE *yypminor /* The object to be destroyed */ -){ - ParseARG_FETCH; - switch( yymajor ){ - /* Here is inserted the actions which take place when a - ** terminal or non-terminal is destroyed. This can happen - ** when the symbol is popped from the stack during a - ** reduce or during error processing or when a parser is - ** being destroyed before it is finished parsing. - ** - ** Note: during a reduce, the only symbols destroyed are those - ** which appear on the RHS of the rule, but which are not used - ** inside the C code. - */ -%% - default: break; /* If no destructor action specified: do nothing */ - } -} - -/* -** Pop the parser's stack once. -** -** If there is a destructor routine associated with the token which -** is popped from the stack, then call it. -** -** Return the major token number for the symbol popped. -*/ -static int yy_pop_parser_stack(yyParser *pParser){ - YYCODETYPE yymajor; - yyStackEntry *yytos = &pParser->yystack[pParser->yyidx]; - - if( pParser->yyidx<0 ) return 0; -#if LEMON_SUPPORT_TRACING /* __MOJOSHADER__ */ - if( yyTraceFILE && pParser->yyidx>=0 ){ - fprintf(yyTraceFILE,"%sPopping %s\n", - yyTracePrompt, - yyTokenName[yytos->major]); - } -#endif - yymajor = yytos->major; - yy_destructor(pParser, yymajor, &yytos->minor); - pParser->yyidx--; - return yymajor; -} - -/* -** Deallocate and destroy a parser. Destructors are all called for -** all stack elements before shutting the parser down. -** -** Inputs: -**
    -**
  • A pointer to the parser. This should be a pointer -** obtained from ParseAlloc. -**
  • A pointer to a function used to reclaim memory obtained -** from malloc. -**
-*/ -#if __MOJOSHADER__ -static -#endif -void ParseFree( - void *p, /* The parser to be deleted */ -#if __MOJOSHADER__ - void (*freeProc)(void*,void*), /* Function used to reclaim memory */ - void *malloc_data -#else - void (*freeProc)(void*) /* Function used to reclaim memory */ -#endif -){ - yyParser *pParser = (yyParser*)p; - if( pParser==0 ) return; - while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser); -#if YYSTACKDEPTH<=0 - free(pParser->yystack); -#endif -#if __MOJOSHADER__ - (*freeProc)((void*)pParser, malloc_data); -#else - (*freeProc)((void*)pParser); -#endif -} - -/* -** Return the peak depth of the stack for a parser. -*/ -#ifdef YYTRACKMAXSTACKDEPTH -static int ParseStackPeak(void *p){ - yyParser *pParser = (yyParser*)p; - return pParser->yyidxMax; -} -#endif - -/* -** Find the appropriate action for a parser given the terminal -** look-ahead token iLookAhead. -** -** If the look-ahead token is YYNOCODE, then check to see if the action is -** independent of the look-ahead. If it is, return the action, otherwise -** return YY_NO_ACTION. -*/ -static int yy_find_shift_action( - yyParser *pParser, /* The parser */ - YYCODETYPE iLookAhead /* The look-ahead token */ -){ - int i; - int stateno = pParser->yystack[pParser->yyidx].stateno; - - if( stateno>YY_SHIFT_COUNT - || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){ - return yy_default[stateno]; - } - assert( iLookAhead!=YYNOCODE ); - i += iLookAhead; - if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ - if( iLookAhead>0 ){ -#ifdef YYFALLBACK - YYCODETYPE iFallback; /* Fallback token */ - if( iLookAhead %s\n", - yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]); - } -#endif - return yy_find_shift_action(pParser, iFallback); - } -#endif -#ifdef YYWILDCARD - { - int j = i - iLookAhead + YYWILDCARD; - if( -#if YY_SHIFT_MIN+YYWILDCARD<0 - j>=0 && -#endif -#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT - j %s\n", - yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]); - } -#endif /* NDEBUG */ - return yy_action[j]; - } - } -#endif /* YYWILDCARD */ - } - return yy_default[stateno]; - }else{ - return yy_action[i]; - } -} - -/* -** Find the appropriate action for a parser given the non-terminal -** look-ahead token iLookAhead. -** -** If the look-ahead token is YYNOCODE, then check to see if the action is -** independent of the look-ahead. If it is, return the action, otherwise -** return YY_NO_ACTION. -*/ -static int yy_find_reduce_action( - int stateno, /* Current state number */ - YYCODETYPE iLookAhead /* The look-ahead token */ -){ - int i; -#ifdef YYERRORSYMBOL - if( stateno>YY_REDUCE_COUNT ){ - return yy_default[stateno]; - } -#else - assert( stateno<=YY_REDUCE_COUNT ); -#endif - i = yy_reduce_ofst[stateno]; - assert( i!=YY_REDUCE_USE_DFLT ); - assert( iLookAhead!=YYNOCODE ); - i += iLookAhead; -#ifdef YYERRORSYMBOL - if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ - return yy_default[stateno]; - } -#else - assert( i>=0 && iyyidx--; -#if LEMON_SUPPORT_TRACING /* __MOJOSHADER__ */ - if( yyTraceFILE ){ - fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt); - } -#endif - while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); - /* Here code is inserted which will execute if the parser - ** stack every overflows */ -%% - ParseARG_STORE; /* Suppress warning about unused %extra_argument var */ -} - -/* -** Perform a shift action. -*/ -static void yy_shift( - yyParser *yypParser, /* The parser to be shifted */ - int yyNewState, /* The new state to shift in */ - int yyMajor, /* The major token to shift in */ - YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */ -){ - yyStackEntry *yytos; - yypParser->yyidx++; -#ifdef YYTRACKMAXSTACKDEPTH - if( yypParser->yyidx>yypParser->yyidxMax ){ - yypParser->yyidxMax = yypParser->yyidx; - } -#endif -#if YYSTACKDEPTH>0 - if( yypParser->yyidx>=YYSTACKDEPTH ){ - yyStackOverflow(yypParser, yypMinor); - return; - } -#else - if( yypParser->yyidx>=yypParser->yystksz ){ - yyGrowStack(yypParser); - if( yypParser->yyidx>=yypParser->yystksz ){ - yyStackOverflow(yypParser, yypMinor); - return; - } - } -#endif - yytos = &yypParser->yystack[yypParser->yyidx]; - yytos->stateno = (YYACTIONTYPE)yyNewState; - yytos->major = (YYCODETYPE)yyMajor; - yytos->minor = *yypMinor; -#if LEMON_SUPPORT_TRACING /* __MOJOSHADER__ */ - if( yyTraceFILE && yypParser->yyidx>0 ){ - int i; - fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState); - fprintf(yyTraceFILE,"%sStack:",yyTracePrompt); - for(i=1; i<=yypParser->yyidx; i++) - fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]); - fprintf(yyTraceFILE,"\n"); - } -#endif -} - -/* The following table contains information about every rule that -** is used during the reduce. -*/ -static const struct { - YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ - unsigned char nrhs; /* Number of right-hand side symbols in the rule */ -} yyRuleInfo[] = { -%% -}; - -static void yy_accept(yyParser*); /* Forward Declaration */ - -/* -** Perform a reduce action and the shift that must immediately -** follow the reduce. -*/ -static void yy_reduce( - yyParser *yypParser, /* The parser */ - int yyruleno /* Number of the rule by which to reduce */ -){ - int yygoto; /* The next state */ - int yyact; /* The next action */ - YYMINORTYPE yygotominor; /* The LHS of the rule reduced */ - yyStackEntry *yymsp; /* The top of the parser's stack */ - int yysize; /* Amount to pop the stack */ - ParseARG_FETCH; - yymsp = &yypParser->yystack[yypParser->yyidx]; -#if LEMON_SUPPORT_TRACING /* __MOJOSHADER__ */ - if( yyTraceFILE && yyruleno>=0 - && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){ - fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt, - yyRuleName[yyruleno]); - } -#endif /* NDEBUG */ - - /* Silence complaints from purify about yygotominor being uninitialized - ** in some cases when it is copied into the stack after the following - ** switch. yygotominor is uninitialized when a rule reduces that does - ** not set the value of its left-hand side nonterminal. Leaving the - ** value of the nonterminal uninitialized is utterly harmless as long - ** as the value is never used. So really the only thing this code - ** accomplishes is to quieten purify. - ** - ** 2007-01-16: The wireshark project (www.wireshark.org) reports that - ** without this code, their parser segfaults. I'm not sure what there - ** parser is doing to make this happen. This is the second bug report - ** from wireshark this week. Clearly they are stressing Lemon in ways - ** that it has not been previously stressed... (SQLite ticket #2172) - */ - /*memset(&yygotominor, 0, sizeof(yygotominor));*/ - yygotominor = yyzerominor; - - - switch( yyruleno ){ - /* Beginning here are the reduction cases. A typical example - ** follows: - ** case 0: - ** #line - ** { ... } // User supplied code - ** #line - ** break; - */ -%% - }; - yygoto = yyRuleInfo[yyruleno].lhs; - yysize = yyRuleInfo[yyruleno].nrhs; - yypParser->yyidx -= yysize; - yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto); - if( yyact < YYNSTATE ){ -#if LEMON_SUPPORT_TRACING /* __MOJOSHADER__ */ - /* If we are not debugging and the reduce action popped at least - ** one element off the stack, then we can push the new element back - ** onto the stack here, and skip the stack overflow test in yy_shift(). - ** That gives a significant speed improvement. */ - if( yysize ){ - yypParser->yyidx++; - yymsp -= yysize-1; - yymsp->stateno = (YYACTIONTYPE)yyact; - yymsp->major = (YYCODETYPE)yygoto; - yymsp->minor = yygotominor; - }else -#endif - { - yy_shift(yypParser,yyact,yygoto,&yygotominor); - } - }else{ - assert( yyact == YYNSTATE + YYNRULE + 1 ); - yy_accept(yypParser); - } -} - -/* -** The following code executes when the parse fails -*/ -#ifndef YYNOERRORRECOVERY -static void yy_parse_failed( - yyParser *yypParser /* The parser */ -){ - ParseARG_FETCH; -#if LEMON_SUPPORT_TRACING /* __MOJOSHADER__ */ - if( yyTraceFILE ){ - fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt); - } -#endif - while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); - /* Here code is inserted which will be executed whenever the - ** parser fails */ -%% - ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ -} -#endif /* YYNOERRORRECOVERY */ - -/* -** The following code executes when a syntax error first occurs. -*/ -static void yy_syntax_error( - yyParser *yypParser, /* The parser */ - int yymajor, /* The major type of the error token */ - YYMINORTYPE yyminor /* The minor type of the error token */ -){ - ParseARG_FETCH; -#define TOKEN (yyminor.yy0) -%% - ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ -} - -/* -** The following is executed when the parser accepts -*/ -static void yy_accept( - yyParser *yypParser /* The parser */ -){ - ParseARG_FETCH; -#if LEMON_SUPPORT_TRACING /* __MOJOSHADER__ */ - if( yyTraceFILE ){ - fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt); - } -#endif - while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); - /* Here code is inserted which will be executed whenever the - ** parser accepts */ -%% - ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ -} - -/* The main parser program. -** The first argument is a pointer to a structure obtained from -** "ParseAlloc" which describes the current state of the parser. -** The second argument is the major token number. The third is -** the minor token. The fourth optional argument is whatever the -** user wants (and specified in the grammar) and is available for -** use by the action routines. -** -** Inputs: -**
    -**
  • A pointer to the parser (an opaque structure.) -**
  • The major token number. -**
  • The minor token number. -**
  • An option argument of a grammar-specified type. -**
-** -** Outputs: -** None. -*/ -#if __MOJOSHADER__ -static -#endif -void Parse( - void *yyp, /* The parser */ - int yymajor, /* The major token code number */ - ParseTOKENTYPE yyminor /* The value for the token */ - ParseARG_PDECL /* Optional %extra_argument parameter */ -){ - YYMINORTYPE yyminorunion; - int yyact; /* The parser action. */ - int yyendofinput; /* True if we are at the end of input */ -#ifdef YYERRORSYMBOL - int yyerrorhit = 0; /* True if yymajor has invoked an error */ -#endif - yyParser *yypParser; /* The parser */ - - /* (re)initialize the parser, if necessary */ - yypParser = (yyParser*)yyp; - if( yypParser->yyidx<0 ){ -#if YYSTACKDEPTH<=0 - if( yypParser->yystksz <=0 ){ - /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/ - yyminorunion = yyzerominor; - yyStackOverflow(yypParser, &yyminorunion); - return; - } -#endif - yypParser->yyidx = 0; - yypParser->yyerrcnt = -1; - yypParser->yystack[0].stateno = 0; - yypParser->yystack[0].major = 0; - } - yyminorunion.yy0 = yyminor; - yyendofinput = (yymajor==0); - ParseARG_STORE; - -#if LEMON_SUPPORT_TRACING /* __MOJOSHADER__ */ - if( yyTraceFILE ){ - fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]); - } -#endif - - do{ - yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor); - if( yyactyyerrcnt--; - yymajor = YYNOCODE; - }else if( yyact < YYNSTATE + YYNRULE ){ - yy_reduce(yypParser,yyact-YYNSTATE); - }else{ - assert( yyact == YY_ERROR_ACTION ); -#ifdef YYERRORSYMBOL - int yymx; -#endif -#if LEMON_SUPPORT_TRACING /* __MOJOSHADER__ */ - if( yyTraceFILE ){ - fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt); - } -#endif -#ifdef YYERRORSYMBOL - /* A syntax error has occurred. - ** The response to an error depends upon whether or not the - ** grammar defines an error token "ERROR". - ** - ** This is what we do if the grammar does define ERROR: - ** - ** * Call the %syntax_error function. - ** - ** * Begin popping the stack until we enter a state where - ** it is legal to shift the error symbol, then shift - ** the error symbol. - ** - ** * Set the error count to three. - ** - ** * Begin accepting and shifting new tokens. No new error - ** processing will occur until three tokens have been - ** shifted successfully. - ** - */ - if( yypParser->yyerrcnt<0 ){ - yy_syntax_error(yypParser,yymajor,yyminorunion); - } - yymx = yypParser->yystack[yypParser->yyidx].major; - if( yymx==YYERRORSYMBOL || yyerrorhit ){ -#if LEMON_SUPPORT_TRACING /* __MOJOSHADER__ */ - if( yyTraceFILE ){ - fprintf(yyTraceFILE,"%sDiscard input token %s\n", - yyTracePrompt,yyTokenName[yymajor]); - } -#endif - yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion); - yymajor = YYNOCODE; - }else{ - while( - yypParser->yyidx >= 0 && - yymx != YYERRORSYMBOL && - (yyact = yy_find_reduce_action( - yypParser->yystack[yypParser->yyidx].stateno, - YYERRORSYMBOL)) >= YYNSTATE - ){ - yy_pop_parser_stack(yypParser); - } - if( yypParser->yyidx < 0 || yymajor==0 ){ - yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); - yy_parse_failed(yypParser); - yymajor = YYNOCODE; - }else if( yymx!=YYERRORSYMBOL ){ - YYMINORTYPE u2; - u2.YYERRSYMDT = 0; - yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2); - } - } - yypParser->yyerrcnt = 3; - yyerrorhit = 1; -#elif defined(YYNOERRORRECOVERY) - /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to - ** do any kind of error recovery. Instead, simply invoke the syntax - ** error routine and continue going as if nothing had happened. - ** - ** Applications can set this macro (for example inside %include) if - ** they intend to abandon the parse upon the first syntax error seen. - */ - yy_syntax_error(yypParser,yymajor,yyminorunion); - yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); - yymajor = YYNOCODE; - -#else /* YYERRORSYMBOL is not defined */ - /* This is what we do if the grammar does not define ERROR: - ** - ** * Report an error message, and throw away the input token. - ** - ** * If the input token is $, then fail the parse. - ** - ** As before, subsequent error messages are suppressed until - ** three input tokens have been successfully shifted. - */ - if( yypParser->yyerrcnt<=0 ){ - yy_syntax_error(yypParser,yymajor,yyminorunion); - } - yypParser->yyerrcnt = 3; - yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); - if( yyendofinput ){ - yy_parse_failed(yypParser); - } - yymajor = YYNOCODE; -#endif - } - }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 ); - return; -} diff --git a/mojoshader/mojoshader.c b/mojoshader/mojoshader.c index 9bfa6ca..486d7e0 100644 --- a/mojoshader/mojoshader.c +++ b/mojoshader/mojoshader.c @@ -16,489 +16,7 @@ // - A maximum of three temp registers can be used in a single instruction. #define __MOJOSHADER_INTERNAL__ 1 -#include "mojoshader_internal.h" - -typedef struct ConstantsList -{ - MOJOSHADER_constant constant; - struct ConstantsList *next; -} ConstantsList; - -typedef struct VariableList -{ - MOJOSHADER_uniformType type; - int index; - int count; - ConstantsList *constant; - int used; - int emit_position; // used in some profiles. - struct VariableList *next; -} VariableList; - -typedef struct RegisterList -{ - RegisterType regtype; - int regnum; - MOJOSHADER_usage usage; - unsigned int index; - int writemask; - int misc; - int written; - const VariableList *array; - struct RegisterList *next; -} RegisterList; - -typedef struct -{ - const uint32 *token; // this is the unmolested token in the stream. - int regnum; - int swizzle; // xyzw (all four, not split out). - int swizzle_x; - int swizzle_y; - int swizzle_z; - int swizzle_w; - SourceMod src_mod; - RegisterType regtype; - int relative; - RegisterType relative_regtype; - int relative_regnum; - int relative_component; - const VariableList *relative_array; -} SourceArgInfo; - -struct Profile; // predeclare. - -typedef struct CtabData -{ - int have_ctab; - int symbol_count; - MOJOSHADER_symbol *symbols; -} CtabData; - -// Context...this is state that changes as we parse through a shader... -typedef struct Context -{ - int isfail; - int out_of_memory; - MOJOSHADER_malloc malloc; - MOJOSHADER_free free; - void *malloc_data; - int current_position; - const uint32 *orig_tokens; - const uint32 *tokens; - uint32 tokencount; - const MOJOSHADER_swizzle *swizzles; - unsigned int swizzles_count; - const MOJOSHADER_samplerMap *samplermap; - unsigned int samplermap_count; - Buffer *output; - Buffer *preflight; - Buffer *globals; - Buffer *helpers; - Buffer *subroutines; - Buffer *mainline_intro; - Buffer *mainline; - Buffer *ignore; - Buffer *output_stack[2]; - int indent_stack[2]; - int output_stack_len; - int indent; - const char *shader_type_str; - const char *endline; - int endline_len; - int profileid; - const struct Profile *profile; - MOJOSHADER_shaderType shader_type; - uint8 major_ver; - uint8 minor_ver; - DestArgInfo dest_arg; - SourceArgInfo source_args[5]; - SourceArgInfo predicate_arg; // for predicated instructions. - uint32 dwords[4]; - uint32 version_token; - int instruction_count; - uint32 instruction_controls; - uint32 previous_opcode; - int coissue; - int loops; - int reps; - int max_reps; - int cmps; - int scratch_registers; - int max_scratch_registers; - int branch_labels_stack_index; - int branch_labels_stack[32]; - int assigned_branch_labels; - int assigned_vertex_attributes; - int last_address_reg_component; - RegisterList used_registers; - RegisterList defined_registers; - ErrorList *errors; - int constant_count; - ConstantsList *constants; - int uniform_count; - int uniform_float4_count; - int uniform_int4_count; - int uniform_bool_count; - RegisterList uniforms; - int attribute_count; - RegisterList attributes; - int sampler_count; - RegisterList samplers; - VariableList *variables; // variables to register mapping. - int centroid_allowed; - CtabData ctab; - int have_relative_input_registers; - int have_multi_color_outputs; - int determined_constants_arrays; - int predicated; - int uses_pointsize; - int uses_fog; - int glsl_generated_lit_helper; - int glsl_generated_texldd_setup; - int glsl_generated_texm3x3spec_helper; - int arb1_wrote_position; - int have_preshader; - int ignores_ctab; - int reset_texmpad; - int texm3x2pad_dst0; - int texm3x2pad_src0; - int texm3x3pad_dst0; - int texm3x3pad_src0; - int texm3x3pad_dst1; - int texm3x3pad_src1; - MOJOSHADER_preshader *preshader; - -#if SUPPORT_PROFILE_ARB1_NV - int profile_supports_nv2; - int profile_supports_nv3; - int profile_supports_nv4; -#endif -#if SUPPORT_PROFILE_GLSL120 - int profile_supports_glsl120; -#endif -} Context; - - -// Use these macros so we can remove all bits of these profiles from the build. -#if SUPPORT_PROFILE_ARB1_NV -#define support_nv2(ctx) ((ctx)->profile_supports_nv2) -#define support_nv3(ctx) ((ctx)->profile_supports_nv3) -#define support_nv4(ctx) ((ctx)->profile_supports_nv4) -#else -#define support_nv2(ctx) (0) -#define support_nv3(ctx) (0) -#define support_nv4(ctx) (0) -#endif - -#if SUPPORT_PROFILE_GLSL120 -#define support_glsl120(ctx) ((ctx)->profile_supports_glsl120) -#else -#define support_glsl120(ctx) (0) -#endif - - -// Profile entry points... - -// one emit function for each opcode in each profile. -typedef void (*emit_function)(Context *ctx); - -// one emit function for starting output in each profile. -typedef void (*emit_start)(Context *ctx, const char *profilestr); - -// one emit function for ending output in each profile. -typedef void (*emit_end)(Context *ctx); - -// one emit function for phase opcode output in each profile. -typedef void (*emit_phase)(Context *ctx); - -// one emit function for finalizing output in each profile. -typedef void (*emit_finalize)(Context *ctx); - -// one emit function for global definitions in each profile. -typedef void (*emit_global)(Context *ctx, RegisterType regtype, int regnum); - -// one emit function for relative uniform arrays in each profile. -typedef void (*emit_array)(Context *ctx, VariableList *var); - -// one emit function for relative constants arrays in each profile. -typedef void (*emit_const_array)(Context *ctx, - const struct ConstantsList *constslist, - int base, int size); - -// one emit function for uniforms in each profile. -typedef void (*emit_uniform)(Context *ctx, RegisterType regtype, int regnum, - const VariableList *var); - -// one emit function for samplers in each profile. -typedef void (*emit_sampler)(Context *ctx, int stage, TextureType ttype, - int texbem); - -// one emit function for attributes in each profile. -typedef void (*emit_attribute)(Context *ctx, RegisterType regtype, int regnum, - MOJOSHADER_usage usage, int index, int wmask, - int flags); - -// one args function for each possible sequence of opcode arguments. -typedef int (*args_function)(Context *ctx); - -// one state function for each opcode where we have state machine updates. -typedef void (*state_function)(Context *ctx); - -// one function for varnames in each profile. -typedef const char *(*varname_function)(Context *c, RegisterType t, int num); - -// one function for const var array in each profile. -typedef const char *(*const_array_varname_function)(Context *c, int base, int size); - -typedef struct Profile -{ - const char *name; - emit_start start_emitter; - emit_end end_emitter; - emit_phase phase_emitter; - emit_global global_emitter; - emit_array array_emitter; - emit_const_array const_array_emitter; - emit_uniform uniform_emitter; - emit_sampler sampler_emitter; - emit_attribute attribute_emitter; - emit_finalize finalize_emitter; - varname_function get_varname; - const_array_varname_function get_const_array_varname; -} Profile; - - -// Convenience functions for allocators... -#if !MOJOSHADER_FORCE_ALLOCATOR -void *MOJOSHADER_internal_malloc(int bytes, void *d) { return malloc(bytes); } -void MOJOSHADER_internal_free(void *ptr, void *d) { free(ptr); } -#endif - -MOJOSHADER_error MOJOSHADER_out_of_mem_error = { - "Out of memory", NULL, MOJOSHADER_POSITION_NONE -}; - -MOJOSHADER_parseData MOJOSHADER_out_of_mem_data = { - 1, &MOJOSHADER_out_of_mem_error, 0, 0, 0, 0, - MOJOSHADER_TYPE_UNKNOWN, 0, 0, 0, 0 -}; - - -// !!! FIXME: cut and paste between every damned source file follows... -// !!! FIXME: We need to make some sort of ContextBase that applies to all -// !!! FIXME: files and move this stuff to mojoshader_common.c ... - -static inline void out_of_memory(Context *ctx) -{ - ctx->isfail = ctx->out_of_memory = 1; -} // out_of_memory - -static inline void *Malloc(Context *ctx, const size_t len) -{ - void *retval = ctx->malloc((int) len, ctx->malloc_data); - if (retval == NULL) - out_of_memory(ctx); - return retval; -} // Malloc - -static inline char *StrDup(Context *ctx, const char *str) -{ - char *retval = (char *) Malloc(ctx, strlen(str) + 1); - if (retval != NULL) - strcpy(retval, str); - return retval; -} // StrDup - -static inline void Free(Context *ctx, void *ptr) -{ - ctx->free(ptr, ctx->malloc_data); -} // Free - -static void *MallocBridge(int bytes, void *data) -{ - return Malloc((Context *) data, (size_t) bytes); -} // MallocBridge - -static void FreeBridge(void *ptr, void *data) -{ - Free((Context *) data, ptr); -} // FreeBridge - - -// jump between output sections in the context... - -static int set_output(Context *ctx, Buffer **section) -{ - // only create output sections on first use. - if (*section == NULL) - { - *section = buffer_create(256, MallocBridge, FreeBridge, ctx); - if (*section == NULL) - return 0; - } // if - - ctx->output = *section; - return 1; -} // set_output - -static void push_output(Context *ctx, Buffer **section) -{ - assert(ctx->output_stack_len < (int) (STATICARRAYLEN(ctx->output_stack))); - ctx->output_stack[ctx->output_stack_len] = ctx->output; - ctx->indent_stack[ctx->output_stack_len] = ctx->indent; - ctx->output_stack_len++; - if (!set_output(ctx, section)) - return; - ctx->indent = 0; -} // push_output - -static inline void pop_output(Context *ctx) -{ - assert(ctx->output_stack_len > 0); - ctx->output_stack_len--; - ctx->output = ctx->output_stack[ctx->output_stack_len]; - ctx->indent = ctx->indent_stack[ctx->output_stack_len]; -} // pop_output - - - -// Shader model version magic... - -static inline uint32 ver_ui32(const uint8 major, const uint8 minor) -{ - return ( (((uint32) major) << 16) | (((minor) == 0xFF) ? 1 : (minor)) ); -} // version_ui32 - -static inline int shader_version_supported(const uint8 maj, const uint8 min) -{ - return (ver_ui32(maj,min) <= ver_ui32(MAX_SHADER_MAJOR, MAX_SHADER_MINOR)); -} // shader_version_supported - -static inline int shader_version_atleast(const Context *ctx, const uint8 maj, - const uint8 min) -{ - return (ver_ui32(ctx->major_ver, ctx->minor_ver) >= ver_ui32(maj, min)); -} // shader_version_atleast - -static inline int shader_version_exactly(const Context *ctx, const uint8 maj, - const uint8 min) -{ - return ((ctx->major_ver == maj) && (ctx->minor_ver == min)); -} // shader_version_exactly - -static inline int shader_is_pixel(const Context *ctx) -{ - return (ctx->shader_type == MOJOSHADER_TYPE_PIXEL); -} // shader_is_pixel - -static inline int shader_is_vertex(const Context *ctx) -{ - return (ctx->shader_type == MOJOSHADER_TYPE_VERTEX); -} // shader_is_vertex - - -static inline int isfail(const Context *ctx) -{ - return ctx->isfail; -} // isfail - - -static void failf(Context *ctx, const char *fmt, ...) ISPRINTF(2,3); -static void failf(Context *ctx, const char *fmt, ...) -{ - ctx->isfail = 1; - if (ctx->out_of_memory) - return; - - // no filename at this level (we pass a NULL to errorlist_add_va()...) - va_list ap; - va_start(ap, fmt); - errorlist_add_va(ctx->errors, NULL, ctx->current_position, fmt, ap); - va_end(ap); -} // failf - - -static inline void fail(Context *ctx, const char *reason) -{ - failf(ctx, "%s", reason); -} // fail - - -static void output_line(Context *ctx, const char *fmt, ...) ISPRINTF(2,3); -static void output_line(Context *ctx, const char *fmt, ...) -{ - assert(ctx->output != NULL); - if (isfail(ctx)) - return; // we failed previously, don't go on... - - const int indent = ctx->indent; - if (indent > 0) - { - char *indentbuf = (char *) alloca(indent); - memset(indentbuf, '\t', indent); - buffer_append(ctx->output, indentbuf, indent); - } // if - - va_list ap; - va_start(ap, fmt); - buffer_append_va(ctx->output, fmt, ap); - va_end(ap); - - buffer_append(ctx->output, ctx->endline, ctx->endline_len); -} // output_line - - -static inline void output_blank_line(Context *ctx) -{ - assert(ctx->output != NULL); - if (!isfail(ctx)) - buffer_append(ctx->output, ctx->endline, ctx->endline_len); -} // output_blank_line - - -// !!! FIXME: this is sort of nasty. -static void floatstr(Context *ctx, char *buf, size_t bufsize, float f, - int leavedecimal) -{ - const size_t len = snprintf(buf, bufsize, "%f", f); - if ((len+2) >= bufsize) - fail(ctx, "BUG: internal buffer is too small"); - else - { - char *end = buf + len; - char *ptr = strchr(buf, '.'); - if (ptr == NULL) - { - if (leavedecimal) - strcat(buf, ".0"); - return; // done. - } // if - - while (--end != ptr) - { - if (*end != '0') - { - end++; - break; - } // if - } // while - if ((leavedecimal) && (end == ptr)) - end += 2; - *end = '\0'; // chop extra '0' or all decimal places off. - } // else -} // floatstr - -static inline TextureType cvtMojoToD3DSamplerType(const MOJOSHADER_samplerType type) -{ - return (TextureType) (((int) type) + 2); -} // cvtMojoToD3DSamplerType - -static inline MOJOSHADER_samplerType cvtD3DToMojoSamplerType(const TextureType type) -{ - return (MOJOSHADER_samplerType) (((int) type) - 2); -} // cvtD3DToMojoSamplerType - +#include "profiles/mojoshader_profile.h" // Deal with register lists... !!! FIXME: I sort of hate this. @@ -512,70 +30,6 @@ static void free_reglist(MOJOSHADER_free f, void *d, RegisterList *item) } // while } // free_reglist -static inline uint32 reg_to_ui32(const RegisterType regtype, const int regnum) -{ - return ( ((uint32) regtype) | (((uint32) regnum) << 16) ); -} // reg_to_uint32 - -// !!! FIXME: ditch this for a hash table. -static RegisterList *reglist_insert(Context *ctx, RegisterList *prev, - const RegisterType regtype, - const int regnum) -{ - const uint32 newval = reg_to_ui32(regtype, regnum); - RegisterList *item = prev->next; - while (item != NULL) - { - const uint32 val = reg_to_ui32(item->regtype, item->regnum); - if (newval == val) - return item; // already set, so we're done. - else if (newval < val) // insert it here. - break; - else // if (newval > val) - { - // keep going, we're not to the insertion point yet. - prev = item; - item = item->next; - } // else - } // while - - // we need to insert an entry after (prev). - item = (RegisterList *) Malloc(ctx, sizeof (RegisterList)); - if (item != NULL) - { - item->regtype = regtype; - item->regnum = regnum; - item->usage = MOJOSHADER_USAGE_UNKNOWN; - item->index = 0; - item->writemask = 0; - item->misc = 0; - item->array = NULL; - item->next = prev->next; - prev->next = item; - } // if - - return item; -} // reglist_insert - -static RegisterList *reglist_find(const RegisterList *prev, - const RegisterType rtype, const int regnum) -{ - const uint32 newval = reg_to_ui32(rtype, regnum); - RegisterList *item = prev->next; - while (item != NULL) - { - const uint32 val = reg_to_ui32(item->regtype, item->regnum); - if (newval == val) - return item; // here it is. - else if (newval < val) // should have been here if it existed. - return NULL; - else // if (newval > val) - item = item->next; - } // while - - return NULL; // wasn't in the list. -} // reglist_find - static inline const RegisterList *reglist_exists(RegisterList *prev, const RegisterType regtype, const int regnum) @@ -590,33 +44,6 @@ static inline int register_was_written(Context *ctx, const RegisterType rtype, return (reg && reg->written); } // register_was_written -static inline RegisterList *set_used_register(Context *ctx, - const RegisterType regtype, - const int regnum, - const int written) -{ - RegisterList *reg = NULL; - if ((regtype == REG_TYPE_COLOROUT) && (regnum > 0)) - ctx->have_multi_color_outputs = 1; - - reg = reglist_insert(ctx, &ctx->used_registers, regtype, regnum); - if (reg && written) - reg->written = 1; - return reg; -} // set_used_register - -static inline int get_used_register(Context *ctx, const RegisterType regtype, - const int regnum) -{ - return (reglist_exists(&ctx->used_registers, regtype, regnum) != NULL); -} // get_used_register - -static inline void set_defined_register(Context *ctx, const RegisterType rtype, - const int regnum) -{ - reglist_insert(ctx, &ctx->defined_registers, rtype, regnum); -} // set_defined_register - static inline int get_defined_register(Context *ctx, const RegisterType rtype, const int regnum) { @@ -639,6 +66,16 @@ static void add_attribute_register(Context *ctx, const RegisterType rtype, ctx->uses_fog = 1; // note that we have to check this later. } // add_attribute_register +static inline TextureType cvtMojoToD3DSamplerType(const MOJOSHADER_samplerType type) +{ + return (TextureType) (((int) type) + 2); +} // cvtMojoToD3DSamplerType + +static inline MOJOSHADER_samplerType cvtD3DToMojoSamplerType(const TextureType type) +{ + return (MOJOSHADER_samplerType) (((int) type) - 2); +} // cvtD3DToMojoSamplerType + static inline void add_sampler(Context *ctx, const int regnum, TextureType ttype, const int texbem) { @@ -665,80 +102,6 @@ static inline void add_sampler(Context *ctx, const int regnum, item->misc |= texbem; } // add_sampler - -static inline int writemask_xyzw(const int writemask) -{ - return (writemask == 0xF); // 0xF == 1111. No explicit mask (full!). -} // writemask_xyzw - - -static inline int writemask_xyz(const int writemask) -{ - return (writemask == 0x7); // 0x7 == 0111. (that is: xyz) -} // writemask_xyz - - -static inline int writemask_xy(const int writemask) -{ - return (writemask == 0x3); // 0x3 == 0011. (that is: xy) -} // writemask_xy - - -static inline int writemask_x(const int writemask) -{ - return (writemask == 0x1); // 0x1 == 0001. (that is: x) -} // writemask_x - - -static inline int writemask_y(const int writemask) -{ - return (writemask == 0x2); // 0x1 == 0010. (that is: y) -} // writemask_y - - -static inline int replicate_swizzle(const int swizzle) -{ - return ( (((swizzle >> 0) & 0x3) == ((swizzle >> 2) & 0x3)) && - (((swizzle >> 2) & 0x3) == ((swizzle >> 4) & 0x3)) && - (((swizzle >> 4) & 0x3) == ((swizzle >> 6) & 0x3)) ); -} // replicate_swizzle - - -static inline int no_swizzle(const int swizzle) -{ - return (swizzle == 0xE4); // 0xE4 == 11100100 ... 0 1 2 3. No swizzle. -} // no_swizzle - - -static inline int vecsize_from_writemask(const int m) -{ - return (m & 1) + ((m >> 1) & 1) + ((m >> 2) & 1) + ((m >> 3) & 1); -} // vecsize_from_writemask - - -static inline void set_dstarg_writemask(DestArgInfo *dst, const int mask) -{ - dst->writemask = mask; - dst->writemask0 = ((mask >> 0) & 1); - dst->writemask1 = ((mask >> 1) & 1); - dst->writemask2 = ((mask >> 2) & 1); - dst->writemask3 = ((mask >> 3) & 1); -} // set_dstarg_writemask - - -static int allocate_scratch_register(Context *ctx) -{ - const int retval = ctx->scratch_registers++; - if (retval >= ctx->max_scratch_registers) - ctx->max_scratch_registers = retval + 1; - return retval; -} // allocate_scratch_register - -static int allocate_branch_label(Context *ctx) -{ - return ctx->assigned_branch_labels++; -} // allocate_branch_label - static inline void adjust_token_position(Context *ctx, const int incr) { ctx->tokens += incr; @@ -746,5423 +109,177 @@ static inline void adjust_token_position(Context *ctx, const int incr) ctx->current_position += incr * sizeof (uint32); } // adjust_token_position +// Generate emitter declarations for each profile with this macro... + +#define PREDECLARE_PROFILE(prof) \ + void emit_##prof##_start(Context *ctx, const char *profilestr); \ + void emit_##prof##_end(Context *ctx); \ + void emit_##prof##_phase(Context *ctx); \ + void emit_##prof##_finalize(Context *ctx); \ + void emit_##prof##_global(Context *ctx, RegisterType regtype, int regnum);\ + void emit_##prof##_array(Context *ctx, VariableList *var); \ + void emit_##prof##_const_array(Context *ctx, const ConstantsList *clist, \ + int base, int size); \ + void emit_##prof##_uniform(Context *ctx, RegisterType regtype, int regnum,\ + const VariableList *var); \ + void emit_##prof##_sampler(Context *ctx, int stage, TextureType ttype, \ + int tb); \ + void emit_##prof##_attribute(Context *ctx, RegisterType regtype, \ + int regnum, MOJOSHADER_usage usage, \ + int index, int wmask, int flags); \ + void emit_##prof##_NOP(Context *ctx); \ + void emit_##prof##_MOV(Context *ctx); \ + void emit_##prof##_ADD(Context *ctx); \ + void emit_##prof##_SUB(Context *ctx); \ + void emit_##prof##_MAD(Context *ctx); \ + void emit_##prof##_MUL(Context *ctx); \ + void emit_##prof##_RCP(Context *ctx); \ + void emit_##prof##_RSQ(Context *ctx); \ + void emit_##prof##_DP3(Context *ctx); \ + void emit_##prof##_DP4(Context *ctx); \ + void emit_##prof##_MIN(Context *ctx); \ + void emit_##prof##_MAX(Context *ctx); \ + void emit_##prof##_SLT(Context *ctx); \ + void emit_##prof##_SGE(Context *ctx); \ + void emit_##prof##_EXP(Context *ctx); \ + void emit_##prof##_LOG(Context *ctx); \ + void emit_##prof##_LIT(Context *ctx); \ + void emit_##prof##_DST(Context *ctx); \ + void emit_##prof##_LRP(Context *ctx); \ + void emit_##prof##_FRC(Context *ctx); \ + void emit_##prof##_M4X4(Context *ctx); \ + void emit_##prof##_M4X3(Context *ctx); \ + void emit_##prof##_M3X4(Context *ctx); \ + void emit_##prof##_M3X3(Context *ctx); \ + void emit_##prof##_M3X2(Context *ctx); \ + void emit_##prof##_CALL(Context *ctx); \ + void emit_##prof##_CALLNZ(Context *ctx); \ + void emit_##prof##_LOOP(Context *ctx); \ + void emit_##prof##_ENDLOOP(Context *ctx); \ + void emit_##prof##_LABEL(Context *ctx); \ + void emit_##prof##_DCL(Context *ctx); \ + void emit_##prof##_POW(Context *ctx); \ + void emit_##prof##_CRS(Context *ctx); \ + void emit_##prof##_SGN(Context *ctx); \ + void emit_##prof##_ABS(Context *ctx); \ + void emit_##prof##_NRM(Context *ctx); \ + void emit_##prof##_SINCOS(Context *ctx); \ + void emit_##prof##_REP(Context *ctx); \ + void emit_##prof##_ENDREP(Context *ctx); \ + void emit_##prof##_IF(Context *ctx); \ + void emit_##prof##_IFC(Context *ctx); \ + void emit_##prof##_ELSE(Context *ctx); \ + void emit_##prof##_ENDIF(Context *ctx); \ + void emit_##prof##_BREAK(Context *ctx); \ + void emit_##prof##_BREAKC(Context *ctx); \ + void emit_##prof##_MOVA(Context *ctx); \ + void emit_##prof##_DEFB(Context *ctx); \ + void emit_##prof##_DEFI(Context *ctx); \ + void emit_##prof##_TEXCRD(Context *ctx); \ + void emit_##prof##_TEXKILL(Context *ctx); \ + void emit_##prof##_TEXLD(Context *ctx); \ + void emit_##prof##_TEXBEM(Context *ctx); \ + void emit_##prof##_TEXBEML(Context *ctx); \ + void emit_##prof##_TEXREG2AR(Context *ctx); \ + void emit_##prof##_TEXREG2GB(Context *ctx); \ + void emit_##prof##_TEXM3X2PAD(Context *ctx); \ + void emit_##prof##_TEXM3X2TEX(Context *ctx); \ + void emit_##prof##_TEXM3X3PAD(Context *ctx); \ + void emit_##prof##_TEXM3X3TEX(Context *ctx); \ + void emit_##prof##_TEXM3X3SPEC(Context *ctx); \ + void emit_##prof##_TEXM3X3VSPEC(Context *ctx); \ + void emit_##prof##_EXPP(Context *ctx); \ + void emit_##prof##_LOGP(Context *ctx); \ + void emit_##prof##_CND(Context *ctx); \ + void emit_##prof##_DEF(Context *ctx); \ + void emit_##prof##_TEXREG2RGB(Context *ctx); \ + void emit_##prof##_TEXDP3TEX(Context *ctx); \ + void emit_##prof##_TEXM3X2DEPTH(Context *ctx); \ + void emit_##prof##_TEXDP3(Context *ctx); \ + void emit_##prof##_TEXM3X3(Context *ctx); \ + void emit_##prof##_TEXDEPTH(Context *ctx); \ + void emit_##prof##_CMP(Context *ctx); \ + void emit_##prof##_BEM(Context *ctx); \ + void emit_##prof##_DP2ADD(Context *ctx); \ + void emit_##prof##_DSX(Context *ctx); \ + void emit_##prof##_DSY(Context *ctx); \ + void emit_##prof##_TEXLDD(Context *ctx); \ + void emit_##prof##_SETP(Context *ctx); \ + void emit_##prof##_TEXLDL(Context *ctx); \ + void emit_##prof##_BREAKP(Context *ctx); \ + void emit_##prof##_RESERVED(Context *ctx); \ + void emit_##prof##_RET(Context *ctx); \ + const char *get_##prof##_varname(Context *ctx, RegisterType rt, \ + int regnum); \ + const char *get_##prof##_const_array_varname(Context *ctx, \ + int base, int size); + +// Check for profile support... -// D3D stuff that's used in more than just the d3d profile... - -static int isscalar(Context *ctx, const MOJOSHADER_shaderType shader_type, - const RegisterType rtype, const int rnum) -{ - const int uses_psize = ctx->uses_pointsize; - const int uses_fog = ctx->uses_fog; - if ( (rtype == REG_TYPE_OUTPUT) && ((uses_psize) || (uses_fog)) ) - { - const RegisterList *reg = reglist_find(&ctx->attributes, rtype, rnum); - if (reg != NULL) - { - const MOJOSHADER_usage usage = reg->usage; - return ( (uses_psize && (usage == MOJOSHADER_USAGE_POINTSIZE)) || - (uses_fog && (usage == MOJOSHADER_USAGE_FOG)) ); - } // if - } // if +#define AT_LEAST_ONE_PROFILE 0 - return scalar_register(shader_type, rtype, rnum); -} // isscalar +#if !SUPPORT_PROFILE_BYTECODE +#define PROFILE_EMITTER_BYTECODE(op) +#else +#undef AT_LEAST_ONE_PROFILE +#define AT_LEAST_ONE_PROFILE 1 +#define PROFILE_EMITTER_BYTECODE(op) emit_BYTECODE_##op, +PREDECLARE_PROFILE(BYTECODE) +#endif -static const char swizzle_channels[] = { 'x', 'y', 'z', 'w' }; +#if !SUPPORT_PROFILE_D3D +#define PROFILE_EMITTER_D3D(op) +#else +#undef AT_LEAST_ONE_PROFILE +#define AT_LEAST_ONE_PROFILE 1 +#define PROFILE_EMITTER_D3D(op) emit_D3D_##op, +PREDECLARE_PROFILE(D3D) +#endif +#if !SUPPORT_PROFILE_HLSL +#define PROFILE_EMITTER_HLSL(op) +#else +#undef AT_LEAST_ONE_PROFILE +#define AT_LEAST_ONE_PROFILE 1 +#define PROFILE_EMITTER_HLSL(op) emit_HLSL_##op, +PREDECLARE_PROFILE(HLSL) +#endif -static const char *usagestrs[] = { - "_position", "_blendweight", "_blendindices", "_normal", "_psize", - "_texcoord", "_tangent", "_binormal", "_tessfactor", "_positiont", - "_color", "_fog", "_depth", "_sample" -}; +#if !SUPPORT_PROFILE_GLSL +#define PROFILE_EMITTER_GLSL(op) +#else +#undef AT_LEAST_ONE_PROFILE +#define AT_LEAST_ONE_PROFILE 1 +#define PROFILE_EMITTER_GLSL(op) emit_GLSL_##op, +PREDECLARE_PROFILE(GLSL) +#endif -static const char *get_D3D_register_string(Context *ctx, - RegisterType regtype, - int regnum, char *regnum_str, - size_t regnum_size) -{ - const char *retval = NULL; - int has_number = 1; +#if !SUPPORT_PROFILE_METAL +#define PROFILE_EMITTER_METAL(op) +#else +#undef AT_LEAST_ONE_PROFILE +#define AT_LEAST_ONE_PROFILE 1 +#define PROFILE_EMITTER_METAL(op) emit_METAL_##op, +PREDECLARE_PROFILE(METAL) +#endif - switch (regtype) - { - case REG_TYPE_TEMP: - retval = "r"; - break; - - case REG_TYPE_INPUT: - retval = "v"; - break; - - case REG_TYPE_CONST: - retval = "c"; - break; - - case REG_TYPE_ADDRESS: // (or REG_TYPE_TEXTURE, same value.) - retval = shader_is_vertex(ctx) ? "a" : "t"; - break; - - case REG_TYPE_RASTOUT: - switch ((RastOutType) regnum) - { - case RASTOUT_TYPE_POSITION: retval = "oPos"; break; - case RASTOUT_TYPE_FOG: retval = "oFog"; break; - case RASTOUT_TYPE_POINT_SIZE: retval = "oPts"; break; - } // switch - has_number = 0; - break; - - case REG_TYPE_ATTROUT: - retval = "oD"; - break; - - case REG_TYPE_OUTPUT: // (or REG_TYPE_TEXCRDOUT, same value.) - if (shader_is_vertex(ctx) && shader_version_atleast(ctx, 3, 0)) - retval = "o"; - else - retval = "oT"; - break; - - case REG_TYPE_CONSTINT: - retval = "i"; - break; - - case REG_TYPE_COLOROUT: - retval = "oC"; - break; - - case REG_TYPE_DEPTHOUT: - retval = "oDepth"; - has_number = 0; - break; - - case REG_TYPE_SAMPLER: - retval = "s"; - break; - - case REG_TYPE_CONSTBOOL: - retval = "b"; - break; - - case REG_TYPE_LOOP: - retval = "aL"; - has_number = 0; - break; - - case REG_TYPE_MISCTYPE: - switch ((const MiscTypeType) regnum) - { - case MISCTYPE_TYPE_POSITION: retval = "vPos"; break; - case MISCTYPE_TYPE_FACE: retval = "vFace"; break; - } // switch - has_number = 0; - break; - - case REG_TYPE_LABEL: - retval = "l"; - break; - - case REG_TYPE_PREDICATE: - retval = "p"; - break; - - //case REG_TYPE_TEMPFLOAT16: // !!! FIXME: don't know this asm string - default: - fail(ctx, "unknown register type"); - retval = "???"; - has_number = 0; - break; - } // switch - - if (has_number) - snprintf(regnum_str, regnum_size, "%u", (uint) regnum); - else - regnum_str[0] = '\0'; - - return retval; -} // get_D3D_register_string - - -// !!! FIXME: can we split the profile code out to separate source files? - -#define AT_LEAST_ONE_PROFILE 0 - -#if !SUPPORT_PROFILE_D3D -#define PROFILE_EMITTER_D3D(op) -#else -#undef AT_LEAST_ONE_PROFILE -#define AT_LEAST_ONE_PROFILE 1 -#define PROFILE_EMITTER_D3D(op) emit_D3D_##op, - -static const char *make_D3D_srcarg_string_in_buf(Context *ctx, - const SourceArgInfo *arg, - char *buf, size_t buflen) -{ - const char *premod_str = ""; - const char *postmod_str = ""; - switch (arg->src_mod) - { - case SRCMOD_NEGATE: - premod_str = "-"; - break; - - case SRCMOD_BIASNEGATE: - premod_str = "-"; - // fall through. - case SRCMOD_BIAS: - postmod_str = "_bias"; - break; - - case SRCMOD_SIGNNEGATE: - premod_str = "-"; - // fall through. - case SRCMOD_SIGN: - postmod_str = "_bx2"; - break; - - case SRCMOD_COMPLEMENT: - premod_str = "1-"; - break; - - case SRCMOD_X2NEGATE: - premod_str = "-"; - // fall through. - case SRCMOD_X2: - postmod_str = "_x2"; - break; - - case SRCMOD_DZ: - postmod_str = "_dz"; - break; - - case SRCMOD_DW: - postmod_str = "_dw"; - break; - - case SRCMOD_ABSNEGATE: - premod_str = "-"; - // fall through. - case SRCMOD_ABS: - postmod_str = "_abs"; - break; - - case SRCMOD_NOT: - premod_str = "!"; - break; - - case SRCMOD_NONE: - case SRCMOD_TOTAL: - break; // stop compiler whining. - } // switch - - - char regnum_str[16]; - const char *regtype_str = get_D3D_register_string(ctx, arg->regtype, - arg->regnum, regnum_str, - sizeof (regnum_str)); - - if (regtype_str == NULL) - { - fail(ctx, "Unknown source register type."); - *buf = '\0'; - return buf; - } // if - - const char *rel_lbracket = ""; - const char *rel_rbracket = ""; - char rel_swizzle[4] = { '\0' }; - char rel_regnum_str[16] = { '\0' }; - const char *rel_regtype_str = ""; - if (arg->relative) - { - rel_swizzle[0] = '.'; - rel_swizzle[1] = swizzle_channels[arg->relative_component]; - rel_swizzle[2] = '\0'; - rel_lbracket = "["; - rel_rbracket = "]"; - rel_regtype_str = get_D3D_register_string(ctx, arg->relative_regtype, - arg->relative_regnum, - rel_regnum_str, - sizeof (rel_regnum_str)); - - if (regtype_str == NULL) - { - fail(ctx, "Unknown relative source register type."); - *buf = '\0'; - return buf; - } // if - } // if - - char swizzle_str[6]; - size_t i = 0; - const int scalar = isscalar(ctx, ctx->shader_type, arg->regtype, arg->regnum); - if (!scalar && !no_swizzle(arg->swizzle)) - { - swizzle_str[i++] = '.'; - swizzle_str[i++] = swizzle_channels[arg->swizzle_x]; - swizzle_str[i++] = swizzle_channels[arg->swizzle_y]; - swizzle_str[i++] = swizzle_channels[arg->swizzle_z]; - swizzle_str[i++] = swizzle_channels[arg->swizzle_w]; - - // .xyzz is the same as .xyz, .z is the same as .zzzz, etc. - while (swizzle_str[i-1] == swizzle_str[i-2]) - i--; - } // if - swizzle_str[i] = '\0'; - assert(i < sizeof (swizzle_str)); - - // !!! FIXME: c12[a0.x] actually needs to be c[a0.x + 12] - snprintf(buf, buflen, "%s%s%s%s%s%s%s%s%s%s", - premod_str, regtype_str, regnum_str, postmod_str, - rel_lbracket, rel_regtype_str, rel_regnum_str, rel_swizzle, - rel_rbracket, swizzle_str); - // !!! FIXME: make sure the scratch buffer was large enough. - return buf; -} // make_D3D_srcarg_string_in_buf - - -static const char *make_D3D_destarg_string(Context *ctx, char *buf, - const size_t buflen) -{ - const DestArgInfo *arg = &ctx->dest_arg; - - const char *result_shift_str = ""; - switch (arg->result_shift) - { - case 0x1: result_shift_str = "_x2"; break; - case 0x2: result_shift_str = "_x4"; break; - case 0x3: result_shift_str = "_x8"; break; - case 0xD: result_shift_str = "_d8"; break; - case 0xE: result_shift_str = "_d4"; break; - case 0xF: result_shift_str = "_d2"; break; - } // switch - - const char *sat_str = (arg->result_mod & MOD_SATURATE) ? "_sat" : ""; - const char *pp_str = (arg->result_mod & MOD_PP) ? "_pp" : ""; - const char *cent_str = (arg->result_mod & MOD_CENTROID) ? "_centroid" : ""; - - char regnum_str[16]; - const char *regtype_str = get_D3D_register_string(ctx, arg->regtype, - arg->regnum, regnum_str, - sizeof (regnum_str)); - if (regtype_str == NULL) - { - fail(ctx, "Unknown destination register type."); - *buf = '\0'; - return buf; - } // if - - char writemask_str[6]; - size_t i = 0; - const int scalar = isscalar(ctx, ctx->shader_type, arg->regtype, arg->regnum); - if (!scalar && !writemask_xyzw(arg->writemask)) - { - writemask_str[i++] = '.'; - if (arg->writemask0) writemask_str[i++] = 'x'; - if (arg->writemask1) writemask_str[i++] = 'y'; - if (arg->writemask2) writemask_str[i++] = 'z'; - if (arg->writemask3) writemask_str[i++] = 'w'; - } // if - writemask_str[i] = '\0'; - assert(i < sizeof (writemask_str)); - - const char *pred_left = ""; - const char *pred_right = ""; - char pred[32] = { '\0' }; - if (ctx->predicated) - { - pred_left = "("; - pred_right = ") "; - make_D3D_srcarg_string_in_buf(ctx, &ctx->predicate_arg, - pred, sizeof (pred)); - } // if - - // may turn out something like "_x2_sat_pp_centroid (!p0.x) r0.xyzw" ... - snprintf(buf, buflen, "%s%s%s%s %s%s%s%s%s%s", - result_shift_str, sat_str, pp_str, cent_str, - pred_left, pred, pred_right, - regtype_str, regnum_str, writemask_str); - // !!! FIXME: make sure the scratch buffer was large enough. - return buf; -} // make_D3D_destarg_string - - -static const char *make_D3D_srcarg_string(Context *ctx, const size_t idx, - char *buf, size_t buflen) -{ - if (idx >= STATICARRAYLEN(ctx->source_args)) - { - fail(ctx, "Too many source args"); - *buf = '\0'; - return buf; - } // if - - const SourceArgInfo *arg = &ctx->source_args[idx]; - return make_D3D_srcarg_string_in_buf(ctx, arg, buf, buflen); -} // make_D3D_srcarg_string - -static const char *get_D3D_varname_in_buf(Context *ctx, RegisterType rt, - int regnum, char *buf, - const size_t len) -{ - char regnum_str[16]; - const char *regtype_str = get_D3D_register_string(ctx, rt, regnum, - regnum_str, sizeof (regnum_str)); - snprintf(buf,len,"%s%s", regtype_str, regnum_str); - return buf; -} // get_D3D_varname_in_buf - - -static const char *get_D3D_varname(Context *ctx, RegisterType rt, int regnum) -{ - char buf[64]; - get_D3D_varname_in_buf(ctx, rt, regnum, buf, sizeof (buf)); - return StrDup(ctx, buf); -} // get_D3D_varname - - -static const char *get_D3D_const_array_varname(Context *ctx, int base, int size) -{ - char buf[64]; - snprintf(buf, sizeof (buf), "c_array_%d_%d", base, size); - return StrDup(ctx, buf); -} // get_D3D_const_array_varname - - -static void emit_D3D_start(Context *ctx, const char *profilestr) -{ - const uint major = (uint) ctx->major_ver; - const uint minor = (uint) ctx->minor_ver; - char minor_str[16]; - - ctx->ignores_ctab = 1; - - if (minor == 0xFF) - strcpy(minor_str, "sw"); - else if ((major > 1) && (minor == 1)) - strcpy(minor_str, "x"); // for >= SM2, apparently this is "x". Weird. - else - snprintf(minor_str, sizeof (minor_str), "%u", (uint) minor); - - output_line(ctx, "%s_%u_%s", ctx->shader_type_str, major, minor_str); -} // emit_D3D_start - - -static void emit_D3D_end(Context *ctx) -{ - output_line(ctx, "end"); -} // emit_D3D_end - - -static void emit_D3D_phase(Context *ctx) -{ - output_line(ctx, "phase"); -} // emit_D3D_phase - - -static void emit_D3D_finalize(Context *ctx) -{ - // no-op. -} // emit_D3D_finalize - - -static void emit_D3D_global(Context *ctx, RegisterType regtype, int regnum) -{ - // no-op. -} // emit_D3D_global - - -static void emit_D3D_array(Context *ctx, VariableList *var) -{ - // no-op. -} // emit_D3D_array - - -static void emit_D3D_const_array(Context *ctx, const ConstantsList *clist, - int base, int size) -{ - // no-op. -} // emit_D3D_const_array - - -static void emit_D3D_uniform(Context *ctx, RegisterType regtype, int regnum, - const VariableList *var) -{ - // no-op. -} // emit_D3D_uniform - - -static void emit_D3D_sampler(Context *ctx, int s, TextureType ttype, int tb) -{ - // no-op. -} // emit_D3D_sampler - - -static void emit_D3D_attribute(Context *ctx, RegisterType regtype, int regnum, - MOJOSHADER_usage usage, int index, int wmask, - int flags) -{ - // no-op. -} // emit_D3D_attribute - - -static void emit_D3D_RESERVED(Context *ctx) -{ - // do nothing; fails in the state machine. -} // emit_D3D_RESERVED - - -// Generic D3D opcode emitters. A list of macros generate all the entry points -// that call into these... - -static char *lowercase(char *dst, const char *src) -{ - int i = 0; - do - { - const char ch = src[i]; - dst[i] = (((ch >= 'A') && (ch <= 'Z')) ? (ch - ('A' - 'a')) : ch); - } while (src[i++]); - return dst; -} // lowercase - - -static void emit_D3D_opcode_d(Context *ctx, const char *opcode) -{ - char dst[64]; make_D3D_destarg_string(ctx, dst, sizeof (dst)); - opcode = lowercase((char *) alloca(strlen(opcode) + 1), opcode); - output_line(ctx, "%s%s%s", ctx->coissue ? "+" : "", opcode, dst); -} // emit_D3D_opcode_d - - -static void emit_D3D_opcode_s(Context *ctx, const char *opcode) -{ - char src0[64]; make_D3D_srcarg_string(ctx, 0, src0, sizeof (src0)); - opcode = lowercase((char *) alloca(strlen(opcode) + 1), opcode); - output_line(ctx, "%s%s %s", ctx->coissue ? "+" : "", opcode, src0); -} // emit_D3D_opcode_s - - -static void emit_D3D_opcode_ss(Context *ctx, const char *opcode) -{ - char src0[64]; make_D3D_srcarg_string(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_D3D_srcarg_string(ctx, 1, src1, sizeof (src1)); - opcode = lowercase((char *) alloca(strlen(opcode) + 1), opcode); - output_line(ctx, "%s%s %s, %s", ctx->coissue ? "+" : "", opcode, src0, src1); -} // emit_D3D_opcode_ss - - -static void emit_D3D_opcode_ds(Context *ctx, const char *opcode) -{ - char dst[64]; make_D3D_destarg_string(ctx, dst, sizeof (dst)); - char src0[64]; make_D3D_srcarg_string(ctx, 0, src0, sizeof (src0)); - opcode = lowercase((char *) alloca(strlen(opcode) + 1), opcode); - output_line(ctx, "%s%s%s, %s", ctx->coissue ? "+" : "", opcode, dst, src0); -} // emit_D3D_opcode_ds - - -static void emit_D3D_opcode_dss(Context *ctx, const char *opcode) -{ - char dst[64]; make_D3D_destarg_string(ctx, dst, sizeof (dst)); - char src0[64]; make_D3D_srcarg_string(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_D3D_srcarg_string(ctx, 1, src1, sizeof (src1)); - opcode = lowercase((char *) alloca(strlen(opcode) + 1), opcode); - output_line(ctx, "%s%s%s, %s, %s", ctx->coissue ? "+" : "", - opcode, dst, src0, src1); -} // emit_D3D_opcode_dss - - -static void emit_D3D_opcode_dsss(Context *ctx, const char *opcode) -{ - char dst[64]; make_D3D_destarg_string(ctx, dst, sizeof (dst)); - char src0[64]; make_D3D_srcarg_string(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_D3D_srcarg_string(ctx, 1, src1, sizeof (src1)); - char src2[64]; make_D3D_srcarg_string(ctx, 2, src2, sizeof (src2)); - opcode = lowercase((char *) alloca(strlen(opcode) + 1), opcode); - output_line(ctx, "%s%s%s, %s, %s, %s", ctx->coissue ? "+" : "", - opcode, dst, src0, src1, src2); -} // emit_D3D_opcode_dsss - - -static void emit_D3D_opcode_dssss(Context *ctx, const char *opcode) -{ - char dst[64]; make_D3D_destarg_string(ctx, dst, sizeof (dst)); - char src0[64]; make_D3D_srcarg_string(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_D3D_srcarg_string(ctx, 1, src1, sizeof (src1)); - char src2[64]; make_D3D_srcarg_string(ctx, 2, src2, sizeof (src2)); - char src3[64]; make_D3D_srcarg_string(ctx, 3, src3, sizeof (src3)); - opcode = lowercase((char *) alloca(strlen(opcode) + 1), opcode); - output_line(ctx,"%s%s%s, %s, %s, %s, %s", ctx->coissue ? "+" : "", - opcode, dst, src0, src1, src2, src3); -} // emit_D3D_opcode_dssss - - -static void emit_D3D_opcode(Context *ctx, const char *opcode) -{ - opcode = lowercase((char *) alloca(strlen(opcode) + 1), opcode); - output_line(ctx, "%s%s", ctx->coissue ? "+" : "", opcode); -} // emit_D3D_opcode - - -#define EMIT_D3D_OPCODE_FUNC(op) \ - static void emit_D3D_##op(Context *ctx) { \ - emit_D3D_opcode(ctx, #op); \ - } -#define EMIT_D3D_OPCODE_D_FUNC(op) \ - static void emit_D3D_##op(Context *ctx) { \ - emit_D3D_opcode_d(ctx, #op); \ - } -#define EMIT_D3D_OPCODE_S_FUNC(op) \ - static void emit_D3D_##op(Context *ctx) { \ - emit_D3D_opcode_s(ctx, #op); \ - } -#define EMIT_D3D_OPCODE_SS_FUNC(op) \ - static void emit_D3D_##op(Context *ctx) { \ - emit_D3D_opcode_ss(ctx, #op); \ - } -#define EMIT_D3D_OPCODE_DS_FUNC(op) \ - static void emit_D3D_##op(Context *ctx) { \ - emit_D3D_opcode_ds(ctx, #op); \ - } -#define EMIT_D3D_OPCODE_DSS_FUNC(op) \ - static void emit_D3D_##op(Context *ctx) { \ - emit_D3D_opcode_dss(ctx, #op); \ - } -#define EMIT_D3D_OPCODE_DSSS_FUNC(op) \ - static void emit_D3D_##op(Context *ctx) { \ - emit_D3D_opcode_dsss(ctx, #op); \ - } -#define EMIT_D3D_OPCODE_DSSSS_FUNC(op) \ - static void emit_D3D_##op(Context *ctx) { \ - emit_D3D_opcode_dssss(ctx, #op); \ - } - -EMIT_D3D_OPCODE_FUNC(NOP) -EMIT_D3D_OPCODE_DS_FUNC(MOV) -EMIT_D3D_OPCODE_DSS_FUNC(ADD) -EMIT_D3D_OPCODE_DSS_FUNC(SUB) -EMIT_D3D_OPCODE_DSSS_FUNC(MAD) -EMIT_D3D_OPCODE_DSS_FUNC(MUL) -EMIT_D3D_OPCODE_DS_FUNC(RCP) -EMIT_D3D_OPCODE_DS_FUNC(RSQ) -EMIT_D3D_OPCODE_DSS_FUNC(DP3) -EMIT_D3D_OPCODE_DSS_FUNC(DP4) -EMIT_D3D_OPCODE_DSS_FUNC(MIN) -EMIT_D3D_OPCODE_DSS_FUNC(MAX) -EMIT_D3D_OPCODE_DSS_FUNC(SLT) -EMIT_D3D_OPCODE_DSS_FUNC(SGE) -EMIT_D3D_OPCODE_DS_FUNC(EXP) -EMIT_D3D_OPCODE_DS_FUNC(LOG) -EMIT_D3D_OPCODE_DS_FUNC(LIT) -EMIT_D3D_OPCODE_DSS_FUNC(DST) -EMIT_D3D_OPCODE_DSSS_FUNC(LRP) -EMIT_D3D_OPCODE_DS_FUNC(FRC) -EMIT_D3D_OPCODE_DSS_FUNC(M4X4) -EMIT_D3D_OPCODE_DSS_FUNC(M4X3) -EMIT_D3D_OPCODE_DSS_FUNC(M3X4) -EMIT_D3D_OPCODE_DSS_FUNC(M3X3) -EMIT_D3D_OPCODE_DSS_FUNC(M3X2) -EMIT_D3D_OPCODE_S_FUNC(CALL) -EMIT_D3D_OPCODE_SS_FUNC(CALLNZ) -EMIT_D3D_OPCODE_SS_FUNC(LOOP) -EMIT_D3D_OPCODE_FUNC(RET) -EMIT_D3D_OPCODE_FUNC(ENDLOOP) -EMIT_D3D_OPCODE_S_FUNC(LABEL) -EMIT_D3D_OPCODE_DSS_FUNC(POW) -EMIT_D3D_OPCODE_DSS_FUNC(CRS) -EMIT_D3D_OPCODE_DSSS_FUNC(SGN) -EMIT_D3D_OPCODE_DS_FUNC(ABS) -EMIT_D3D_OPCODE_DS_FUNC(NRM) -EMIT_D3D_OPCODE_S_FUNC(REP) -EMIT_D3D_OPCODE_FUNC(ENDREP) -EMIT_D3D_OPCODE_S_FUNC(IF) -EMIT_D3D_OPCODE_FUNC(ELSE) -EMIT_D3D_OPCODE_FUNC(ENDIF) -EMIT_D3D_OPCODE_FUNC(BREAK) -EMIT_D3D_OPCODE_DS_FUNC(MOVA) -EMIT_D3D_OPCODE_D_FUNC(TEXKILL) -EMIT_D3D_OPCODE_DS_FUNC(TEXBEM) -EMIT_D3D_OPCODE_DS_FUNC(TEXBEML) -EMIT_D3D_OPCODE_DS_FUNC(TEXREG2AR) -EMIT_D3D_OPCODE_DS_FUNC(TEXREG2GB) -EMIT_D3D_OPCODE_DS_FUNC(TEXM3X2PAD) -EMIT_D3D_OPCODE_DS_FUNC(TEXM3X2TEX) -EMIT_D3D_OPCODE_DS_FUNC(TEXM3X3PAD) -EMIT_D3D_OPCODE_DS_FUNC(TEXM3X3TEX) -EMIT_D3D_OPCODE_DSS_FUNC(TEXM3X3SPEC) -EMIT_D3D_OPCODE_DS_FUNC(TEXM3X3VSPEC) -EMIT_D3D_OPCODE_DS_FUNC(EXPP) -EMIT_D3D_OPCODE_DS_FUNC(LOGP) -EMIT_D3D_OPCODE_DSSS_FUNC(CND) -EMIT_D3D_OPCODE_DS_FUNC(TEXREG2RGB) -EMIT_D3D_OPCODE_DS_FUNC(TEXDP3TEX) -EMIT_D3D_OPCODE_DS_FUNC(TEXM3X2DEPTH) -EMIT_D3D_OPCODE_DS_FUNC(TEXDP3) -EMIT_D3D_OPCODE_DS_FUNC(TEXM3X3) -EMIT_D3D_OPCODE_D_FUNC(TEXDEPTH) -EMIT_D3D_OPCODE_DSSS_FUNC(CMP) -EMIT_D3D_OPCODE_DSS_FUNC(BEM) -EMIT_D3D_OPCODE_DSSS_FUNC(DP2ADD) -EMIT_D3D_OPCODE_DS_FUNC(DSX) -EMIT_D3D_OPCODE_DS_FUNC(DSY) -EMIT_D3D_OPCODE_DSSSS_FUNC(TEXLDD) -EMIT_D3D_OPCODE_DSS_FUNC(TEXLDL) -EMIT_D3D_OPCODE_S_FUNC(BREAKP) - -// special cases for comparison opcodes... -static const char *get_D3D_comparison_string(Context *ctx) -{ - static const char *comps[] = { - "", "_gt", "_eq", "_ge", "_lt", "_ne", "_le" - }; - - if (ctx->instruction_controls >= STATICARRAYLEN(comps)) - { - fail(ctx, "unknown comparison control"); - return ""; - } // if - - return comps[ctx->instruction_controls]; -} // get_D3D_comparison_string - -static void emit_D3D_BREAKC(Context *ctx) -{ - char op[16]; - snprintf(op, sizeof (op), "break%s", get_D3D_comparison_string(ctx)); - emit_D3D_opcode_ss(ctx, op); -} // emit_D3D_BREAKC - -static void emit_D3D_IFC(Context *ctx) -{ - char op[16]; - snprintf(op, sizeof (op), "if%s", get_D3D_comparison_string(ctx)); - emit_D3D_opcode_ss(ctx, op); -} // emit_D3D_IFC - -static void emit_D3D_SETP(Context *ctx) -{ - char op[16]; - snprintf(op, sizeof (op), "setp%s", get_D3D_comparison_string(ctx)); - emit_D3D_opcode_dss(ctx, op); -} // emit_D3D_SETP - -static void emit_D3D_DEF(Context *ctx) -{ - char dst[64]; - make_D3D_destarg_string(ctx, dst, sizeof (dst)); - const float *val = (const float *) ctx->dwords; // !!! FIXME: could be int? - char val0[32]; - char val1[32]; - char val2[32]; - char val3[32]; - floatstr(ctx, val0, sizeof (val0), val[0], 0); - floatstr(ctx, val1, sizeof (val1), val[1], 0); - floatstr(ctx, val2, sizeof (val2), val[2], 0); - floatstr(ctx, val3, sizeof (val3), val[3], 0); - output_line(ctx, "def%s, %s, %s, %s, %s", dst, val0, val1, val2, val3); -} // emit_D3D_DEF - -static void emit_D3D_DEFI(Context *ctx) -{ - char dst[64]; - make_D3D_destarg_string(ctx, dst, sizeof (dst)); - const int32 *x = (const int32 *) ctx->dwords; - output_line(ctx, "defi%s, %d, %d, %d, %d", dst, - (int) x[0], (int) x[1], (int) x[2], (int) x[3]); -} // emit_D3D_DEFI - -static void emit_D3D_DEFB(Context *ctx) -{ - char dst[64]; - make_D3D_destarg_string(ctx, dst, sizeof (dst)); - output_line(ctx, "defb%s, %s", dst, ctx->dwords[0] ? "true" : "false"); -} // emit_D3D_DEFB - - -static void emit_D3D_DCL(Context *ctx) -{ - char dst[64]; - make_D3D_destarg_string(ctx, dst, sizeof (dst)); - const DestArgInfo *arg = &ctx->dest_arg; - const char *usage_str = ""; - char index_str[16] = { '\0' }; - - if (arg->regtype == REG_TYPE_SAMPLER) - { - switch ((const TextureType) ctx->dwords[0]) - { - case TEXTURE_TYPE_2D: usage_str = "_2d"; break; - case TEXTURE_TYPE_CUBE: usage_str = "_cube"; break; - case TEXTURE_TYPE_VOLUME: usage_str = "_volume"; break; - default: fail(ctx, "unknown sampler texture type"); return; - } // switch - } // if - - else if (arg->regtype == REG_TYPE_MISCTYPE) - { - switch ((const MiscTypeType) arg->regnum) - { - case MISCTYPE_TYPE_POSITION: - case MISCTYPE_TYPE_FACE: - usage_str = ""; // just become "dcl vFace" or whatever. - break; - default: fail(ctx, "unknown misc register type"); return; - } // switch - } // else if - - else - { - const uint32 usage = ctx->dwords[0]; - const uint32 index = ctx->dwords[1]; - usage_str = usagestrs[usage]; - if (index != 0) - snprintf(index_str, sizeof (index_str), "%u", (uint) index); - } // else - - output_line(ctx, "dcl%s%s%s", usage_str, index_str, dst); -} // emit_D3D_DCL - - -static void emit_D3D_TEXCRD(Context *ctx) -{ - // this opcode looks and acts differently depending on the shader model. - if (shader_version_atleast(ctx, 1, 4)) - emit_D3D_opcode_ds(ctx, "texcrd"); - else - emit_D3D_opcode_d(ctx, "texcoord"); -} // emit_D3D_TEXCOORD - -static void emit_D3D_TEXLD(Context *ctx) -{ - // this opcode looks and acts differently depending on the shader model. - if (shader_version_atleast(ctx, 2, 0)) - { - if (ctx->instruction_controls == CONTROL_TEXLD) - emit_D3D_opcode_dss(ctx, "texld"); - else if (ctx->instruction_controls == CONTROL_TEXLDP) - emit_D3D_opcode_dss(ctx, "texldp"); - else if (ctx->instruction_controls == CONTROL_TEXLDB) - emit_D3D_opcode_dss(ctx, "texldb"); - } // if - - else if (shader_version_atleast(ctx, 1, 4)) - { - emit_D3D_opcode_ds(ctx, "texld"); - } // else if - - else - { - emit_D3D_opcode_d(ctx, "tex"); - } // else -} // emit_D3D_TEXLD - -static void emit_D3D_SINCOS(Context *ctx) -{ - // this opcode needs extra registers for sm2 and lower. - if (!shader_version_atleast(ctx, 3, 0)) - emit_D3D_opcode_dsss(ctx, "sincos"); - else - emit_D3D_opcode_ds(ctx, "sincos"); -} // emit_D3D_SINCOS - - -#undef EMIT_D3D_OPCODE_FUNC -#undef EMIT_D3D_OPCODE_D_FUNC -#undef EMIT_D3D_OPCODE_S_FUNC -#undef EMIT_D3D_OPCODE_SS_FUNC -#undef EMIT_D3D_OPCODE_DS_FUNC -#undef EMIT_D3D_OPCODE_DSS_FUNC -#undef EMIT_D3D_OPCODE_DSSS_FUNC -#undef EMIT_D3D_OPCODE_DSSSS_FUNC - -#endif // SUPPORT_PROFILE_D3D - - -#if !SUPPORT_PROFILE_BYTECODE -#define PROFILE_EMITTER_BYTECODE(op) -#else -#undef AT_LEAST_ONE_PROFILE -#define AT_LEAST_ONE_PROFILE 1 -#define PROFILE_EMITTER_BYTECODE(op) emit_BYTECODE_##op, - -static void emit_BYTECODE_start(Context *ctx, const char *profilestr) -{ - ctx->ignores_ctab = 1; - - // just copy the whole token stream and make all other emitters no-ops. - if (set_output(ctx, &ctx->mainline)) - { - const size_t len = ctx->tokencount * sizeof (uint32); - buffer_append(ctx->mainline, (const char *) ctx->tokens, len); - } // if -} // emit_BYTECODE_start - -static void emit_BYTECODE_end(Context *ctx) {} -static void emit_BYTECODE_phase(Context *ctx) {} -static void emit_BYTECODE_finalize(Context *ctx) {} -static void emit_BYTECODE_global(Context *ctx, RegisterType t, int n) {} -static void emit_BYTECODE_array(Context *ctx, VariableList *var) {} -static void emit_BYTECODE_sampler(Context *c, int s, TextureType t, int tb) {} -static void emit_BYTECODE_const_array(Context *ctx, const ConstantsList *c, - int base, int size) {} -static void emit_BYTECODE_uniform(Context *ctx, RegisterType t, int n, - const VariableList *var) {} -static void emit_BYTECODE_attribute(Context *ctx, RegisterType t, int n, - MOJOSHADER_usage u, int i, int w, - int f) {} - -static const char *get_BYTECODE_varname(Context *ctx, RegisterType rt, int regnum) -{ - char regnum_str[16]; - const char *regtype_str = get_D3D_register_string(ctx, rt, regnum, - regnum_str, sizeof (regnum_str)); - char buf[64]; - snprintf(buf, sizeof (buf), "%s%s", regtype_str, regnum_str); - return StrDup(ctx, buf); -} // get_BYTECODE_varname - -static const char *get_BYTECODE_const_array_varname(Context *ctx, int base, int size) -{ - char buf[64]; - snprintf(buf, sizeof (buf), "c_array_%d_%d", base, size); - return StrDup(ctx, buf); -} // get_BYTECODE_const_array_varname - -#define EMIT_BYTECODE_OPCODE_FUNC(op) \ - static void emit_BYTECODE_##op(Context *ctx) {} - -EMIT_BYTECODE_OPCODE_FUNC(RESERVED) -EMIT_BYTECODE_OPCODE_FUNC(NOP) -EMIT_BYTECODE_OPCODE_FUNC(MOV) -EMIT_BYTECODE_OPCODE_FUNC(ADD) -EMIT_BYTECODE_OPCODE_FUNC(SUB) -EMIT_BYTECODE_OPCODE_FUNC(MAD) -EMIT_BYTECODE_OPCODE_FUNC(MUL) -EMIT_BYTECODE_OPCODE_FUNC(RCP) -EMIT_BYTECODE_OPCODE_FUNC(RSQ) -EMIT_BYTECODE_OPCODE_FUNC(DP3) -EMIT_BYTECODE_OPCODE_FUNC(DP4) -EMIT_BYTECODE_OPCODE_FUNC(MIN) -EMIT_BYTECODE_OPCODE_FUNC(MAX) -EMIT_BYTECODE_OPCODE_FUNC(SLT) -EMIT_BYTECODE_OPCODE_FUNC(SGE) -EMIT_BYTECODE_OPCODE_FUNC(EXP) -EMIT_BYTECODE_OPCODE_FUNC(LOG) -EMIT_BYTECODE_OPCODE_FUNC(LIT) -EMIT_BYTECODE_OPCODE_FUNC(DST) -EMIT_BYTECODE_OPCODE_FUNC(LRP) -EMIT_BYTECODE_OPCODE_FUNC(FRC) -EMIT_BYTECODE_OPCODE_FUNC(M4X4) -EMIT_BYTECODE_OPCODE_FUNC(M4X3) -EMIT_BYTECODE_OPCODE_FUNC(M3X4) -EMIT_BYTECODE_OPCODE_FUNC(M3X3) -EMIT_BYTECODE_OPCODE_FUNC(M3X2) -EMIT_BYTECODE_OPCODE_FUNC(CALL) -EMIT_BYTECODE_OPCODE_FUNC(CALLNZ) -EMIT_BYTECODE_OPCODE_FUNC(LOOP) -EMIT_BYTECODE_OPCODE_FUNC(RET) -EMIT_BYTECODE_OPCODE_FUNC(ENDLOOP) -EMIT_BYTECODE_OPCODE_FUNC(LABEL) -EMIT_BYTECODE_OPCODE_FUNC(POW) -EMIT_BYTECODE_OPCODE_FUNC(CRS) -EMIT_BYTECODE_OPCODE_FUNC(SGN) -EMIT_BYTECODE_OPCODE_FUNC(ABS) -EMIT_BYTECODE_OPCODE_FUNC(NRM) -EMIT_BYTECODE_OPCODE_FUNC(SINCOS) -EMIT_BYTECODE_OPCODE_FUNC(REP) -EMIT_BYTECODE_OPCODE_FUNC(ENDREP) -EMIT_BYTECODE_OPCODE_FUNC(IF) -EMIT_BYTECODE_OPCODE_FUNC(ELSE) -EMIT_BYTECODE_OPCODE_FUNC(ENDIF) -EMIT_BYTECODE_OPCODE_FUNC(BREAK) -EMIT_BYTECODE_OPCODE_FUNC(MOVA) -EMIT_BYTECODE_OPCODE_FUNC(TEXKILL) -EMIT_BYTECODE_OPCODE_FUNC(TEXBEM) -EMIT_BYTECODE_OPCODE_FUNC(TEXBEML) -EMIT_BYTECODE_OPCODE_FUNC(TEXREG2AR) -EMIT_BYTECODE_OPCODE_FUNC(TEXREG2GB) -EMIT_BYTECODE_OPCODE_FUNC(TEXM3X2PAD) -EMIT_BYTECODE_OPCODE_FUNC(TEXM3X2TEX) -EMIT_BYTECODE_OPCODE_FUNC(TEXM3X3PAD) -EMIT_BYTECODE_OPCODE_FUNC(TEXM3X3TEX) -EMIT_BYTECODE_OPCODE_FUNC(TEXM3X3SPEC) -EMIT_BYTECODE_OPCODE_FUNC(TEXM3X3VSPEC) -EMIT_BYTECODE_OPCODE_FUNC(EXPP) -EMIT_BYTECODE_OPCODE_FUNC(LOGP) -EMIT_BYTECODE_OPCODE_FUNC(CND) -EMIT_BYTECODE_OPCODE_FUNC(TEXREG2RGB) -EMIT_BYTECODE_OPCODE_FUNC(TEXDP3TEX) -EMIT_BYTECODE_OPCODE_FUNC(TEXM3X2DEPTH) -EMIT_BYTECODE_OPCODE_FUNC(TEXDP3) -EMIT_BYTECODE_OPCODE_FUNC(TEXM3X3) -EMIT_BYTECODE_OPCODE_FUNC(TEXDEPTH) -EMIT_BYTECODE_OPCODE_FUNC(CMP) -EMIT_BYTECODE_OPCODE_FUNC(BEM) -EMIT_BYTECODE_OPCODE_FUNC(DP2ADD) -EMIT_BYTECODE_OPCODE_FUNC(DSX) -EMIT_BYTECODE_OPCODE_FUNC(DSY) -EMIT_BYTECODE_OPCODE_FUNC(TEXLDD) -EMIT_BYTECODE_OPCODE_FUNC(TEXLDL) -EMIT_BYTECODE_OPCODE_FUNC(BREAKP) -EMIT_BYTECODE_OPCODE_FUNC(BREAKC) -EMIT_BYTECODE_OPCODE_FUNC(IFC) -EMIT_BYTECODE_OPCODE_FUNC(SETP) -EMIT_BYTECODE_OPCODE_FUNC(DEF) -EMIT_BYTECODE_OPCODE_FUNC(DEFI) -EMIT_BYTECODE_OPCODE_FUNC(DEFB) -EMIT_BYTECODE_OPCODE_FUNC(DCL) -EMIT_BYTECODE_OPCODE_FUNC(TEXCRD) -EMIT_BYTECODE_OPCODE_FUNC(TEXLD) - -#undef EMIT_BYTECODE_OPCODE_FUNC - -#endif // SUPPORT_PROFILE_BYTECODE - - -#if !SUPPORT_PROFILE_GLSL -#define PROFILE_EMITTER_GLSL(op) -#else -#undef AT_LEAST_ONE_PROFILE -#define AT_LEAST_ONE_PROFILE 1 -#define PROFILE_EMITTER_GLSL(op) emit_GLSL_##op, - -#define EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(op) \ - static void emit_GLSL_##op(Context *ctx) { \ - fail(ctx, #op " unimplemented in glsl profile"); \ - } - -static inline const char *get_GLSL_register_string(Context *ctx, - const RegisterType regtype, const int regnum, - char *regnum_str, const size_t regnum_size) -{ - // turns out these are identical at the moment. - return get_D3D_register_string(ctx,regtype,regnum,regnum_str,regnum_size); -} // get_GLSL_register_string - -static const char *get_GLSL_uniform_type(Context *ctx, const RegisterType rtype) -{ - switch (rtype) - { - case REG_TYPE_CONST: return "vec4"; - case REG_TYPE_CONSTINT: return "ivec4"; - case REG_TYPE_CONSTBOOL: return "bool"; - default: fail(ctx, "BUG: used a uniform we don't know how to define."); - } // switch - - return NULL; -} // get_GLSL_uniform_type - -static const char *get_GLSL_varname_in_buf(Context *ctx, RegisterType rt, - int regnum, char *buf, - const size_t len) -{ - char regnum_str[16]; - const char *regtype_str = get_GLSL_register_string(ctx, rt, regnum, - regnum_str, sizeof (regnum_str)); - snprintf(buf,len,"%s_%s%s", ctx->shader_type_str, regtype_str, regnum_str); - return buf; -} // get_GLSL_varname_in_buf - - -static const char *get_GLSL_varname(Context *ctx, RegisterType rt, int regnum) -{ - char buf[64]; - get_GLSL_varname_in_buf(ctx, rt, regnum, buf, sizeof (buf)); - return StrDup(ctx, buf); -} // get_GLSL_varname - - -static inline const char *get_GLSL_const_array_varname_in_buf(Context *ctx, - const int base, const int size, - char *buf, const size_t buflen) -{ - const char *type = ctx->shader_type_str; - snprintf(buf, buflen, "%s_const_array_%d_%d", type, base, size); - return buf; -} // get_GLSL_const_array_varname_in_buf - -static const char *get_GLSL_const_array_varname(Context *ctx, int base, int size) -{ - char buf[64]; - get_GLSL_const_array_varname_in_buf(ctx, base, size, buf, sizeof (buf)); - return StrDup(ctx, buf); -} // get_GLSL_const_array_varname - - -static inline const char *get_GLSL_input_array_varname(Context *ctx, - char *buf, const size_t buflen) -{ - snprintf(buf, buflen, "%s", "vertex_input_array"); - return buf; -} // get_GLSL_input_array_varname - - -static const char *get_GLSL_uniform_array_varname(Context *ctx, - const RegisterType regtype, - char *buf, const size_t len) -{ - const char *shadertype = ctx->shader_type_str; - const char *type = get_GLSL_uniform_type(ctx, regtype); - snprintf(buf, len, "%s_uniforms_%s", shadertype, type); - return buf; -} // get_GLSL_uniform_array_varname - -static const char *get_GLSL_destarg_varname(Context *ctx, char *buf, size_t len) -{ - const DestArgInfo *arg = &ctx->dest_arg; - return get_GLSL_varname_in_buf(ctx, arg->regtype, arg->regnum, buf, len); -} // get_GLSL_destarg_varname - -static const char *get_GLSL_srcarg_varname(Context *ctx, const size_t idx, - char *buf, size_t len) -{ - if (idx >= STATICARRAYLEN(ctx->source_args)) - { - fail(ctx, "Too many source args"); - *buf = '\0'; - return buf; - } // if - - const SourceArgInfo *arg = &ctx->source_args[idx]; - return get_GLSL_varname_in_buf(ctx, arg->regtype, arg->regnum, buf, len); -} // get_GLSL_srcarg_varname - - -static const char *make_GLSL_destarg_assign(Context *, char *, const size_t, - const char *, ...) ISPRINTF(4,5); - -static const char *make_GLSL_destarg_assign(Context *ctx, char *buf, - const size_t buflen, - const char *fmt, ...) -{ - int need_parens = 0; - const DestArgInfo *arg = &ctx->dest_arg; - - if (arg->writemask == 0) - { - *buf = '\0'; - return buf; // no writemask? It's a no-op. - } // if - - char clampbuf[32] = { '\0' }; - const char *clampleft = ""; - const char *clampright = ""; - if (arg->result_mod & MOD_SATURATE) - { - const int vecsize = vecsize_from_writemask(arg->writemask); - clampleft = "clamp("; - if (vecsize == 1) - clampright = ", 0.0, 1.0)"; - else - { - snprintf(clampbuf, sizeof (clampbuf), - ", vec%d(0.0), vec%d(1.0))", vecsize, vecsize); - clampright = clampbuf; - } // else - } // if - - // MSDN says MOD_PP is a hint and many implementations ignore it. So do we. - - // CENTROID only allowed in DCL opcodes, which shouldn't come through here. - assert((arg->result_mod & MOD_CENTROID) == 0); - - if (ctx->predicated) - { - fail(ctx, "predicated destinations unsupported"); // !!! FIXME - *buf = '\0'; - return buf; - } // if - - char operation[256]; - va_list ap; - va_start(ap, fmt); - const int len = vsnprintf(operation, sizeof (operation), fmt, ap); - va_end(ap); - if (len >= sizeof (operation)) - { - fail(ctx, "operation string too large"); // I'm lazy. :P - *buf = '\0'; - return buf; - } // if - - const char *result_shift_str = ""; - switch (arg->result_shift) - { - case 0x1: result_shift_str = " * 2.0"; break; - case 0x2: result_shift_str = " * 4.0"; break; - case 0x3: result_shift_str = " * 8.0"; break; - case 0xD: result_shift_str = " / 8.0"; break; - case 0xE: result_shift_str = " / 4.0"; break; - case 0xF: result_shift_str = " / 2.0"; break; - } // switch - need_parens |= (result_shift_str[0] != '\0'); - - char regnum_str[16]; - const char *regtype_str = get_GLSL_register_string(ctx, arg->regtype, - arg->regnum, regnum_str, - sizeof (regnum_str)); - char writemask_str[6]; - size_t i = 0; - const int scalar = isscalar(ctx, ctx->shader_type, arg->regtype, arg->regnum); - if (!scalar && !writemask_xyzw(arg->writemask)) - { - writemask_str[i++] = '.'; - if (arg->writemask0) writemask_str[i++] = 'x'; - if (arg->writemask1) writemask_str[i++] = 'y'; - if (arg->writemask2) writemask_str[i++] = 'z'; - if (arg->writemask3) writemask_str[i++] = 'w'; - } // if - writemask_str[i] = '\0'; - assert(i < sizeof (writemask_str)); - - const char *leftparen = (need_parens) ? "(" : ""; - const char *rightparen = (need_parens) ? ")" : ""; - - snprintf(buf, buflen, "%s_%s%s%s = %s%s%s%s%s%s;", - ctx->shader_type_str, regtype_str, regnum_str, writemask_str, - clampleft, leftparen, operation, rightparen, result_shift_str, - clampright); - // !!! FIXME: make sure the scratch buffer was large enough. - return buf; -} // make_GLSL_destarg_assign - - -static char *make_GLSL_swizzle_string(char *swiz_str, const size_t strsize, - const int swizzle, const int writemask) -{ - size_t i = 0; - if ( (!no_swizzle(swizzle)) || (!writemask_xyzw(writemask)) ) - { - const int writemask0 = (writemask >> 0) & 0x1; - const int writemask1 = (writemask >> 1) & 0x1; - const int writemask2 = (writemask >> 2) & 0x1; - const int writemask3 = (writemask >> 3) & 0x1; - - const int swizzle_x = (swizzle >> 0) & 0x3; - const int swizzle_y = (swizzle >> 2) & 0x3; - const int swizzle_z = (swizzle >> 4) & 0x3; - const int swizzle_w = (swizzle >> 6) & 0x3; - - swiz_str[i++] = '.'; - if (writemask0) swiz_str[i++] = swizzle_channels[swizzle_x]; - if (writemask1) swiz_str[i++] = swizzle_channels[swizzle_y]; - if (writemask2) swiz_str[i++] = swizzle_channels[swizzle_z]; - if (writemask3) swiz_str[i++] = swizzle_channels[swizzle_w]; - } // if - assert(i < strsize); - swiz_str[i] = '\0'; - return swiz_str; -} // make_GLSL_swizzle_string - - -static const char *make_GLSL_srcarg_string(Context *ctx, const size_t idx, - const int writemask, char *buf, - const size_t buflen) -{ - *buf = '\0'; - - if (idx >= STATICARRAYLEN(ctx->source_args)) - { - fail(ctx, "Too many source args"); - return buf; - } // if - - const SourceArgInfo *arg = &ctx->source_args[idx]; - - const char *premod_str = ""; - const char *postmod_str = ""; - switch (arg->src_mod) - { - case SRCMOD_NEGATE: - premod_str = "-"; - break; - - case SRCMOD_BIASNEGATE: - premod_str = "-("; - postmod_str = " - 0.5)"; - break; - - case SRCMOD_BIAS: - premod_str = "("; - postmod_str = " - 0.5)"; - break; - - case SRCMOD_SIGNNEGATE: - premod_str = "-(("; - postmod_str = " - 0.5) * 2.0)"; - break; - - case SRCMOD_SIGN: - premod_str = "(("; - postmod_str = " - 0.5) * 2.0)"; - break; - - case SRCMOD_COMPLEMENT: - premod_str = "(1.0 - "; - postmod_str = ")"; - break; - - case SRCMOD_X2NEGATE: - premod_str = "-("; - postmod_str = " * 2.0)"; - break; - - case SRCMOD_X2: - premod_str = "("; - postmod_str = " * 2.0)"; - break; - - case SRCMOD_DZ: - fail(ctx, "SRCMOD_DZ unsupported"); return buf; // !!! FIXME - postmod_str = "_dz"; - break; - - case SRCMOD_DW: - fail(ctx, "SRCMOD_DW unsupported"); return buf; // !!! FIXME - postmod_str = "_dw"; - break; - - case SRCMOD_ABSNEGATE: - premod_str = "-abs("; - postmod_str = ")"; - break; - - case SRCMOD_ABS: - premod_str = "abs("; - postmod_str = ")"; - break; - - case SRCMOD_NOT: - premod_str = "!"; - break; - - case SRCMOD_NONE: - case SRCMOD_TOTAL: - break; // stop compiler whining. - } // switch - - const char *regtype_str = NULL; - - if (!arg->relative) - { - regtype_str = get_GLSL_varname_in_buf(ctx, arg->regtype, arg->regnum, - (char *) alloca(64), 64); - } // if - - const char *rel_lbracket = ""; - char rel_offset[32] = { '\0' }; - const char *rel_rbracket = ""; - char rel_swizzle[4] = { '\0' }; - const char *rel_regtype_str = ""; - if (arg->relative) - { - if (arg->regtype == REG_TYPE_INPUT) - regtype_str=get_GLSL_input_array_varname(ctx,(char*)alloca(64),64); - else - { - assert(arg->regtype == REG_TYPE_CONST); - const int arrayidx = arg->relative_array->index; - const int offset = arg->regnum - arrayidx; - assert(offset >= 0); - if (arg->relative_array->constant) - { - const int arraysize = arg->relative_array->count; - regtype_str = get_GLSL_const_array_varname_in_buf(ctx, - arrayidx, arraysize, (char *) alloca(64), 64); - if (offset != 0) - snprintf(rel_offset, sizeof (rel_offset), "%d + ", offset); - } // if - else - { - regtype_str = get_GLSL_uniform_array_varname(ctx, arg->regtype, - (char *) alloca(64), 64); - if (offset == 0) - { - snprintf(rel_offset, sizeof (rel_offset), - "ARRAYBASE_%d + ", arrayidx); - } // if - else - { - snprintf(rel_offset, sizeof (rel_offset), - "(ARRAYBASE_%d + %d) + ", arrayidx, offset); - } // else - } // else - } // else - - rel_lbracket = "["; - - rel_regtype_str = get_GLSL_varname_in_buf(ctx, arg->relative_regtype, - arg->relative_regnum, - (char *) alloca(64), 64); - rel_swizzle[0] = '.'; - rel_swizzle[1] = swizzle_channels[arg->relative_component]; - rel_swizzle[2] = '\0'; - rel_rbracket = "]"; - } // if - - char swiz_str[6] = { '\0' }; - if (!isscalar(ctx, ctx->shader_type, arg->regtype, arg->regnum)) - { - make_GLSL_swizzle_string(swiz_str, sizeof (swiz_str), - arg->swizzle, writemask); - } // if - - if (regtype_str == NULL) - { - fail(ctx, "Unknown source register type."); - return buf; - } // if - - snprintf(buf, buflen, "%s%s%s%s%s%s%s%s%s", - premod_str, regtype_str, rel_lbracket, rel_offset, - rel_regtype_str, rel_swizzle, rel_rbracket, swiz_str, - postmod_str); - // !!! FIXME: make sure the scratch buffer was large enough. - return buf; -} // make_GLSL_srcarg_string - -// generate some convenience functions. -#define MAKE_GLSL_SRCARG_STRING_(mask, bitmask) \ - static inline const char *make_GLSL_srcarg_string_##mask(Context *ctx, \ - const size_t idx, char *buf, \ - const size_t buflen) { \ - return make_GLSL_srcarg_string(ctx, idx, bitmask, buf, buflen); \ - } -MAKE_GLSL_SRCARG_STRING_(x, (1 << 0)) -MAKE_GLSL_SRCARG_STRING_(y, (1 << 1)) -MAKE_GLSL_SRCARG_STRING_(z, (1 << 2)) -MAKE_GLSL_SRCARG_STRING_(w, (1 << 3)) -MAKE_GLSL_SRCARG_STRING_(scalar, (1 << 0)) -MAKE_GLSL_SRCARG_STRING_(full, 0xF) -MAKE_GLSL_SRCARG_STRING_(masked, ctx->dest_arg.writemask) -MAKE_GLSL_SRCARG_STRING_(vec3, 0x7) -MAKE_GLSL_SRCARG_STRING_(vec2, 0x3) -#undef MAKE_GLSL_SRCARG_STRING_ - -// special cases for comparison opcodes... - -static const char *get_GLSL_comparison_string_scalar(Context *ctx) -{ - static const char *comps[] = { "", ">", "==", ">=", "<", "!=", "<=" }; - if (ctx->instruction_controls >= STATICARRAYLEN(comps)) - { - fail(ctx, "unknown comparison control"); - return ""; - } // if - - return comps[ctx->instruction_controls]; -} // get_GLSL_comparison_string_scalar - -static const char *get_GLSL_comparison_string_vector(Context *ctx) -{ - static const char *comps[] = { - "", "greaterThan", "equal", "greaterThanEqual", "lessThan", - "notEqual", "lessThanEqual" - }; - - if (ctx->instruction_controls >= STATICARRAYLEN(comps)) - { - fail(ctx, "unknown comparison control"); - return ""; - } // if - - return comps[ctx->instruction_controls]; -} // get_GLSL_comparison_string_vector - - -static void emit_GLSL_start(Context *ctx, const char *profilestr) -{ - if (!shader_is_vertex(ctx) && !shader_is_pixel(ctx)) - { - failf(ctx, "Shader type %u unsupported in this profile.", - (uint) ctx->shader_type); - return; - } // if - - else if (strcmp(profilestr, MOJOSHADER_PROFILE_GLSL) == 0) - { - // No gl_FragData[] before GLSL 1.10, so we have to force the version. - push_output(ctx, &ctx->preflight); - output_line(ctx, "#version 110"); - pop_output(ctx); - } // else if - - #if SUPPORT_PROFILE_GLSL120 - else if (strcmp(profilestr, MOJOSHADER_PROFILE_GLSL120) == 0) - { - ctx->profile_supports_glsl120 = 1; - push_output(ctx, &ctx->preflight); - output_line(ctx, "#version 120"); - pop_output(ctx); - } // else if - #endif - - else - { - failf(ctx, "Profile '%s' unsupported or unknown.", profilestr); - return; - } // else - - push_output(ctx, &ctx->mainline_intro); - output_line(ctx, "void main()"); - output_line(ctx, "{"); - pop_output(ctx); - - set_output(ctx, &ctx->mainline); - ctx->indent++; -} // emit_GLSL_start - -static void emit_GLSL_RET(Context *ctx); -static void emit_GLSL_end(Context *ctx) -{ - // ps_1_* writes color to r0 instead oC0. We move it to the right place. - // We don't have to worry about a RET opcode messing this up, since - // RET isn't available before ps_2_0. - if (shader_is_pixel(ctx) && !shader_version_atleast(ctx, 2, 0)) - { - const char *shstr = ctx->shader_type_str; - set_used_register(ctx, REG_TYPE_COLOROUT, 0, 1); - output_line(ctx, "%s_oC0 = %s_r0;", shstr, shstr); - } // if - - if (ctx->shader_type == MOJOSHADER_TYPE_VERTEX) { - //fix the opengl/directx coord mapping - //see wine glsl_shader.c for details - //TODO: fix if we've already seen a ret - output_line(ctx, "gl_Position.y = gl_Position.y * posFixup.y;"); - output_line(ctx, "gl_Position.xy += posFixup.zw * gl_Position.ww;"); - output_line(ctx, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;"); - } - - // force a RET opcode if we're at the end of the stream without one. - if (ctx->previous_opcode != OPCODE_RET) - emit_GLSL_RET(ctx); -} // emit_GLSL_end - -static void emit_GLSL_phase(Context *ctx) -{ - // no-op in GLSL. -} // emit_GLSL_phase - -static void output_GLSL_uniform_array(Context *ctx, const RegisterType regtype, - const int size) -{ - if (size > 0) - { - char buf[64]; - get_GLSL_uniform_array_varname(ctx, regtype, buf, sizeof (buf)); - output_line(ctx, "uniform vec4 %s[%d];", buf, size); - } // if -} // output_GLSL_uniform_array - -static void emit_GLSL_finalize(Context *ctx) -{ - - // throw some blank lines around to make source more readable. - push_output(ctx, &ctx->globals); - output_blank_line(ctx); - pop_output(ctx); - - // If we had a relative addressing of REG_TYPE_INPUT, we need to build - // an array for it at the start of main(). GLSL doesn't let you specify - // arrays of attributes. - //vec4 blah_array[BIGGEST_ARRAY]; - if (ctx->have_relative_input_registers) // !!! FIXME - fail(ctx, "Relative addressing of input registers not supported."); - - push_output(ctx, &ctx->preflight); - output_GLSL_uniform_array(ctx, REG_TYPE_CONST, ctx->uniform_float4_count); - output_GLSL_uniform_array(ctx, REG_TYPE_CONSTINT, ctx->uniform_int4_count); - output_GLSL_uniform_array(ctx, REG_TYPE_CONSTBOOL, ctx->uniform_bool_count); - - if (ctx->shader_type == MOJOSHADER_TYPE_VERTEX) { - output_line(ctx, "uniform vec4 posFixup;"); - } - - pop_output(ctx); -} // emit_GLSL_finalize - -static void emit_GLSL_global(Context *ctx, RegisterType regtype, int regnum) -{ - char varname[64]; - get_GLSL_varname_in_buf(ctx, regtype, regnum, varname, sizeof (varname)); - - push_output(ctx, &ctx->globals); - switch (regtype) - { - case REG_TYPE_ADDRESS: - if (shader_is_vertex(ctx)) - output_line(ctx, "ivec4 %s;", varname); - else if (shader_is_pixel(ctx)) // actually REG_TYPE_TEXTURE. - { - // We have to map texture registers to temps for ps_1_1, since - // they work like temps, initialize with tex coords, and the - // ps_1_1 TEX opcode expects to overwrite it. - if (!shader_version_atleast(ctx, 1, 4)) - { - output_line(ctx, "vec4 %s = gl_TexCoord[%d];", - varname, regnum); - } // if - } // else if - break; - case REG_TYPE_PREDICATE: - output_line(ctx, "bvec4 %s;", varname); - break; - case REG_TYPE_TEMP: - output_line(ctx, "vec4 %s;", varname); - break; - case REG_TYPE_LOOP: - break; // no-op. We declare these in for loops at the moment. - case REG_TYPE_LABEL: - break; // no-op. If we see it here, it means we optimized it out. - default: - fail(ctx, "BUG: we used a register we don't know how to define."); - break; - } // switch - pop_output(ctx); -} // emit_GLSL_global - -static void emit_GLSL_array(Context *ctx, VariableList *var) -{ - // All uniforms (except constant arrays, which only get pushed once at - // compile time) are now packed into a single array, so we can batch - // the uniform transfers. So this is doesn't actually define an array - // here; the one, big array is emitted during finalization instead. - // However, we need to #define the offset into the one, big array here, - // and let dereferences use that #define. - const int base = var->index; - const int glslbase = ctx->uniform_float4_count; - push_output(ctx, &ctx->globals); - output_line(ctx, "#define ARRAYBASE_%d %d", base, glslbase); - pop_output(ctx); - var->emit_position = glslbase; -} // emit_GLSL_array - -static void emit_GLSL_const_array(Context *ctx, const ConstantsList *clist, - int base, int size) -{ - char varname[64]; - get_GLSL_const_array_varname_in_buf(ctx,base,size,varname,sizeof(varname)); - -#if 0 - // !!! FIXME: fails on Nvidia's and Apple's GL, even with #version 120. - // !!! FIXME: (the 1.20 spec says it should work, though, I think...) - if (support_glsl120(ctx)) - { - // GLSL 1.20 can do constant arrays. - const char *cstr = NULL; - push_output(ctx, &ctx->globals); - output_line(ctx, "const vec4 %s[%d] = vec4[%d](", varname, size, size); - ctx->indent++; - - int i; - for (i = 0; i < size; i++) - { - while (clist->constant.type != MOJOSHADER_UNIFORM_FLOAT) - clist = clist->next; - assert(clist->constant.index == (base + i)); - - char val0[32]; - char val1[32]; - char val2[32]; - char val3[32]; - floatstr(ctx, val0, sizeof (val0), clist->constant.value.f[0], 1); - floatstr(ctx, val1, sizeof (val1), clist->constant.value.f[1], 1); - floatstr(ctx, val2, sizeof (val2), clist->constant.value.f[2], 1); - floatstr(ctx, val3, sizeof (val3), clist->constant.value.f[3], 1); - - output_line(ctx, "vec4(%s, %s, %s, %s)%s", val0, val1, val2, val3, - (i < (size-1)) ? "," : ""); - - clist = clist->next; - } // for - - ctx->indent--; - output_line(ctx, ");"); - pop_output(ctx); - } // if - - else -#endif - { - // stock GLSL 1.0 can't do constant arrays, so make a uniform array - // and have the OpenGL glue assign it at link time. Lame! - push_output(ctx, &ctx->globals); - output_line(ctx, "uniform vec4 %s[%d];", varname, size); - pop_output(ctx); - } // else -} // emit_GLSL_const_array - -static void emit_GLSL_uniform(Context *ctx, RegisterType regtype, int regnum, - const VariableList *var) -{ - // Now that we're pushing all the uniforms as one big array, pack these - // down, so if we only use register c439, it'll actually map to - // glsl_uniforms_vec4[0]. As we push one big array, this will prevent - // uploading unused data. - - char varname[64]; - char name[64]; - int index = 0; - - get_GLSL_varname_in_buf(ctx, regtype, regnum, varname, sizeof (varname)); - - push_output(ctx, &ctx->globals); - - if (var == NULL) - { - get_GLSL_uniform_array_varname(ctx, regtype, name, sizeof (name)); - - if (regtype == REG_TYPE_CONST) - index = ctx->uniform_float4_count; - else if (regtype == REG_TYPE_CONSTINT) - index = ctx->uniform_int4_count; - else if (regtype == REG_TYPE_CONSTBOOL) - index = ctx->uniform_bool_count; - else // get_GLSL_uniform_array_varname() would have called fail(). - assert(isfail(ctx)); - - output_line(ctx, "#define %s %s[%d]", varname, name, index); - } // if - - else - { - const int arraybase = var->index; - if (var->constant) - { - get_GLSL_const_array_varname_in_buf(ctx, arraybase, var->count, - name, sizeof (name)); - index = (regnum - arraybase); - } // if - else - { - assert(var->emit_position != -1); - get_GLSL_uniform_array_varname(ctx, regtype, name, sizeof (name)); - index = (regnum - arraybase) + var->emit_position; - } // else - - output_line(ctx, "#define %s %s[%d]", varname, name, index); - } // else - - pop_output(ctx); -} // emit_GLSL_uniform - -static void emit_GLSL_sampler(Context *ctx,int stage,TextureType ttype,int tb) -{ - const char *type = ""; - switch (ttype) - { - case TEXTURE_TYPE_2D: type = "sampler2D"; break; - case TEXTURE_TYPE_CUBE: type = "samplerCube"; break; - case TEXTURE_TYPE_VOLUME: type = "sampler3D"; break; - default: fail(ctx, "BUG: used a sampler we don't know how to define."); - } // switch - - char var[64]; - get_GLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, stage, var, sizeof (var)); - - push_output(ctx, &ctx->globals); - output_line(ctx, "uniform %s %s;", type, var); - if (tb) // This sampler used a ps_1_1 TEXBEM opcode? - { - char name[64]; - const int index = ctx->uniform_float4_count; - ctx->uniform_float4_count += 2; - get_GLSL_uniform_array_varname(ctx, REG_TYPE_CONST, name, sizeof (name)); - output_line(ctx, "#define %s_texbem %s[%d]", var, name, index); - output_line(ctx, "#define %s_texbeml %s[%d]", var, name, index+1); - } // if - pop_output(ctx); -} // emit_GLSL_sampler - -static void emit_GLSL_attribute(Context *ctx, RegisterType regtype, int regnum, - MOJOSHADER_usage usage, int index, int wmask, - int flags) -{ - // !!! FIXME: this function doesn't deal with write masks at all yet! - const char *usage_str = NULL; - const char *arrayleft = ""; - const char *arrayright = ""; - char index_str[16] = { '\0' }; - char var[64]; - - get_GLSL_varname_in_buf(ctx, regtype, regnum, var, sizeof (var)); - - //assert((flags & MOD_PP) == 0); // !!! FIXME: is PP allowed? - - if (index != 0) // !!! FIXME: a lot of these MUST be zero. - snprintf(index_str, sizeof (index_str), "%u", (uint) index); - - if (shader_is_vertex(ctx)) - { - // pre-vs3 output registers. - // these don't ever happen in DCL opcodes, I think. Map to vs_3_* - // output registers. - if (!shader_version_atleast(ctx, 3, 0)) - { - if (regtype == REG_TYPE_RASTOUT) - { - regtype = REG_TYPE_OUTPUT; - index = regnum; - switch ((const RastOutType) regnum) - { - case RASTOUT_TYPE_POSITION: - usage = MOJOSHADER_USAGE_POSITION; - break; - case RASTOUT_TYPE_FOG: - usage = MOJOSHADER_USAGE_FOG; - break; - case RASTOUT_TYPE_POINT_SIZE: - usage = MOJOSHADER_USAGE_POINTSIZE; - break; - } // switch - } // if - - else if (regtype == REG_TYPE_ATTROUT) - { - regtype = REG_TYPE_OUTPUT; - usage = MOJOSHADER_USAGE_COLOR; - index = regnum; - } // else if - - else if (regtype == REG_TYPE_TEXCRDOUT) - { - regtype = REG_TYPE_OUTPUT; - usage = MOJOSHADER_USAGE_TEXCOORD; - index = regnum; - } // else if - } // if - - // to avoid limitations of various GL entry points for input - // attributes (glSecondaryColorPointer() can only take 3 component - // items, glVertexPointer() can't do GL_UNSIGNED_BYTE, many other - // issues), we set up all inputs as generic vertex attributes, so we - // can pass data in just about any form, and ignore the built-in GLSL - // attributes like gl_SecondaryColor. Output needs to use the the - // built-ins, though, but we don't have to worry about the GL entry - // point limitations there. - - if (regtype == REG_TYPE_INPUT) - { - push_output(ctx, &ctx->globals); - output_line(ctx, "attribute vec4 %s;", var); - pop_output(ctx); - } // if - - else if (regtype == REG_TYPE_OUTPUT) - { - push_output(ctx, &ctx->globals); - - switch (usage) - { - case MOJOSHADER_USAGE_POSITION: - usage_str = "gl_Position"; - break; - case MOJOSHADER_USAGE_POINTSIZE: - usage_str = "gl_PointSize"; - break; - case MOJOSHADER_USAGE_COLOR: - index_str[0] = '\0'; // no explicit number. - - if (index == 0) { - output_line(ctx, "varying vec4 vFrontColor;"); - //usage_str = "gl_FrontColor"; - usage_str = "vFrontColor"; - } else if (index == 1) { - output_line(ctx, "varying vec4 vFrontSecondaryColor;"); - //usage_str = "gl_FrontSecondaryColor"; - usage_str = "vFrontSecondaryColor"; - } - - break; - case MOJOSHADER_USAGE_FOG: - output_line(ctx, "varying float vFogFragCoord;"); - //usage_str = "gl_FogFragCoord"; - usage_str = "vFogFragCoord"; - break; - case MOJOSHADER_USAGE_TEXCOORD: - snprintf(index_str, sizeof (index_str), "%u", (uint) index); - output_line(ctx, "varying vec4 vTexCoord%s;", index_str); - usage_str = "vTexCoord"; - //usage_str = "gl_TexCoord"; - //arrayleft = "["; - //arrayright = "]"; - break; - default: - // !!! FIXME: we need to deal with some more built-in varyings here. - break; - } // switch - - // !!! FIXME: the #define is a little hacky, but it means we don't - // !!! FIXME: have to track these separately if this works. - // no mapping to built-in var? Just make it a regular global, pray. - if (usage_str == NULL) - output_line(ctx, "vec4 %s;", var); - else - { - //output_line(ctx, "#define %s %s%s%s%s", var, usage_str, - // arrayleft, index_str, arrayright); - output_line(ctx, "#define %s %s%s", var, usage_str, index_str); - } // else - pop_output(ctx); - } // else if - - else - { - fail(ctx, "unknown vertex shader attribute register"); - } // else - } // if - - else if (shader_is_pixel(ctx)) - { - // samplers DCLs get handled in emit_GLSL_sampler(). - - if (flags & MOD_CENTROID) // !!! FIXME - { - failf(ctx, "centroid unsupported in %s profile", ctx->profile->name); - return; - } // if - - if (regtype == REG_TYPE_COLOROUT) - { - if (!ctx->have_multi_color_outputs) - usage_str = "gl_FragColor"; // maybe faster? - else - { - snprintf(index_str, sizeof (index_str), "%u", (uint) regnum); - usage_str = "gl_FragData"; - arrayleft = "["; - arrayright = "]"; - } // else - } // if - - else if (regtype == REG_TYPE_DEPTHOUT) - usage_str = "gl_FragDepth"; - - // !!! FIXME: can you actualy have a texture register with COLOR usage? - else if ((regtype == REG_TYPE_TEXTURE) || (regtype == REG_TYPE_INPUT)) - { - push_output(ctx, &ctx->globals); - if (usage == MOJOSHADER_USAGE_TEXCOORD) - { - // ps_1_1 does a different hack for this attribute. - // Refer to emit_GLSL_global()'s REG_TYPE_TEXTURE code. - if (shader_version_atleast(ctx, 1, 4)) - { - snprintf(index_str, sizeof (index_str), "%u", (uint) index); - output_line(ctx, "varying vec4 vTexCoord%s;", index_str); - output_line(ctx, "#define %s vTexCoord%s", var, index_str); - //usage_str = "gl_TexCoord"; - //arrayleft = "["; - //arrayright = "]"; - } // if - } // if - - else if (usage == MOJOSHADER_USAGE_COLOR) - { - index_str[0] = '\0'; // no explicit number. - if (index == 0) { - output_line(ctx, "varying vec4 vFrontColor;"); - usage_str = "vFrontColor"; - //usage_str = "gl_Color"; - } else if (index == 1) { - output_line(ctx, "varying vec4 vFrontSecondaryColor;"); - usage_str = "vFrontSecondaryColor"; - //usage_str = "gl_SecondaryColor"; - } else { - fail(ctx, "unsupported color index"); - } - } // else if - pop_output(ctx); - } // else if - - else if (regtype == REG_TYPE_MISCTYPE) - { - const MiscTypeType mt = (MiscTypeType) regnum; - if (mt == MISCTYPE_TYPE_FACE) - { - push_output(ctx, &ctx->globals); - output_line(ctx, "float %s = gl_FrontFacing ? 1.0 : -1.0;", var); - pop_output(ctx); - } // if - else if (mt == MISCTYPE_TYPE_POSITION) - { - index_str[0] = '\0'; // no explicit number. - usage_str = "gl_FragCoord"; // !!! FIXME: is this the same coord space as D3D? - } // else if - else - { - fail(ctx, "BUG: unhandled misc register"); - } // else - } // else if - - else - { - fail(ctx, "unknown pixel shader attribute register"); - } // else - - if (usage_str != NULL) - { - push_output(ctx, &ctx->globals); - output_line(ctx, "#define %s %s%s%s%s", var, usage_str, - arrayleft, index_str, arrayright); - pop_output(ctx); - } // if - } // else if - - else - { - fail(ctx, "Unknown shader type"); // state machine should catch this. - } // else -} // emit_GLSL_attribute - -static void emit_GLSL_NOP(Context *ctx) -{ - // no-op is a no-op. :) -} // emit_GLSL_NOP - -static void emit_GLSL_MOV(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "%s", src0); - output_line(ctx, "%s", code); -} // emit_GLSL_MOV - -static void emit_GLSL_ADD(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "%s + %s", src0, src1); - output_line(ctx, "%s", code); -} // emit_GLSL_ADD - -static void emit_GLSL_SUB(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "%s - %s", src0, src1); - output_line(ctx, "%s", code); -} // emit_GLSL_SUB - -static void emit_GLSL_MAD(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); - char src2[64]; make_GLSL_srcarg_string_masked(ctx, 2, src2, sizeof (src2)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "(%s * %s) + %s", src0, src1, src2); - output_line(ctx, "%s", code); -} // emit_GLSL_MAD - -static void emit_GLSL_MUL(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "%s * %s", src0, src1); - output_line(ctx, "%s", code); -} // emit_GLSL_MUL - -static void emit_GLSL_RCP(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "1.0 / %s", src0); - output_line(ctx, "%s", code); -} // emit_GLSL_RCP - -static void emit_GLSL_RSQ(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "inversesqrt(%s)", src0); - output_line(ctx, "%s", code); -} // emit_GLSL_RSQ - -static void emit_GLSL_dotprod(Context *ctx, const char *src0, const char *src1, - const char *extra) -{ - const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); - char castleft[16] = { '\0' }; - const char *castright = ""; - if (vecsize != 1) - { - snprintf(castleft, sizeof (castleft), "vec%d(", vecsize); - castright = ")"; - } // if - - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "%sdot(%s, %s)%s%s", - castleft, src0, src1, extra, castright); - output_line(ctx, "%s", code); -} // emit_GLSL_dotprod - -static void emit_GLSL_DP3(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_GLSL_srcarg_string_vec3(ctx, 1, src1, sizeof (src1)); - emit_GLSL_dotprod(ctx, src0, src1, ""); -} // emit_GLSL_DP3 - -static void emit_GLSL_DP4(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_GLSL_srcarg_string_full(ctx, 1, src1, sizeof (src1)); - emit_GLSL_dotprod(ctx, src0, src1, ""); -} // emit_GLSL_DP4 - -static void emit_GLSL_MIN(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "min(%s, %s)", src0, src1); - output_line(ctx, "%s", code); -} // emit_GLSL_MIN - -static void emit_GLSL_MAX(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "max(%s, %s)", src0, src1); - output_line(ctx, "%s", code); -} // emit_GLSL_MAX - -static void emit_GLSL_SLT(Context *ctx) -{ - const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); - char code[128]; - - // float(bool) or vec(bvec) results in 0.0 or 1.0, like SLT wants. - if (vecsize == 1) - make_GLSL_destarg_assign(ctx, code, sizeof (code), "float(%s < %s)", src0, src1); - else - { - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "vec%d(lessThan(%s, %s))", - vecsize, src0, src1); - } // else - output_line(ctx, "%s", code); -} // emit_GLSL_SLT - -static void emit_GLSL_SGE(Context *ctx) -{ - const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); - char code[128]; - - // float(bool) or vec(bvec) results in 0.0 or 1.0, like SGE wants. - if (vecsize == 1) - { - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "float(%s >= %s)", src0, src1); - } // if - else - { - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "vec%d(greaterThanEqual(%s, %s))", - vecsize, src0, src1); - } // else - output_line(ctx, "%s", code); -} // emit_GLSL_SGE - -static void emit_GLSL_EXP(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "exp2(%s)", src0); - output_line(ctx, "%s", code); -} // emit_GLSL_EXP - -static void emit_GLSL_LOG(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "log2(%s)", src0); - output_line(ctx, "%s", code); -} // emit_GLSL_LOG - -static void emit_GLSL_LIT_helper(Context *ctx) -{ - const char *maxp = "127.9961"; // value from the dx9 reference. - - if (ctx->glsl_generated_lit_helper) - return; - - ctx->glsl_generated_lit_helper = 1; - - push_output(ctx, &ctx->helpers); - output_line(ctx, "vec4 LIT(const vec4 src)"); - output_line(ctx, "{"); ctx->indent++; - output_line(ctx, "float power = clamp(src.w, -%s, %s);",maxp,maxp); - output_line(ctx, "vec4 retval = vec4(1.0, 0.0, 0.0, 1.0);"); - output_line(ctx, "if (src.x > 0.0) {"); ctx->indent++; - output_line(ctx, "retval.y = src.x;"); - output_line(ctx, "if (src.y > 0.0) {"); ctx->indent++; - output_line(ctx, "retval.z = pow(src.y, power);"); ctx->indent--; - output_line(ctx, "}"); ctx->indent--; - output_line(ctx, "}"); - output_line(ctx, "return retval;"); ctx->indent--; - output_line(ctx, "}"); - output_blank_line(ctx); - pop_output(ctx); -} // emit_GLSL_LIT_helper - -static void emit_GLSL_LIT(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); - char code[128]; - emit_GLSL_LIT_helper(ctx); - make_GLSL_destarg_assign(ctx, code, sizeof (code), "LIT(%s)", src0); - output_line(ctx, "%s", code); -} // emit_GLSL_LIT - -static void emit_GLSL_DST(Context *ctx) -{ - // !!! FIXME: needs to take ctx->dst_arg.writemask into account. - char src0_y[64]; make_GLSL_srcarg_string_y(ctx, 0, src0_y, sizeof (src0_y)); - char src1_y[64]; make_GLSL_srcarg_string_y(ctx, 1, src1_y, sizeof (src1_y)); - char src0_z[64]; make_GLSL_srcarg_string_z(ctx, 0, src0_z, sizeof (src0_z)); - char src1_w[64]; make_GLSL_srcarg_string_w(ctx, 1, src1_w, sizeof (src1_w)); - - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "vec4(1.0, %s * %s, %s, %s)", - src0_y, src1_y, src0_z, src1_w); - output_line(ctx, "%s", code); -} // emit_GLSL_DST - -static void emit_GLSL_LRP(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); - char src2[64]; make_GLSL_srcarg_string_masked(ctx, 2, src2, sizeof (src2)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "mix(%s, %s, %s)", - src2, src1, src0); - output_line(ctx, "%s", code); -} // emit_GLSL_LRP - -static void emit_GLSL_FRC(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "fract(%s)", src0); - output_line(ctx, "%s", code); -} // emit_GLSL_FRC - -static void emit_GLSL_M4X4(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); - char row0[64]; make_GLSL_srcarg_string_full(ctx, 1, row0, sizeof (row0)); - char row1[64]; make_GLSL_srcarg_string_full(ctx, 2, row1, sizeof (row1)); - char row2[64]; make_GLSL_srcarg_string_full(ctx, 3, row2, sizeof (row2)); - char row3[64]; make_GLSL_srcarg_string_full(ctx, 4, row3, sizeof (row3)); - char code[256]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "vec4(dot(%s, %s), dot(%s, %s), dot(%s, %s), dot(%s, %s))", - src0, row0, src0, row1, src0, row2, src0, row3); - output_line(ctx, "%s", code); -} // emit_GLSL_M4X4 - -static void emit_GLSL_M4X3(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); - char row0[64]; make_GLSL_srcarg_string_full(ctx, 1, row0, sizeof (row0)); - char row1[64]; make_GLSL_srcarg_string_full(ctx, 2, row1, sizeof (row1)); - char row2[64]; make_GLSL_srcarg_string_full(ctx, 3, row2, sizeof (row2)); - char code[256]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "vec3(dot(%s, %s), dot(%s, %s), dot(%s, %s))", - src0, row0, src0, row1, src0, row2); - output_line(ctx, "%s", code); -} // emit_GLSL_M4X3 - -static void emit_GLSL_M3X4(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); - char row0[64]; make_GLSL_srcarg_string_vec3(ctx, 1, row0, sizeof (row0)); - char row1[64]; make_GLSL_srcarg_string_vec3(ctx, 2, row1, sizeof (row1)); - char row2[64]; make_GLSL_srcarg_string_vec3(ctx, 3, row2, sizeof (row2)); - char row3[64]; make_GLSL_srcarg_string_vec3(ctx, 4, row3, sizeof (row3)); - - char code[256]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "vec4(dot(%s, %s), dot(%s, %s), " - "dot(%s, %s), dot(%s, %s))", - src0, row0, src0, row1, - src0, row2, src0, row3); - output_line(ctx, "%s", code); -} // emit_GLSL_M3X4 - -static void emit_GLSL_M3X3(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); - char row0[64]; make_GLSL_srcarg_string_vec3(ctx, 1, row0, sizeof (row0)); - char row1[64]; make_GLSL_srcarg_string_vec3(ctx, 2, row1, sizeof (row1)); - char row2[64]; make_GLSL_srcarg_string_vec3(ctx, 3, row2, sizeof (row2)); - char code[256]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "vec3(dot(%s, %s), dot(%s, %s), dot(%s, %s))", - src0, row0, src0, row1, src0, row2); - output_line(ctx, "%s", code); -} // emit_GLSL_M3X3 - -static void emit_GLSL_M3X2(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); - char row0[64]; make_GLSL_srcarg_string_vec3(ctx, 1, row0, sizeof (row0)); - char row1[64]; make_GLSL_srcarg_string_vec3(ctx, 2, row1, sizeof (row1)); - - char code[256]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "vec2(dot(%s, %s), dot(%s, %s))", - src0, row0, src0, row1); - output_line(ctx, "%s", code); -} // emit_GLSL_M3X2 - -static void emit_GLSL_CALL(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - if (ctx->loops > 0) - output_line(ctx, "%s(aL);", src0); - else - output_line(ctx, "%s();", src0); -} // emit_GLSL_CALL - -static void emit_GLSL_CALLNZ(Context *ctx) -{ - // !!! FIXME: if src1 is a constbool that's true, we can remove the - // !!! FIXME: if. If it's false, we can make this a no-op. - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); - - if (ctx->loops > 0) - output_line(ctx, "if (%s) { %s(aL); }", src1, src0); - else - output_line(ctx, "if (%s) { %s(); }", src1, src0); -} // emit_GLSL_CALLNZ - -static void emit_GLSL_LOOP(Context *ctx) -{ - // !!! FIXME: swizzle? - char var[64]; get_GLSL_srcarg_varname(ctx, 1, var, sizeof (var)); - assert(ctx->source_args[0].regnum == 0); // in case they add aL1 someday. - output_line(ctx, "{"); - ctx->indent++; - output_line(ctx, "const int aLend = %s.x + %s.y;", var, var); - output_line(ctx, "for (int aL = %s.y; aL < aLend; aL += %s.z) {", var, var); - ctx->indent++; -} // emit_GLSL_LOOP - -static void emit_GLSL_RET(Context *ctx) -{ - // thankfully, the MSDN specs say a RET _has_ to end a function...no - // early returns. So if you hit one, you know you can safely close - // a high-level function. - ctx->indent--; - output_line(ctx, "}"); - output_blank_line(ctx); - set_output(ctx, &ctx->subroutines); -} // emit_GLSL_RET - -static void emit_GLSL_ENDLOOP(Context *ctx) -{ - ctx->indent--; - output_line(ctx, "}"); - ctx->indent--; - output_line(ctx, "}"); -} // emit_GLSL_ENDLOOP - -static void emit_GLSL_LABEL(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - const int label = ctx->source_args[0].regnum; - RegisterList *reg = reglist_find(&ctx->used_registers, REG_TYPE_LABEL, label); - assert(ctx->output == ctx->subroutines); // not mainline, etc. - assert(ctx->indent == 0); // we shouldn't be in the middle of a function. - - // MSDN specs say CALL* has to come before the LABEL, so we know if we - // can ditch the entire function here as unused. - if (reg == NULL) - set_output(ctx, &ctx->ignore); // Func not used. Parse, but don't output. - - // !!! FIXME: it would be nice if we could determine if a function is - // !!! FIXME: only called once and, if so, forcibly inline it. - - const char *uses_loopreg = ((reg) && (reg->misc == 1)) ? "int aL" : ""; - output_line(ctx, "void %s(%s)", src0, uses_loopreg); - output_line(ctx, "{"); - ctx->indent++; -} // emit_GLSL_LABEL - -static void emit_GLSL_DCL(Context *ctx) -{ - // no-op. We do this in our emit_attribute() and emit_uniform(). -} // emit_GLSL_DCL - -static void emit_GLSL_POW(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "pow(abs(%s), %s)", src0, src1); - output_line(ctx, "%s", code); -} // emit_GLSL_POW - -static void emit_GLSL_CRS(Context *ctx) -{ - // !!! FIXME: needs to take ctx->dst_arg.writemask into account. - char src0[64]; make_GLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_GLSL_srcarg_string_vec3(ctx, 1, src1, sizeof (src1)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "cross(%s, %s)", src0, src1); - output_line(ctx, "%s", code); -} // emit_GLSL_CRS - -static void emit_GLSL_SGN(Context *ctx) -{ - // (we don't need the temporary registers specified for the D3D opcode.) - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "sign(%s)", src0); - output_line(ctx, "%s", code); -} // emit_GLSL_SGN - -static void emit_GLSL_ABS(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "abs(%s)", src0); - output_line(ctx, "%s", code); -} // emit_GLSL_ABS - -static void emit_GLSL_NRM(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "normalize(%s)", src0); - output_line(ctx, "%s", code); -} // emit_GLSL_NRM - -static void emit_GLSL_SINCOS(Context *ctx) -{ - // we don't care about the temp registers that <= sm2 demands; ignore them. - // sm2 also talks about what components are left untouched vs. undefined, - // but we just leave those all untouched with GLSL write masks (which - // would fulfill the "undefined" requirement, too). - const int mask = ctx->dest_arg.writemask; - char src0[64]; make_GLSL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); - char code[128] = { '\0' }; - - if (writemask_x(mask)) - make_GLSL_destarg_assign(ctx, code, sizeof (code), "cos(%s)", src0); - else if (writemask_y(mask)) - make_GLSL_destarg_assign(ctx, code, sizeof (code), "sin(%s)", src0); - else if (writemask_xy(mask)) - { - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "vec2(cos(%s), sin(%s))", src0, src0); - } // else if - - output_line(ctx, "%s", code); -} // emit_GLSL_SINCOS - -static void emit_GLSL_REP(Context *ctx) -{ - // !!! FIXME: - // msdn docs say legal loop values are 0 to 255. We can check DEFI values - // at parse time, but if they are pulling a value from a uniform, do - // we clamp here? - // !!! FIXME: swizzle is legal here, right? - char src0[64]; make_GLSL_srcarg_string_x(ctx, 0, src0, sizeof (src0)); - const uint rep = (uint) ctx->reps; - output_line(ctx, "for (int rep%u = 0; rep%u < %s; rep%u++) {", - rep, rep, src0, rep); - ctx->indent++; -} // emit_GLSL_REP - -static void emit_GLSL_ENDREP(Context *ctx) -{ - ctx->indent--; - output_line(ctx, "}"); -} // emit_GLSL_ENDREP - -static void emit_GLSL_IF(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); - output_line(ctx, "if (%s) {", src0); - ctx->indent++; -} // emit_GLSL_IF - -static void emit_GLSL_IFC(Context *ctx) -{ - const char *comp = get_GLSL_comparison_string_scalar(ctx); - char src0[64]; make_GLSL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_GLSL_srcarg_string_scalar(ctx, 1, src1, sizeof (src1)); - output_line(ctx, "if (%s %s %s) {", src0, comp, src1); - ctx->indent++; -} // emit_GLSL_IFC - -static void emit_GLSL_ELSE(Context *ctx) -{ - ctx->indent--; - output_line(ctx, "} else {"); - ctx->indent++; -} // emit_GLSL_ELSE - -static void emit_GLSL_ENDIF(Context *ctx) -{ - ctx->indent--; - output_line(ctx, "}"); -} // emit_GLSL_ENDIF - -static void emit_GLSL_BREAK(Context *ctx) -{ - output_line(ctx, "break;"); -} // emit_GLSL_BREAK - -static void emit_GLSL_BREAKC(Context *ctx) -{ - const char *comp = get_GLSL_comparison_string_scalar(ctx); - char src0[64]; make_GLSL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_GLSL_srcarg_string_scalar(ctx, 1, src1, sizeof (src1)); - output_line(ctx, "if (%s %s %s) { break; }", src0, comp, src1); -} // emit_GLSL_BREAKC - -static void emit_GLSL_MOVA(Context *ctx) -{ - const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char code[128]; - - if (vecsize == 1) - { - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "int(floor(abs(%s) + 0.5) * sign(%s))", - src0, src0); - } // if - - else - { - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s))", - vecsize, src0, vecsize, src0); - } // else - - output_line(ctx, "%s", code); -} // emit_GLSL_MOVA - -static void emit_GLSL_DEFB(Context *ctx) -{ - char varname[64]; get_GLSL_destarg_varname(ctx, varname, sizeof (varname)); - push_output(ctx, &ctx->globals); - output_line(ctx, "const bool %s = %s;", - varname, ctx->dwords[0] ? "true" : "false"); - pop_output(ctx); -} // emit_GLSL_DEFB - -static void emit_GLSL_DEFI(Context *ctx) -{ - char varname[64]; get_GLSL_destarg_varname(ctx, varname, sizeof (varname)); - const int32 *x = (const int32 *) ctx->dwords; - push_output(ctx, &ctx->globals); - output_line(ctx, "const ivec4 %s = ivec4(%d, %d, %d, %d);", - varname, (int) x[0], (int) x[1], (int) x[2], (int) x[3]); - pop_output(ctx); -} // emit_GLSL_DEFI - -EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXCRD) - -static void emit_GLSL_TEXKILL(Context *ctx) -{ - char dst[64]; get_GLSL_destarg_varname(ctx, dst, sizeof (dst)); - output_line(ctx, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;", dst); -} // emit_GLSL_TEXKILL - -static void glsl_texld(Context *ctx, const int texldd) -{ - if (!shader_version_atleast(ctx, 1, 4)) - { - DestArgInfo *info = &ctx->dest_arg; - char dst[64]; - char sampler[64]; - char code[128] = {0}; - - assert(!texldd); - - RegisterList *sreg; - sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, info->regnum); - const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); - - // !!! FIXME: this code counts on the register not having swizzles, etc. - get_GLSL_destarg_varname(ctx, dst, sizeof (dst)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, - sampler, sizeof (sampler)); - - if (ttype == TEXTURE_TYPE_2D) - { - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "texture2D(%s, %s.xy)", - sampler, dst); - } - else if (ttype == TEXTURE_TYPE_CUBE) - { - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "textureCube(%s, %s.xyz)", - sampler, dst); - } - else if (ttype == TEXTURE_TYPE_VOLUME) - { - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "texture3D(%s, %s.xyz)", - sampler, dst); - } - else - { - fail(ctx, "unexpected texture type"); - } // else - output_line(ctx, "%s", code); - } // if - - else if (!shader_version_atleast(ctx, 2, 0)) - { - // ps_1_4 is different, too! - fail(ctx, "TEXLD == Shader Model 1.4 unimplemented."); // !!! FIXME - return; - } // else if - - else - { - const SourceArgInfo *samp_arg = &ctx->source_args[1]; - RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, - samp_arg->regnum); - const char *funcname = NULL; - char src0[64] = { '\0' }; - char src1[64]; get_GLSL_srcarg_varname(ctx, 1, src1, sizeof (src1)); // !!! FIXME: SRC_MOD? - char src2[64] = { '\0' }; - char src3[64] = { '\0' }; - - if (sreg == NULL) - { - fail(ctx, "TEXLD using undeclared sampler"); - return; - } // if - - if (texldd) - { - make_GLSL_srcarg_string_vec2(ctx, 2, src2, sizeof (src2)); - make_GLSL_srcarg_string_vec2(ctx, 3, src3, sizeof (src3)); - } // if - - // !!! FIXME: can TEXLDD set instruction_controls? - // !!! FIXME: does the d3d bias value map directly to GLSL? - const char *biassep = ""; - char bias[64] = { '\0' }; - if (ctx->instruction_controls == CONTROL_TEXLDB) - { - biassep = ", "; - make_GLSL_srcarg_string_w(ctx, 0, bias, sizeof (bias)); - } // if - - switch ((const TextureType) sreg->index) - { - case TEXTURE_TYPE_2D: - if (ctx->instruction_controls == CONTROL_TEXLDP) - { - funcname = "texture2DProj"; - make_GLSL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); - } // if - else // texld/texldb - { - funcname = "texture2D"; - make_GLSL_srcarg_string_vec2(ctx, 0, src0, sizeof (src0)); - } // else - break; - case TEXTURE_TYPE_CUBE: - if (ctx->instruction_controls == CONTROL_TEXLDP) - fail(ctx, "TEXLDP on a cubemap"); // !!! FIXME: is this legal? - funcname = "textureCube"; - make_GLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); - break; - case TEXTURE_TYPE_VOLUME: - if (ctx->instruction_controls == CONTROL_TEXLDP) - { - funcname = "texture3DProj"; - make_GLSL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); - } // if - else // texld/texldb - { - funcname = "texture3D"; - make_GLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); - } // else - break; - default: - fail(ctx, "unknown texture type"); - return; - } // switch - - assert(!isscalar(ctx, ctx->shader_type, samp_arg->regtype, samp_arg->regnum)); - char swiz_str[6] = { '\0' }; - make_GLSL_swizzle_string(swiz_str, sizeof (swiz_str), - samp_arg->swizzle, ctx->dest_arg.writemask); - - char code[128]; - if (texldd) - { - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "%sGrad(%s, %s, %s, %s)%s", funcname, - src1, src0, src2, src3, swiz_str); - } // if - else - { - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "%s(%s, %s%s%s)%s", funcname, - src1, src0, biassep, bias, swiz_str); - } // else - - output_line(ctx, "%s", code); - } // else -} // glsl_texld - -static void emit_GLSL_TEXLD(Context *ctx) -{ - glsl_texld(ctx, 0); -} // emit_GLSL_TEXLD - - -static void emit_GLSL_TEXBEM(Context *ctx) -{ - DestArgInfo *info = &ctx->dest_arg; - char dst[64]; get_GLSL_destarg_varname(ctx, dst, sizeof (dst)); - char src[64]; get_GLSL_srcarg_varname(ctx, 0, src, sizeof (src)); - char sampler[64]; - char code[512]; - - // !!! FIXME: this code counts on the register not having swizzles, etc. - get_GLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, - sampler, sizeof (sampler)); - - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "texture2D(%s, vec2(%s.x + (%s_texbem.x * %s.x) + (%s_texbem.z * %s.y)," - " %s.y + (%s_texbem.y * %s.x) + (%s_texbem.w * %s.y)))", - sampler, - dst, sampler, src, sampler, src, - dst, sampler, src, sampler, src); - - output_line(ctx, "%s", code); -} // emit_GLSL_TEXBEM - - -static void emit_GLSL_TEXBEML(Context *ctx) -{ - // !!! FIXME: this code counts on the register not having swizzles, etc. - DestArgInfo *info = &ctx->dest_arg; - char dst[64]; get_GLSL_destarg_varname(ctx, dst, sizeof (dst)); - char src[64]; get_GLSL_srcarg_varname(ctx, 0, src, sizeof (src)); - char sampler[64]; - char code[512]; - - get_GLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, - sampler, sizeof (sampler)); - - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "(texture2D(%s, vec2(%s.x + (%s_texbem.x * %s.x) + (%s_texbem.z * %s.y)," - " %s.y + (%s_texbem.y * %s.x) + (%s_texbem.w * %s.y)))) *" - " ((%s.z * %s_texbeml.x) + %s_texbem.y)", - sampler, - dst, sampler, src, sampler, src, - dst, sampler, src, sampler, src, - src, sampler, sampler); - - output_line(ctx, "%s", code); -} // emit_GLSL_TEXBEML - -EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2AR) // !!! FIXME -EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2GB) // !!! FIXME - - -static void emit_GLSL_TEXM3X2PAD(Context *ctx) -{ - // no-op ... work happens in emit_GLSL_TEXM3X2TEX(). -} // emit_GLSL_TEXM3X2PAD - -static void emit_GLSL_TEXM3X2TEX(Context *ctx) -{ - if (ctx->texm3x2pad_src0 == -1) - return; - - DestArgInfo *info = &ctx->dest_arg; - char dst[64]; - char src0[64]; - char src1[64]; - char src2[64]; - char sampler[64]; - char code[512]; - - // !!! FIXME: this code counts on the register not having swizzles, etc. - get_GLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, - sampler, sizeof (sampler)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x2pad_src0, - src0, sizeof (src0)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x2pad_dst0, - src1, sizeof (src1)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, - src2, sizeof (src2)); - get_GLSL_destarg_varname(ctx, dst, sizeof (dst)); - - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "texture2D(%s, vec2(dot(%s.xyz, %s.xyz), dot(%s.xyz, %s.xyz)))", - sampler, src0, src1, src2, dst); - - output_line(ctx, "%s", code); -} // emit_GLSL_TEXM3X2TEX - -static void emit_GLSL_TEXM3X3PAD(Context *ctx) -{ - // no-op ... work happens in emit_GLSL_TEXM3X3*(). -} // emit_GLSL_TEXM3X3PAD - -static void emit_GLSL_TEXM3X3TEX(Context *ctx) -{ - if (ctx->texm3x3pad_src1 == -1) - return; - - DestArgInfo *info = &ctx->dest_arg; - char dst[64]; - char src0[64]; - char src1[64]; - char src2[64]; - char src3[64]; - char src4[64]; - char sampler[64]; - char code[512]; - - // !!! FIXME: this code counts on the register not having swizzles, etc. - get_GLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, - sampler, sizeof (sampler)); - - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, - src0, sizeof (src0)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, - src1, sizeof (src1)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, - src2, sizeof (src2)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, - src3, sizeof (src3)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, - src4, sizeof (src4)); - get_GLSL_destarg_varname(ctx, dst, sizeof (dst)); - - RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, - info->regnum); - const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); - const char *ttypestr = (ttype == TEXTURE_TYPE_CUBE) ? "Cube" : "3D"; - - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "texture%s(%s," - " vec3(dot(%s.xyz, %s.xyz)," - " dot(%s.xyz, %s.xyz)," - " dot(%s.xyz, %s.xyz)))", - ttypestr, sampler, src0, src1, src2, src3, dst, src4); - - output_line(ctx, "%s", code); -} // emit_GLSL_TEXM3X3TEX - -static void emit_GLSL_TEXM3X3SPEC_helper(Context *ctx) -{ - if (ctx->glsl_generated_texm3x3spec_helper) - return; - - ctx->glsl_generated_texm3x3spec_helper = 1; - - push_output(ctx, &ctx->helpers); - output_line(ctx, "vec3 TEXM3X3SPEC_reflection(const vec3 normal, const vec3 eyeray)"); - output_line(ctx, "{"); ctx->indent++; - output_line(ctx, "return (2.0 * ((normal * eyeray) / (normal * normal)) * normal) - eyeray;"); ctx->indent--; - output_line(ctx, "}"); - output_blank_line(ctx); - pop_output(ctx); -} // emit_GLSL_TEXM3X3SPEC_helper - -static void emit_GLSL_TEXM3X3SPEC(Context *ctx) -{ - if (ctx->texm3x3pad_src1 == -1) - return; - - DestArgInfo *info = &ctx->dest_arg; - char dst[64]; - char src0[64]; - char src1[64]; - char src2[64]; - char src3[64]; - char src4[64]; - char src5[64]; - char sampler[64]; - char code[512]; - - emit_GLSL_TEXM3X3SPEC_helper(ctx); - - // !!! FIXME: this code counts on the register not having swizzles, etc. - get_GLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, - sampler, sizeof (sampler)); - - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, - src0, sizeof (src0)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, - src1, sizeof (src1)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, - src2, sizeof (src2)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, - src3, sizeof (src3)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, - src4, sizeof (src4)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[1].regnum, - src5, sizeof (src5)); - get_GLSL_destarg_varname(ctx, dst, sizeof (dst)); - - RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, - info->regnum); - const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); - const char *ttypestr = (ttype == TEXTURE_TYPE_CUBE) ? "Cube" : "3D"; - - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "texture%s(%s, " - "TEXM3X3SPEC_reflection(" - "vec3(" - "dot(%s.xyz, %s.xyz), " - "dot(%s.xyz, %s.xyz), " - "dot(%s.xyz, %s.xyz)" - ")," - "%s.xyz," - ")" - ")", - ttypestr, sampler, src0, src1, src2, src3, dst, src4, src5); - - output_line(ctx, "%s", code); -} // emit_GLSL_TEXM3X3SPEC - -static void emit_GLSL_TEXM3X3VSPEC(Context *ctx) -{ - if (ctx->texm3x3pad_src1 == -1) - return; - - DestArgInfo *info = &ctx->dest_arg; - char dst[64]; - char src0[64]; - char src1[64]; - char src2[64]; - char src3[64]; - char src4[64]; - char sampler[64]; - char code[512]; - - emit_GLSL_TEXM3X3SPEC_helper(ctx); - - // !!! FIXME: this code counts on the register not having swizzles, etc. - get_GLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, - sampler, sizeof (sampler)); - - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, - src0, sizeof (src0)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, - src1, sizeof (src1)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, - src2, sizeof (src2)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, - src3, sizeof (src3)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, - src4, sizeof (src4)); - get_GLSL_destarg_varname(ctx, dst, sizeof (dst)); - - RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, - info->regnum); - const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); - const char *ttypestr = (ttype == TEXTURE_TYPE_CUBE) ? "Cube" : "3D"; - - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "texture%s(%s, " - "TEXM3X3SPEC_reflection(" - "vec3(" - "dot(%s.xyz, %s.xyz), " - "dot(%s.xyz, %s.xyz), " - "dot(%s.xyz, %s.xyz)" - "), " - "vec3(%s.w, %s.w, %s.w)" - ")" - ")", - ttypestr, sampler, src0, src1, src2, src3, dst, src4, src0, src2, dst); - - output_line(ctx, "%s", code); -} // emit_GLSL_TEXM3X3VSPEC - -static void emit_GLSL_EXPP(Context *ctx) -{ - // !!! FIXME: msdn's asm docs don't list this opcode, I'll have to check the driver documentation. - emit_GLSL_EXP(ctx); // I guess this is just partial precision EXP? -} // emit_GLSL_EXPP - -static void emit_GLSL_LOGP(Context *ctx) -{ - // LOGP is just low-precision LOG, but we'll take the higher precision. - emit_GLSL_LOG(ctx); -} // emit_GLSL_LOGP - -// common code between CMP and CND. -static void emit_GLSL_comparison_operations(Context *ctx, const char *cmp) -{ - int i, j; - DestArgInfo *dst = &ctx->dest_arg; - const SourceArgInfo *srcarg0 = &ctx->source_args[0]; - const int origmask = dst->writemask; - int used_swiz[4] = { 0, 0, 0, 0 }; - const int writemask[4] = { dst->writemask0, dst->writemask1, - dst->writemask2, dst->writemask3 }; - const int src0swiz[4] = { srcarg0->swizzle_x, srcarg0->swizzle_y, - srcarg0->swizzle_z, srcarg0->swizzle_w }; - - for (i = 0; i < 4; i++) - { - int mask = (1 << i); - - if (!writemask[i]) continue; - if (used_swiz[i]) continue; - - // This is a swizzle we haven't checked yet. - used_swiz[i] = 1; - - // see if there are any other elements swizzled to match (.yyyy) - for (j = i + 1; j < 4; j++) - { - if (!writemask[j]) continue; - if (src0swiz[i] != src0swiz[j]) continue; - mask |= (1 << j); - used_swiz[j] = 1; - } // for - - // okay, (mask) should be the writemask of swizzles we like. - - //return make_GLSL_srcarg_string(ctx, idx, (1 << 0)); - - char src0[64]; - char src1[64]; - char src2[64]; - make_GLSL_srcarg_string(ctx, 0, (1 << i), src0, sizeof (src0)); - make_GLSL_srcarg_string(ctx, 1, mask, src1, sizeof (src1)); - make_GLSL_srcarg_string(ctx, 2, mask, src2, sizeof (src2)); - - set_dstarg_writemask(dst, mask); - - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "((%s %s) ? %s : %s)", - src0, cmp, src1, src2); - output_line(ctx, "%s", code); - } // for - - set_dstarg_writemask(dst, origmask); -} // emit_GLSL_comparison_operations - -static void emit_GLSL_CND(Context *ctx) -{ - emit_GLSL_comparison_operations(ctx, "> 0.5"); -} // emit_GLSL_CND - -static void emit_GLSL_DEF(Context *ctx) -{ - const float *val = (const float *) ctx->dwords; // !!! FIXME: could be int? - char varname[64]; get_GLSL_destarg_varname(ctx, varname, sizeof (varname)); - char val0[32]; floatstr(ctx, val0, sizeof (val0), val[0], 1); - char val1[32]; floatstr(ctx, val1, sizeof (val1), val[1], 1); - char val2[32]; floatstr(ctx, val2, sizeof (val2), val[2], 1); - char val3[32]; floatstr(ctx, val3, sizeof (val3), val[3], 1); - - push_output(ctx, &ctx->globals); - output_line(ctx, "const vec4 %s = vec4(%s, %s, %s, %s);", - varname, val0, val1, val2, val3); - pop_output(ctx); -} // emit_GLSL_DEF - -EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2RGB) // !!! FIXME -EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXDP3TEX) // !!! FIXME -EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXM3X2DEPTH) // !!! FIXME -EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXDP3) // !!! FIXME - -static void emit_GLSL_TEXM3X3(Context *ctx) -{ - if (ctx->texm3x3pad_src1 == -1) - return; - - char dst[64]; - char src0[64]; - char src1[64]; - char src2[64]; - char src3[64]; - char src4[64]; - char code[512]; - - // !!! FIXME: this code counts on the register not having swizzles, etc. - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, - src0, sizeof (src0)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, - src1, sizeof (src1)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, - src2, sizeof (src2)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, - src3, sizeof (src3)); - get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, - src4, sizeof (src4)); - get_GLSL_destarg_varname(ctx, dst, sizeof (dst)); - - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "vec4(dot(%s.xyz, %s.xyz), dot(%s.xyz, %s.xyz), dot(%s.xyz, %s.xyz), 1.0)", - src0, src1, src2, src3, dst, src4); - - output_line(ctx, "%s", code); -} // emit_GLSL_TEXM3X3 - -EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXDEPTH) // !!! FIXME - -static void emit_GLSL_CMP(Context *ctx) -{ - emit_GLSL_comparison_operations(ctx, ">= 0.0"); -} // emit_GLSL_CMP - -EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(BEM) // !!! FIXME - -static void emit_GLSL_DP2ADD(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_vec2(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_GLSL_srcarg_string_vec2(ctx, 1, src1, sizeof (src1)); - char src2[64]; make_GLSL_srcarg_string_scalar(ctx, 2, src2, sizeof (src2)); - char extra[64]; snprintf(extra, sizeof (extra), " + %s", src2); - emit_GLSL_dotprod(ctx, src0, src1, extra); -} // emit_GLSL_DP2ADD - -static void emit_GLSL_DSX(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "dFdx(%s)", src0); - output_line(ctx, "%s", code); -} // emit_GLSL_DSX - -static void emit_GLSL_DSY(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char code[128]; - make_GLSL_destarg_assign(ctx, code, sizeof (code), "dFdy(%s)", src0); - output_line(ctx, "%s", code); -} // emit_GLSL_DSY - -static void emit_GLSL_TEXLDD(Context *ctx) -{ - // !!! FIXME: - // GLSL 1.30 introduced textureGrad() for this, but it looks like the - // functions are overloaded instead of texture2DGrad() (etc). - - // GL_shader_texture_lod and GL_EXT_gpu_shader4 added texture2DGrad*(), - // so we'll use them if available. Failing that, we'll just fallback - // to a regular texture2D call and hope the mipmap it chooses is close - // enough. - if (!ctx->glsl_generated_texldd_setup) - { - ctx->glsl_generated_texldd_setup = 1; - push_output(ctx, &ctx->preflight); - output_line(ctx, "#if GL_ARB_shader_texture_lod"); - output_line(ctx, "#extension GL_ARB_shader_texture_lod : enable"); - output_line(ctx, "#define texture2DGrad texture2DGradARB"); - output_line(ctx, "#define texture2DProjGrad texture2DProjARB"); - output_line(ctx, "#elif GL_EXT_gpu_shader4"); - output_line(ctx, "#extension GL_EXT_gpu_shader4 : enable"); - output_line(ctx, "#else"); - output_line(ctx, "#define texture2DGrad(a,b,c,d) texture2D(a,b)"); - output_line(ctx, "#define texture2DProjGrad(a,b,c,d) texture2DProj(a,b)"); - output_line(ctx, "#endif"); - output_blank_line(ctx); - pop_output(ctx); - } // if - - glsl_texld(ctx, 1); -} // emit_GLSL_TEXLDD - -static void emit_GLSL_SETP(Context *ctx) -{ - const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); - char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); - char code[128]; - - // destination is always predicate register (which is type bvec4). - if (vecsize == 1) - { - const char *comp = get_GLSL_comparison_string_scalar(ctx); - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "(%s %s %s)", src0, comp, src1); - } // if - else - { - const char *comp = get_GLSL_comparison_string_vector(ctx); - make_GLSL_destarg_assign(ctx, code, sizeof (code), - "%s(%s, %s)", comp, src0, src1); - } // else - - output_line(ctx, "%s", code); -} // emit_GLSL_SETP - -static void emit_GLSL_TEXLDL(Context *ctx) -{ - // !!! FIXME: The spec says we can't use GLSL's texture*Lod() built-ins - // !!! FIXME: from fragment shaders for some inexplicable reason. - // !!! FIXME: For now, you'll just have to suffer with the potentially - // !!! FIXME: wrong mipmap until I can figure something out. - emit_GLSL_TEXLD(ctx); -} // emit_GLSL_TEXLDL - -static void emit_GLSL_BREAKP(Context *ctx) -{ - char src0[64]; make_GLSL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); - output_line(ctx, "if (%s) { break; }", src0); -} // emit_GLSL_BREAKP - -static void emit_GLSL_RESERVED(Context *ctx) -{ - // do nothing; fails in the state machine. -} // emit_GLSL_RESERVED - -#endif // SUPPORT_PROFILE_GLSL - - - -#if !SUPPORT_PROFILE_ARB1 -#define PROFILE_EMITTER_ARB1(op) -#else -#undef AT_LEAST_ONE_PROFILE -#define AT_LEAST_ONE_PROFILE 1 -#define PROFILE_EMITTER_ARB1(op) emit_ARB1_##op, - -static inline const char *get_ARB1_register_string(Context *ctx, - const RegisterType regtype, const int regnum, - char *regnum_str, const size_t regnum_size) -{ - // turns out these are identical at the moment. - return get_D3D_register_string(ctx,regtype,regnum,regnum_str,regnum_size); -} // get_ARB1_register_string - -static const char *allocate_ARB1_scratch_reg_name(Context *ctx, char *buf, - const size_t buflen) -{ - const int scratch = allocate_scratch_register(ctx); - snprintf(buf, buflen, "scratch%d", scratch); - return buf; -} // allocate_ARB1_scratch_reg_name - -static inline const char *get_ARB1_branch_label_name(Context *ctx, const int id, - char *buf, const size_t buflen) -{ - snprintf(buf, buflen, "branch_label%d", id); - return buf; -} // get_ARB1_branch_label_name - -static const char *get_ARB1_varname_in_buf(Context *ctx, const RegisterType rt, - const int regnum, char *buf, - const size_t buflen) -{ - // turns out these are identical at the moment. - return get_D3D_varname_in_buf(ctx, rt, regnum, buf, buflen); -} // get_ARB1_varname_in_buf - -static const char *get_ARB1_varname(Context *ctx, const RegisterType rt, - const int regnum) -{ - // turns out these are identical at the moment. - return get_D3D_varname(ctx, rt, regnum); -} // get_ARB1_varname - - -static inline const char *get_ARB1_const_array_varname_in_buf(Context *ctx, - const int base, const int size, - char *buf, const size_t buflen) -{ - snprintf(buf, buflen, "c_array_%d_%d", base, size); - return buf; -} // get_ARB1_const_array_varname_in_buf - - -static const char *get_ARB1_const_array_varname(Context *ctx, int base, int size) -{ - char buf[64]; - get_ARB1_const_array_varname_in_buf(ctx, base, size, buf, sizeof (buf)); - return StrDup(ctx, buf); -} // get_ARB1_const_array_varname - - -static const char *make_ARB1_srcarg_string_in_buf(Context *ctx, - const SourceArgInfo *arg, - char *buf, size_t buflen) -{ - // !!! FIXME: this can hit pathological cases where we look like this... - // - // dp3 r1.xyz, t0_bx2, t0_bx2 - // mad r1.xyz, t0_bias, 1-r1, t0_bx2 - // - // ...which do a lot of duplicate work in arb1... - // - // SUB scratch0, t0, { 0.5, 0.5, 0.5, 0.5 }; - // MUL scratch0, scratch0, { 2.0, 2.0, 2.0, 2.0 }; - // SUB scratch1, t0, { 0.5, 0.5, 0.5, 0.5 }; - // MUL scratch1, scratch1, { 2.0, 2.0, 2.0, 2.0 }; - // DP3 r1.xyz, scratch0, scratch1; - // SUB scratch0, t0, { 0.5, 0.5, 0.5, 0.5 }; - // SUB scratch1, { 1.0, 1.0, 1.0, 1.0 }, r1; - // SUB scratch2, t0, { 0.5, 0.5, 0.5, 0.5 }; - // MUL scratch2, scratch2, { 2.0, 2.0, 2.0, 2.0 }; - // MAD r1.xyz, scratch0, scratch1, scratch2; - // - // ...notice that the dp3 calculates the same value into two scratch - // registers. This case is easier to handle; just see if multiple - // source args are identical, build it up once, and use the same - // scratch register for multiple arguments in that opcode. - // Even better still, only calculate things once across instructions, - // and be smart about letting it linger in a scratch register until we - // definitely don't need the calculation anymore. That's harder to - // write, though. - - char regnum_str[16] = { '\0' }; - - // !!! FIXME: use get_ARB1_varname_in_buf() instead? - const char *regtype_str = NULL; - if (!arg->relative) - { - regtype_str = get_ARB1_register_string(ctx, arg->regtype, - arg->regnum, regnum_str, - sizeof (regnum_str)); - } // if - - const char *rel_lbracket = ""; - char rel_offset[32] = { '\0' }; - const char *rel_rbracket = ""; - char rel_swizzle[4] = { '\0' }; - const char *rel_regtype_str = ""; - if (arg->relative) - { - rel_regtype_str = get_ARB1_varname_in_buf(ctx, arg->relative_regtype, - arg->relative_regnum, - (char *) alloca(64), 64); - - rel_swizzle[0] = '.'; - rel_swizzle[1] = swizzle_channels[arg->relative_component]; - rel_swizzle[2] = '\0'; - - if (!support_nv2(ctx)) - { - // The address register in ARB1 only allows the '.x' component, so - // we need to load the component we need from a temp vector - // register into .x as needed. - assert(arg->relative_regtype == REG_TYPE_ADDRESS); - assert(arg->relative_regnum == 0); - if (ctx->last_address_reg_component != arg->relative_component) - { - output_line(ctx, "ARL %s.x, addr%d.%c;", rel_regtype_str, - arg->relative_regnum, - swizzle_channels[arg->relative_component]); - ctx->last_address_reg_component = arg->relative_component; - } // if - - rel_swizzle[1] = 'x'; - } // if - - if (arg->regtype == REG_TYPE_INPUT) - regtype_str = "vertex.attrib"; - else - { - assert(arg->regtype == REG_TYPE_CONST); - const int arrayidx = arg->relative_array->index; - const int arraysize = arg->relative_array->count; - const int offset = arg->regnum - arrayidx; - assert(offset >= 0); - regtype_str = get_ARB1_const_array_varname_in_buf(ctx, arrayidx, - arraysize, (char *) alloca(64), 64); - if (offset != 0) - snprintf(rel_offset, sizeof (rel_offset), " + %d", offset); - } // else - - rel_lbracket = "["; - rel_rbracket = "]"; - } // if - - // This is the source register with everything but swizzle and source mods. - snprintf(buf, buflen, "%s%s%s%s%s%s%s", regtype_str, regnum_str, - rel_lbracket, rel_regtype_str, rel_swizzle, rel_offset, - rel_rbracket); - - // Some of the source mods need to generate instructions to a temp - // register, in which case we'll replace the register name. - const SourceMod mod = arg->src_mod; - const int inplace = ( (mod == SRCMOD_NONE) || (mod == SRCMOD_NEGATE) || - ((mod == SRCMOD_ABS) && support_nv2(ctx)) ); - - if (!inplace) - { - const size_t len = 64; - char *stackbuf = (char *) alloca(len); - regtype_str = allocate_ARB1_scratch_reg_name(ctx, stackbuf, len); - regnum_str[0] = '\0'; // move value to scratch register. - rel_lbracket = ""; // scratch register won't use array. - rel_rbracket = ""; - rel_offset[0] = '\0'; - rel_swizzle[0] = '\0'; - rel_regtype_str = ""; - } // if - - const char *premod_str = ""; - const char *postmod_str = ""; - switch (mod) - { - case SRCMOD_NEGATE: - premod_str = "-"; - break; - - case SRCMOD_BIASNEGATE: - premod_str = "-"; - // fall through. - case SRCMOD_BIAS: - output_line(ctx, "SUB %s, %s, { 0.5, 0.5, 0.5, 0.5 };", - regtype_str, buf); - break; - - case SRCMOD_SIGNNEGATE: - premod_str = "-"; - // fall through. - case SRCMOD_SIGN: - output_line(ctx, - "MAD %s, %s, { 2.0, 2.0, 2.0, 2.0 }, { -1.0, -1.0, -1.0, -1.0 };", - regtype_str, buf); - break; - - case SRCMOD_COMPLEMENT: - output_line(ctx, "SUB %s, { 1.0, 1.0, 1.0, 1.0 }, %s;", - regtype_str, buf); - break; - - case SRCMOD_X2NEGATE: - premod_str = "-"; - // fall through. - case SRCMOD_X2: - output_line(ctx, "MUL %s, %s, { 2.0, 2.0, 2.0, 2.0 };", - regtype_str, buf); - break; - - case SRCMOD_DZ: - fail(ctx, "SRCMOD_DZ currently unsupported in arb1"); - postmod_str = "_dz"; - break; - - case SRCMOD_DW: - fail(ctx, "SRCMOD_DW currently unsupported in arb1"); - postmod_str = "_dw"; - break; - - case SRCMOD_ABSNEGATE: - premod_str = "-"; - // fall through. - case SRCMOD_ABS: - if (!support_nv2(ctx)) // GL_NV_vertex_program2_option adds this. - output_line(ctx, "ABS %s, %s;", regtype_str, buf); - else - { - premod_str = (mod == SRCMOD_ABSNEGATE) ? "-|" : "|"; - postmod_str = "|"; - } // else - break; - - case SRCMOD_NOT: - fail(ctx, "SRCMOD_NOT currently unsupported in arb1"); - premod_str = "!"; - break; - - case SRCMOD_NONE: - case SRCMOD_TOTAL: - break; // stop compiler whining. - } // switch - - char swizzle_str[6]; - size_t i = 0; - - if (support_nv4(ctx)) // vFace must be output as "vFace.x" in nv4. - { - if (arg->regtype == REG_TYPE_MISCTYPE) - { - if ( ((const MiscTypeType) arg->regnum) == MISCTYPE_TYPE_FACE ) - { - swizzle_str[i++] = '.'; - swizzle_str[i++] = 'x'; - } // if - } // if - } // if - - const int scalar = isscalar(ctx, ctx->shader_type, arg->regtype, arg->regnum); - if (!scalar && !no_swizzle(arg->swizzle)) - { - swizzle_str[i++] = '.'; - - // .xxxx is the same as .x, but .xx is illegal...scalar or full! - if (replicate_swizzle(arg->swizzle)) - swizzle_str[i++] = swizzle_channels[arg->swizzle_x]; - else - { - swizzle_str[i++] = swizzle_channels[arg->swizzle_x]; - swizzle_str[i++] = swizzle_channels[arg->swizzle_y]; - swizzle_str[i++] = swizzle_channels[arg->swizzle_z]; - swizzle_str[i++] = swizzle_channels[arg->swizzle_w]; - } // else - } // if - swizzle_str[i] = '\0'; - assert(i < sizeof (swizzle_str)); - - snprintf(buf, buflen, "%s%s%s%s%s%s%s%s%s%s", premod_str, - regtype_str, regnum_str, rel_lbracket, - rel_regtype_str, rel_swizzle, rel_offset, rel_rbracket, - swizzle_str, postmod_str); - // !!! FIXME: make sure the scratch buffer was large enough. - return buf; -} // make_ARB1_srcarg_string_in_buf - -static const char *get_ARB1_destarg_varname(Context *ctx, char *buf, - const size_t buflen) -{ - const DestArgInfo *arg = &ctx->dest_arg; - return get_ARB1_varname_in_buf(ctx, arg->regtype, arg->regnum, buf, buflen); -} // get_ARB1_destarg_varname - -static const char *get_ARB1_srcarg_varname(Context *ctx, const size_t idx, - char *buf, const size_t buflen) -{ - if (idx >= STATICARRAYLEN(ctx->source_args)) - { - fail(ctx, "Too many source args"); - *buf = '\0'; - return buf; - } // if - - const SourceArgInfo *arg = &ctx->source_args[idx]; - return get_ARB1_varname_in_buf(ctx, arg->regtype, arg->regnum, buf, buflen); -} // get_ARB1_srcarg_varname - - -static const char *make_ARB1_destarg_string(Context *ctx, char *buf, - const size_t buflen) -{ - const DestArgInfo *arg = &ctx->dest_arg; - - *buf = '\0'; - - const char *sat_str = ""; - if (arg->result_mod & MOD_SATURATE) - { - // nv4 can use ".SAT" in all program types. - // For less than nv4, the "_SAT" modifier is only available in - // fragment shaders. Every thing else will fake it later in - // emit_ARB1_dest_modifiers() ... - if (support_nv4(ctx)) - sat_str = ".SAT"; - else if (shader_is_pixel(ctx)) - sat_str = "_SAT"; - } // if - - const char *pp_str = ""; - if (arg->result_mod & MOD_PP) - { - // Most ARB1 profiles can't do partial precision (MOD_PP), but that's - // okay. The spec says lots of Direct3D implementations ignore the - // flag anyhow. - if (support_nv4(ctx)) - pp_str = "H"; - } // if - - // CENTROID only allowed in DCL opcodes, which shouldn't come through here. - assert((arg->result_mod & MOD_CENTROID) == 0); - - char regnum_str[16]; - const char *regtype_str = get_ARB1_register_string(ctx, arg->regtype, - arg->regnum, regnum_str, - sizeof (regnum_str)); - if (regtype_str == NULL) - { - fail(ctx, "Unknown destination register type."); - return buf; - } // if - - char writemask_str[6]; - size_t i = 0; - const int scalar = isscalar(ctx, ctx->shader_type, arg->regtype, arg->regnum); - if (!scalar && !writemask_xyzw(arg->writemask)) - { - writemask_str[i++] = '.'; - if (arg->writemask0) writemask_str[i++] = 'x'; - if (arg->writemask1) writemask_str[i++] = 'y'; - if (arg->writemask2) writemask_str[i++] = 'z'; - if (arg->writemask3) writemask_str[i++] = 'w'; - } // if - writemask_str[i] = '\0'; - assert(i < sizeof (writemask_str)); - - const char *pred_left = ""; - const char *pred_right = ""; - char pred[32] = { '\0' }; - if (ctx->predicated) - { - fail(ctx, "dest register predication currently unsupported in arb1"); - return buf; - pred_left = "("; - pred_right = ") "; - make_ARB1_srcarg_string_in_buf(ctx, &ctx->predicate_arg, - pred, sizeof (pred)); - } // if - - snprintf(buf, buflen, "%s%s %s%s%s", pp_str, sat_str, - regtype_str, regnum_str, writemask_str); - // !!! FIXME: make sure the scratch buffer was large enough. - return buf; -} // make_ARB1_destarg_string - - -static void emit_ARB1_dest_modifiers(Context *ctx) -{ - const DestArgInfo *arg = &ctx->dest_arg; - - if (arg->result_shift != 0x0) - { - char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); - const char *multiplier = NULL; - - switch (arg->result_shift) - { - case 0x1: multiplier = "2.0"; break; - case 0x2: multiplier = "4.0"; break; - case 0x3: multiplier = "8.0"; break; - case 0xD: multiplier = "0.125"; break; - case 0xE: multiplier = "0.25"; break; - case 0xF: multiplier = "0.5"; break; - } // switch - - if (multiplier != NULL) - { - char var[64]; get_ARB1_destarg_varname(ctx, var, sizeof (var)); - output_line(ctx, "MUL%s, %s, %s;", dst, var, multiplier); - } // if - } // if - - if (arg->result_mod & MOD_SATURATE) - { - // nv4 and/or pixel shaders just used the "SAT" modifier, instead. - if ( (!support_nv4(ctx)) && (!shader_is_pixel(ctx)) ) - { - char var[64]; get_ARB1_destarg_varname(ctx, var, sizeof (var)); - char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); - output_line(ctx, "MIN%s, %s, 1.0;", dst, var); - output_line(ctx, "MAX%s, %s, 0.0;", dst, var); - } // if - } // if -} // emit_ARB1_dest_modifiers - - -static const char *make_ARB1_srcarg_string(Context *ctx, const size_t idx, - char *buf, const size_t buflen) -{ - if (idx >= STATICARRAYLEN(ctx->source_args)) - { - fail(ctx, "Too many source args"); - *buf = '\0'; - return buf; - } // if - - const SourceArgInfo *arg = &ctx->source_args[idx]; - return make_ARB1_srcarg_string_in_buf(ctx, arg, buf, buflen); -} // make_ARB1_srcarg_string - -static void emit_ARB1_opcode_ds(Context *ctx, const char *opcode) -{ - char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); - char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); - output_line(ctx, "%s%s, %s;", opcode, dst, src0); - emit_ARB1_dest_modifiers(ctx); -} // emit_ARB1_opcode_ds - -static void emit_ARB1_opcode_dss(Context *ctx, const char *opcode) -{ - char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); - char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_ARB1_srcarg_string(ctx, 1, src1, sizeof (src1)); - output_line(ctx, "%s%s, %s, %s;", opcode, dst, src0, src1); - emit_ARB1_dest_modifiers(ctx); -} // emit_ARB1_opcode_dss - -static void emit_ARB1_opcode_dsss(Context *ctx, const char *opcode) -{ - char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); - char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_ARB1_srcarg_string(ctx, 1, src1, sizeof (src1)); - char src2[64]; make_ARB1_srcarg_string(ctx, 2, src2, sizeof (src2)); - output_line(ctx, "%s%s, %s, %s, %s;", opcode, dst, src0, src1, src2); - emit_ARB1_dest_modifiers(ctx); -} // emit_ARB1_opcode_dsss - - -#define EMIT_ARB1_OPCODE_FUNC(op) \ - static void emit_ARB1_##op(Context *ctx) { \ - emit_ARB1_opcode(ctx, #op); \ - } -#define EMIT_ARB1_OPCODE_D_FUNC(op) \ - static void emit_ARB1_##op(Context *ctx) { \ - emit_ARB1_opcode_d(ctx, #op); \ - } -#define EMIT_ARB1_OPCODE_S_FUNC(op) \ - static void emit_ARB1_##op(Context *ctx) { \ - emit_ARB1_opcode_s(ctx, #op); \ - } -#define EMIT_ARB1_OPCODE_SS_FUNC(op) \ - static void emit_ARB1_##op(Context *ctx) { \ - emit_ARB1_opcode_ss(ctx, #op); \ - } -#define EMIT_ARB1_OPCODE_DS_FUNC(op) \ - static void emit_ARB1_##op(Context *ctx) { \ - emit_ARB1_opcode_ds(ctx, #op); \ - } -#define EMIT_ARB1_OPCODE_DSS_FUNC(op) \ - static void emit_ARB1_##op(Context *ctx) { \ - emit_ARB1_opcode_dss(ctx, #op); \ - } -#define EMIT_ARB1_OPCODE_DSSS_FUNC(op) \ - static void emit_ARB1_##op(Context *ctx) { \ - emit_ARB1_opcode_dsss(ctx, #op); \ - } -#define EMIT_ARB1_OPCODE_DSSSS_FUNC(op) \ - static void emit_ARB1_##op(Context *ctx) { \ - emit_ARB1_opcode_dssss(ctx, #op); \ - } -#define EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(op) \ - static void emit_ARB1_##op(Context *ctx) { \ - failf(ctx, #op " unimplemented in %s profile", ctx->profile->name); \ - } - - -static void emit_ARB1_start(Context *ctx, const char *profilestr) -{ - const char *shader_str = NULL; - const char *shader_full_str = NULL; - if (shader_is_vertex(ctx)) - { - shader_str = "vp"; - shader_full_str = "vertex"; - } // if - else if (shader_is_pixel(ctx)) - { - shader_str = "fp"; - shader_full_str = "fragment"; - } // else if - else - { - failf(ctx, "Shader type %u unsupported in this profile.", - (uint) ctx->shader_type); - return; - } // if - - set_output(ctx, &ctx->preflight); - - if (strcmp(profilestr, MOJOSHADER_PROFILE_ARB1) == 0) - output_line(ctx, "!!ARB%s1.0", shader_str); - - #if SUPPORT_PROFILE_ARB1_NV - else if (strcmp(profilestr, MOJOSHADER_PROFILE_NV2) == 0) - { - ctx->profile_supports_nv2 = 1; - output_line(ctx, "!!ARB%s1.0", shader_str); - output_line(ctx, "OPTION NV_%s_program2;", shader_full_str); - } // else if - - else if (strcmp(profilestr, MOJOSHADER_PROFILE_NV3) == 0) - { - // there's no NV_fragment_program3, so just use 2. - const int ver = shader_is_pixel(ctx) ? 2 : 3; - ctx->profile_supports_nv2 = 1; - ctx->profile_supports_nv3 = 1; - output_line(ctx, "!!ARB%s1.0", shader_str); - output_line(ctx, "OPTION NV_%s_program%d;", shader_full_str, ver); - } // else if - - else if (strcmp(profilestr, MOJOSHADER_PROFILE_NV4) == 0) - { - ctx->profile_supports_nv2 = 1; - ctx->profile_supports_nv3 = 1; - ctx->profile_supports_nv4 = 1; - output_line(ctx, "!!NV%s4.0", shader_str); - } // else if - #endif - - else - { - failf(ctx, "Profile '%s' unsupported or unknown.", profilestr); - } // else - - set_output(ctx, &ctx->mainline); -} // emit_ARB1_start - -static void emit_ARB1_end(Context *ctx) -{ - // ps_1_* writes color to r0 instead oC0. We move it to the right place. - // We don't have to worry about a RET opcode messing this up, since - // RET isn't available before ps_2_0. - if (shader_is_pixel(ctx) && !shader_version_atleast(ctx, 2, 0)) - { - set_used_register(ctx, REG_TYPE_COLOROUT, 0, 1); - output_line(ctx, "MOV oC0, r0;"); - } // if - - output_line(ctx, "END"); -} // emit_ARB1_end - -static void emit_ARB1_phase(Context *ctx) -{ - // no-op in arb1. -} // emit_ARB1_phase - -static inline const char *arb1_float_temp(const Context *ctx) -{ - // nv4 lets you specify data type. - return (support_nv4(ctx)) ? "FLOAT TEMP" : "TEMP"; -} // arb1_float_temp - -static void emit_ARB1_finalize(Context *ctx) -{ - push_output(ctx, &ctx->preflight); - - if (shader_is_vertex(ctx) && !ctx->arb1_wrote_position) - output_line(ctx, "OPTION ARB_position_invariant;"); - - if (shader_is_pixel(ctx) && ctx->have_multi_color_outputs) - output_line(ctx, "OPTION ARB_draw_buffers;"); - - pop_output(ctx); - - const char *tmpstr = arb1_float_temp(ctx); - int i; - push_output(ctx, &ctx->globals); - for (i = 0; i < ctx->max_scratch_registers; i++) - { - char buf[64]; - allocate_ARB1_scratch_reg_name(ctx, buf, sizeof (buf)); - output_line(ctx, "%s %s;", tmpstr, buf); - } // for - - // nv2 fragment programs (and anything nv4) have a real REP/ENDREP. - if ( (support_nv2(ctx)) && (!shader_is_pixel(ctx)) && (!support_nv4(ctx)) ) - { - // set up temps for nv2 REP/ENDREP emulation through branching. - for (i = 0; i < ctx->max_reps; i++) - output_line(ctx, "TEMP rep%d;", i); - } // if - - pop_output(ctx); - assert(ctx->scratch_registers == ctx->max_scratch_registers); -} // emit_ARB1_finalize - -static void emit_ARB1_global(Context *ctx, RegisterType regtype, int regnum) -{ - // !!! FIXME: dependency on ARB1 profile. // !!! FIXME about FIXME: huh? - char varname[64]; - get_ARB1_varname_in_buf(ctx, regtype, regnum, varname, sizeof (varname)); - - push_output(ctx, &ctx->globals); - switch (regtype) - { - case REG_TYPE_ADDRESS: - if (shader_is_pixel(ctx)) // actually REG_TYPE_TEXTURE. - { - // We have to map texture registers to temps for ps_1_1, since - // they work like temps, initialize with tex coords, and the - // ps_1_1 TEX opcode expects to overwrite it. - if (!shader_version_atleast(ctx, 1, 4)) - { - output_line(ctx, "%s %s;", arb1_float_temp(ctx), varname); - push_output(ctx, &ctx->mainline_intro); - output_line(ctx, "MOV %s, fragment.texcoord[%d];", - varname, regnum); - pop_output(ctx); - } // if - break; - } // if - - // nv4 replaced address registers with generic int registers. - if (support_nv4(ctx)) - output_line(ctx, "INT TEMP %s;", varname); - else - { - // nv2 has four-component address already, but stock arb1 has - // to emulate it in a temporary, and move components to the - // scalar ADDRESS register on demand. - output_line(ctx, "ADDRESS %s;", varname); - if (!support_nv2(ctx)) - output_line(ctx, "TEMP addr%d;", regnum); - } // else - break; - - //case REG_TYPE_PREDICATE: - // output_line(ctx, "bvec4 %s;", varname); - // break; - case REG_TYPE_TEMP: - output_line(ctx, "%s %s;", arb1_float_temp(ctx), varname); - break; - //case REG_TYPE_LOOP: - // break; // no-op. We declare these in for loops at the moment. - //case REG_TYPE_LABEL: - // break; // no-op. If we see it here, it means we optimized it out. - default: - fail(ctx, "BUG: we used a register we don't know how to define."); - break; - } // switch - pop_output(ctx); -} // emit_ARB1_global - -static void emit_ARB1_array(Context *ctx, VariableList *var) -{ - // All uniforms are now packed tightly into the program.local array, - // instead of trying to map them to the d3d registers. So this needs to - // map to the next piece of the array we haven't used yet. Thankfully, - // arb1 lets you make a PARAM array that maps to a subset of another - // array; we don't need to do offsets, since myarray[0] can map to - // program.local[5] without any extra math from us. - const int base = var->index; - const int size = var->count; - const int arb1base = ctx->uniform_float4_count + - ctx->uniform_int4_count + - ctx->uniform_bool_count; - char varname[64]; - get_ARB1_const_array_varname_in_buf(ctx, base, size, varname, sizeof (varname)); - push_output(ctx, &ctx->globals); - output_line(ctx, "PARAM %s[%d] = { program.local[%d..%d] };", varname, - size, arb1base, (arb1base + size) - 1); - pop_output(ctx); - var->emit_position = arb1base; -} // emit_ARB1_array - -static void emit_ARB1_const_array(Context *ctx, const ConstantsList *clist, - int base, int size) -{ - char varname[64]; - get_ARB1_const_array_varname_in_buf(ctx, base, size, varname, sizeof (varname)); - int i; - - push_output(ctx, &ctx->globals); - output_line(ctx, "PARAM %s[%d] = {", varname, size); - ctx->indent++; - - for (i = 0; i < size; i++) - { - while (clist->constant.type != MOJOSHADER_UNIFORM_FLOAT) - clist = clist->next; - assert(clist->constant.index == (base + i)); - - char val0[32]; - char val1[32]; - char val2[32]; - char val3[32]; - floatstr(ctx, val0, sizeof (val0), clist->constant.value.f[0], 1); - floatstr(ctx, val1, sizeof (val1), clist->constant.value.f[1], 1); - floatstr(ctx, val2, sizeof (val2), clist->constant.value.f[2], 1); - floatstr(ctx, val3, sizeof (val3), clist->constant.value.f[3], 1); - - output_line(ctx, "{ %s, %s, %s, %s }%s", val0, val1, val2, val3, - (i < (size-1)) ? "," : ""); - - clist = clist->next; - } // for - - ctx->indent--; - output_line(ctx, "};"); - pop_output(ctx); -} // emit_ARB1_const_array - -static void emit_ARB1_uniform(Context *ctx, RegisterType regtype, int regnum, - const VariableList *var) -{ - // We pack these down into the program.local array, so if we only use - // register c439, it'll actually map to program.local[0]. This will - // prevent overflows when we actually have enough resources to run. - - const char *arrayname = "program.local"; - int index = 0; - - char varname[64]; - get_ARB1_varname_in_buf(ctx, regtype, regnum, varname, sizeof (varname)); - - push_output(ctx, &ctx->globals); - - if (var == NULL) - { - // all types share one array (rather, all types convert to float4). - index = ctx->uniform_float4_count + ctx->uniform_int4_count + - ctx->uniform_bool_count; - } // if - - else - { - const int arraybase = var->index; - if (var->constant) - { - const int arraysize = var->count; - arrayname = get_ARB1_const_array_varname_in_buf(ctx, arraybase, - arraysize, (char *) alloca(64), 64); - index = (regnum - arraybase); - } // if - else - { - assert(var->emit_position != -1); - index = (regnum - arraybase) + var->emit_position; - } // else - } // else - - output_line(ctx, "PARAM %s = %s[%d];", varname, arrayname, index); - pop_output(ctx); -} // emit_ARB1_uniform - -static void emit_ARB1_sampler(Context *ctx,int stage,TextureType ttype,int tb) -{ - // this is mostly a no-op...you don't predeclare samplers in arb1. - - if (tb) // This sampler used a ps_1_1 TEXBEM opcode? - { - const int index = ctx->uniform_float4_count + ctx->uniform_int4_count + - ctx->uniform_bool_count; - char var[64]; - get_ARB1_varname_in_buf(ctx, REG_TYPE_SAMPLER, stage, var, sizeof(var)); - push_output(ctx, &ctx->globals); - output_line(ctx, "PARAM %s_texbem = program.local[%d];", var, index); - output_line(ctx, "PARAM %s_texbeml = program.local[%d];", var, index+1); - pop_output(ctx); - ctx->uniform_float4_count += 2; - } // if -} // emit_ARB1_sampler - -// !!! FIXME: a lot of cut-and-paste here from emit_GLSL_attribute(). -static void emit_ARB1_attribute(Context *ctx, RegisterType regtype, int regnum, - MOJOSHADER_usage usage, int index, int wmask, - int flags) -{ - // !!! FIXME: this function doesn't deal with write masks at all yet! - const char *usage_str = NULL; - const char *arrayleft = ""; - const char *arrayright = ""; - char index_str[16] = { '\0' }; - - char varname[64]; - get_ARB1_varname_in_buf(ctx, regtype, regnum, varname, sizeof (varname)); - - //assert((flags & MOD_PP) == 0); // !!! FIXME: is PP allowed? - - if (index != 0) // !!! FIXME: a lot of these MUST be zero. - snprintf(index_str, sizeof (index_str), "%u", (uint) index); - - if (shader_is_vertex(ctx)) - { - // pre-vs3 output registers. - // these don't ever happen in DCL opcodes, I think. Map to vs_3_* - // output registers. - if (!shader_version_atleast(ctx, 3, 0)) - { - if (regtype == REG_TYPE_RASTOUT) - { - regtype = REG_TYPE_OUTPUT; - index = regnum; - switch ((const RastOutType) regnum) - { - case RASTOUT_TYPE_POSITION: - usage = MOJOSHADER_USAGE_POSITION; - break; - case RASTOUT_TYPE_FOG: - usage = MOJOSHADER_USAGE_FOG; - break; - case RASTOUT_TYPE_POINT_SIZE: - usage = MOJOSHADER_USAGE_POINTSIZE; - break; - } // switch - } // if - - else if (regtype == REG_TYPE_ATTROUT) - { - regtype = REG_TYPE_OUTPUT; - usage = MOJOSHADER_USAGE_COLOR; - index = regnum; - } // else if - - else if (regtype == REG_TYPE_TEXCRDOUT) - { - regtype = REG_TYPE_OUTPUT; - usage = MOJOSHADER_USAGE_TEXCOORD; - index = regnum; - } // else if - } // if - - // to avoid limitations of various GL entry points for input - // attributes (glSecondaryColorPointer() can only take 3 component - // items, glVertexPointer() can't do GL_UNSIGNED_BYTE, many other - // issues), we set up all inputs as generic vertex attributes, so we - // can pass data in just about any form, and ignore the built-in GLSL - // attributes like gl_SecondaryColor. Output needs to use the the - // built-ins, though, but we don't have to worry about the GL entry - // point limitations there. - - if (regtype == REG_TYPE_INPUT) - { - const int attr = ctx->assigned_vertex_attributes++; - push_output(ctx, &ctx->globals); - output_line(ctx, "ATTRIB %s = vertex.attrib[%d];", varname, attr); - pop_output(ctx); - } // if - - else if (regtype == REG_TYPE_OUTPUT) - { - switch (usage) - { - case MOJOSHADER_USAGE_POSITION: - ctx->arb1_wrote_position = 1; - usage_str = "result.position"; - break; - case MOJOSHADER_USAGE_POINTSIZE: - usage_str = "result.pointsize"; - break; - case MOJOSHADER_USAGE_COLOR: - index_str[0] = '\0'; // no explicit number. - if (index == 0) - usage_str = "result.color.primary"; - else if (index == 1) - usage_str = "result.color.secondary"; - break; - case MOJOSHADER_USAGE_FOG: - usage_str = "result.fogcoord"; - break; - case MOJOSHADER_USAGE_TEXCOORD: - snprintf(index_str, sizeof (index_str), "%u", (uint) index); - usage_str = "result.texcoord"; - arrayleft = "["; - arrayright = "]"; - break; - default: - // !!! FIXME: we need to deal with some more built-in varyings here. - break; - } // switch - - // !!! FIXME: the #define is a little hacky, but it means we don't - // !!! FIXME: have to track these separately if this works. - push_output(ctx, &ctx->globals); - // no mapping to built-in var? Just make it a regular global, pray. - if (usage_str == NULL) - output_line(ctx, "%s %s;", arb1_float_temp(ctx), varname); - else - { - output_line(ctx, "OUTPUT %s = %s%s%s%s;", varname, usage_str, - arrayleft, index_str, arrayright); - } // else - pop_output(ctx); - } // else if - - else - { - fail(ctx, "unknown vertex shader attribute register"); - } // else - } // if - - else if (shader_is_pixel(ctx)) - { - const char *paramtype_str = "ATTRIB"; - - // samplers DCLs get handled in emit_ARB1_sampler(). - - if (flags & MOD_CENTROID) - { - if (!support_nv4(ctx)) // GL_NV_fragment_program4 adds centroid. - { - // !!! FIXME: should we just wing it without centroid here? - failf(ctx, "centroid unsupported in %s profile", - ctx->profile->name); - return; - } // if - - paramtype_str = "CENTROID ATTRIB"; - } // if - - if (regtype == REG_TYPE_COLOROUT) - { - paramtype_str = "OUTPUT"; - usage_str = "result.color"; - if (ctx->have_multi_color_outputs) - { - // We have to gamble that you have GL_ARB_draw_buffers. - // You probably do at this point if you have a sane setup. - snprintf(index_str, sizeof (index_str), "%u", (uint) regnum); - arrayleft = "["; - arrayright = "]"; - } // if - } // if - - else if (regtype == REG_TYPE_DEPTHOUT) - { - paramtype_str = "OUTPUT"; - usage_str = "result.depth"; - } // else if - - // !!! FIXME: can you actualy have a texture register with COLOR usage? - else if ((regtype == REG_TYPE_TEXTURE) || (regtype == REG_TYPE_INPUT)) - { - if (usage == MOJOSHADER_USAGE_TEXCOORD) - { - // ps_1_1 does a different hack for this attribute. - // Refer to emit_ARB1_global()'s REG_TYPE_TEXTURE code. - if (shader_version_atleast(ctx, 1, 4)) - { - snprintf(index_str, sizeof (index_str), "%u", (uint) index); - usage_str = "fragment.texcoord"; - arrayleft = "["; - arrayright = "]"; - } // if - } // if - - else if (usage == MOJOSHADER_USAGE_COLOR) - { - index_str[0] = '\0'; // no explicit number. - if (index == 0) - usage_str = "fragment.color.primary"; - else if (index == 1) - usage_str = "fragment.color.secondary"; - else - fail(ctx, "unsupported color index"); - } // else if - } // else if - - else if (regtype == REG_TYPE_MISCTYPE) - { - const MiscTypeType mt = (MiscTypeType) regnum; - if (mt == MISCTYPE_TYPE_FACE) - { - if (support_nv4(ctx)) // FINALLY, a vFace equivalent in nv4! - { - index_str[0] = '\0'; // no explicit number. - usage_str = "fragment.facing"; - } // if - else - { - failf(ctx, "vFace unsupported in %s profile", - ctx->profile->name); - } // else - } // if - else if (mt == MISCTYPE_TYPE_POSITION) - { - index_str[0] = '\0'; // no explicit number. - usage_str = "fragment.position"; // !!! FIXME: is this the same coord space as D3D? - } // else if - else - { - fail(ctx, "BUG: unhandled misc register"); - } // else - } // else if - - else - { - fail(ctx, "unknown pixel shader attribute register"); - } // else - - if (usage_str != NULL) - { - push_output(ctx, &ctx->globals); - output_line(ctx, "%s %s = %s%s%s%s;", paramtype_str, varname, - usage_str, arrayleft, index_str, arrayright); - pop_output(ctx); - } // if - } // else if - - else - { - fail(ctx, "Unknown shader type"); // state machine should catch this. - } // else -} // emit_ARB1_attribute - -static void emit_ARB1_RESERVED(Context *ctx) { /* no-op. */ } - -static void emit_ARB1_NOP(Context *ctx) -{ - // There is no NOP in arb1. Just don't output anything here. -} // emit_ARB1_NOP - -EMIT_ARB1_OPCODE_DS_FUNC(MOV) -EMIT_ARB1_OPCODE_DSS_FUNC(ADD) -EMIT_ARB1_OPCODE_DSS_FUNC(SUB) -EMIT_ARB1_OPCODE_DSSS_FUNC(MAD) -EMIT_ARB1_OPCODE_DSS_FUNC(MUL) -EMIT_ARB1_OPCODE_DS_FUNC(RCP) - -static void emit_ARB1_RSQ(Context *ctx) -{ - // nv4 doesn't force abs() on this, so negative values will generate NaN. - // The spec says you should force the abs() yourself. - if (!support_nv4(ctx)) - { - emit_ARB1_opcode_ds(ctx, "RSQ"); // pre-nv4 implies ABS. - return; - } // if - - // we can optimize this to use nv2's |abs| construct in some cases. - if ( (ctx->source_args[0].src_mod == SRCMOD_NONE) || - (ctx->source_args[0].src_mod == SRCMOD_NEGATE) || - (ctx->source_args[0].src_mod == SRCMOD_ABSNEGATE) ) - ctx->source_args[0].src_mod = SRCMOD_ABS; - - char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); - char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); - - if (ctx->source_args[0].src_mod == SRCMOD_ABS) - output_line(ctx, "RSQ%s, %s;", dst, src0); - else - { - char buf[64]; allocate_ARB1_scratch_reg_name(ctx, buf, sizeof (buf)); - output_line(ctx, "ABS %s, %s;", buf, src0); - output_line(ctx, "RSQ%s, %s.x;", dst, buf); - } // else - - emit_ARB1_dest_modifiers(ctx); -} // emit_ARB1_RSQ - -EMIT_ARB1_OPCODE_DSS_FUNC(DP3) -EMIT_ARB1_OPCODE_DSS_FUNC(DP4) -EMIT_ARB1_OPCODE_DSS_FUNC(MIN) -EMIT_ARB1_OPCODE_DSS_FUNC(MAX) -EMIT_ARB1_OPCODE_DSS_FUNC(SLT) -EMIT_ARB1_OPCODE_DSS_FUNC(SGE) - -static void emit_ARB1_EXP(Context *ctx) { emit_ARB1_opcode_ds(ctx, "EX2"); } - -static void arb1_log(Context *ctx, const char *opcode) -{ - // !!! FIXME: SRCMOD_NEGATE can be made into SRCMOD_ABS here, too - // we can optimize this to use nv2's |abs| construct in some cases. - if ( (ctx->source_args[0].src_mod == SRCMOD_NONE) || - (ctx->source_args[0].src_mod == SRCMOD_ABSNEGATE) ) - ctx->source_args[0].src_mod = SRCMOD_ABS; - - char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); - char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); - - if (ctx->source_args[0].src_mod == SRCMOD_ABS) - output_line(ctx, "%s%s, %s;", opcode, dst, src0); - else - { - char buf[64]; allocate_ARB1_scratch_reg_name(ctx, buf, sizeof (buf)); - output_line(ctx, "ABS %s, %s;", buf, src0); - output_line(ctx, "%s%s, %s.x;", opcode, dst, buf); - } // else - - emit_ARB1_dest_modifiers(ctx); -} // arb1_log - - -static void emit_ARB1_LOG(Context *ctx) -{ - arb1_log(ctx, "LG2"); -} // emit_ARB1_LOG - - -EMIT_ARB1_OPCODE_DS_FUNC(LIT) -EMIT_ARB1_OPCODE_DSS_FUNC(DST) - -static void emit_ARB1_LRP(Context *ctx) -{ - if (shader_is_pixel(ctx)) // fragment shaders have a matching LRP opcode. - emit_ARB1_opcode_dsss(ctx, "LRP"); - else - { - char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); - char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_ARB1_srcarg_string(ctx, 1, src1, sizeof (src1)); - char src2[64]; make_ARB1_srcarg_string(ctx, 2, src2, sizeof (src2)); - char buf[64]; allocate_ARB1_scratch_reg_name(ctx, buf, sizeof (buf)); - - // LRP is: dest = src2 + src0 * (src1 - src2) - output_line(ctx, "SUB %s, %s, %s;", buf, src1, src2); - output_line(ctx, "MAD%s, %s, %s, %s;", dst, buf, src0, src2); - emit_ARB1_dest_modifiers(ctx); - } // else -} // emit_ARB1_LRP - -EMIT_ARB1_OPCODE_DS_FUNC(FRC) - -static void arb1_MxXy(Context *ctx, const int x, const int y) -{ - DestArgInfo *dstarg = &ctx->dest_arg; - const int origmask = dstarg->writemask; - char src0[64]; - int i; - - make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); - - for (i = 0; i < y; i++) - { - char dst[64]; - char row[64]; - make_ARB1_srcarg_string(ctx, i + 1, row, sizeof (row)); - set_dstarg_writemask(dstarg, 1 << i); - make_ARB1_destarg_string(ctx, dst, sizeof (dst)); - output_line(ctx, "DP%d%s, %s, %s;", x, dst, src0, row); - } // for - - set_dstarg_writemask(dstarg, origmask); - emit_ARB1_dest_modifiers(ctx); -} // arb1_MxXy - -static void emit_ARB1_M4X4(Context *ctx) { arb1_MxXy(ctx, 4, 4); } -static void emit_ARB1_M4X3(Context *ctx) { arb1_MxXy(ctx, 4, 3); } -static void emit_ARB1_M3X4(Context *ctx) { arb1_MxXy(ctx, 3, 4); } -static void emit_ARB1_M3X3(Context *ctx) { arb1_MxXy(ctx, 3, 3); } -static void emit_ARB1_M3X2(Context *ctx) { arb1_MxXy(ctx, 3, 2); } - -static void emit_ARB1_CALL(Context *ctx) -{ - if (!support_nv2(ctx)) // no branching in stock ARB1. - { - failf(ctx, "branching unsupported in %s profile", ctx->profile->name); - return; - } // if - - char labelstr[64]; - get_ARB1_srcarg_varname(ctx, 0, labelstr, sizeof (labelstr)); - output_line(ctx, "CAL %s;", labelstr); -} // emit_ARB1_CALL - -static void emit_ARB1_CALLNZ(Context *ctx) -{ - // !!! FIXME: if src1 is a constbool that's true, we can remove the - // !!! FIXME: if. If it's false, we can make this a no-op. - - if (!support_nv2(ctx)) // no branching in stock ARB1. - failf(ctx, "branching unsupported in %s profile", ctx->profile->name); - else - { - // !!! FIXME: double-check this. - char labelstr[64]; - char scratch[64]; - char src1[64]; - get_ARB1_srcarg_varname(ctx, 0, labelstr, sizeof (labelstr)); - get_ARB1_srcarg_varname(ctx, 1, src1, sizeof (src1)); - allocate_ARB1_scratch_reg_name(ctx, scratch, sizeof (scratch)); - output_line(ctx, "MOVC %s, %s;", scratch, src1); - output_line(ctx, "CAL %s (NE.x);", labelstr); - } // else -} // emit_ARB1_CALLNZ - -// !!! FIXME: needs BRA in nv2, LOOP in nv2 fragment progs, and REP in nv4. -EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(LOOP) - -static void emit_ARB1_RET(Context *ctx) -{ - // don't fail() if no nv2...maybe we're just ending the mainline? - // if we're ending a LABEL that had no CALL, this would all be written - // to ctx->ignore anyhow, so this should be "safe" ... arb1 profile will - // just end up throwing all this code out. - if (support_nv2(ctx)) // no branching in stock ARB1. - output_line(ctx, "RET;"); - set_output(ctx, &ctx->mainline); // in case we were ignoring this function. -} // emit_ARB1_RET - - -EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(ENDLOOP) - -static void emit_ARB1_LABEL(Context *ctx) -{ - if (!support_nv2(ctx)) // no branching in stock ARB1. - return; // don't fail()...maybe we never use it, but do fail in CALL. - - const int label = ctx->source_args[0].regnum; - RegisterList *reg = reglist_find(&ctx->used_registers, REG_TYPE_LABEL, label); - - // MSDN specs say CALL* has to come before the LABEL, so we know if we - // can ditch the entire function here as unused. - if (reg == NULL) - set_output(ctx, &ctx->ignore); // Func not used. Parse, but don't output. - - // !!! FIXME: it would be nice if we could determine if a function is - // !!! FIXME: only called once and, if so, forcibly inline it. - - //const char *uses_loopreg = ((reg) && (reg->misc == 1)) ? "int aL" : ""; - char labelstr[64]; - get_ARB1_srcarg_varname(ctx, 0, labelstr, sizeof (labelstr)); - output_line(ctx, "%s:", labelstr); -} // emit_ARB1_LABEL - - -static void emit_ARB1_POW(Context *ctx) -{ - // we can optimize this to use nv2's |abs| construct in some cases. - if ( (ctx->source_args[0].src_mod == SRCMOD_NONE) || - (ctx->source_args[0].src_mod == SRCMOD_ABSNEGATE) ) - ctx->source_args[0].src_mod = SRCMOD_ABS; - - char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); - char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_ARB1_srcarg_string(ctx, 1, src1, sizeof (src1)); - - if (ctx->source_args[0].src_mod == SRCMOD_ABS) - output_line(ctx, "POW%s, %s, %s;", dst, src0, src1); - else - { - char buf[64]; allocate_ARB1_scratch_reg_name(ctx, buf, sizeof (buf)); - output_line(ctx, "ABS %s, %s;", buf, src0); - output_line(ctx, "POW%s, %s.x, %s;", dst, buf, src1); - } // else - - emit_ARB1_dest_modifiers(ctx); -} // emit_ARB1_POW - -static void emit_ARB1_CRS(Context *ctx) { emit_ARB1_opcode_dss(ctx, "XPD"); } - -static void emit_ARB1_SGN(Context *ctx) -{ - if (support_nv2(ctx)) - emit_ARB1_opcode_ds(ctx, "SSG"); - else - { - char dst[64]; - char src0[64]; - char scratch1[64]; - char scratch2[64]; - make_ARB1_destarg_string(ctx, dst, sizeof (dst)); - make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); - allocate_ARB1_scratch_reg_name(ctx, scratch1, sizeof (scratch1)); - allocate_ARB1_scratch_reg_name(ctx, scratch2, sizeof (scratch2)); - output_line(ctx, "SLT %s, %s, 0.0;", scratch1, src0); - output_line(ctx, "SLT %s, -%s, 0.0;", scratch2, src0); - output_line(ctx, "ADD%s -%s, %s;", dst, scratch1, scratch2); - emit_ARB1_dest_modifiers(ctx); - } // else -} // emit_ARB1_SGN - -EMIT_ARB1_OPCODE_DS_FUNC(ABS) - -static void emit_ARB1_NRM(Context *ctx) -{ - // nv2 fragment programs (and anything nv4) have a real NRM. - if ( (support_nv4(ctx)) || ((support_nv2(ctx)) && (shader_is_pixel(ctx))) ) - emit_ARB1_opcode_ds(ctx, "NRM"); - else - { - char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); - char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); - char buf[64]; allocate_ARB1_scratch_reg_name(ctx, buf, sizeof (buf)); - output_line(ctx, "DP3 %s.w, %s, %s;", buf, src0, src0); - output_line(ctx, "RSQ %s.w, %s.w;", buf, buf); - output_line(ctx, "MUL%s, %s.w, %s;", dst, buf, src0); - emit_ARB1_dest_modifiers(ctx); - } // else -} // emit_ARB1_NRM - - -static void emit_ARB1_SINCOS(Context *ctx) -{ - // we don't care about the temp registers that <= sm2 demands; ignore them. - const int mask = ctx->dest_arg.writemask; - - // arb1 fragment programs and everything nv4 have sin/cos/sincos opcodes. - if ((shader_is_pixel(ctx)) || (support_nv4(ctx))) - { - char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); - char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); - if (writemask_x(mask)) - output_line(ctx, "COS%s, %s;", dst, src0); - else if (writemask_y(mask)) - output_line(ctx, "SIN%s, %s;", dst, src0); - else if (writemask_xy(mask)) - output_line(ctx, "SCS%s, %s;", dst, src0); - } // if - - // nv2+ profiles have sin and cos opcodes. - else if (support_nv2(ctx)) - { - char dst[64]; get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); - char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); - if (writemask_x(mask)) - output_line(ctx, "COS %s.x, %s;", dst, src0); - else if (writemask_y(mask)) - output_line(ctx, "SIN %s.y, %s;", dst, src0); - else if (writemask_xy(mask)) - { - output_line(ctx, "SIN %s.x, %s;", dst, src0); - output_line(ctx, "COS %s.y, %s;", dst, src0); - } // else if - } // if - - else // big nasty. - { - char dst[64]; get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); - char src0[64]; get_ARB1_srcarg_varname(ctx, 0, src0, sizeof (src0)); - const int need_sin = (writemask_x(mask) || writemask_xy(mask)); - const int need_cos = (writemask_y(mask) || writemask_xy(mask)); - char scratch[64]; - - if (need_sin || need_cos) - allocate_ARB1_scratch_reg_name(ctx, scratch, sizeof (scratch)); - - // These sin() and cos() approximations originally found here: - // http://www.devmaster.net/forums/showthread.php?t=5784 - // - // const float B = 4.0f / M_PI; - // const float C = -4.0f / (M_PI * M_PI); - // float y = B * x + C * x * fabs(x); - // - // // optional better precision... - // const float P = 0.225f; - // y = P * (y * fabs(y) - y) + y; - // - // - // That first thing can be reduced to: - // const float y = ((1.2732395447351626861510701069801f * x) + - // ((-0.40528473456935108577551785283891f * x) * fabs(x))); - - if (need_sin) - { - // !!! FIXME: use SRCMOD_ABS here? - output_line(ctx, "ABS %s.x, %s.x;", dst, src0); - output_line(ctx, "MUL %s.x, %s.x, -0.40528473456935108577551785283891;", dst, dst); - output_line(ctx, "MUL %s.x, %s.x, 1.2732395447351626861510701069801;", scratch, src0); - output_line(ctx, "MAD %s.x, %s.x, %s.x, %s.x;", dst, dst, src0, scratch); - } // if - - // cosine is sin(x + M_PI/2), but you have to wrap x to pi: - // if (x+(M_PI/2) > M_PI) - // x -= 2 * M_PI; - // - // which is... - // if (x+(1.57079637050628662109375) > 3.1415927410125732421875) - // x += -6.283185482025146484375; - - if (need_cos) - { - output_line(ctx, "ADD %s.x, %s.x, 1.57079637050628662109375;", scratch, src0); - output_line(ctx, "SGE %s.y, %s.x, 3.1415927410125732421875;", scratch, scratch); - output_line(ctx, "MAD %s.x, %s.y, -6.283185482025146484375, %s.x;", scratch, scratch, scratch); - output_line(ctx, "ABS %s.x, %s.x;", dst, src0); - output_line(ctx, "MUL %s.x, %s.x, -0.40528473456935108577551785283891;", dst, dst); - output_line(ctx, "MUL %s.x, %s.x, 1.2732395447351626861510701069801;", scratch, src0); - output_line(ctx, "MAD %s.y, %s.x, %s.x, %s.x;", dst, dst, src0, scratch); - } // if - } // else - - // !!! FIXME: might not have done anything. Don't emit if we didn't. - if (!isfail(ctx)) - emit_ARB1_dest_modifiers(ctx); -} // emit_ARB1_SINCOS - - -static void emit_ARB1_REP(Context *ctx) -{ - char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); - - // nv2 fragment programs (and everything nv4) have a real REP. - if ( (support_nv4(ctx)) || ((support_nv2(ctx)) && (shader_is_pixel(ctx))) ) - output_line(ctx, "REP %s;", src0); - - else if (support_nv2(ctx)) - { - // no REP, but we can use branches. - char failbranch[32]; - char topbranch[32]; - const int toplabel = allocate_branch_label(ctx); - const int faillabel = allocate_branch_label(ctx); - get_ARB1_branch_label_name(ctx,faillabel,failbranch,sizeof(failbranch)); - get_ARB1_branch_label_name(ctx,toplabel,topbranch,sizeof(topbranch)); - - assert(((size_t) ctx->branch_labels_stack_index) < - STATICARRAYLEN(ctx->branch_labels_stack)-1); - - ctx->branch_labels_stack[ctx->branch_labels_stack_index++] = toplabel; - ctx->branch_labels_stack[ctx->branch_labels_stack_index++] = faillabel; - - char scratch[32]; - snprintf(scratch, sizeof (scratch), "rep%d", ctx->reps); - output_line(ctx, "MOVC %s.x, %s;", scratch, src0); - output_line(ctx, "BRA %s (LE.x);", failbranch); - output_line(ctx, "%s:", topbranch); - } // else if - - else // stock ARB1 has no branching. - { - fail(ctx, "branching unsupported in this profile"); - } // else -} // emit_ARB1_REP - - -static void emit_ARB1_ENDREP(Context *ctx) -{ - // nv2 fragment programs (and everything nv4) have a real ENDREP. - if ( (support_nv4(ctx)) || ((support_nv2(ctx)) && (shader_is_pixel(ctx))) ) - output_line(ctx, "ENDREP;"); - - else if (support_nv2(ctx)) - { - // no ENDREP, but we can use branches. - assert(ctx->branch_labels_stack_index >= 2); - - char failbranch[32]; - char topbranch[32]; - const int faillabel = ctx->branch_labels_stack[--ctx->branch_labels_stack_index]; - const int toplabel = ctx->branch_labels_stack[--ctx->branch_labels_stack_index]; - get_ARB1_branch_label_name(ctx,faillabel,failbranch,sizeof(failbranch)); - get_ARB1_branch_label_name(ctx,toplabel,topbranch,sizeof(topbranch)); - - char scratch[32]; - snprintf(scratch, sizeof (scratch), "rep%d", ctx->reps); - output_line(ctx, "SUBC %s.x, %s.x, 1.0;", scratch, scratch); - output_line(ctx, "BRA %s (GT.x);", topbranch); - output_line(ctx, "%s:", failbranch); - } // else if - - else // stock ARB1 has no branching. - { - fail(ctx, "branching unsupported in this profile"); - } // else -} // emit_ARB1_ENDREP - - -static void nv2_if(Context *ctx) -{ - // The condition code register MUST be set up before this! - // nv2 fragment programs (and everything nv4) have a real IF. - if ( (support_nv4(ctx)) || (shader_is_pixel(ctx)) ) - output_line(ctx, "IF EQ.x;"); - else - { - // there's no IF construct, but we can use a branch to a label. - char failbranch[32]; - const int label = allocate_branch_label(ctx); - get_ARB1_branch_label_name(ctx, label, failbranch, sizeof (failbranch)); - - assert(((size_t) ctx->branch_labels_stack_index) - < STATICARRAYLEN(ctx->branch_labels_stack)); - - ctx->branch_labels_stack[ctx->branch_labels_stack_index++] = label; - - // !!! FIXME: should this be NE? (EQ would jump to the ELSE for the IF condition, right?). - output_line(ctx, "BRA %s (EQ.x);", failbranch); - } // else -} // nv2_if - - -static void emit_ARB1_IF(Context *ctx) -{ - if (support_nv2(ctx)) - { - char buf[64]; allocate_ARB1_scratch_reg_name(ctx, buf, sizeof (buf)); - char src0[64]; get_ARB1_srcarg_varname(ctx, 0, src0, sizeof (src0)); - output_line(ctx, "MOVC %s.x, %s;", buf, src0); - nv2_if(ctx); - } // if - - else // stock ARB1 has no branching. - { - failf(ctx, "branching unsupported in %s profile", ctx->profile->name); - } // else -} // emit_ARB1_IF - - -static void emit_ARB1_ELSE(Context *ctx) -{ - // nv2 fragment programs (and everything nv4) have a real ELSE. - if ( (support_nv4(ctx)) || ((support_nv2(ctx)) && (shader_is_pixel(ctx))) ) - output_line(ctx, "ELSE;"); - - else if (support_nv2(ctx)) - { - // there's no ELSE construct, but we can use a branch to a label. - assert(ctx->branch_labels_stack_index > 0); - - // At the end of the IF block, unconditionally jump to the ENDIF. - const int endlabel = allocate_branch_label(ctx); - char endbranch[32]; - get_ARB1_branch_label_name(ctx,endlabel,endbranch,sizeof (endbranch)); - output_line(ctx, "BRA %s;", endbranch); - - // Now mark the ELSE section with a lable. - const int elselabel = ctx->branch_labels_stack[ctx->branch_labels_stack_index-1]; - char elsebranch[32]; - get_ARB1_branch_label_name(ctx,elselabel,elsebranch,sizeof(elsebranch)); - output_line(ctx, "%s:", elsebranch); - - // Replace the ELSE label with the ENDIF on the label stack. - ctx->branch_labels_stack[ctx->branch_labels_stack_index-1] = endlabel; - } // else if - - else // stock ARB1 has no branching. - { - failf(ctx, "branching unsupported in %s profile", ctx->profile->name); - } // else -} // emit_ARB1_ELSE - - -static void emit_ARB1_ENDIF(Context *ctx) -{ - // nv2 fragment programs (and everything nv4) have a real ENDIF. - if ( (support_nv4(ctx)) || ((support_nv2(ctx)) && (shader_is_pixel(ctx))) ) - output_line(ctx, "ENDIF;"); - - else if (support_nv2(ctx)) - { - // there's no ENDIF construct, but we can use a branch to a label. - assert(ctx->branch_labels_stack_index > 0); - const int endlabel = ctx->branch_labels_stack[--ctx->branch_labels_stack_index]; - char endbranch[32]; - get_ARB1_branch_label_name(ctx,endlabel,endbranch,sizeof (endbranch)); - output_line(ctx, "%s:", endbranch); - } // if - - else // stock ARB1 has no branching. - { - failf(ctx, "branching unsupported in %s profile", ctx->profile->name); - } // else -} // emit_ARB1_ENDIF - - -static void emit_ARB1_BREAK(Context *ctx) -{ - // nv2 fragment programs (and everything nv4) have a real BREAK. - if ( (support_nv4(ctx)) || ((support_nv2(ctx)) && (shader_is_pixel(ctx))) ) - output_line(ctx, "BRK;"); - - else if (support_nv2(ctx)) - { - // no BREAK, but we can use branches. - assert(ctx->branch_labels_stack_index >= 2); - const int faillabel = ctx->branch_labels_stack[ctx->branch_labels_stack_index]; - char failbranch[32]; - get_ARB1_branch_label_name(ctx,faillabel,failbranch,sizeof(failbranch)); - output_line(ctx, "BRA %s;", failbranch); - } // else if - - else // stock ARB1 has no branching. - { - failf(ctx, "branching unsupported in %s profile", ctx->profile->name); - } // else -} // emit_ARB1_BREAK - - -static void emit_ARB1_MOVA(Context *ctx) -{ - // nv2 and nv3 can use the ARR opcode. - // But nv4 removed ARR (and ADDRESS registers!). Just ROUND to an INT. - if (support_nv4(ctx)) - emit_ARB1_opcode_ds(ctx, "ROUND.S"); // !!! FIXME: don't use a modifier here. - else if ((support_nv2(ctx)) || (support_nv3(ctx))) - emit_ARB1_opcode_ds(ctx, "ARR"); - else - { - char src0[64]; - char scratch[64]; - char addr[32]; - - make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); - allocate_ARB1_scratch_reg_name(ctx, scratch, sizeof (scratch)); - snprintf(addr, sizeof (addr), "addr%d", ctx->dest_arg.regnum); - - // !!! FIXME: we can optimize this if src_mod is ABS or ABSNEGATE. - - // ARL uses floor(), but D3D expects round-to-nearest. - // There is probably a more efficient way to do this. - if (shader_is_pixel(ctx)) // CMP only exists in fragment programs. :/ - output_line(ctx, "CMP %s, %s, -1.0, 1.0;", scratch, src0); - else - { - output_line(ctx, "SLT %s, %s, 0.0;", scratch, src0); - output_line(ctx, "MAD %s, %s, -2.0, 1.0;", scratch, scratch); - } // else - - output_line(ctx, "ABS %s, %s;", addr, src0); - output_line(ctx, "ADD %s, %s, 0.5;", addr, addr); - output_line(ctx, "FLR %s, %s;", addr, addr); - output_line(ctx, "MUL %s, %s, %s;", addr, addr, scratch); - - // we don't handle these right now, since emit_ARB1_dest_modifiers(ctx) - // wants to look at dest_arg, not our temp register. - assert(ctx->dest_arg.result_mod == 0); - assert(ctx->dest_arg.result_shift == 0); - - // we assign to the actual address register as needed. - ctx->last_address_reg_component = -1; - } // else -} // emit_ARB1_MOVA - - -static void emit_ARB1_TEXKILL(Context *ctx) -{ - // d3d kills on xyz, arb1 kills on xyzw. Fix the swizzle. - // We just map the x component to w. If it's negative, the fragment - // would discard anyhow, otherwise, it'll pass through okay. This saves - // us a temp register. - char dst[64]; - get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); - output_line(ctx, "KIL %s.xyzx;", dst); -} // emit_ARB1_TEXKILL - -static void arb1_texbem(Context *ctx, const int luminance) -{ - // !!! FIXME: this code counts on the register not having swizzles, etc. - const int stage = ctx->dest_arg.regnum; - char dst[64]; get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); - char src[64]; get_ARB1_srcarg_varname(ctx, 0, src, sizeof (src)); - char tmp[64]; allocate_ARB1_scratch_reg_name(ctx, tmp, sizeof (tmp)); - char sampler[64]; - get_ARB1_varname_in_buf(ctx, REG_TYPE_SAMPLER, stage, - sampler, sizeof (sampler)); - - output_line(ctx, "MUL %s, %s_texbem.xzyw, %s.xyxy;", tmp, sampler, src); - output_line(ctx, "ADD %s.xy, %s.xzxx, %s.ywxx;", tmp, tmp, tmp); - output_line(ctx, "ADD %s.xy, %s, %s;", tmp, tmp, dst); - output_line(ctx, "TEX %s, %s, texture[%d], 2D;", dst, tmp, stage); - - if (luminance) // TEXBEML, not just TEXBEM? - { - output_line(ctx, "MAD %s, %s.zzzz, %s_texbeml.xxxx, %s_texbeml.yyyy;", - tmp, src, sampler, sampler); - output_line(ctx, "MUL %s, %s, %s;", dst, dst, tmp); - } // if - - emit_ARB1_dest_modifiers(ctx); -} // arb1_texbem - -static void emit_ARB1_TEXBEM(Context *ctx) -{ - arb1_texbem(ctx, 0); -} // emit_ARB1_TEXBEM - -static void emit_ARB1_TEXBEML(Context *ctx) -{ - arb1_texbem(ctx, 1); -} // emit_ARB1_TEXBEML - -EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2AR) -EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2GB) - - -static void emit_ARB1_TEXM3X2PAD(Context *ctx) -{ - // no-op ... work happens in emit_ARB1_TEXM3X2TEX(). -} // emit_ARB1_TEXM3X2PAD - -static void emit_ARB1_TEXM3X2TEX(Context *ctx) -{ - if (ctx->texm3x2pad_src0 == -1) - return; - - char dst[64]; - char src0[64]; - char src1[64]; - char src2[64]; - - // !!! FIXME: this code counts on the register not having swizzles, etc. - const int stage = ctx->dest_arg.regnum; - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x2pad_src0, - src0, sizeof (src0)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x2pad_dst0, - src1, sizeof (src1)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, - src2, sizeof (src2)); - get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); - - output_line(ctx, "DP3 %s.y, %s, %s;", dst, src2, dst); - output_line(ctx, "DP3 %s.x, %s, %s;", dst, src0, src1); - output_line(ctx, "TEX %s, %s, texture[%d], 2D;", dst, dst, stage); - emit_ARB1_dest_modifiers(ctx); -} // emit_ARB1_TEXM3X2TEX - - -static void emit_ARB1_TEXM3X3PAD(Context *ctx) -{ - // no-op ... work happens in emit_ARB1_TEXM3X3*(). -} // emit_ARB1_TEXM3X3PAD - - -static void emit_ARB1_TEXM3X3TEX(Context *ctx) -{ - if (ctx->texm3x3pad_src1 == -1) - return; - - char dst[64]; - char src0[64]; - char src1[64]; - char src2[64]; - char src3[64]; - char src4[64]; - - // !!! FIXME: this code counts on the register not having swizzles, etc. - const int stage = ctx->dest_arg.regnum; - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, - src0, sizeof (src0)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, - src1, sizeof (src1)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, - src2, sizeof (src2)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, - src3, sizeof (src3)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, - src4, sizeof (src4)); - get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); - - RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, stage); - const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); - const char *ttypestr = (ttype == TEXTURE_TYPE_CUBE) ? "CUBE" : "3D"; - - output_line(ctx, "DP3 %s.z, %s, %s;", dst, dst, src4); - output_line(ctx, "DP3 %s.x, %s, %s;", dst, src0, src1); - output_line(ctx, "DP3 %s.y, %s, %s;", dst, src2, src3); - output_line(ctx, "TEX %s, %s, texture[%d], %s;", dst, dst, stage, ttypestr); - emit_ARB1_dest_modifiers(ctx); -} // emit_ARB1_TEXM3X3TEX - -static void emit_ARB1_TEXM3X3SPEC(Context *ctx) -{ - if (ctx->texm3x3pad_src1 == -1) - return; - - char dst[64]; - char src0[64]; - char src1[64]; - char src2[64]; - char src3[64]; - char src4[64]; - char src5[64]; - char tmp[64]; - char tmp2[64]; - - // !!! FIXME: this code counts on the register not having swizzles, etc. - const int stage = ctx->dest_arg.regnum; - allocate_ARB1_scratch_reg_name(ctx, tmp, sizeof (tmp)); - allocate_ARB1_scratch_reg_name(ctx, tmp2, sizeof (tmp2)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, - src0, sizeof (src0)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, - src1, sizeof (src1)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, - src2, sizeof (src2)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, - src3, sizeof (src3)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, - src4, sizeof (src4)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[1].regnum, - src5, sizeof (src5)); - get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); - - RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, stage); - const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); - const char *ttypestr = (ttype == TEXTURE_TYPE_CUBE) ? "CUBE" : "3D"; - - output_line(ctx, "DP3 %s.z, %s, %s;", dst, dst, src4); - output_line(ctx, "DP3 %s.x, %s, %s;", dst, src0, src1); - output_line(ctx, "DP3 %s.y, %s, %s;", dst, src2, src3); - output_line(ctx, "MUL %s, %s, %s;", tmp, dst, dst); // normal * normal - output_line(ctx, "MUL %s, %s, %s;", tmp2, dst, src5); // normal * eyeray - - // !!! FIXME: This is goofy. There's got to be a way to do vector-wide - // !!! FIXME: divides or reciprocals...right? - output_line(ctx, "RCP %s.x, %s.x;", tmp2, tmp2); - output_line(ctx, "RCP %s.y, %s.y;", tmp2, tmp2); - output_line(ctx, "RCP %s.z, %s.z;", tmp2, tmp2); - output_line(ctx, "RCP %s.w, %s.w;", tmp2, tmp2); - output_line(ctx, "MUL %s, %s, %s;", tmp, tmp, tmp2); - - output_line(ctx, "MUL %s, %s, { 2.0, 2.0, 2.0, 2.0 };", tmp, tmp); - output_line(ctx, "MAD %s, %s, %s, -%s;", tmp, tmp, dst, src5); - output_line(ctx, "TEX %s, %s, texture[%d], %s;", dst, tmp, stage, ttypestr); - emit_ARB1_dest_modifiers(ctx); -} // emit_ARB1_TEXM3X3SPEC - -static void emit_ARB1_TEXM3X3VSPEC(Context *ctx) -{ - if (ctx->texm3x3pad_src1 == -1) - return; - - char dst[64]; - char src0[64]; - char src1[64]; - char src2[64]; - char src3[64]; - char src4[64]; - char tmp[64]; - char tmp2[64]; - char tmp3[64]; - - // !!! FIXME: this code counts on the register not having swizzles, etc. - const int stage = ctx->dest_arg.regnum; - allocate_ARB1_scratch_reg_name(ctx, tmp, sizeof (tmp)); - allocate_ARB1_scratch_reg_name(ctx, tmp2, sizeof (tmp2)); - allocate_ARB1_scratch_reg_name(ctx, tmp3, sizeof (tmp3)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, - src0, sizeof (src0)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, - src1, sizeof (src1)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, - src2, sizeof (src2)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, - src3, sizeof (src3)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, - src4, sizeof (src4)); - get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); - - RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, stage); - const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); - const char *ttypestr = (ttype == TEXTURE_TYPE_CUBE) ? "CUBE" : "3D"; - - output_line(ctx, "MOV %s.x, %s.w;", tmp3, src0); - output_line(ctx, "MOV %s.y, %s.w;", tmp3, src2); - output_line(ctx, "MOV %s.z, %s.w;", tmp3, dst); - output_line(ctx, "DP3 %s.z, %s, %s;", dst, dst, src4); - output_line(ctx, "DP3 %s.x, %s, %s;", dst, src0, src1); - output_line(ctx, "DP3 %s.y, %s, %s;", dst, src2, src3); - output_line(ctx, "MUL %s, %s, %s;", tmp, dst, dst); // normal * normal - output_line(ctx, "MUL %s, %s, %s;", tmp2, dst, tmp3); // normal * eyeray - - // !!! FIXME: This is goofy. There's got to be a way to do vector-wide - // !!! FIXME: divides or reciprocals...right? - output_line(ctx, "RCP %s.x, %s.x;", tmp2, tmp2); - output_line(ctx, "RCP %s.y, %s.y;", tmp2, tmp2); - output_line(ctx, "RCP %s.z, %s.z;", tmp2, tmp2); - output_line(ctx, "RCP %s.w, %s.w;", tmp2, tmp2); - output_line(ctx, "MUL %s, %s, %s;", tmp, tmp, tmp2); - - output_line(ctx, "MUL %s, %s, { 2.0, 2.0, 2.0, 2.0 };", tmp, tmp); - output_line(ctx, "MAD %s, %s, %s, -%s;", tmp, tmp, dst, tmp3); - output_line(ctx, "TEX %s, %s, texture[%d], %s;", dst, tmp, stage, ttypestr); - emit_ARB1_dest_modifiers(ctx); -} // emit_ARB1_TEXM3X3VSPEC - -static void emit_ARB1_EXPP(Context *ctx) { emit_ARB1_opcode_ds(ctx, "EX2"); } -static void emit_ARB1_LOGP(Context *ctx) { arb1_log(ctx, "LG2"); } - -static void emit_ARB1_CND(Context *ctx) -{ - char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); - char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_ARB1_srcarg_string(ctx, 1, src1, sizeof (src1)); - char src2[64]; make_ARB1_srcarg_string(ctx, 2, src2, sizeof (src2)); - char tmp[64]; allocate_ARB1_scratch_reg_name(ctx, tmp, sizeof (tmp)); - - // CND compares against 0.5, but we need to compare against 0.0... - // ...subtract to make up the difference. - output_line(ctx, "SUB %s, %s, { 0.5, 0.5, 0.5, 0.5 };", tmp, src0); - // D3D tests (src0 >= 0.0), but ARB1 tests (src0 < 0.0) ... so just - // switch src1 and src2 to get the same results. - output_line(ctx, "CMP%s, %s, %s, %s;", dst, tmp, src2, src1); - emit_ARB1_dest_modifiers(ctx); -} // emit_ARB1_CND - -EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2RGB) -EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(TEXDP3TEX) -EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(TEXM3X2DEPTH) -EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(TEXDP3) - -static void emit_ARB1_TEXM3X3(Context *ctx) -{ - if (ctx->texm3x3pad_src1 == -1) - return; - - char dst[64]; - char src0[64]; - char src1[64]; - char src2[64]; - char src3[64]; - char src4[64]; - - // !!! FIXME: this code counts on the register not having swizzles, etc. - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, - src0, sizeof (src0)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, - src1, sizeof (src1)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, - src2, sizeof (src2)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, - src3, sizeof (src3)); - get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, - src4, sizeof (src4)); - get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); - - output_line(ctx, "DP3 %s.z, %s, %s;", dst, dst, src4); - output_line(ctx, "DP3 %s.x, %s, %s;", dst, src0, src1); - output_line(ctx, "DP3 %s.y, %s, %s;", dst, src2, src3); - output_line(ctx, "MOV %s.w, { 1.0, 1.0, 1.0, 1.0 };", dst); - emit_ARB1_dest_modifiers(ctx); -} // emit_ARB1_TEXM3X3 - -EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(TEXDEPTH) - -static void emit_ARB1_CMP(Context *ctx) -{ - char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); - char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_ARB1_srcarg_string(ctx, 1, src1, sizeof (src1)); - char src2[64]; make_ARB1_srcarg_string(ctx, 2, src2, sizeof (src2)); - // D3D tests (src0 >= 0.0), but ARB1 tests (src0 < 0.0) ... so just - // switch src1 and src2 to get the same results. - output_line(ctx, "CMP%s, %s, %s, %s;", dst, src0, src2, src1); - emit_ARB1_dest_modifiers(ctx); -} // emit_ARB1_CMP - -EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(BEM) - - -static void emit_ARB1_DP2ADD(Context *ctx) -{ - if (support_nv4(ctx)) // nv4 has a built-in equivalent to DP2ADD. - emit_ARB1_opcode_dsss(ctx, "DP2A"); - else - { - char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); - char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); - char src1[64]; make_ARB1_srcarg_string(ctx, 1, src1, sizeof (src1)); - char src2[64]; make_ARB1_srcarg_string(ctx, 2, src2, sizeof (src2)); - char scratch[64]; - - // DP2ADD is: - // dst = (src0.r * src1.r) + (src0.g * src1.g) + src2.replicate_swiz - allocate_ARB1_scratch_reg_name(ctx, scratch, sizeof (scratch)); - output_line(ctx, "MUL %s, %s, %s;", scratch, src0, src1); - output_line(ctx, "ADD %s, %s.x, %s.y;", scratch, scratch, scratch); - output_line(ctx, "ADD%s, %s.x, %s;", dst, scratch, src2); - emit_ARB1_dest_modifiers(ctx); - } // else -} // emit_ARB1_DP2ADD - - -static void emit_ARB1_DSX(Context *ctx) -{ - if (support_nv2(ctx)) // nv2 has a built-in equivalent to DSX. - emit_ARB1_opcode_ds(ctx, "DDX"); - else - failf(ctx, "DSX unsupported in %s profile", ctx->profile->name); -} // emit_ARB1_DSX - - -static void emit_ARB1_DSY(Context *ctx) -{ - if (support_nv2(ctx)) // nv2 has a built-in equivalent to DSY. - emit_ARB1_opcode_ds(ctx, "DDY"); - else - failf(ctx, "DSY unsupported in %s profile", ctx->profile->name); -} // emit_ARB1_DSY - -static void arb1_texld(Context *ctx, const char *opcode, const int texldd) -{ - // !!! FIXME: Hack: "TEXH" is invalid in nv4. Fix this more cleanly. - if ((ctx->dest_arg.result_mod & MOD_PP) && (support_nv4(ctx))) - ctx->dest_arg.result_mod &= ~MOD_PP; - - char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); - - const int sm1 = !shader_version_atleast(ctx, 1, 4); - const int regnum = sm1 ? ctx->dest_arg.regnum : ctx->source_args[1].regnum; - RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, regnum); - - const char *ttype = NULL; - char src0[64]; - if (sm1) - get_ARB1_destarg_varname(ctx, src0, sizeof (src0)); - else - get_ARB1_srcarg_varname(ctx, 0, src0, sizeof (src0)); - //char src1[64]; get_ARB1_srcarg_varname(ctx, 1, src1, sizeof (src1)); // !!! FIXME: SRC_MOD? - - char src2[64] = { 0 }; - char src3[64] = { 0 }; - - if (texldd) - { - make_ARB1_srcarg_string(ctx, 2, src2, sizeof (src2)); - make_ARB1_srcarg_string(ctx, 3, src3, sizeof (src3)); - } // if - - // !!! FIXME: this should be in state_TEXLD, not in the arb1/glsl emitters. - if (sreg == NULL) - { - fail(ctx, "TEXLD using undeclared sampler"); - return; - } // if - - // SM1 only specifies dst, so don't check swizzle there. - if ( !sm1 && (!no_swizzle(ctx->source_args[1].swizzle)) ) - { - // !!! FIXME: does this ever actually happen? - fail(ctx, "BUG: can't handle TEXLD with sampler swizzle at the moment"); - } // if - - switch ((const TextureType) sreg->index) - { - case TEXTURE_TYPE_2D: ttype = "2D"; break; // !!! FIXME: "RECT"? - case TEXTURE_TYPE_CUBE: ttype = "CUBE"; break; - case TEXTURE_TYPE_VOLUME: ttype = "3D"; break; - default: fail(ctx, "unknown texture type"); return; - } // switch - - if (texldd) - { - output_line(ctx, "%s%s, %s, %s, %s, texture[%d], %s;", opcode, dst, - src0, src2, src3, regnum, ttype); - } // if - else - { - output_line(ctx, "%s%s, %s, texture[%d], %s;", opcode, dst, src0, - regnum, ttype); - } // else -} // arb1_texld - - -static void emit_ARB1_TEXLDD(Context *ctx) -{ - // With GL_NV_fragment_program2, we can use the TXD opcode. - // In stock arb1, we can settle for a standard texld, which isn't - // perfect, but oh well. - if (support_nv2(ctx)) - arb1_texld(ctx, "TXD", 1); - else - arb1_texld(ctx, "TEX", 0); -} // emit_ARB1_TEXLDD - - -static void emit_ARB1_TEXLDL(Context *ctx) -{ - if ((shader_is_vertex(ctx)) && (!support_nv3(ctx))) - { - failf(ctx, "Vertex shader TEXLDL unsupported in %s profile", - ctx->profile->name); - return; - } // if - - else if ((shader_is_pixel(ctx)) && (!support_nv2(ctx))) - { - failf(ctx, "Pixel shader TEXLDL unsupported in %s profile", - ctx->profile->name); - return; - } // if - - // !!! FIXME: this doesn't map exactly to TEXLDL. Review this. - arb1_texld(ctx, "TXL", 0); -} // emit_ARB1_TEXLDL - - -EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(BREAKP) -EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(BREAKC) - -static void emit_ARB1_IFC(Context *ctx) -{ - if (support_nv2(ctx)) - { - static const char *comps[] = { - "", "SGTC", "SEQC", "SGEC", "SGTC", "SNEC", "SLEC" - }; - - if (ctx->instruction_controls >= STATICARRAYLEN(comps)) - { - fail(ctx, "unknown comparison control"); - return; - } // if - - char src0[64]; - char src1[64]; - char scratch[64]; - - const char *comp = comps[ctx->instruction_controls]; - get_ARB1_srcarg_varname(ctx, 0, src0, sizeof (src0)); - get_ARB1_srcarg_varname(ctx, 1, src1, sizeof (src1)); - allocate_ARB1_scratch_reg_name(ctx, scratch, sizeof (scratch)); - output_line(ctx, "%s %s.x, %s, %s;", comp, scratch, src0, src1); - nv2_if(ctx); - } // if - - else // stock ARB1 has no branching. - { - failf(ctx, "branching unsupported in %s profile", ctx->profile->name); - } // else -} // emit_ARB1_IFC - - -EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(SETP) - -static void emit_ARB1_DEF(Context *ctx) -{ - const float *val = (const float *) ctx->dwords; // !!! FIXME: could be int? - char dst[64]; get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); - char val0[32]; floatstr(ctx, val0, sizeof (val0), val[0], 1); - char val1[32]; floatstr(ctx, val1, sizeof (val1), val[1], 1); - char val2[32]; floatstr(ctx, val2, sizeof (val2), val[2], 1); - char val3[32]; floatstr(ctx, val3, sizeof (val3), val[3], 1); - - push_output(ctx, &ctx->globals); - output_line(ctx, "PARAM %s = { %s, %s, %s, %s };", - dst, val0, val1, val2, val3); - pop_output(ctx); -} // emit_ARB1_DEF - -static void emit_ARB1_DEFI(Context *ctx) -{ - char dst[64]; get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); - const int32 *x = (const int32 *) ctx->dwords; - push_output(ctx, &ctx->globals); - output_line(ctx, "PARAM %s = { %d, %d, %d, %d };", - dst, (int) x[0], (int) x[1], (int) x[2], (int) x[3]); - pop_output(ctx); -} // emit_ARB1_DEFI - -static void emit_ARB1_DEFB(Context *ctx) -{ - char dst[64]; get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); - push_output(ctx, &ctx->globals); - output_line(ctx, "PARAM %s = %d;", dst, ctx->dwords[0] ? 1 : 0); - pop_output(ctx); -} // emit_ARB1_DEFB - -static void emit_ARB1_DCL(Context *ctx) -{ - // no-op. We do this in our emit_attribute() and emit_uniform(). -} // emit_ARB1_DCL - -EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(TEXCRD) - -static void emit_ARB1_TEXLD(Context *ctx) -{ - if (!shader_version_atleast(ctx, 1, 4)) - { - arb1_texld(ctx, "TEX", 0); - return; - } // if - - else if (!shader_version_atleast(ctx, 2, 0)) - { - // ps_1_4 is different, too! - fail(ctx, "TEXLD == Shader Model 1.4 unimplemented."); // !!! FIXME - return; - } // if - - // !!! FIXME: do texldb and texldp map between OpenGL and D3D correctly? - if (ctx->instruction_controls == CONTROL_TEXLD) - arb1_texld(ctx, "TEX", 0); - else if (ctx->instruction_controls == CONTROL_TEXLDP) - arb1_texld(ctx, "TXP", 0); - else if (ctx->instruction_controls == CONTROL_TEXLDB) - arb1_texld(ctx, "TXB", 0); -} // emit_ARB1_TEXLD - -#endif // SUPPORT_PROFILE_ARB1 +#if !SUPPORT_PROFILE_ARB1 +#define PROFILE_EMITTER_ARB1(op) +#else +#undef AT_LEAST_ONE_PROFILE +#define AT_LEAST_ONE_PROFILE 1 +#define PROFILE_EMITTER_ARB1(op) emit_ARB1_##op, +PREDECLARE_PROFILE(ARB1) +#endif +#if !SUPPORT_PROFILE_SPIRV +#define PROFILE_EMITTER_SPIRV(op) +#else +#undef AT_LEAST_ONE_PROFILE +#define AT_LEAST_ONE_PROFILE 1 +#define PROFILE_EMITTER_SPIRV(op) emit_SPIRV_##op, +PREDECLARE_PROFILE(SPIRV) +#endif #if !AT_LEAST_ONE_PROFILE #error No profiles are supported. Fix your build. @@ -6192,12 +309,21 @@ static const Profile profiles[] = #if SUPPORT_PROFILE_BYTECODE DEFINE_PROFILE(BYTECODE) #endif +#if SUPPORT_PROFILE_HLSL + DEFINE_PROFILE(HLSL) +#endif #if SUPPORT_PROFILE_GLSL DEFINE_PROFILE(GLSL) #endif #if SUPPORT_PROFILE_ARB1 DEFINE_PROFILE(ARB1) #endif +#if SUPPORT_PROFILE_METAL + DEFINE_PROFILE(METAL) +#endif +#if SUPPORT_PROFILE_SPIRV + DEFINE_PROFILE(SPIRV) +#endif }; #undef DEFINE_PROFILE @@ -6205,19 +331,24 @@ static const Profile profiles[] = // This is for profiles that extend other profiles... static const struct { const char *from; const char *to; } profileMap[] = { + { MOJOSHADER_PROFILE_GLSPIRV, MOJOSHADER_PROFILE_SPIRV }, + { MOJOSHADER_PROFILE_GLSLES, MOJOSHADER_PROFILE_GLSL }, + { MOJOSHADER_PROFILE_GLSLES3, MOJOSHADER_PROFILE_GLSL }, { MOJOSHADER_PROFILE_GLSL120, MOJOSHADER_PROFILE_GLSL }, { MOJOSHADER_PROFILE_NV2, MOJOSHADER_PROFILE_ARB1 }, { MOJOSHADER_PROFILE_NV3, MOJOSHADER_PROFILE_ARB1 }, { MOJOSHADER_PROFILE_NV4, MOJOSHADER_PROFILE_ARB1 }, }; - // The PROFILE_EMITTER_* items MUST be in the same order as profiles[]! #define PROFILE_EMITTERS(op) { \ PROFILE_EMITTER_D3D(op) \ PROFILE_EMITTER_BYTECODE(op) \ + PROFILE_EMITTER_HLSL(op) \ PROFILE_EMITTER_GLSL(op) \ PROFILE_EMITTER_ARB1(op) \ + PROFILE_EMITTER_METAL(op) \ + PROFILE_EMITTER_SPIRV(op) \ } static int parse_destination_token(Context *ctx, DestArgInfo *info) @@ -6318,7 +449,7 @@ static int parse_destination_token(Context *ctx, DestArgInfo *info) fail(ctx, "Centroid modifier not allowed here"); } // if - if ((info->regtype < 0) || (info->regtype > REG_TYPE_MAX)) + if (/*(info->regtype < 0) ||*/ (info->regtype > REG_TYPE_MAX)) fail(ctx, "Register type is out of range"); if (!isfail(ctx)) @@ -6418,7 +549,7 @@ static void determine_constants_arrays(Context *ctx) var->emit_position = -1; var->next = ctx->variables; ctx->variables = var; - } // else + } // if start = i; // set this as new start of sequence. } // if @@ -6427,6 +558,31 @@ static void determine_constants_arrays(Context *ctx) } // for } // determine_constants_arrays +static void shader_model_1_input_usage(const int regnum, MOJOSHADER_usage *usage, int *index) +{ + *index = 0; + switch (regnum) // these are hardcoded for Shader Model 1: v0 is POSITION, v1 is BLENDWEIGHT, etc. + { + case 0: *usage = MOJOSHADER_USAGE_POSITION; break; + case 1: *usage = MOJOSHADER_USAGE_BLENDWEIGHT; break; + case 2: *usage = MOJOSHADER_USAGE_BLENDINDICES; break; + case 3: *usage = MOJOSHADER_USAGE_NORMAL; break; + case 4: *usage = MOJOSHADER_USAGE_POINTSIZE; break; + case 5: *usage = MOJOSHADER_USAGE_COLOR; break; // diffuse + case 6: *usage = MOJOSHADER_USAGE_COLOR; *index = 1; break; // specular + case 7: *usage = MOJOSHADER_USAGE_TEXCOORD; break; + case 8: *usage = MOJOSHADER_USAGE_TEXCOORD; *index = 1; break; + case 9: *usage = MOJOSHADER_USAGE_TEXCOORD; *index = 2; break; + case 10: *usage = MOJOSHADER_USAGE_TEXCOORD; *index = 3; break; + case 11: *usage = MOJOSHADER_USAGE_TEXCOORD; *index = 4; break; + case 12: *usage = MOJOSHADER_USAGE_TEXCOORD; *index = 5; break; + case 13: *usage = MOJOSHADER_USAGE_TEXCOORD; *index = 6; break; + case 14: *usage = MOJOSHADER_USAGE_TEXCOORD; *index = 7; break; + case 15: *usage = MOJOSHADER_USAGE_POSITION; *index = 1; break; + case 16: *usage = MOJOSHADER_USAGE_NORMAL; *index = 1; break; + default: *usage = MOJOSHADER_USAGE_UNKNOWN; break; + } // switch +} // shader_model_1_input_usage static int adjust_swizzle(const Context *ctx, const RegisterType regtype, const int regnum, const int swizzle) @@ -6436,15 +592,31 @@ static int adjust_swizzle(const Context *ctx, const RegisterType regtype, else if (ctx->swizzles_count == 0) return swizzle; - const RegisterList *reg = reglist_find(&ctx->attributes, regtype, regnum); - if (reg == NULL) + MOJOSHADER_usage usage = MOJOSHADER_USAGE_UNKNOWN; + int index = 0; + + // Shader Model 1 didn't have to predeclare attribute variables, so + // reglist_find won't be able to look them up at this point, but + // their usages don't change. + if (!shader_version_atleast(ctx, 2, 0)) + shader_model_1_input_usage(regnum, &usage, &index); + else + { + const RegisterList *reg = reglist_find(&ctx->attributes, regtype, regnum); + if (reg == NULL) + return swizzle; + usage = reg->usage; + index = reg->index; + } // else + + if (usage == MOJOSHADER_USAGE_UNKNOWN) return swizzle; size_t i; for (i = 0; i < ctx->swizzles_count; i++) { const MOJOSHADER_swizzle *swiz = &ctx->swizzles[i]; - if ((swiz->usage == reg->usage) && (swiz->index == reg->index)) + if ((swiz->usage == usage) && (swiz->index == index)) { return ( (((int)(swiz->swizzles[((swizzle >> 0) & 0x3)])) << 0) | (((int)(swiz->swizzles[((swizzle >> 2) & 0x3)])) << 2) | @@ -6522,39 +694,53 @@ static int parse_source_token(Context *ctx, SourceArgInfo *info) if ( (shader_is_pixel(ctx)) && (!shader_version_atleast(ctx, 3, 0)) ) fail(ctx, "Relative addressing in pixel shader version < 3.0"); - const uint32 reltoken = SWAP32(*(ctx->tokens)); - // swallow token for now, for multiple calls in a row. - adjust_token_position(ctx, 1); + // Shader Model 1 doesn't have an extra token to specify the + // relative register: it's always a0.x. + if (!shader_version_atleast(ctx, 2, 0)) + { + info->relative_regnum = 0; + info->relative_regtype = REG_TYPE_ADDRESS; + info->relative_component = 0; + } // if - const int relswiz = (int) ((reltoken >> 16) & 0xFF); - info->relative_regnum = (int) (reltoken & 0x7ff); - info->relative_regtype = (RegisterType) - (((reltoken >> 28) & 0x7) | - ((reltoken >> 8) & 0x18)); + else // Shader Model 2 and later... + { + const uint32 reltoken = SWAP32(*(ctx->tokens)); + // swallow token for now, for multiple calls in a row. + adjust_token_position(ctx, 1); - if (((reltoken >> 31) & 0x1) == 0) - fail(ctx, "bit #31 in relative address must be set"); + const int relswiz = (int) ((reltoken >> 16) & 0xFF); + info->relative_regnum = (int) (reltoken & 0x7ff); + info->relative_regtype = (RegisterType) + (((reltoken >> 28) & 0x7) | + ((reltoken >> 8) & 0x18)); - if ((reltoken & 0xF00E000) != 0) // usused bits. - fail(ctx, "relative address reserved bit must be zero"); + if (((reltoken >> 31) & 0x1) == 0) + fail(ctx, "bit #31 in relative address must be set"); - switch (info->relative_regtype) - { - case REG_TYPE_LOOP: - case REG_TYPE_ADDRESS: - break; - default: + if ((reltoken & 0xF00E000) != 0) // usused bits. + fail(ctx, "relative address reserved bit must be zero"); + + switch (info->relative_regtype) + { + case REG_TYPE_LOOP: + case REG_TYPE_ADDRESS: + break; + default: + fail(ctx, "invalid register for relative address"); + break; + } // switch + + if (info->relative_regnum != 0) // true for now. fail(ctx, "invalid register for relative address"); - break; - } // switch - if (info->relative_regnum != 0) // true for now. - fail(ctx, "invalid register for relative address"); + if ( (info->relative_regtype != REG_TYPE_LOOP) && !replicate_swizzle(relswiz) ) + fail(ctx, "relative address needs replicate swizzle"); - if (!replicate_swizzle(relswiz)) - fail(ctx, "relative address needs replicate swizzle"); + info->relative_component = (relswiz & 0x3); - info->relative_component = (relswiz & 0x3); + retval++; + } // else if (info->regtype == REG_TYPE_INPUT) { @@ -6597,8 +783,6 @@ static int parse_source_token(Context *ctx, SourceArgInfo *info) { fail(ctx, "relative addressing of invalid register"); } // else - - retval++; } // if switch (info->src_mod) @@ -6626,8 +810,9 @@ static int parse_source_token(Context *ctx, SourceArgInfo *info) case SRCMOD_NOT: // !!! FIXME: I _think_ this is right... if (shader_version_atleast(ctx, 2, 0)) { - if (info->regtype != REG_TYPE_PREDICATE) - fail(ctx, "NOT only allowed on predicate register."); + if (info->regtype != REG_TYPE_PREDICATE + && info->regtype != REG_TYPE_CONSTBOOL) + fail(ctx, "NOT only allowed on bool registers."); } // if break; @@ -6881,6 +1066,35 @@ static int parse_args_DCL(Context *ctx) ctx->dwords[0] = usage; ctx->dwords[1] = index; } // if + else if (regtype == REG_TYPE_TEXTURE) + { + const uint32 usage = (token & 0xF); + const uint32 index = ((token >> 16) & 0xF); + if (usage == MOJOSHADER_USAGE_TEXCOORD) + { + if (index > 7) + fail(ctx, "DCL texcoord usage must have 0-7 index"); + } // if + else if (usage == MOJOSHADER_USAGE_COLOR) + { + if (index != 0) + fail(ctx, "DCL texcoord usage must have 0 index"); + } // else if + else + fail(ctx, "Invalid DCL texture usage"); + + reserved_mask = 0x7FF0FFE0; + ctx->dwords[0] = usage; + ctx->dwords[1] = index; + } // else if + else if (regtype == REG_TYPE_SAMPLER) + { + const uint32 ttype = ((token >> 27) & 0xF); + if (!valid_texture_type(ttype)) + fail(ctx, "Unknown sampler texture type"); + reserved_mask = 0x0FFFFFFF; + ctx->dwords[0] = ttype; + } // else if else { unsupported = 1; @@ -7122,29 +1336,22 @@ static void state_DCL(Context *ctx) if (ctx->instruction_count != 0) fail(ctx, "DCL token must come before any instructions"); - else if (shader_is_vertex(ctx)) - { - const MOJOSHADER_usage usage = (const MOJOSHADER_usage) ctx->dwords[0]; - const int index = ctx->dwords[1]; - if (usage >= MOJOSHADER_USAGE_TOTAL) - { - fail(ctx, "unknown DCL usage"); - return; - } // if - add_attribute_register(ctx, regtype, regnum, usage, index, wmask, mods); - } // if - - else if (shader_is_pixel(ctx)) + else if (shader_is_vertex(ctx) || shader_is_pixel(ctx)) { if (regtype == REG_TYPE_SAMPLER) add_sampler(ctx, regnum, (TextureType) ctx->dwords[0], 0); else { - const MOJOSHADER_usage usage = (MOJOSHADER_usage) ctx->dwords[0]; + const MOJOSHADER_usage usage = (const MOJOSHADER_usage) ctx->dwords[0]; const int index = ctx->dwords[1]; + if (usage >= MOJOSHADER_USAGE_TOTAL) + { + fail(ctx, "unknown DCL usage"); + return; + } // if add_attribute_register(ctx, regtype, regnum, usage, index, wmask, mods); } // else - } // else if + } // if else { @@ -7298,9 +1505,10 @@ static void check_call_loop_wrappage(Context *ctx, const int regnum) const int current_usage = (ctx->loops > 0) ? 1 : -1; RegisterList *reg = reglist_find(&ctx->used_registers, REG_TYPE_LABEL, regnum); - assert(reg != NULL); - if (reg->misc == 0) + if (reg == NULL) + fail(ctx, "Invalid label for CALL"); + else if (reg->misc == 0) reg->misc = current_usage; else if (reg->misc != current_usage) { @@ -7335,9 +1543,15 @@ static void state_MOVA(Context *ctx) static void state_RCP(Context *ctx) { if (!replicate_swizzle(ctx->source_args[0].swizzle)) - fail(ctx, "RCP without replicate swizzzle"); + fail(ctx, "RCP without replicate swizzle"); } // state_RCP +static void state_RSQ(Context *ctx) +{ + if (!replicate_swizzle(ctx->source_args[0].swizzle)) + fail(ctx, "RSQ without replicate swizzle"); +} // state_RSQ + static void state_LOOP(Context *ctx) { if (ctx->source_args[0].regtype != REG_TYPE_LOOP) @@ -7362,7 +1576,7 @@ static void state_BREAKP(Context *ctx) if (regtype != REG_TYPE_PREDICATE) fail(ctx, "BREAKP argument isn't predicate register"); else if (!replicate_swizzle(ctx->source_args[0].swizzle)) - fail(ctx, "BREAKP without replicate swizzzle"); + fail(ctx, "BREAKP without replicate swizzle"); else if ((ctx->loops == 0) && (ctx->reps == 0)) fail(ctx, "BREAKP outside LOOP/ENDLOOP or REP/ENDREP"); } // state_BREAKP @@ -7508,8 +1722,6 @@ static void state_IF(Context *ctx) const RegisterType regtype = ctx->source_args[0].regtype; if ((regtype != REG_TYPE_PREDICATE) && (regtype != REG_TYPE_CONSTBOOL)) fail(ctx, "IF src0 must be CONSTBOOL or PREDICATE"); - else if (!replicate_swizzle(ctx->source_args[0].swizzle)) - fail(ctx, "IF src0 must have replicate swizzle"); // !!! FIXME: track if nesting depth. } // state_IF @@ -7773,8 +1985,6 @@ static void state_TEXLD(Context *ctx) if (info->regtype != REG_TYPE_TEXTURE) fail(ctx, "TEX param must be a texture register"); add_sampler(ctx, sampler, TEXTURE_TYPE_2D, 0); - add_attribute_register(ctx, REG_TYPE_TEXTURE, sampler, - MOJOSHADER_USAGE_TEXCOORD, sampler, 0xF, 0); } // else } // state_TEXLD @@ -7813,20 +2023,16 @@ typedef struct // of the instruction token. static const Instruction instructions[] = { - #define INSTRUCTION_STATE(op, opstr, slots, a, t) { \ + #define INSTRUCTION_STATE(op, opstr, slots, a, t, w) { \ opstr, slots, t, parse_args_##a, state_##op, PROFILE_EMITTERS(op) \ }, - #define INSTRUCTION(op, opstr, slots, a, t) { \ - opstr, slots, t, parse_args_##a, 0, PROFILE_EMITTERS(op) \ + #define INSTRUCTION(op, opstr, slots, a, t, w) { \ + opstr, slots, t, parse_args_##a, NULL, PROFILE_EMITTERS(op) \ }, #define MOJOSHADER_DO_INSTRUCTION_TABLE 1 #include "mojoshader_internal.h" - #undef MOJOSHADER_DO_INSTRUCTION_TABLE - - #undef INSTRUCTION - #undef INSTRUCTION_STATE }; @@ -8003,9 +2209,10 @@ static int parse_ctab_string(const uint8 *start, const uint32 bytes, static int parse_ctab_typeinfo(Context *ctx, const uint8 *start, const uint32 bytes, const uint32 pos, - MOJOSHADER_symbolTypeInfo *info) + MOJOSHADER_symbolTypeInfo *info, + const int depth) { - if ((pos + 16) >= bytes) + if ((bytes <= pos) || ((bytes - pos) < 16)) return 0; // corrupt CTAB. const uint16 *typeptr = (const uint16 *) (start + pos); @@ -8015,26 +2222,45 @@ static int parse_ctab_typeinfo(Context *ctx, const uint8 *start, info->rows = (unsigned int) SWAP16(typeptr[2]); info->columns = (unsigned int) SWAP16(typeptr[3]); info->elements = (unsigned int) SWAP16(typeptr[4]); - info->member_count = (unsigned int) SWAP16(typeptr[5]); - if ((pos + 16 + (info->member_count * 8)) >= bytes) + if (info->parameter_class >= MOJOSHADER_SYMCLASS_TOTAL) + { + failf(ctx, "Unknown parameter class (0x%X)", info->parameter_class); + info->parameter_class = MOJOSHADER_SYMCLASS_SCALAR; + } // if + + if (info->parameter_type >= MOJOSHADER_SYMTYPE_TOTAL) + { + failf(ctx, "Unknown parameter type (0x%X)", info->parameter_type); + info->parameter_type = MOJOSHADER_SYMTYPE_INT; + } // if + + const unsigned int member_count = (unsigned int) SWAP16(typeptr[5]); + info->member_count = 0; + info->members = NULL; + + if ((pos + 16 + (member_count * 8)) >= bytes) return 0; // corrupt CTAB. - if (info->member_count == 0) - info->members = NULL; - else + if (member_count > 0) { - const size_t len = sizeof (MOJOSHADER_symbolStructMember) * - info->member_count; + if (depth > 300) // make sure we aren't in an infinite loop here. + { + fail(ctx, "Possible infinite loop in CTAB structure."); + return 0; + } // if + + const size_t len = sizeof (MOJOSHADER_symbolStructMember) * member_count; info->members = (MOJOSHADER_symbolStructMember *) Malloc(ctx, len); if (info->members == NULL) return 1; // we'll check ctx->out_of_memory later. memset(info->members, '\0', len); + info->member_count = member_count; } // else - int i; - const uint32 *member = (const uint32 *)((const uint8 *) (&typeptr[6])); - for (i = 0; i < info->member_count; i++) + unsigned int i; + const uint32 *member = (const uint32 *) (start + typeptr[6]); + for (i = 0; i < member_count; i++) { MOJOSHADER_symbolStructMember *mbr = &info->members[i]; const uint32 name = SWAP32(member[0]); @@ -8047,7 +2273,7 @@ static int parse_ctab_typeinfo(Context *ctx, const uint8 *start, mbr->name = StrDup(ctx, (const char *) (start + name)); if (mbr->name == NULL) return 1; // we'll check ctx->out_of_memory later. - if (!parse_ctab_typeinfo(ctx, start, bytes, memberinfopos, &mbr->info)) + if (!parse_ctab_typeinfo(ctx, start, bytes, memberinfopos, &mbr->info, depth + 1)) return 0; if (ctx->out_of_memory) return 1; // drop out now. @@ -8070,7 +2296,12 @@ static void parse_constant_table(Context *ctx, const uint32 *tokens, if (id != CTAB_ID) return; // not the constant table. - assert(ctab->have_ctab == 0); // !!! FIXME: can you have more than one? + if (ctab->have_ctab) // !!! FIXME: can you have more than one? + { + fail(ctx, "Shader has multiple CTAB sections"); + return; + } // if + ctab->have_ctab = 1; const uint8 *start = (uint8 *) &tokens[2]; @@ -8090,19 +2321,26 @@ static void parse_constant_table(Context *ctx, const uint32 *tokens, if (size != CTAB_SIZE) goto corrupt_ctab; + else if (constants > 1000000) // sanity check. + goto corrupt_ctab; - //if (version != okay_version) goto corrupt_ctab; + if (version != okay_version) goto corrupt_ctab; if (creator >= bytes) goto corrupt_ctab; - if ((constantinfo + (constants * CINFO_SIZE)) >= bytes) goto corrupt_ctab; + if (constantinfo >= bytes) goto corrupt_ctab; + if ((bytes - constantinfo) < (constants * CINFO_SIZE)) goto corrupt_ctab; if (target >= bytes) goto corrupt_ctab; if (!parse_ctab_string(start, bytes, target)) goto corrupt_ctab; // !!! FIXME: check that (start+target) points to "ps_3_0", etc. + ctab->symbols = NULL; + if (constants > 0) + { + ctab->symbols = (MOJOSHADER_symbol *) Malloc(ctx, sizeof (MOJOSHADER_symbol) * constants); + if (ctab->symbols == NULL) + return; + memset(ctab->symbols, '\0', sizeof (MOJOSHADER_symbol) * constants); + } // if ctab->symbol_count = constants; - ctab->symbols = (MOJOSHADER_symbol*)Malloc(ctx, sizeof (MOJOSHADER_symbol) * constants); - if (ctab->symbols == NULL) - return; - memset(ctab->symbols, '\0', sizeof (MOJOSHADER_symbol) * constants); uint32 i = 0; for (i = 0; i < constants; i++) @@ -8155,7 +2393,7 @@ static void parse_constant_table(Context *ctx, const uint32 *tokens, sym->register_set = (MOJOSHADER_symbolRegisterSet) regset; sym->register_index = (unsigned int) regidx; sym->register_count = (unsigned int) regcnt; - if (!parse_ctab_typeinfo(ctx, start, bytes, typeinf, &sym->info)) + if (!parse_ctab_typeinfo(ctx, start, bytes, typeinf, &sym->info, 0)) goto corrupt_ctab; // sym->name will get free()'d later. else if (ctx->out_of_memory) return; // just bail now. @@ -8205,34 +2443,33 @@ typedef struct PreshaderBlockInfo // My presumption is that Microsoft's Effects framework runs the preshaders on // the CPU, then loads the constant register file appropriately before handing // off to the GPU. As such, we do the same. -static void parse_preshader(Context *ctx, uint32 tokcount) +static void parse_preshader(Context *ctx, const uint32 *tokens, uint32 tokcount) { - const uint32 *tokens = ctx->tokens; - - if (SWAP32(tokens[1]) == PRES_ID) { - if (tokcount <= 2) return; - //hax - tokens += 2; - tokcount -= 2; - } - +#ifndef MOJOSHADER_EFFECT_SUPPORT + fail(ctx, "Preshader found, but effect support is disabled!"); +#else + uint32 i; + assert(ctx->have_preshader == 0); // !!! FIXME: can you have more than one? ctx->have_preshader = 1; // !!! FIXME: I don't know what specific versions signify, but we need to // !!! FIXME: save this to test against the CTAB version field, if // !!! FIXME: nothing else. - // !!! FIXME: 0x02 0x01 is probably the version (fx_2_1), + // !!! FIXME: 0x02 0x0? is probably the version (fx_2_?), // !!! FIXME: and 0x4658 is the magic, like a real shader's version token. - const uint32 okay_versions[] = {0x46580201, 0x46580200}; - if (SWAP32(tokens[0]) != okay_versions[0] && SWAP32(tokens[0]) != okay_versions[1]) + const uint32 version_magic = 0x46580000; + const uint32 min_version = 0x00000200 | version_magic; + const uint32 max_version = 0x00000201 | version_magic; + const uint32 version = SWAP32(tokens[0]); + if (version < min_version || version > max_version) { - failf(ctx, "Unsupported preshader version %6x.", tokens[0]); + fail(ctx, "Unsupported preshader version."); return; // fail because the shader will malfunction w/o this. } // if - tokens += 1; - tokcount -= 1; + tokens++; + tokcount--; // All sections of a preshader are packed into separate comment tokens, // inside the containing comment token block. Find them all before @@ -8248,6 +2485,13 @@ static void parse_preshader(Context *ctx, uint32 tokcount) if ( (!is_comment_token(ctx, *tokens, &subtokcount)) || (subtokcount > tokcount) ) { + // !!! FIXME: Standalone preshaders have this EOS-looking token, + // !!! FIXME: sometimes followed by tokens that don't appear to + // !!! FIXME: have anything to do with the rest of the blob. + // !!! FIXME: So for now, treat this as a special "EOS" comment. + if (SWAP32(*tokens) == 0xFFFF) + break; + fail(ctx, "Bogus preshader data."); return; } // if @@ -8287,15 +2531,20 @@ static void parse_preshader(Context *ctx, uint32 tokcount) } // while if (!ctab.seen) { fail(ctx, "No CTAB block in preshader."); return; } - //if (!prsi.seen) { fail(ctx, "No PRSI block in preshader."); return; } if (!fxlc.seen) { fail(ctx, "No FXLC block in preshader."); return; } if (!clit.seen) { fail(ctx, "No CLIT block in preshader."); return; } + // prsi.seen is optional, apparently. MOJOSHADER_preshader *preshader = (MOJOSHADER_preshader *) Malloc(ctx, sizeof (MOJOSHADER_preshader)); if (preshader == NULL) return; + memset(preshader, '\0', sizeof (MOJOSHADER_preshader)); + preshader->malloc = ctx->malloc; + preshader->free = ctx->free; + preshader->malloc_data = ctx->malloc_data; + ctx->preshader = preshader; // Let's set up the constant literals first... @@ -8318,31 +2567,34 @@ static void parse_preshader(Context *ctx, uint32 tokcount) if (preshader->literals == NULL) return; // oh well. const double *litptr = (const double *) (clit.tokens + 2); - int i; - for (i = 0; i < lit_count; i++) - preshader->literals[i] = SWAPDBL(litptr[i]); + // !!! FIXME: This should be a SWAPDBL loop, but in addition to + // !!! FIXME: never having an implementation, it turns out some + // !!! FIXME: MinGW versions do not optimize this correctly, which + // !!! FIXME: can cause random crashes on Win64. -flibit + //for (i = 0; i < lit_count; i++) + // preshader->literals[i] = SWAPDBL(litptr[i]); + memcpy(preshader->literals, litptr, len); } // else if } // else - - - //const uint32 first_output_reg = SWAP32(prsi.tokens[1]); - // !!! FIXME: there are a lot of fields here I don't know about. - // !!! FIXME: maybe [2] and [3] are for int4 and bool registers? - //const uint32 output_reg_count = SWAP32(prsi.tokens[4]); - // !!! FIXME: maybe [5] and [6] are for int4 and bool registers? - uint32 output_map_count; + // Parse out the PRSI block. This is used to map the output registers. + uint32 output_map_count = 0; const uint32 *output_map = NULL; - if (prsi.seen) { - // Parse out the PRSI block. This is used to map the output registers. + if (prsi.seen) + { if (prsi.tokcount < 8) { fail(ctx, "Bogus preshader PRSI data"); return; } // if - + + //const uint32 first_output_reg = SWAP32(prsi.tokens[1]); + // !!! FIXME: there are a lot of fields here I don't know about. + // !!! FIXME: maybe [2] and [3] are for int4 and bool registers? + //const uint32 output_reg_count = SWAP32(prsi.tokens[4]); + // !!! FIXME: maybe [5] and [6] are for int4 and bool registers? output_map_count = SWAP32(prsi.tokens[7]); - + prsi.tokcount -= 8; prsi.tokens += 8; @@ -8351,16 +2603,14 @@ static void parse_preshader(Context *ctx, uint32 tokcount) fail(ctx, "Bogus preshader PRSI data"); return; } // if - + output_map = prsi.tokens; - } else { - output_map_count = 0; - } + } // if // Now we'll figure out the CTAB... CtabData ctabdata = { 0, 0, 0 }; parse_constant_table(ctx, ctab.tokens - 1, ctab.tokcount * 4, - okay_versions[1], 0, &ctabdata); + version, 0, &ctabdata); // preshader owns this now. Don't free it in this function. preshader->symbol_count = ctabdata.symbol_count; @@ -8375,10 +2625,9 @@ static void parse_preshader(Context *ctx, uint32 tokcount) // The FXLC block has the actual instructions... uint32 opcode_count = SWAP32(fxlc.tokens[1]); - size_t len = sizeof (MOJOSHADER_preshaderInstruction) * opcode_count; + const size_t len = sizeof (MOJOSHADER_preshaderInstruction) * opcode_count; preshader->instruction_count = (unsigned int) opcode_count; - preshader->instructions = (MOJOSHADER_preshaderInstruction *) - Malloc(ctx, len); + preshader->instructions = (MOJOSHADER_preshaderInstruction *) Malloc(ctx, len); if (preshader->instructions == NULL) return; memset(preshader->instructions, '\0', len); @@ -8395,9 +2644,8 @@ static void parse_preshader(Context *ctx, uint32 tokcount) while (opcode_count--) { const uint32 opcodetok = SWAP32(fxlc.tokens[0]); - MOJOSHADER_preshaderOpcode opcode = MOJOSHADER_PRESHADEROP_NOP; - switch ((opcodetok >> 16) & 0x7FF0) + switch ((opcodetok >> 16) & 0xFFFF) { case 0x1000: opcode = MOJOSHADER_PRESHADEROP_MOV; break; case 0x1010: opcode = MOJOSHADER_PRESHADEROP_NEG; break; @@ -8453,50 +2701,28 @@ static void parse_preshader(Context *ctx, uint32 tokcount) MOJOSHADER_preshaderOperand *operand = inst->operands; while (operand_count--) { - - // !!! FIXME: don't quite know how this works - unsigned int subOps = (unsigned int) SWAP32(fxlc.tokens[0]); - operand->indexingType = 0; - while (subOps--) { - switch (fxlc.tokens[1]) { - case 2: - { - operand->indexingType = 2; - operand->indexingIndex = fxlc.tokens[2]; - break; - } - default: - { - failf(ctx, "unkn indexer %d\n", fxlc.tokens[1]); - break; - } - } - //type info? - fxlc.tokens += 2; - fxlc.tokcount -= 2; - } - const unsigned int item = (unsigned int) SWAP32(fxlc.tokens[2]); - - operand->type = (MOJOSHADER_preshaderOperandType)SWAP32(fxlc.tokens[1]); - switch (operand->type) + // !!! FIXME: Is this used anywhere other than INPUT? -flibit + const uint32 numarrays = SWAP32(fxlc.tokens[0]); + switch (SWAP32(fxlc.tokens[1])) { - case MOJOSHADER_PRESHADEROPERAND_LITERAL: // literal from CLIT block. + case 1: // literal from CLIT block. { - if (item >= preshader->literal_count) + if (item > preshader->literal_count) { fail(ctx, "Bogus preshader literal index."); break; } // if + operand->type = MOJOSHADER_PRESHADEROPERAND_LITERAL; break; } // case - case MOJOSHADER_PRESHADEROPERAND_INPUT: // item from ctabdata. + case 2: // item from ctabdata. { - int i; MOJOSHADER_symbol *sym = ctabdata.symbols; - for (i = 0; i < ctabdata.symbol_count; i++, sym++) + const uint32 symcount = (uint32) ctabdata.symbol_count; + for (i = 0; i < symcount; i++, sym++) { const uint32 base = sym->register_index * 4; const uint32 count = sym->register_count * 4; @@ -8509,12 +2735,33 @@ static void parse_preshader(Context *ctx, uint32 tokcount) fail(ctx, "Bogus preshader input index."); break; } // if + operand->type = MOJOSHADER_PRESHADEROPERAND_INPUT; + if (numarrays > 0) + { + // malloc the array symbol name array + const uint32 siz = numarrays * sizeof (uint32); + operand->array_register_count = numarrays; + operand->array_registers = (uint32 *) Malloc(ctx, siz); + memset(operand->array_registers, '\0', siz); + // Get each register base, indicating the arrays used. + // !!! FIXME: fail if fxlc.tokcount*2 > numarrays ? + for (i = 0; i < numarrays; i++) + { + const uint32 jmp = SWAP32(fxlc.tokens[4]); + const uint32 bigjmp = (jmp >> 4) * 4; + const uint32 ltljmp = (jmp >> 2) & 3; + operand->array_registers[i] = bigjmp + ltljmp; + fxlc.tokens += 2; + fxlc.tokcount -= 2; + } // for + } // if break; } // case - case MOJOSHADER_PRESHADEROPERAND_OUTPUT: + case 4: { - int i; + operand->type = MOJOSHADER_PRESHADEROPERAND_OUTPUT; + for (i = 0; i < output_map_count; i++) { const uint32 base = output_map[(i*2)] * 4; @@ -8522,26 +2769,27 @@ static void parse_preshader(Context *ctx, uint32 tokcount) if ( (base <= item) && ((base + count) > item) ) break; } // for - if (output_map_count > 0 && i == output_map_count) + + if (i == output_map_count) { - fail(ctx, "Bogus preshader output index."); - break; + if (prsi.seen) // No PRSI tokens, no output map. + fail(ctx, "Bogus preshader output index."); } // if break; } // case - case MOJOSHADER_PRESHADEROPERAND_TEMP: + case 7: { + operand->type = MOJOSHADER_PRESHADEROPERAND_TEMP; if (item >= preshader->temp_count) preshader->temp_count = item + 1; break; } // case + default: - { - failf(ctx, "unknown operand type %d\n", operand->type); + assert(0 && "Unhandled fxlc.tokens[1] in parse_preshader!"); break; - } } // switch operand->index = item; @@ -8553,19 +2801,40 @@ static void parse_preshader(Context *ctx, uint32 tokcount) inst++; } // while -} // parse_preshader + // Registers need to be vec4, round up to nearest 4 + preshader->temp_count = (preshader->temp_count + 3) & ~3; + + unsigned int largest = 0; + const MOJOSHADER_symbol *sym = preshader->symbols; + const uint32 symcount = (uint32) preshader->symbol_count; + for (i = 0; i < symcount; i++, sym++) + { + const unsigned int val = sym->register_index + sym->register_count; + if (val > largest) + largest = val; + } // for + + if (largest > 0) + { + const size_t len = largest * sizeof (float) * 4; + preshader->registers = (float *) Malloc(ctx, len); + memset(preshader->registers, '\0', len); + preshader->register_count = largest; + } // if +#endif +} // parse_preshader static int parse_comment_token(Context *ctx) { uint32 commenttoks = 0; if (is_comment_token(ctx, *ctx->tokens, &commenttoks)) { - if ((commenttoks >= 1) && (commenttoks < ctx->tokencount)) + if ((commenttoks >= 2) && (commenttoks < ctx->tokencount)) { const uint32 id = SWAP32(ctx->tokens[1]); if (id == PRES_ID) - parse_preshader(ctx, commenttoks); + parse_preshader(ctx, ctx->tokens + 2, commenttoks - 2); else if (id == CTAB_ID) { parse_constant_table(ctx, ctx->tokens, commenttoks * 4, @@ -8584,7 +2853,9 @@ static int parse_end_token(Context *ctx) if (SWAP32(*(ctx->tokens)) != 0x0000FFFF) // end token always 0x0000FFFF. return 0; // not us, eat no tokens. - if (ctx->tokencount != 1) // we _must_ be last. If not: fail. + if (!ctx->know_shader_size) // this is the end of stream! + ctx->tokencount = 1; + else if (ctx->tokencount != 1) // we _must_ be last. If not: fail. fail(ctx, "end token before end of stream"); if (!isfail(ctx)) @@ -8661,6 +2932,7 @@ static int find_profile_id(const char *profile) static Context *build_context(const char *profile, + const char *mainfn, const unsigned char *tokenbuf, const unsigned int bufsize, const MOJOSHADER_swizzle *swiz, @@ -8682,7 +2954,8 @@ static Context *build_context(const char *profile, ctx->malloc_data = d; ctx->tokens = (const uint32 *) tokenbuf; ctx->orig_tokens = (const uint32 *) tokenbuf; - ctx->tokencount = bufsize / sizeof (uint32); + ctx->know_shader_size = (bufsize != 0); + ctx->tokencount = ctx->know_shader_size ? (bufsize / sizeof (uint32)) : 0xFFFFFFFF; ctx->swizzles = swiz; ctx->swizzles_count = swizcount; ctx->samplermap = smap; @@ -8712,12 +2985,23 @@ static Context *build_context(const char *profile, return NULL; } // if - const int profileid = find_profile_id(profile); - ctx->profileid = profileid; - if (profileid >= 0) - ctx->profile = &profiles[profileid]; - else - failf(ctx, "Profile '%s' is unknown or unsupported", profile); + if (mainfn != NULL) + { + if (strlen(mainfn) > 55) // !!! FIXME: just to keep things sane. Lots of hardcoded stack arrays... + failf(ctx, "Main function name '%s' is too big", mainfn); + else + ctx->mainfn = StrDup(ctx, mainfn); + } // if + + if (profile != NULL) + { + const int profileid = find_profile_id(profile); + ctx->profileid = profileid; + if (profileid >= 0) + ctx->profile = &profiles[profileid]; + else + failf(ctx, "Profile '%s' is unknown or unsupported", profile); + } // if return ctx; } // build_context @@ -8748,7 +3032,7 @@ static void free_variable_list(MOJOSHADER_free f, void *d, VariableList *item) static void free_sym_typeinfo(MOJOSHADER_free f, void *d, MOJOSHADER_symbolTypeInfo *typeinfo) { - int i; + unsigned int i; for (i = 0; i < typeinfo->member_count; i++) { f((void *) typeinfo->members[i].name, d); @@ -8771,19 +3055,6 @@ static void free_symbols(MOJOSHADER_free f, void *d, MOJOSHADER_symbol *syms, } // free_symbols -static void free_preshader(MOJOSHADER_free f, void *d, - MOJOSHADER_preshader *preshader) -{ - if (preshader != NULL) - { - f((void *) preshader->literals, d); - f((void *) preshader->instructions, d); - free_symbols(f, d, preshader->symbols, preshader->symbol_count); - f((void *) preshader, d); - } // if -} // free_preshader - - static void destroy_context(Context *ctx) { if (ctx != NULL) @@ -8792,10 +3063,15 @@ static void destroy_context(Context *ctx) void *d = ctx->malloc_data; buffer_destroy(ctx->preflight); buffer_destroy(ctx->globals); + buffer_destroy(ctx->inputs); + buffer_destroy(ctx->outputs); buffer_destroy(ctx->helpers); buffer_destroy(ctx->subroutines); buffer_destroy(ctx->mainline_intro); + buffer_destroy(ctx->mainline_arguments); + buffer_destroy(ctx->mainline_top); buffer_destroy(ctx->mainline); + buffer_destroy(ctx->postflight); buffer_destroy(ctx->ignore); free_constants_list(f, d, ctx->constants); free_reglist(f, d, ctx->used_registers.next); @@ -8806,7 +3082,8 @@ static void destroy_context(Context *ctx) free_variable_list(f, d, ctx->variables); errorlist_destroy(ctx->errors); free_symbols(f, d, ctx->ctab.symbols, ctx->ctab.symbol_count); - free_preshader(f, d, ctx->preshader); + MOJOSHADER_freePreshader(ctx->preshader); + f((void *) ctx->mainfn, d); f(ctx, d); } // if } // destroy_context @@ -8816,8 +3093,9 @@ static char *build_output(Context *ctx, size_t *len) { // add a byte for a null terminator. Buffer *buffers[] = { - ctx->preflight, ctx->globals, ctx->helpers, - ctx->subroutines, ctx->mainline_intro, ctx->mainline + ctx->preflight, ctx->globals, ctx->inputs, ctx->outputs, ctx->helpers, + ctx->subroutines, ctx->mainline_intro, ctx->mainline_arguments, + ctx->mainline_top, ctx->mainline, ctx->postflight // don't append ctx->ignore ... that's why it's called "ignore" }; char *retval = buffer_merge(buffers, STATICARRAYLEN(buffers), len); @@ -9022,11 +3300,6 @@ static MOJOSHADER_attribute *build_attributes(Context *ctx, int *_count) case REG_TYPE_DEPTHOUT: ignore = 1; break; - case REG_TYPE_TEXTURE: - case REG_TYPE_MISCTYPE: - case REG_TYPE_INPUT: - ignore = shader_is_pixel(ctx); - break; default: ignore = 0; break; @@ -9034,16 +3307,11 @@ static MOJOSHADER_attribute *build_attributes(Context *ctx, int *_count) if (!ignore) { - if (shader_is_pixel(ctx)) - fail(ctx, "BUG: pixel shader with vertex attributes"); - else - { - wptr->usage = item->usage; - wptr->index = item->index; - wptr->name = alloc_varname(ctx, item); - wptr++; - count++; - } // else + wptr->usage = item->usage; + wptr->index = item->index; + wptr->name = alloc_varname(ctx, item); + wptr++; + count++; } // if item = item->next; @@ -9239,11 +3507,36 @@ static MOJOSHADER_parseData *build_parsedata(Context *ctx) retval->symbol_count = ctx->ctab.symbol_count; retval->symbols = ctx->ctab.symbols; retval->preshader = ctx->preshader; + retval->mainfn = ctx->mainfn; + +#if SUPPORT_PROFILE_SPIRV + if (strcmp(retval->profile, MOJOSHADER_PROFILE_SPIRV) == 0 + || strcmp(retval->profile, MOJOSHADER_PROFILE_GLSPIRV) == 0) + { + size_t i, max; + int binary_size = retval->output_len - sizeof(SpirvPatchTable); + uint32 *binary = (uint32 *) retval->output; + SpirvPatchTable *table = (SpirvPatchTable *) &retval->output[binary_size]; + + if (table->vpflip.offset) binary[table->vpflip.offset] = table->vpflip.location; + if (table->array_vec4.offset) binary[table->array_vec4.offset] = table->array_vec4.location; + if (table->array_ivec4.offset) binary[table->array_ivec4.offset] = table->array_ivec4.location; + if (table->array_bool.offset) binary[table->array_bool.offset] = table->array_bool.location; + + for (i = 0, max = STATICARRAYLEN(table->samplers); i < max; i++) + { + SpirvPatchEntry entry = table->samplers[i]; + if (entry.offset) + binary[entry.offset] = entry.location; + } // for + } // if +#endif // SUPPORT_PROFILE_SPIRV // we don't own these now, retval does. ctx->ctab.symbols = NULL; ctx->preshader = NULL; ctx->ctab.symbol_count = 0; + ctx->mainfn = NULL; } // else retval->error_count = error_count; @@ -9255,7 +3548,6 @@ static MOJOSHADER_parseData *build_parsedata(Context *ctx) return retval; } // build_parsedata - static void process_definitions(Context *ctx) { // !!! FIXME: apparently, pre ps_3_0, sampler registers don't need to be @@ -9273,11 +3565,10 @@ static void process_definitions(Context *ctx) RegisterList *next = item->next; const RegisterType regtype = item->regtype; const int regnum = item->regnum; + MOJOSHADER_usage usage; if (!get_defined_register(ctx, regtype, regnum)) { - MOJOSHADER_usage usage; - // haven't already dealt with this one. switch (regtype) { @@ -9294,39 +3585,29 @@ static void process_definitions(Context *ctx) return; } // if - //find the usage - //hack copypastad from emit_GLSL_attribute - usage = MOJOSHADER_USAGE_UNKNOWN; + // Apparently this is an attribute that wasn't DCL'd. + // Add it to the attribute list; deal with it later. if (regtype == REG_TYPE_RASTOUT) { - switch ((const RastOutType) regnum) - { - case RASTOUT_TYPE_POSITION: - usage = MOJOSHADER_USAGE_POSITION; - break; - case RASTOUT_TYPE_FOG: - usage = MOJOSHADER_USAGE_FOG; - break; - case RASTOUT_TYPE_POINT_SIZE: - usage = MOJOSHADER_USAGE_POINTSIZE; - break; - } // switch + if ((RastOutType) regnum == RASTOUT_TYPE_POSITION) + usage = MOJOSHADER_USAGE_POSITION; + else if ((RastOutType) regnum == RASTOUT_TYPE_FOG) + usage = MOJOSHADER_USAGE_FOG; + else if ((RastOutType) regnum==RASTOUT_TYPE_POINT_SIZE) + usage = MOJOSHADER_USAGE_POINTSIZE; } // if - - else if (regtype == REG_TYPE_ATTROUT) + else if (regtype == REG_TYPE_ATTROUT || + regtype == REG_TYPE_COLOROUT) { usage = MOJOSHADER_USAGE_COLOR; } // else if - else if (regtype == REG_TYPE_TEXCRDOUT) - { usage = MOJOSHADER_USAGE_TEXCOORD; - } // else if + else if (regtype == REG_TYPE_DEPTHOUT) + usage = MOJOSHADER_USAGE_DEPTH; - // Apparently this is an attribute that wasn't DCL'd. - // Add it to the attribute list; deal with it later. - add_attribute_register(ctx, item->regtype, item->regnum, - usage, 0, 0xF, 0); + add_attribute_register(ctx, regtype, regnum, usage, + regnum, 0xF, 0); break; case REG_TYPE_ADDRESS: @@ -9350,13 +3631,27 @@ static void process_definitions(Context *ctx) case REG_TYPE_INPUT: // You don't have to dcl_ your inputs in Shader Model 1. - if (shader_is_pixel(ctx)&&!shader_version_atleast(ctx,2,0)) + if (!shader_version_atleast(ctx,2,0)) { - add_attribute_register(ctx, regtype, regnum, - MOJOSHADER_USAGE_COLOR, regnum, - 0xF, 0); - break; + if (shader_is_pixel(ctx)) + { + add_attribute_register(ctx, regtype, regnum, + MOJOSHADER_USAGE_COLOR, regnum, + 0xF, 0); + break; + } // if + else if (shader_is_vertex(ctx)) + { + int index = 0; + shader_model_1_input_usage(regnum, &usage, &index); + if (usage != MOJOSHADER_USAGE_UNKNOWN) + { + add_attribute_register(ctx, regtype, regnum, usage, index, 0xF, 0); + break; + } // if + } // else if } // if + // fall through... default: @@ -9369,8 +3664,7 @@ static void process_definitions(Context *ctx) } // while // okay, now deal with uniform/constant arrays... - VariableList *var; - for (var = ctx->variables; var != NULL; var = var->next) + for (VariableList *var = ctx->variables; var != NULL; var = var->next) { if (var->used) { @@ -9383,8 +3677,8 @@ static void process_definitions(Context *ctx) { ctx->profile->array_emitter(ctx, var); ctx->uniform_float4_count += var->count; - ctx->uniform_count++; } // else + ctx->uniform_count++; } // if } // for @@ -9392,6 +3686,7 @@ static void process_definitions(Context *ctx) for (item = ctx->uniforms.next; item != NULL; item = item->next) { int arraysize = -1; + VariableList *var = NULL; // check if this is a register contained in an array... if (item->regtype == REG_TYPE_CONST) @@ -9462,27 +3757,6 @@ static void verify_swizzles(Context *ctx) } // for } // verify_swizzles -DLLEXPORT -const MOJOSHADER_parseData *MOJOSHADER_parseExpression(const unsigned char *tokenbuf, - const unsigned int bufsize, - MOJOSHADER_malloc m, - MOJOSHADER_free f, void *d) -{ - MOJOSHADER_parseData *retval; - Context *ctx = NULL; - if ( ((m == NULL) && (f != NULL)) || ((m != NULL) && (f == NULL)) ) - return NULL; // supply both or neither. - - ctx = build_context("glsl120", tokenbuf, bufsize, NULL, 0, NULL, 0, m, f, d); - if (ctx == NULL) - return NULL; - - parse_preshader(ctx, bufsize/4-1); - retval = build_parsedata(ctx); - destroy_context(ctx); - - return retval; -} // API entry point... @@ -9491,8 +3765,8 @@ const MOJOSHADER_parseData *MOJOSHADER_parseExpression(const unsigned char *toke // attempts to read from a temporary register that has not been written by a // previous instruction." (true for ps_1_*, maybe others). Check this. -DLLEXPORT const MOJOSHADER_parseData *MOJOSHADER_parse(const char *profile, + const char *mainfn, const unsigned char *tokenbuf, const unsigned int bufsize, const MOJOSHADER_swizzle *swiz, @@ -9510,11 +3784,14 @@ const MOJOSHADER_parseData *MOJOSHADER_parse(const char *profile, if ( ((m == NULL) && (f != NULL)) || ((m != NULL) && (f == NULL)) ) return &MOJOSHADER_out_of_mem_data; // supply both or neither. - ctx = build_context(profile, tokenbuf, bufsize, swiz, swizcount, + ctx = build_context(profile, mainfn, tokenbuf, bufsize, swiz, swizcount, smap, smapcount, m, f, d); if (ctx == NULL) return &MOJOSHADER_out_of_mem_data; - + + if (profile == NULL) // build_context allows NULL; check this ourselves. + fail(ctx, "Profile name is NULL"); + if (isfail(ctx)) { retval = build_parsedata(ctx); @@ -9524,6 +3801,9 @@ const MOJOSHADER_parseData *MOJOSHADER_parse(const char *profile, verify_swizzles(ctx); + if (!ctx->mainfn) + ctx->mainfn = StrDup(ctx, "main"); + // Version token always comes first. ctx->current_position = 0; rc = parse_version_token(ctx, profile); @@ -9548,6 +3828,9 @@ const MOJOSHADER_parseData *MOJOSHADER_parse(const char *profile, // parse out the rest of the tokens after the version token... while (ctx->tokencount > 0) { + if (!ctx->know_shader_size) + ctx->tokencount = 0xFFFFFFFF; // keep this value obscenely large. + // reset for each token. if (isfail(ctx)) { @@ -9604,6 +3887,7 @@ void MOJOSHADER_freeParseData(const MOJOSHADER_parseData *_data) // we don't f(data->profile), because that's internal static data. + f((void *) data->mainfn, d); f((void *) data->output, d); f((void *) data->constants, d); f((void *) data->swizzles, d); @@ -9632,7 +3916,7 @@ void MOJOSHADER_freeParseData(const MOJOSHADER_parseData *_data) f((void *) data->samplers, d); free_symbols(f, d, data->symbols, data->symbol_count); - free_preshader(f, d, data->preshader); + MOJOSHADER_freePreshader(data->preshader); f(data, d); } // MOJOSHADER_freeParseData @@ -9655,15 +3939,132 @@ int MOJOSHADER_maxShaderModel(const char *profile) #define PROFILE_SHADER_MODEL(p,v) if (strcmp(profile, p) == 0) return v; PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_D3D, 3); PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_BYTECODE, 3); + PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_HLSL, 3); PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_GLSL, 3); PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_GLSL120, 3); + PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_GLSLES, 3); PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_ARB1, 2); PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_NV2, 2); PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_NV3, 2); PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_NV4, 3); + PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_METAL, 3); + PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_SPIRV, 3); + PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_GLSPIRV, 3); #undef PROFILE_SHADER_MODEL return -1; // unknown profile? } // MOJOSHADER_maxShaderModel + +const MOJOSHADER_preshader *MOJOSHADER_parsePreshader(const unsigned char *buf, + const unsigned int buflen, + MOJOSHADER_malloc m, + MOJOSHADER_free f, + void *d) +{ + MOJOSHADER_preshader *retval = NULL; + + // We need just enough Context for allocators and error state. + Context *ctx = build_context(NULL, NULL, buf, buflen, NULL, 0, NULL, 0, m, f, d); + if (ctx == NULL) + { + return retval; // !!! FIXME: Out of memory struct for MOJOSHADER_preshader + } + parse_preshader(ctx, ctx->tokens, ctx->tokencount); + if (!isfail(ctx)) + { + retval = ctx->preshader; + ctx->preshader = NULL; // don't let destroy_context() eat the retval. + } // if + + destroy_context(ctx); + return retval; +} // MOJOSHADER_parsePreshader + +void MOJOSHADER_freePreshader(const MOJOSHADER_preshader *preshader) +{ + if (preshader != NULL) + { + unsigned int i, j; + void *d = preshader->malloc_data; + MOJOSHADER_free f = preshader->free; + if (f == NULL) f = MOJOSHADER_internal_free; + + f((void *) preshader->literals, d); + for (i = 0; i < preshader->instruction_count; i++) + { + for (j = 0; j < preshader->instructions[i].operand_count; j++) + f((void *) preshader->instructions[i].operands[j].array_registers, d); + } // for + f((void *) preshader->instructions, d); + f((void *) preshader->registers, d); + free_symbols(f, d, preshader->symbols, preshader->symbol_count); + f((void *) preshader, d); + } // if +} // MOJOSHADER_freePreshader + +#if SUPPORT_PROFILE_SPIRV +#include /* SpvOp, SpvOpConvertUToF, SpvOpConvertSToF, SpvOpCopyObject */ +#endif + +int MOJOSHADER_linkSPIRVShaders(const MOJOSHADER_parseData *vertex_spirv, + const MOJOSHADER_parseData *pixel_spirv, + const MOJOSHADER_vertexAttribute *vertexAttributes, + const int vertexAttributeCount) +{ +#if SUPPORT_PROFILE_SPIRV + // We have to patch the SPIR-V output to ensure type consistency. The non-float types are: + // BYTE4 - 5 + // SHORT2 - 6 + // SHORT4 - 7 + int vDataLen = vertex_spirv->output_len - sizeof(SpirvPatchTable); + SpirvPatchTable *vTable = (SpirvPatchTable *) &vertex_spirv->output[vDataLen]; + + for (int i = 0; i < vertexAttributeCount; i += 1) + { + const MOJOSHADER_vertexAttribute *element = &vertexAttributes[i]; + uint32 typeDecl, typeLoad; + SpvOp opcodeLoad; + + if (element->vertexElementFormat >= MOJOSHADER_VERTEXELEMENTFORMAT_BYTE4 && element->vertexElementFormat <= MOJOSHADER_VERTEXELEMENTFORMAT_SHORT4) + { + const int isByte = (element->vertexElementFormat == MOJOSHADER_VERTEXELEMENTFORMAT_BYTE4); + typeDecl = isByte ? vTable->tid_uvec4_p : vTable->tid_ivec4_p; + typeLoad = isByte ? vTable->tid_uvec4 : vTable->tid_ivec4; + opcodeLoad = isByte ? SpvOpConvertUToF : SpvOpConvertSToF; + } + else + { + typeDecl = vTable->tid_vec4_p; + typeLoad = vTable->tid_vec4; + opcodeLoad = SpvOpCopyObject; + } + + uint32 typeDeclOffset = vTable->attrib_type_offsets[element->usage][element->usageIndex]; + if (typeDeclOffset > 0) // Vertex attribs passed may not exist in the vertex shader + { + ((uint32*)vertex_spirv->output)[typeDeclOffset] = typeDecl; + for (uint32 j = 0; j < vTable->attrib_type_load_offsets[element->usage][element->usageIndex].num_loads; j += 1) + { + + uint32 typeLoadOffset = vTable->attrib_type_load_offsets[element->usage][element->usageIndex].load_types[j]; + uint32 opcodeLoadOffset = vTable->attrib_type_load_offsets[element->usage][element->usageIndex].load_opcodes[j]; + if (typeLoadOffset > 0) + ((uint32*)vertex_spirv->output)[typeLoadOffset] = typeLoad; + if (opcodeLoadOffset > 0) + { + uint32* ptr_to_opcode_u32 = &((uint32*)vertex_spirv->output)[opcodeLoadOffset]; + *ptr_to_opcode_u32 = (*ptr_to_opcode_u32 & 0xFFFF0000) | opcodeLoad; + } // if + } // for + } // if + } // if + + MOJOSHADER_spirv_link_attributes(vertex_spirv, pixel_spirv, 0); + return sizeof(SpirvPatchTable); +#else + return 0; +#endif +} + // end of mojoshader.c ... diff --git a/mojoshader/mojoshader.h b/mojoshader/mojoshader.h index 87cc010..fa08032 100644 --- a/mojoshader/mojoshader.h +++ b/mojoshader/mojoshader.h @@ -27,14 +27,43 @@ extern "C" { #define MOJOSHADER_CHANGESET "???" #endif +#ifndef DECLSPEC +#if _MSC_VER && _DLL +#define DECLSPEC __declspec(dllexport) +#else +#define DECLSPEC +#endif +#endif + +#ifndef MOJOSHADERCALL +#ifdef _WIN32 +#define MOJOSHADERCALL __cdecl +#else +#define MOJOSHADERCALL +#endif +#endif + +/* -Wpedantic nameless union/struct silencing */ +#ifndef MOJOSHADERNAMELESS +#ifdef __GNUC__ +#define MOJOSHADERNAMELESS __extension__ +#else +#define MOJOSHADERNAMELESS +#endif /* __GNUC__ */ +#endif /* MOJOSHADERNAMELESS */ + /* * For determining the version of MojoShader you are using: * const int compiled_against = MOJOSHADER_VERSION; * const int linked_against = MOJOSHADER_version(); * * The version is a single integer that increments, not a major/minor value. + * + * Please note that since moving to git, this function always returns -1; + * when hosted in Mercurial, this number meant something, but even + * there it wasn't reliable. With git, this number no longer exists at all. */ -int MOJOSHADER_version(void); +DECLSPEC int MOJOSHADER_version(void); /* * For determining the revision control changeset of MojoShader you are using: @@ -47,7 +76,7 @@ int MOJOSHADER_version(void); * * Do not attempt to free this string; it's statically allocated. */ -const char *MOJOSHADER_changeset(void); +DECLSPEC const char *MOJOSHADER_changeset(void); /* * These allocators work just like the C runtime's malloc() and free() @@ -57,8 +86,8 @@ const char *MOJOSHADER_changeset(void); * callbacks, in case you need instance-specific data...it is passed through * to your allocator unmolested, and can be NULL if you like. */ -typedef void *(*MOJOSHADER_malloc)(int bytes, void *data); -typedef void (*MOJOSHADER_free)(void *ptr, void *data); +typedef void *(MOJOSHADERCALL *MOJOSHADER_malloc)(int bytes, void *data); +typedef void (MOJOSHADERCALL *MOJOSHADER_free)(void *ptr, void *data); /* @@ -71,7 +100,7 @@ typedef enum MOJOSHADER_TYPE_PIXEL = (1 << 0), MOJOSHADER_TYPE_VERTEX = (1 << 1), MOJOSHADER_TYPE_GEOMETRY = (1 << 2), /* (not supported yet.) */ - MOJOSHADER_TYPE_ANY = 0xFFFFFFFF /* used for bitmasks */ + MOJOSHADER_TYPE_ANY = 0x7FFFFFFF /* used for bitmasks */ } MOJOSHADER_shaderType; /* @@ -88,7 +117,7 @@ typedef enum MOJOSHADER_ATTRIBUTE_UINT, MOJOSHADER_ATTRIBUTE_FLOAT, MOJOSHADER_ATTRIBUTE_DOUBLE, - MOJOSHADER_ATTRIBUTE_HALF_FLOAT, /* MAYBE available in your OpenGL! */ + MOJOSHADER_ATTRIBUTE_HALF_FLOAT /* MAYBE available in your OpenGL! */ } MOJOSHADER_attributeType; /* @@ -99,7 +128,7 @@ typedef enum MOJOSHADER_UNIFORM_UNKNOWN = -1, /* housekeeping value; never returned. */ MOJOSHADER_UNIFORM_FLOAT, MOJOSHADER_UNIFORM_INT, - MOJOSHADER_UNIFORM_BOOL, + MOJOSHADER_UNIFORM_BOOL } MOJOSHADER_uniformType; /* @@ -164,7 +193,7 @@ typedef enum MOJOSHADER_SAMPLER_UNKNOWN = -1, /* housekeeping value; never returned. */ MOJOSHADER_SAMPLER_2D, MOJOSHADER_SAMPLER_CUBE, - MOJOSHADER_SAMPLER_VOLUME, + MOJOSHADER_SAMPLER_VOLUME } MOJOSHADER_samplerType; /* @@ -211,21 +240,21 @@ typedef struct MOJOSHADER_samplerMap typedef enum { MOJOSHADER_USAGE_UNKNOWN = -1, /* housekeeping value; never returned. */ - MOJOSHADER_USAGE_POSITION, - MOJOSHADER_USAGE_BLENDWEIGHT, - MOJOSHADER_USAGE_BLENDINDICES, - MOJOSHADER_USAGE_NORMAL, - MOJOSHADER_USAGE_POINTSIZE, - MOJOSHADER_USAGE_TEXCOORD, - MOJOSHADER_USAGE_TANGENT, - MOJOSHADER_USAGE_BINORMAL, - MOJOSHADER_USAGE_TESSFACTOR, - MOJOSHADER_USAGE_POSITIONT, - MOJOSHADER_USAGE_COLOR, - MOJOSHADER_USAGE_FOG, - MOJOSHADER_USAGE_DEPTH, + MOJOSHADER_USAGE_POSITION, /* 0-15 for Vertex, 1-15 for Pixel */ + MOJOSHADER_USAGE_BLENDWEIGHT, /* 0-15 */ + MOJOSHADER_USAGE_BLENDINDICES, /* 0-15 */ + MOJOSHADER_USAGE_NORMAL, /* 0-15 */ + MOJOSHADER_USAGE_POINTSIZE, /* 0-15 */ + MOJOSHADER_USAGE_TEXCOORD, /* 0-15 */ + MOJOSHADER_USAGE_TANGENT, /* 0-15 */ + MOJOSHADER_USAGE_BINORMAL, /* 0-15 */ + MOJOSHADER_USAGE_TESSFACTOR, /* 0 only */ + MOJOSHADER_USAGE_POSITIONT, /* 0-15 for Vertex, 1-15 for Pixel */ + MOJOSHADER_USAGE_COLOR, /* 0-15 but depends on MRT support */ + MOJOSHADER_USAGE_FOG, /* 0-15 */ + MOJOSHADER_USAGE_DEPTH, /* 0-15 */ MOJOSHADER_USAGE_SAMPLE, - MOJOSHADER_USAGE_TOTAL, /* housekeeping value; never returned. */ + MOJOSHADER_USAGE_TOTAL /* housekeeping value; never returned. */ } MOJOSHADER_usage; /* @@ -270,25 +299,27 @@ typedef struct MOJOSHADER_swizzle typedef enum { - MOJOSHADER_SYMREGSET_BOOL, + MOJOSHADER_SYMREGSET_BOOL=0, MOJOSHADER_SYMREGSET_INT4, MOJOSHADER_SYMREGSET_FLOAT4, MOJOSHADER_SYMREGSET_SAMPLER, + MOJOSHADER_SYMREGSET_TOTAL /* housekeeping value; never returned. */ } MOJOSHADER_symbolRegisterSet; typedef enum { - MOJOSHADER_SYMCLASS_SCALAR, + MOJOSHADER_SYMCLASS_SCALAR=0, MOJOSHADER_SYMCLASS_VECTOR, MOJOSHADER_SYMCLASS_MATRIX_ROWS, MOJOSHADER_SYMCLASS_MATRIX_COLUMNS, MOJOSHADER_SYMCLASS_OBJECT, MOJOSHADER_SYMCLASS_STRUCT, + MOJOSHADER_SYMCLASS_TOTAL /* housekeeping value; never returned. */ } MOJOSHADER_symbolClass; typedef enum { - MOJOSHADER_SYMTYPE_VOID, + MOJOSHADER_SYMTYPE_VOID=0, MOJOSHADER_SYMTYPE_BOOL, MOJOSHADER_SYMTYPE_INT, MOJOSHADER_SYMTYPE_FLOAT, @@ -308,6 +339,7 @@ typedef enum MOJOSHADER_SYMTYPE_PIXELFRAGMENT, MOJOSHADER_SYMTYPE_VERTEXFRAGMENT, MOJOSHADER_SYMTYPE_UNSUPPORTED, + MOJOSHADER_SYMTYPE_TOTAL /* housekeeping value; never returned. */ } MOJOSHADER_symbolType; typedef struct MOJOSHADER_symbolStructMember MOJOSHADER_symbolStructMember; @@ -413,24 +445,23 @@ typedef enum MOJOSHADER_preshaderOpcode MOJOSHADER_PRESHADEROP_ATAN2_SCALAR, MOJOSHADER_PRESHADEROP_DIV_SCALAR, MOJOSHADER_PRESHADEROP_DOT_SCALAR, - MOJOSHADER_PRESHADEROP_NOISE_SCALAR, + MOJOSHADER_PRESHADEROP_NOISE_SCALAR } MOJOSHADER_preshaderOpcode; typedef enum MOJOSHADER_preshaderOperandType { - MOJOSHADER_PRESHADEROPERAND_LITERAL = 1, - MOJOSHADER_PRESHADEROPERAND_INPUT = 2, - MOJOSHADER_PRESHADEROPERAND_OUTPUT = 4, - MOJOSHADER_PRESHADEROPERAND_TEMP = 7, - MOJOSHADER_PRESHADEROPERAND_UNKN = 0xff, + MOJOSHADER_PRESHADEROPERAND_INPUT, + MOJOSHADER_PRESHADEROPERAND_OUTPUT, + MOJOSHADER_PRESHADEROPERAND_LITERAL, + MOJOSHADER_PRESHADEROPERAND_TEMP } MOJOSHADER_preshaderOperandType; typedef struct MOJOSHADER_preshaderOperand { MOJOSHADER_preshaderOperandType type; unsigned int index; - int indexingType; - unsigned int indexingIndex; + unsigned int array_register_count; + unsigned int *array_registers; } MOJOSHADER_preshaderOperand; typedef struct MOJOSHADER_preshaderInstruction @@ -450,6 +481,11 @@ typedef struct MOJOSHADER_preshader MOJOSHADER_symbol *symbols; unsigned int instruction_count; MOJOSHADER_preshaderInstruction *instructions; + unsigned int register_count; + float *registers; + MOJOSHADER_malloc malloc; + MOJOSHADER_free free; + void *malloc_data; } MOJOSHADER_preshader; /* @@ -517,6 +553,16 @@ typedef struct MOJOSHADER_parseData */ int minor_ver; + /* + * This is the main function name of the shader. This will be the + * caller-supplied string even if a given profile ignores it (GLSL, + * for example, always uses "main" in the shader output out of necessity, + * and Direct3D assembly has no concept of a "main function", etc). + * Otherwise, it'll be a default name chosen by the profile ("main") or + * whatnot. + */ + const char *mainfn; + /* * The number of elements pointed to by (uniforms). */ @@ -643,6 +689,11 @@ typedef struct MOJOSHADER_parseData */ #define MOJOSHADER_PROFILE_BYTECODE "bytecode" +/* + * Profile string for HLSL Shader Model 4 output. + */ +#define MOJOSHADER_PROFILE_HLSL "hlsl" + /* * Profile string for GLSL: OpenGL high-level shader language output. */ @@ -653,6 +704,16 @@ typedef struct MOJOSHADER_parseData */ #define MOJOSHADER_PROFILE_GLSL120 "glsl120" +/* + * Profile string for GLSL ES: minor changes to GLSL output for ES compliance. + */ +#define MOJOSHADER_PROFILE_GLSLES "glsles" + +/* + * Profile string for GLSL ES: changes to GLSL output for ES 3.x compliance. + */ +#define MOJOSHADER_PROFILE_GLSLES3 "glsles3" + /* * Profile string for OpenGL ARB 1.0 shaders: GL_ARB_(vertex|fragment)_program. */ @@ -677,19 +738,25 @@ typedef struct MOJOSHADER_parseData #define MOJOSHADER_PROFILE_NV4 "nv4" /* - * Determine the highest supported Shader Model for a profile. + * Profile string for Metal: Apple's lowlevel API's high-level shader language. + */ +#define MOJOSHADER_PROFILE_METAL "metal" + +/* + * Profile string for SPIR-V binary output */ -int MOJOSHADER_maxShaderModel(const char *profile); +#define MOJOSHADER_PROFILE_SPIRV "spirv" -DLLEXPORT -const MOJOSHADER_parseData *MOJOSHADER_parseExpression(const unsigned char *tokenbuf, - const unsigned int bufsize, - MOJOSHADER_malloc m, - MOJOSHADER_free f, void *d); +/* + * Profile string for ARB_gl_spirv-friendly SPIR-V binary output + */ +#define MOJOSHADER_PROFILE_GLSPIRV "glspirv" +/* + * Determine the highest supported Shader Model for a profile. + */ +DECLSPEC int MOJOSHADER_maxShaderModel(const char *profile); -DLLEXPORT -void MOJOSHADER_runPreshader(const MOJOSHADER_preshader*, const float*, float*); /* * Parse a compiled Direct3D shader's bytecode. @@ -735,22 +802,33 @@ void MOJOSHADER_runPreshader(const MOJOSHADER_preshader*, const float*, float*); * use this to override. If you aren't sure about any of this stuff, you can * (and should) almost certainly ignore it: (smap) can be NULL. * + * (bufsize) is the size in bytes of (tokenbuf). If (bufsize) is zero, + * MojoShader will attempt to figure out the size of the buffer, but you + * risk a buffer overflow if you have corrupt data, etc. Supply the value + * if you can. + * + * You should pass a name for your shader's main function in here, via the + * (mainfn) param. Some profiles need this name to be unique. Passing a NULL + * here will pick a reasonable default, and most profiles will ignore it + * anyhow. As the name of the shader's main function, etc, so make it a + * simple name that would match C's identifier rules. Keep it simple! + * * This function is thread safe, so long as (m) and (f) are too, and that * (tokenbuf) remains intact for the duration of the call. This allows you * to parse several shaders on separate CPU cores at the same time. */ +DECLSPEC const MOJOSHADER_parseData *MOJOSHADER_parse(const char *profile, + const char *mainfn, + const unsigned char *tokenbuf, + const unsigned int bufsize, + const MOJOSHADER_swizzle *swiz, + const unsigned int swizcount, + const MOJOSHADER_samplerMap *smap, + const unsigned int smapcount, + MOJOSHADER_malloc m, + MOJOSHADER_free f, + void *d); -DLLEXPORT -const MOJOSHADER_parseData *MOJOSHADER_parse(const char *profile, - const unsigned char *tokenbuf, - const unsigned int bufsize, - const MOJOSHADER_swizzle *swiz, - const unsigned int swizcount, - const MOJOSHADER_samplerMap *smap, - const unsigned int smapcount, - MOJOSHADER_malloc m, - MOJOSHADER_free f, - void *d); /* * Call this to dispose of parsing results when you are done with them. @@ -761,1838 +839,985 @@ const MOJOSHADER_parseData *MOJOSHADER_parse(const char *profile, * This function is thread safe, so long as any allocator you passed into * MOJOSHADER_parse() is, too. */ -void MOJOSHADER_freeParseData(const MOJOSHADER_parseData *data); - - -/* Effects interface... */ /* !!! FIXME: THIS API IS NOT STABLE YET! */ - -typedef struct MOJOSHADER_effectParam -{ - const char *name; - const char *semantic; -} MOJOSHADER_effectParam; - -typedef struct MOJOSHADER_effectState -{ - unsigned int type; -} MOJOSHADER_effectState; - -typedef struct MOJOSHADER_effectPass -{ - const char *name; - unsigned int state_count; - MOJOSHADER_effectState *states; -} MOJOSHADER_effectPass; - -typedef struct MOJOSHADER_effectTechnique -{ - const char *name; - unsigned int pass_count; - MOJOSHADER_effectPass *passes; -} MOJOSHADER_effectTechnique; - -typedef struct MOJOSHADER_effectTexture -{ - unsigned int param; - const char *name; -} MOJOSHADER_effectTexture; +DECLSPEC void MOJOSHADER_freeParseData(const MOJOSHADER_parseData *data); -typedef struct MOJOSHADER_effectShader -{ - unsigned int technique; - unsigned int pass; - const MOJOSHADER_parseData *shader; -} MOJOSHADER_effectShader; /* - * Structure used to return data from parsing of an effect file... + * You almost certainly don't need this function, unless you absolutely know + * why you need it without hesitation. This is useful if you're doing + * extremely low-level shader work or building specialized tools. + * + * Parse a preshader structure. This expects a buffer of bytes that represents + * the preshader data starting with its magic number token and ending at + * the end of the comment tokens that contain this preshader. Note that it + * does _not_ start at the beginning of the comment tokens. + * + * On success, this will return a MOJOSHADER_preshader. This can be + * deallocated later by calling MOJOSHADER_freePreshader(). On failure, + * this will return NULL. Unlike other MojoShader APIs, this assumes you + * either have a complete and valid buffer of preshader tokens or you have + * incomplete/corrupted data, so there is no explicit error reporting. Please + * note that if the system runs out of memory, this function will also return + * NULL without distinction. + * + * This function is thread safe, so long as any allocator you passed into + * MOJOSHADER_parsePreshader() is, too. */ -/* !!! FIXME: most of these ints should be unsigned. */ -typedef struct MOJOSHADER_effect -{ - /* - * The number of elements pointed to by (errors). - */ - int error_count; - - /* - * (error_count) elements of data that specify errors that were generated - * by parsing this shader. - * This can be NULL if there were no errors or if (error_count) is zero. - */ - MOJOSHADER_error *errors; - - /* - * The name of the profile used to parse the shader. Will be NULL on error. - */ - const char *profile; - - /* - * The number of params pointed to by (params). - */ - int param_count; - - /* - * (param_count) elements of data that specify parameter bind points for - * this effect. - * This can be NULL on error or if (param_count) is zero. - */ - MOJOSHADER_effectParam *params; - - /* - * The number of elements pointed to by (techniques). - */ - int technique_count; - - /* - * (technique_count) elements of data that specify techniques used in - * this effect. Each technique contains a series of passes, and each pass - * specifies state and shaders that affect rendering. - * This can be NULL on error or if (technique_count) is zero. - */ - MOJOSHADER_effectTechnique *techniques; - - /* - * The number of elements pointed to by (textures). - */ - int texture_count; - - /* - * (texture_count) elements of data that specify textures used in - * this effect. - * This can be NULL on error or if (texture_count) is zero. - */ - MOJOSHADER_effectTexture *textures; - - /* - * The number of elements pointed to by (shaders). - */ - int shader_count; - - /* - * (shader_count) elements of data that specify shaders used in - * this effect. - * This can be NULL on error or if (shader_count) is zero. - */ - MOJOSHADER_effectShader *shaders; - - /* - * This is the malloc implementation you passed to MOJOSHADER_parseEffect(). - */ - MOJOSHADER_malloc malloc; - - /* - * This is the free implementation you passed to MOJOSHADER_parseEffect(). - */ - MOJOSHADER_free free; - - /* - * This is the pointer you passed as opaque data for your allocator. - */ - void *malloc_data; -} MOJOSHADER_effect; - -/* !!! FIXME: document me. */ -const MOJOSHADER_effect *MOJOSHADER_parseEffect(const char *profile, - const unsigned char *buf, - const unsigned int _len, - const MOJOSHADER_swizzle *swiz, - const unsigned int swizcount, - const MOJOSHADER_samplerMap *smap, - const unsigned int smapcount, - MOJOSHADER_malloc m, - MOJOSHADER_free f, - void *d); - - -/* !!! FIXME: document me. */ -void MOJOSHADER_freeEffect(const MOJOSHADER_effect *effect); +DECLSPEC const MOJOSHADER_preshader *MOJOSHADER_parsePreshader(const unsigned char *buf, + const unsigned int len, + MOJOSHADER_malloc m, + MOJOSHADER_free f, + void *d); -/* Preprocessor interface... */ - /* - * Structure used to pass predefined macros. Maps to D3DXMACRO. - * You can have macro arguments: set identifier to "a(b, c)" or whatever. + * You almost certainly don't need this function, unless you absolutely know + * why you need it without hesitation. This is useful if you're doing + * extremely low-level shader work or building specialized tools. + * + * Call this to dispose of preshader parsing results when you are done with + * them. This will call the MOJOSHADER_free function you provided to + * MOJOSHADER_parsePreshader() multiple times, if you provided one. + * Passing a NULL here is a safe no-op. + * + * You only need to call this function for results from a call to + * MOJOSHADER_parsePreshader(). Other MojoShader structures with a preshader + * field, such as MOJOSHADER_parseData(), should not use this function, as + * the preshader will be deallocated with everything else in + * MOJOSHADER_freeParseData(), etc. + * + * This function is thread safe, so long as any allocator you passed into + * MOJOSHADER_parsePreshader() is, too. */ -typedef struct MOJOSHADER_preprocessorDefine -{ - const char *identifier; - const char *definition; -} MOJOSHADER_preprocessorDefine; +DECLSPEC void MOJOSHADER_freePreshader(const MOJOSHADER_preshader *preshader); + + +/* SPIR-V interface... */ -/* - * Used with the MOJOSHADER_includeOpen callback. Maps to D3DXINCLUDE_TYPE. - */ typedef enum { - MOJOSHADER_INCLUDETYPE_LOCAL, /* local header: #include "blah.h" */ - MOJOSHADER_INCLUDETYPE_SYSTEM /* system header: #include */ -} MOJOSHADER_includeType; - + MOJOSHADER_VERTEXELEMENTFORMAT_SINGLE, + MOJOSHADER_VERTEXELEMENTFORMAT_VECTOR2, + MOJOSHADER_VERTEXELEMENTFORMAT_VECTOR3, + MOJOSHADER_VERTEXELEMENTFORMAT_VECTOR4, + MOJOSHADER_VERTEXELEMENTFORMAT_COLOR, + MOJOSHADER_VERTEXELEMENTFORMAT_BYTE4, + MOJOSHADER_VERTEXELEMENTFORMAT_SHORT2, + MOJOSHADER_VERTEXELEMENTFORMAT_SHORT4, + MOJOSHADER_VERTEXELEMENTFORMAT_NORMALIZEDSHORT2, + MOJOSHADER_VERTEXELEMENTFORMAT_NORMALIZEDSHORT4, + MOJOSHADER_VERTEXELEMENTFORMAT_HALFVECTOR2, + MOJOSHADER_VERTEXELEMENTFORMAT_HALFVECTOR4 +} MOJOSHADER_vertexElementFormat; + +typedef struct MOJOSHADER_vertexAttribute +{ + MOJOSHADER_usage usage; + MOJOSHADER_vertexElementFormat vertexElementFormat; + int usageIndex; +} MOJOSHADER_vertexAttribute; /* - * Structure used to return data from preprocessing of a shader... + * You almost certainly don't need this function, unless you absolutely know + * why you need it without hesitation. This is useful if you're doing + * extremely low-level shader work or building specialized tools. + * + * Call this to patch SPIR-V output returned from MOJOSHADER_parse to correctly + * interpret vertex input and link vertex shader output to pixel shader input. + * + * On success, this returns the size of the shaders' internal "patch table", + * which should be subtracted from the parseData's output_len when passing the + * final SPIR-V to your shader compiler. */ -/* !!! FIXME: most of these ints should be unsigned. */ -typedef struct MOJOSHADER_preprocessData -{ - /* - * The number of elements pointed to by (errors). - */ - int error_count; - - /* - * (error_count) elements of data that specify errors that were generated - * by parsing this shader. - * This can be NULL if there were no errors or if (error_count) is zero. - */ - MOJOSHADER_error *errors; - - /* - * Bytes of output from preprocessing. This is a UTF-8 string. We - * guarantee it to be NULL-terminated. Will be NULL on error. - */ - const char *output; - - /* - * Byte count for output, not counting any null terminator. - * Will be 0 on error. - */ - int output_len; - - /* - * This is the malloc implementation you passed to MOJOSHADER_parse(). - */ - MOJOSHADER_malloc malloc; - - /* - * This is the free implementation you passed to MOJOSHADER_parse(). - */ - MOJOSHADER_free free; +DECLSPEC int MOJOSHADER_linkSPIRVShaders(const MOJOSHADER_parseData *vertex_spirv, + const MOJOSHADER_parseData *pixel_spirv, + const MOJOSHADER_vertexAttribute *vertexAttributes, + const int vertexAttributeCount); - /* - * This is the pointer you passed as opaque data for your allocator. - */ - void *malloc_data; -} MOJOSHADER_preprocessData; +/* OpenGL interface... */ /* - * This callback allows an app to handle #include statements for the - * preprocessor. When the preprocessor sees an #include, it will call this - * function to obtain the contents of the requested file. This is optional; - * the preprocessor will open files directly if no callback is supplied, but - * this allows an app to retrieve data from something other than the - * traditional filesystem (for example, headers packed in a .zip file or - * headers generated on-the-fly). - * - * This function maps to ID3DXInclude::Open() - * - * (inctype) specifies the type of header we wish to include. - * (fname) specifies the name of the file specified on the #include line. - * (parent) is a string of the entire source file containing the include, in - * its original, not-yet-preprocessed state. Note that this is just the - * contents of the specific file, not all source code that the preprocessor - * has seen through other includes, etc. - * (outdata) will be set by the callback to a pointer to the included file's - * contents. The callback is responsible for allocating this however they - * see fit (we provide allocator functions, but you may ignore them). This - * pointer must remain valid until the includeClose callback runs. This - * string does not need to be NULL-terminated. - * (outbytes) will be set by the callback to the number of bytes pointed to - * by (outdata). - * (m),(f), and (d) are the allocator details that the application passed to - * MojoShader. If these were NULL, MojoShader may have replaced them with its - * own internal allocators. + * Signature for function lookup callbacks. MojoShader will call a function + * you provide to get OpenGL entry points (both standard functions and + * extensions). Through this, MojoShader never links directly to OpenGL, + * but relies on you to provide the implementation. This means you can + * swap in different drivers, or hook functions (log every GL call MojoShader + * makes, etc). * - * The callback returns zero on error, non-zero on success. + * (fnname) is the function name we want the address for ("glBegin" or + * whatever. (data) is a void pointer you provide, if this callback needs + * extra information. If you don't need it, you may specify NULL. * - * If you supply an includeOpen callback, you must supply includeClose, too. + * Return the entry point on success, NULL if it couldn't be found. + * Note that this could ask for standard entry points like glEnable(), or + * extensions like glProgramLocalParameterI4ivNV(), so you might need + * to check two places to find the desired entry point, depending on your + * platform (Windows might need to look in OpenGL32.dll and use WGL, etc). */ -typedef int (*MOJOSHADER_includeOpen)(MOJOSHADER_includeType inctype, - const char *fname, const char *parent, - const char **outdata, unsigned int *outbytes, - MOJOSHADER_malloc m, MOJOSHADER_free f, void *d); +typedef void *(MOJOSHADERCALL *MOJOSHADER_glGetProcAddress)(const char *fnname, void *data); + /* - * This callback allows an app to clean up the results of a previous - * includeOpen callback. - * - * This function maps to ID3DXInclude::Close() + * "Contexts" map to OpenGL contexts...you need one per window, or whatever, + * and need to inform MojoShader when you make a new one current. * - * (data) is the data that was returned from a previous call to includeOpen. - * It is now safe to deallocate this data. - * (m),(f), and (d) are the same allocator details that were passed to your - * includeOpen callback. + * "Shaders" refer to individual vertex or pixel programs, and are created + * by "compiling" Direct3D shader bytecode. A vertex and pixel shader are + * "linked" into a "Program" before you can use them to render. * - * If you supply an includeClose callback, you must supply includeOpen, too. + * To the calling application, these are all opaque handles. */ -typedef void (*MOJOSHADER_includeClose)(const char *data, - MOJOSHADER_malloc m, MOJOSHADER_free f, void *d); +typedef struct MOJOSHADER_glContext MOJOSHADER_glContext; +typedef struct MOJOSHADER_glShader MOJOSHADER_glShader; +typedef struct MOJOSHADER_glProgram MOJOSHADER_glProgram; /* - * This function is optional. Even if you are dealing with shader source - * code, you don't need to explicitly use the preprocessor, as the compiler - * and assembler will use it behind the scenes. In fact, you probably never - * need this function unless you are debugging a custom tool (or debugging - * MojoShader itself). - * - * Preprocessing roughly follows the syntax of an ANSI C preprocessor, as - * Microsoft's Direct3D assembler and HLSL compiler use this syntax. Please - * note that we try to match the output you'd get from Direct3D's - * preprocessor, which has some quirks if you're expecting output that matches - * a generic C preprocessor. - * - * This function maps to D3DXPreprocessShader(). - * - * (filename) is a NULL-terminated UTF-8 filename. It can be NULL. We do not - * actually access this file, as we obtain our data from (source). This - * string is copied when we need to report errors while processing (source), - * as opposed to errors in a file referenced via the #include directive in - * (source). If this is NULL, then errors will report the filename as NULL, - * too. - * - * (source) is an string of UTF-8 text to preprocess. It does not need to be - * NULL-terminated. - * - * (sourcelen) is the length of the string pointed to by (source), in bytes. - * - * (defines) points to (define_count) preprocessor definitions, and can be - * NULL. These are treated by the preprocessor as if the source code started - * with one #define for each entry you pass in here. - * - * (include_open) and (include_close) let the app control the preprocessor's - * behaviour for #include statements. Both are optional and can be NULL, but - * both must be specified if either is specified. + * Get a list of available profiles. This will fill in the array (profs) + * with up to (size) pointers of profiles that the current system can handle; + * that is, the profiles are built into MojoShader and the OpenGL extensions + * required for them exist at runtime. This function returns the number of + * available profiles, which may be more, less, or equal to (size). * - * This will return a MOJOSHADER_preprocessorData. You should pass this - * return value to MOJOSHADER_freePreprocessData() when you are done with - * it. + * If there are more than (size) profiles, the (profs) buffer will not + * overflow. You can check the return value for the total number of + * available profiles, allocate more space, and try again if necessary. + * Calling this function with (size) == 0 is legal. * - * This function will never return NULL, even if the system is completely - * out of memory upon entry (in which case, this function returns a static - * MOJOSHADER_preprocessData object, which is still safe to pass to - * MOJOSHADER_freePreprocessData()). + * You can only call this AFTER you have successfully built your GL context + * and made it current. This function will lookup the GL functions it needs + * through the callback you supply, via (lookup) and (lookup_d). The lookup + * function is neither stored nor used by MojoShader after this function + * returns, nor are the functions it might look up. * - * As preprocessing requires some memory to be allocated, you may provide a + * As MojoShader requires some memory to be allocated, you may provide a * custom allocator to this function, which will be used to allocate/free * memory. They function just like malloc() and free(). We do not use * realloc(). If you don't care, pass NULL in for the allocator functions. * If your allocator needs instance-specific data, you may supply it with the - * (d) parameter. This pointer is passed as-is to your (m) and (f) functions. - * - * This function is thread safe, so long as the various callback functions - * are, too, and that the parameters remains intact for the duration of the - * call. This allows you to preprocess several shaders on separate CPU cores - * at the same time. - */ -const MOJOSHADER_preprocessData *MOJOSHADER_preprocess(const char *filename, - const char *source, unsigned int sourcelen, - const MOJOSHADER_preprocessorDefine *defines, - unsigned int define_count, - MOJOSHADER_includeOpen include_open, - MOJOSHADER_includeClose include_close, - MOJOSHADER_malloc m, MOJOSHADER_free f, void *d); - - -/* - * Call this to dispose of preprocessing results when you are done with them. - * This will call the MOJOSHADER_free function you provided to - * MOJOSHADER_preprocess() multiple times, if you provided one. - * Passing a NULL here is a safe no-op. + * (malloc_d) parameter. This pointer is passed as-is to your (m) and (f) + * functions. * - * This function is thread safe, so long as any allocator you passed into - * MOJOSHADER_preprocess() is, too. + * You should not free any strings returned from this function; they are + * pointers to internal, probably static, memory. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. */ -void MOJOSHADER_freePreprocessData(const MOJOSHADER_preprocessData *data); - +DECLSPEC int MOJOSHADER_glAvailableProfiles(MOJOSHADER_glGetProcAddress lookup, + void *lookup_d, + const char **profs, const int size, + MOJOSHADER_malloc m, MOJOSHADER_free f, + void *malloc_d); -/* Assembler interface... */ /* - * This function is optional. Use this to convert Direct3D shader assembly - * language into bytecode, which can be handled by MOJOSHADER_parse(). + * Determine the best profile to use for the current system. * - * (filename) is a NULL-terminated UTF-8 filename. It can be NULL. We do not - * actually access this file, as we obtain our data from (source). This - * string is copied when we need to report errors while processing (source), - * as opposed to errors in a file referenced via the #include directive in - * (source). If this is NULL, then errors will report the filename as NULL, - * too. + * You can only call this AFTER you have successfully built your GL context + * and made it current. This function will lookup the GL functions it needs + * through the callback you supply via (lookup) and (lookup_d). The lookup + * function is neither stored nor used by MojoShader after this function + * returns, nor are the functions it might look up. * - * (source) is an UTF-8 string of valid Direct3D shader assembly source code. - * It does not need to be NULL-terminated. + * Returns the name of the "best" profile on success, NULL if none of the + * available profiles will work on this system. "Best" is a relative term, + * but it generally means the best trade off between feature set and + * performance. The selection algorithm may be arbitrary and complex. * - * (sourcelen) is the length of the string pointed to by (source), in bytes. + * As MojoShader requires some memory to be allocated, you may provide a + * custom allocator to this function, which will be used to allocate/free + * memory. They function just like malloc() and free(). We do not use + * realloc(). If you don't care, pass NULL in for the allocator functions. + * If your allocator needs instance-specific data, you may supply it with the + * (malloc_d) parameter. This pointer is passed as-is to your (m) and (f) + * functions. * - * (comments) points to (comment_count) NULL-terminated UTF-8 strings, and - * can be NULL. These strings are inserted as comments in the bytecode. + * The returned value is an internal static string, and should not be free()'d + * by the caller. If you get a NULL, calling MOJOSHADER_glGetError() might + * shed some light on why. * - * (symbols) points to (symbol_count) symbol structs, and can be NULL. These - * become a CTAB field in the bytecode. This is optional, but - * MOJOSHADER_parse() needs CTAB data for all arrays used in a program, or - * relative addressing will not be permitted, so you'll want to at least - * provide symbol information for those. The symbol data is 100% trusted - * at this time; it will not be checked to see if it matches what was - * assembled in any way whatsoever. + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + */ +DECLSPEC const char *MOJOSHADER_glBestProfile(MOJOSHADER_glGetProcAddress lookup, + void *lookup_d, + MOJOSHADER_malloc m, MOJOSHADER_free f, + void *malloc_d); + +/* + * Prepare MojoShader to manage OpenGL shaders. * - * (defines) points to (define_count) preprocessor definitions, and can be - * NULL. These are treated by the preprocessor as if the source code started - * with one #define for each entry you pass in here. + * You do not need to call this if all you want is MOJOSHADER_parse(). * - * (include_open) and (include_close) let the app control the preprocessor's - * behaviour for #include statements. Both are optional and can be NULL, but - * both must be specified if either is specified. + * You must call this once AFTER you have successfully built your GL context + * and made it current. This function will lookup the GL functions it needs + * through the callback you supply via (lookup) and (lookup_d), after which + * it may call them at any time up until you call + * MOJOSHADER_glDestroyContext(). The lookup function is neither stored nor + * used by MojoShader after this function returns. * - * This will return a MOJOSHADER_parseData, like MOJOSHADER_parse() would, - * except the profile will be MOJOSHADER_PROFILE_BYTECODE and the output - * will be the assembled bytecode instead of some other language. This output - * can be pushed back through MOJOSHADER_parseData() with a different profile. + * (profile) is an OpenGL-specific MojoShader profile, which decides how + * Direct3D bytecode shaders get turned into OpenGL programs, and how they + * are fed to the GL. * - * This function will never return NULL, even if the system is completely - * out of memory upon entry (in which case, this function returns a static - * MOJOSHADER_parseData object, which is still safe to pass to - * MOJOSHADER_freeParseData()). + * (lookup) is a callback that is used to load GL entry points. This callback + * has to look up base GL functions and extension entry points. The pointer + * you supply in (lookup_d) is passed as-is to the callback. * - * As assembling requires some memory to be allocated, you may provide a + * As MojoShader requires some memory to be allocated, you may provide a * custom allocator to this function, which will be used to allocate/free * memory. They function just like malloc() and free(). We do not use * realloc(). If you don't care, pass NULL in for the allocator functions. * If your allocator needs instance-specific data, you may supply it with the - * (d) parameter. This pointer is passed as-is to your (m) and (f) functions. + * (malloc_d) parameter. This pointer is passed as-is to your (m) and (f) + * functions. + * + * Returns a new context on success, NULL on error. If you get a new context, + * you need to make it current before using it with + * MOJOSHADER_glMakeContextCurrent(). * - * This function is thread safe, so long as the various callback functions - * are, too, and that the parameters remains intact for the duration of the - * call. This allows you to assemble several shaders on separate CPU cores - * at the same time. + * This call is NOT thread safe! It must return success before you may call + * any other MOJOSHADER_gl* function. Also, as most OpenGL implementations + * are not thread safe, you should probably only call this from the same + * thread that created the GL context. */ -const MOJOSHADER_parseData *MOJOSHADER_assemble(const char *filename, - const char *source, unsigned int sourcelen, - const char **comments, unsigned int comment_count, - const MOJOSHADER_symbol *symbols, - unsigned int symbol_count, - const MOJOSHADER_preprocessorDefine *defines, - unsigned int define_count, - MOJOSHADER_includeOpen include_open, - MOJOSHADER_includeClose include_close, - MOJOSHADER_malloc m, MOJOSHADER_free f, void *d); - - -/* High level shading language support... */ +DECLSPEC MOJOSHADER_glContext *MOJOSHADER_glCreateContext(const char *profile, + MOJOSHADER_glGetProcAddress lookup, + void *lookup_d, + MOJOSHADER_malloc m, MOJOSHADER_free f, + void *malloc_d); /* - * Source profile strings for HLSL: Direct3D High Level Shading Language. + * You must call this before using the context that you got from + * MOJOSHADER_glCreateContext(), and must use it when you switch to a new GL + * context. + * + * You can only have one MOJOSHADER_glContext per actual GL context, or + * undefined behaviour will result. + * + * It is legal to call this with a NULL pointer to make no context current, + * but you need a valid context to be current to use most of MojoShader. + * + * In current times, this allows one context to be current _per thread_, + * as the internal state inside MojoShader is marked thread local. Each + * new thread should call this function before using the context, even if + * other threads have previously set it current. You _also_ have to set + * the OpenGL context itself current for each thread (and have an OpenGL + * implementation that allows that in the first place). */ -#define MOJOSHADER_SRC_PROFILE_HLSL_VS_1_1 "hlsl_vs_1_1" -#define MOJOSHADER_SRC_PROFILE_HLSL_VS_2_0 "hlsl_vs_2_0" -#define MOJOSHADER_SRC_PROFILE_HLSL_VS_3_0 "hlsl_vs_3_0" -#define MOJOSHADER_SRC_PROFILE_HLSL_PS_1_1 "hlsl_ps_1_1" -#define MOJOSHADER_SRC_PROFILE_HLSL_PS_1_2 "hlsl_ps_1_2" -#define MOJOSHADER_SRC_PROFILE_HLSL_PS_1_3 "hlsl_ps_1_3" -#define MOJOSHADER_SRC_PROFILE_HLSL_PS_1_4 "hlsl_ps_1_4" -#define MOJOSHADER_SRC_PROFILE_HLSL_PS_2_0 "hlsl_ps_2_0" -#define MOJOSHADER_SRC_PROFILE_HLSL_PS_3_0 "hlsl_ps_3_0" - - -/* Abstract Syntax Tree interface... */ +DECLSPEC void MOJOSHADER_glMakeContextCurrent(MOJOSHADER_glContext *ctx); /* - * ATTENTION: This adds a lot of stuff to the API, but almost everyone can - * ignore this section. Seriously, go ahead and skip over anything that has - * "AST" in it, unless you know why you'd want to use it. + * Get any error state we might have picked up. MojoShader will NOT call + * glGetError() internally, but there are other errors we can pick up, + * such as failed shader compilation, etc. + * + * Returns a human-readable string. This string is for debugging purposes, and + * not guaranteed to be localized, coherent, or user-friendly in any way. + * It's for programmers! + * + * The latest error may remain between calls. New errors replace any existing + * error. Don't check this string for a sign that an error happened, check + * return codes instead and use this for explanation when debugging. + * + * Do not free the returned string: it's a pointer to a static internal + * buffer. Do not keep the pointer around, either, as it's likely to become + * invalid as soon as you call into MojoShader again. * - * ALSO: This API is still evolving! We make no promises at this time to keep - * source or binary compatibility for the AST pieces. + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. * - * Important notes: - * - ASTs are the result of parsing the source code: a program that fails to - * compile will often parse successfully. Undeclared variables, - * type incompatibilities, etc, aren't detected at this point. - * - Vector swizzles (the ".xyzw" part of "MyVec4.xyzw") will look like - * structure dereferences. We don't realize these are actually swizzles - * until semantic analysis. - * - MOJOSHADER_astDataType info is not reliable when returned from - * MOJOSHADER_parseAst()! Most of the datatype info will be missing or have - * inaccurate data types. We sort these out during semantic analysis, which - * happens after the AST parsing is complete. A few are filled in, or can - * be deduced fairly trivially by processing several pieces into one. - * It's enough that you can reproduce the original source code, more or - * less, from the AST. + * This call does NOT require a valid MOJOSHADER_glContext to have been made + * current. The error buffer is shared between contexts, so you can get + * error results from a failed MOJOSHADER_glCreateContext(). */ +DECLSPEC const char *MOJOSHADER_glGetError(void); -/* High-level datatypes for AST nodes. */ -typedef enum MOJOSHADER_astDataTypeType -{ - MOJOSHADER_AST_DATATYPE_NONE, - MOJOSHADER_AST_DATATYPE_BOOL, - MOJOSHADER_AST_DATATYPE_INT, - MOJOSHADER_AST_DATATYPE_UINT, - MOJOSHADER_AST_DATATYPE_FLOAT, - MOJOSHADER_AST_DATATYPE_FLOAT_SNORM, - MOJOSHADER_AST_DATATYPE_FLOAT_UNORM, - MOJOSHADER_AST_DATATYPE_HALF, - MOJOSHADER_AST_DATATYPE_DOUBLE, - MOJOSHADER_AST_DATATYPE_STRING, - MOJOSHADER_AST_DATATYPE_SAMPLER_1D, - MOJOSHADER_AST_DATATYPE_SAMPLER_2D, - MOJOSHADER_AST_DATATYPE_SAMPLER_3D, - MOJOSHADER_AST_DATATYPE_SAMPLER_CUBE, - MOJOSHADER_AST_DATATYPE_SAMPLER_STATE, - MOJOSHADER_AST_DATATYPE_SAMPLER_COMPARISON_STATE, - MOJOSHADER_AST_DATATYPE_STRUCT, - MOJOSHADER_AST_DATATYPE_ARRAY, - MOJOSHADER_AST_DATATYPE_VECTOR, - MOJOSHADER_AST_DATATYPE_MATRIX, - MOJOSHADER_AST_DATATYPE_BUFFER, - MOJOSHADER_AST_DATATYPE_FUNCTION, - MOJOSHADER_AST_DATATYPE_USER, -} MOJOSHADER_astDataTypeType; -#define MOJOSHADER_AST_DATATYPE_CONST (1 << 31) - -typedef union MOJOSHADER_astDataType MOJOSHADER_astDataType; - -// This is just part of DataTypeStruct, never appears outside of it. -typedef struct MOJOSHADER_astDataTypeStructMember -{ - const MOJOSHADER_astDataType *datatype; - const char *identifier; -} MOJOSHADER_astDataTypeStructMember; - -typedef struct MOJOSHADER_astDataTypeStruct -{ - MOJOSHADER_astDataTypeType type; - const MOJOSHADER_astDataTypeStructMember *members; - int member_count; -} MOJOSHADER_astDataTypeStruct; - -typedef struct MOJOSHADER_astDataTypeArray -{ - MOJOSHADER_astDataTypeType type; - const MOJOSHADER_astDataType *base; - int elements; -} MOJOSHADER_astDataTypeArray; - -typedef MOJOSHADER_astDataTypeArray MOJOSHADER_astDataTypeVector; +/* + * Get the maximum uniforms a shader can support for the current GL context, + * MojoShader profile, and shader type. You can use this to make decisions + * about what shaders you want to use (for example, a less complicated + * shader may be swapped in for lower-end systems). + * + * Returns the number, or -1 on error. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + */ +DECLSPEC int MOJOSHADER_glMaxUniforms(MOJOSHADER_shaderType shader_type); -typedef struct MOJOSHADER_astDataTypeMatrix -{ - MOJOSHADER_astDataTypeType type; - const MOJOSHADER_astDataType *base; - int rows; - int columns; -} MOJOSHADER_astDataTypeMatrix; +/* + * Compile a buffer of Direct3D shader bytecode into an OpenGL shader. + * You still need to link the shader before you may render with it. + * + * (tokenbuf) is a buffer of Direct3D shader bytecode. + * (bufsize) is the size, in bytes, of the bytecode buffer. + * (swiz), (swizcount), (smap), and (smapcount) are passed to + * MOJOSHADER_parse() unmolested. + * + * Returns NULL on error, or a shader handle on success. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * + * Compiled shaders from this function may not be shared between contexts. + */ +DECLSPEC MOJOSHADER_glShader *MOJOSHADER_glCompileShader(const unsigned char *tokenbuf, + const unsigned int bufsize, + const MOJOSHADER_swizzle *swiz, + const unsigned int swizcount, + const MOJOSHADER_samplerMap *smap, + const unsigned int smapcount); -typedef struct MOJOSHADER_astDataTypeBuffer -{ - MOJOSHADER_astDataTypeType type; - const MOJOSHADER_astDataType *base; -} MOJOSHADER_astDataTypeBuffer; +/* + * Increments a shader's internal refcount. To decrement the refcount, call + * MOJOSHADER_glDeleteShader(). + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + */ +DECLSPEC void MOJOSHADER_glShaderAddRef(MOJOSHADER_glShader *shader); -typedef struct MOJOSHADER_astDataTypeFunction -{ - MOJOSHADER_astDataTypeType type; - const MOJOSHADER_astDataType *retval; - const MOJOSHADER_astDataType **params; - int num_params; - int intrinsic; /* non-zero for built-in functions */ -} MOJOSHADER_astDataTypeFunction; - -typedef struct MOJOSHADER_astDataTypeUser -{ - MOJOSHADER_astDataTypeType type; - const MOJOSHADER_astDataType *details; - const char *name; -} MOJOSHADER_astDataTypeUser; +/* + * Get the MOJOSHADER_parseData structure that was produced from the + * call to MOJOSHADER_glCompileShader(). + * + * This data is read-only, and you should NOT attempt to free it. This + * pointer remains valid until the shader is deleted. + */ +DECLSPEC const MOJOSHADER_parseData *MOJOSHADER_glGetShaderParseData( + MOJOSHADER_glShader *shader); +/* + * Link a vertex and pixel shader into an OpenGL program. + * (vshader) or (pshader) can be NULL, to specify that the GL should use the + * fixed-function pipeline instead of the programmable pipeline for that + * portion of the work. You can reuse shaders in various combinations across + * multiple programs, by relinking different pairs. + * + * It is illegal to give a vertex shader for (pshader) or a pixel shader + * for (vshader). + * + * Once you have successfully linked a program, you may render with it. + * + * Returns NULL on error, or a program handle on success. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * + * Linked programs from this function may not be shared between contexts. + */ +DECLSPEC MOJOSHADER_glProgram *MOJOSHADER_glLinkProgram(MOJOSHADER_glShader *vshader, + MOJOSHADER_glShader *pshader); -union MOJOSHADER_astDataType -{ - MOJOSHADER_astDataTypeType type; - MOJOSHADER_astDataTypeArray array; - MOJOSHADER_astDataTypeStruct structure; - MOJOSHADER_astDataTypeVector vector; - MOJOSHADER_astDataTypeMatrix matrix; - MOJOSHADER_astDataTypeBuffer buffer; - MOJOSHADER_astDataTypeUser user; - MOJOSHADER_astDataTypeFunction function; -}; +/* + * This binds the program (using, for example, glUseProgramObjectARB()), and + * disables all the client-side arrays so we can reset them with new values + * if appropriate. + * + * Call with NULL to disable the programmable pipeline and all enabled + * client-side arrays. + * + * After binding a program, you should update any uniforms you care about + * with MOJOSHADER_glSetVertexShaderUniformF() (etc), set any vertex arrays + * you want to use with MOJOSHADER_glSetVertexAttribute(), and finally call + * MOJOSHADER_glProgramReady() to commit everything to the GL. Then you may + * begin drawing through standard GL entry points. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + */ +DECLSPEC void MOJOSHADER_glBindProgram(MOJOSHADER_glProgram *program); -/* Structures that make up the parse tree... */ +/* + * This binds individual shaders as if you had linked them with + * MOJOSHADER_glLinkProgram(), and used MOJOSHADER_glBindProgram() on the + * linked result. + * + * MojoShader will handle linking behind the scenes, and keep a cache of + * programs linked here. Programs are removed from this cache when one of the + * invidual shaders in it is deleted, otherwise they remain cached so future + * calls to this function don't need to relink a previously-used shader + * grouping. + * + * This function is for convenience, as the API is closer to how Direct3D + * works, and retrofitting linking into your app can be difficult; + * frequently, you just end up building your own cache, anyhow. + * + * Calling with all shaders set to NULL is equivalent to calling + * MOJOSHADER_glBindProgram(NULL). + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + */ +DECLSPEC void MOJOSHADER_glBindShaders(MOJOSHADER_glShader *vshader, + MOJOSHADER_glShader *pshader); -typedef enum MOJOSHADER_astNodeType -{ - MOJOSHADER_AST_OP_START_RANGE, /* expression operators. */ - - MOJOSHADER_AST_OP_START_RANGE_UNARY, /* unary operators. */ - MOJOSHADER_AST_OP_PREINCREMENT, - MOJOSHADER_AST_OP_PREDECREMENT, - MOJOSHADER_AST_OP_NEGATE, - MOJOSHADER_AST_OP_COMPLEMENT, - MOJOSHADER_AST_OP_NOT, - MOJOSHADER_AST_OP_POSTINCREMENT, - MOJOSHADER_AST_OP_POSTDECREMENT, - MOJOSHADER_AST_OP_CAST, - MOJOSHADER_AST_OP_END_RANGE_UNARY, - - MOJOSHADER_AST_OP_START_RANGE_BINARY, /* binary operators. */ - MOJOSHADER_AST_OP_COMMA, - MOJOSHADER_AST_OP_MULTIPLY, - MOJOSHADER_AST_OP_DIVIDE, - MOJOSHADER_AST_OP_MODULO, - MOJOSHADER_AST_OP_ADD, - MOJOSHADER_AST_OP_SUBTRACT, - MOJOSHADER_AST_OP_LSHIFT, - MOJOSHADER_AST_OP_RSHIFT, - MOJOSHADER_AST_OP_LESSTHAN, - MOJOSHADER_AST_OP_GREATERTHAN, - MOJOSHADER_AST_OP_LESSTHANOREQUAL, - MOJOSHADER_AST_OP_GREATERTHANOREQUAL, - MOJOSHADER_AST_OP_EQUAL, - MOJOSHADER_AST_OP_NOTEQUAL, - MOJOSHADER_AST_OP_BINARYAND, - MOJOSHADER_AST_OP_BINARYXOR, - MOJOSHADER_AST_OP_BINARYOR, - MOJOSHADER_AST_OP_LOGICALAND, - MOJOSHADER_AST_OP_LOGICALOR, - MOJOSHADER_AST_OP_ASSIGN, - MOJOSHADER_AST_OP_MULASSIGN, - MOJOSHADER_AST_OP_DIVASSIGN, - MOJOSHADER_AST_OP_MODASSIGN, - MOJOSHADER_AST_OP_ADDASSIGN, - MOJOSHADER_AST_OP_SUBASSIGN, - MOJOSHADER_AST_OP_LSHIFTASSIGN, - MOJOSHADER_AST_OP_RSHIFTASSIGN, - MOJOSHADER_AST_OP_ANDASSIGN, - MOJOSHADER_AST_OP_XORASSIGN, - MOJOSHADER_AST_OP_ORASSIGN, - MOJOSHADER_AST_OP_DEREF_ARRAY, - MOJOSHADER_AST_OP_END_RANGE_BINARY, - - MOJOSHADER_AST_OP_START_RANGE_TERNARY, /* ternary operators. */ - MOJOSHADER_AST_OP_CONDITIONAL, - MOJOSHADER_AST_OP_END_RANGE_TERNARY, - - MOJOSHADER_AST_OP_START_RANGE_DATA, /* expression operands. */ - MOJOSHADER_AST_OP_IDENTIFIER, - MOJOSHADER_AST_OP_INT_LITERAL, - MOJOSHADER_AST_OP_FLOAT_LITERAL, - MOJOSHADER_AST_OP_STRING_LITERAL, - MOJOSHADER_AST_OP_BOOLEAN_LITERAL, - MOJOSHADER_AST_OP_END_RANGE_DATA, - - MOJOSHADER_AST_OP_START_RANGE_MISC, /* other expression things. */ - MOJOSHADER_AST_OP_DEREF_STRUCT, - MOJOSHADER_AST_OP_CALLFUNC, - MOJOSHADER_AST_OP_CONSTRUCTOR, - MOJOSHADER_AST_OP_END_RANGE_MISC, - MOJOSHADER_AST_OP_END_RANGE, - - MOJOSHADER_AST_COMPUNIT_START_RANGE, /* things in global scope. */ - MOJOSHADER_AST_COMPUNIT_FUNCTION, - MOJOSHADER_AST_COMPUNIT_TYPEDEF, - MOJOSHADER_AST_COMPUNIT_STRUCT, - MOJOSHADER_AST_COMPUNIT_VARIABLE, - MOJOSHADER_AST_COMPUNIT_END_RANGE, - - MOJOSHADER_AST_STATEMENT_START_RANGE, /* statements in function scope. */ - MOJOSHADER_AST_STATEMENT_EMPTY, - MOJOSHADER_AST_STATEMENT_BREAK, - MOJOSHADER_AST_STATEMENT_CONTINUE, - MOJOSHADER_AST_STATEMENT_DISCARD, - MOJOSHADER_AST_STATEMENT_BLOCK, - MOJOSHADER_AST_STATEMENT_EXPRESSION, - MOJOSHADER_AST_STATEMENT_IF, - MOJOSHADER_AST_STATEMENT_SWITCH, - MOJOSHADER_AST_STATEMENT_FOR, - MOJOSHADER_AST_STATEMENT_DO, - MOJOSHADER_AST_STATEMENT_WHILE, - MOJOSHADER_AST_STATEMENT_RETURN, - MOJOSHADER_AST_STATEMENT_TYPEDEF, - MOJOSHADER_AST_STATEMENT_STRUCT, - MOJOSHADER_AST_STATEMENT_VARDECL, - MOJOSHADER_AST_STATEMENT_END_RANGE, - - MOJOSHADER_AST_MISC_START_RANGE, /* misc. syntactic glue. */ - MOJOSHADER_AST_FUNCTION_PARAMS, - MOJOSHADER_AST_FUNCTION_SIGNATURE, - MOJOSHADER_AST_SCALAR_OR_ARRAY, - MOJOSHADER_AST_TYPEDEF, - MOJOSHADER_AST_PACK_OFFSET, - MOJOSHADER_AST_VARIABLE_LOWLEVEL, - MOJOSHADER_AST_ANNOTATION, - MOJOSHADER_AST_VARIABLE_DECLARATION, - MOJOSHADER_AST_STRUCT_DECLARATION, - MOJOSHADER_AST_STRUCT_MEMBER, - MOJOSHADER_AST_SWITCH_CASE, - MOJOSHADER_AST_ARGUMENTS, - MOJOSHADER_AST_MISC_END_RANGE, - - MOJOSHADER_AST_END_RANGE -} MOJOSHADER_astNodeType; - -typedef struct MOJOSHADER_astNodeInfo -{ - MOJOSHADER_astNodeType type; - const char *filename; - unsigned int line; -} MOJOSHADER_astNodeInfo; +/* + * This queries for the shaders currently bound to the active context. + * + * This function is only for convenience, specifically for compatibility with + * the effects API. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + */ +DECLSPEC void MOJOSHADER_glGetBoundShaders(MOJOSHADER_glShader **vshader, + MOJOSHADER_glShader **pshader); -typedef enum MOJOSHADER_astVariableAttributes -{ - MOJOSHADER_AST_VARATTR_EXTERN = (1 << 0), - MOJOSHADER_AST_VARATTR_NOINTERPOLATION = (1 << 1), - MOJOSHADER_AST_VARATTR_SHARED = (1 << 2), - MOJOSHADER_AST_VARATTR_STATIC = (1 << 3), - MOJOSHADER_AST_VARATTR_UNIFORM = (1 << 4), - MOJOSHADER_AST_VARATTR_VOLATILE = (1 << 5), - MOJOSHADER_AST_VARATTR_CONST = (1 << 6), - MOJOSHADER_AST_VARATTR_ROWMAJOR = (1 << 7), - MOJOSHADER_AST_VARATTR_COLUMNMAJOR = (1 << 8) -} MOJOSHADER_astVariableAttributes; - -typedef enum MOJOSHADER_astIfAttributes -{ - MOJOSHADER_AST_IFATTR_NONE, - MOJOSHADER_AST_IFATTR_BRANCH, - MOJOSHADER_AST_IFATTR_FLATTEN, - MOJOSHADER_AST_IFATTR_IFALL, - MOJOSHADER_AST_IFATTR_IFANY, - MOJOSHADER_AST_IFATTR_PREDICATE, - MOJOSHADER_AST_IFATTR_PREDICATEBLOCK, -} MOJOSHADER_astIfAttributes; - -typedef enum MOJOSHADER_astSwitchAttributes -{ - MOJOSHADER_AST_SWITCHATTR_NONE, - MOJOSHADER_AST_SWITCHATTR_FLATTEN, - MOJOSHADER_AST_SWITCHATTR_BRANCH, - MOJOSHADER_AST_SWITCHATTR_FORCECASE, - MOJOSHADER_AST_SWITCHATTR_CALL -} MOJOSHADER_astSwitchAttributes; - -/* You can cast any AST node pointer to this. */ -typedef struct MOJOSHADER_astGeneric -{ - MOJOSHADER_astNodeInfo ast; -} MOJOSHADER_astGeneric; - -typedef struct MOJOSHADER_astExpression -{ - MOJOSHADER_astNodeInfo ast; - const MOJOSHADER_astDataType *datatype; -} MOJOSHADER_astExpression; - -typedef struct MOJOSHADER_astArguments -{ - MOJOSHADER_astNodeInfo ast; /* Always MOJOSHADER_AST_ARGUMENTS */ - MOJOSHADER_astExpression *argument; - struct MOJOSHADER_astArguments *next; -} MOJOSHADER_astArguments; - -typedef struct MOJOSHADER_astExpressionUnary -{ - MOJOSHADER_astNodeInfo ast; - const MOJOSHADER_astDataType *datatype; - MOJOSHADER_astExpression *operand; -} MOJOSHADER_astExpressionUnary; - -typedef struct MOJOSHADER_astExpressionBinary -{ - MOJOSHADER_astNodeInfo ast; - const MOJOSHADER_astDataType *datatype; - MOJOSHADER_astExpression *left; - MOJOSHADER_astExpression *right; -} MOJOSHADER_astExpressionBinary; - -typedef struct MOJOSHADER_astExpressionTernary -{ - MOJOSHADER_astNodeInfo ast; - const MOJOSHADER_astDataType *datatype; - MOJOSHADER_astExpression *left; - MOJOSHADER_astExpression *center; - MOJOSHADER_astExpression *right; -} MOJOSHADER_astExpressionTernary; - -/* Identifier indexes aren't available until semantic analysis phase completes. - * It provides a unique id for this identifier's variable. - * It will be negative for global scope, positive for function scope - * (global values are globally unique, function values are only - * unique within the scope of the given function). There's a different - * set of indices if this identifier is a function (positive for - * user-defined functions, negative for intrinsics). - * May be zero for various reasons (unknown identifier, etc). - */ -typedef struct MOJOSHADER_astExpressionIdentifier -{ - MOJOSHADER_astNodeInfo ast; /* Always MOJOSHADER_AST_OP_IDENTIFIER */ - const MOJOSHADER_astDataType *datatype; - const char *identifier; - int index; -} MOJOSHADER_astExpressionIdentifier; - -typedef struct MOJOSHADER_astExpressionIntLiteral -{ - MOJOSHADER_astNodeInfo ast; /* Always MOJOSHADER_AST_OP_INT_LITERAL */ - const MOJOSHADER_astDataType *datatype; /* always AST_DATATYPE_INT */ - int value; -} MOJOSHADER_astExpressionIntLiteral; - -typedef struct MOJOSHADER_astExpressionFloatLiteral -{ - MOJOSHADER_astNodeInfo ast; /* Always MOJOSHADER_AST_OP_FLOAT_LITERAL */ - const MOJOSHADER_astDataType *datatype; /* always AST_DATATYPE_FLOAT */ - double value; -} MOJOSHADER_astExpressionFloatLiteral; - -typedef struct MOJOSHADER_astExpressionStringLiteral -{ - MOJOSHADER_astNodeInfo ast; /* Always MOJOSHADER_AST_OP_STRING_LITERAL */ - const MOJOSHADER_astDataType *datatype; /* always AST_DATATYPE_STRING */ - const char *string; -} MOJOSHADER_astExpressionStringLiteral; - -typedef struct MOJOSHADER_astExpressionBooleanLiteral -{ - MOJOSHADER_astNodeInfo ast; /* Always MOJOSHADER_AST_OP_BOOLEAN_LITERAL */ - const MOJOSHADER_astDataType *datatype; /* always AST_DATATYPE_BOOL */ - int value; /* Always 1 or 0. */ -} MOJOSHADER_astExpressionBooleanLiteral; - -typedef struct MOJOSHADER_astExpressionConstructor -{ - MOJOSHADER_astNodeInfo ast; /* Always MOJOSHADER_AST_OP_CONSTRUCTOR */ - const MOJOSHADER_astDataType *datatype; - MOJOSHADER_astArguments *args; -} MOJOSHADER_astExpressionConstructor; - -typedef struct MOJOSHADER_astExpressionDerefStruct -{ - MOJOSHADER_astNodeInfo ast; /* Always MOJOSHADER_AST_OP_DEREF_STRUCT */ - const MOJOSHADER_astDataType *datatype; - /* !!! FIXME: - * "identifier" is misnamed; this might not be an identifier at all: - * x = FunctionThatReturnsAStruct().SomeMember; - */ - MOJOSHADER_astExpression *identifier; - const char *member; - int isswizzle; /* Always 1 or 0. Never set by parseAst()! */ - int member_index; /* Never set by parseAst()! */ -} MOJOSHADER_astExpressionDerefStruct; - -typedef struct MOJOSHADER_astExpressionCallFunction -{ - MOJOSHADER_astNodeInfo ast; /* Always MOJOSHADER_AST_OP_CALLFUNC */ - const MOJOSHADER_astDataType *datatype; - MOJOSHADER_astExpressionIdentifier *identifier; - MOJOSHADER_astArguments *args; -} MOJOSHADER_astExpressionCallFunction; - -typedef struct MOJOSHADER_astExpressionCast -{ - MOJOSHADER_astNodeInfo ast; /* Always MOJOSHADER_AST_OP_CAST */ - const MOJOSHADER_astDataType *datatype; - MOJOSHADER_astExpression *operand; -} MOJOSHADER_astExpressionCast; - -typedef struct MOJOSHADER_astCompilationUnit -{ - MOJOSHADER_astNodeInfo ast; - struct MOJOSHADER_astCompilationUnit *next; -} MOJOSHADER_astCompilationUnit; - -typedef enum MOJOSHADER_astFunctionStorageClass -{ - MOJOSHADER_AST_FNSTORECLS_NONE, - MOJOSHADER_AST_FNSTORECLS_INLINE -} MOJOSHADER_astFunctionStorageClass; - -typedef enum MOJOSHADER_astInputModifier -{ - MOJOSHADER_AST_INPUTMOD_NONE, - MOJOSHADER_AST_INPUTMOD_IN, - MOJOSHADER_AST_INPUTMOD_OUT, - MOJOSHADER_AST_INPUTMOD_INOUT, - MOJOSHADER_AST_INPUTMOD_UNIFORM -} MOJOSHADER_astInputModifier; - -typedef enum MOJOSHADER_astInterpolationModifier -{ - MOJOSHADER_AST_INTERPMOD_NONE, - MOJOSHADER_AST_INTERPMOD_LINEAR, - MOJOSHADER_AST_INTERPMOD_CENTROID, - MOJOSHADER_AST_INTERPMOD_NOINTERPOLATION, - MOJOSHADER_AST_INTERPMOD_NOPERSPECTIVE, - MOJOSHADER_AST_INTERPMOD_SAMPLE -} MOJOSHADER_astInterpolationModifier; - -typedef struct MOJOSHADER_astFunctionParameters -{ - MOJOSHADER_astNodeInfo ast; - const MOJOSHADER_astDataType *datatype; - MOJOSHADER_astInputModifier input_modifier; - const char *identifier; - const char *semantic; - MOJOSHADER_astInterpolationModifier interpolation_modifier; - MOJOSHADER_astExpression *initializer; - struct MOJOSHADER_astFunctionParameters *next; -} MOJOSHADER_astFunctionParameters; - -typedef struct MOJOSHADER_astFunctionSignature -{ - MOJOSHADER_astNodeInfo ast; - const MOJOSHADER_astDataType *datatype; - const char *identifier; - MOJOSHADER_astFunctionParameters *params; - MOJOSHADER_astFunctionStorageClass storage_class; - const char *semantic; -} MOJOSHADER_astFunctionSignature; - -typedef struct MOJOSHADER_astScalarOrArray -{ - MOJOSHADER_astNodeInfo ast; - const char *identifier; - int isarray; /* boolean: 1 or 0 */ - MOJOSHADER_astExpression *dimension; -} MOJOSHADER_astScalarOrArray; - -typedef struct MOJOSHADER_astAnnotations -{ - MOJOSHADER_astNodeInfo ast; - const MOJOSHADER_astDataType *datatype; - MOJOSHADER_astExpression *initializer; - struct MOJOSHADER_astAnnotations *next; -} MOJOSHADER_astAnnotations; - -typedef struct MOJOSHADER_astPackOffset -{ - MOJOSHADER_astNodeInfo ast; - const char *ident1; /* !!! FIXME: rename this. */ - const char *ident2; -} MOJOSHADER_astPackOffset; - -typedef struct MOJOSHADER_astVariableLowLevel -{ - MOJOSHADER_astNodeInfo ast; - MOJOSHADER_astPackOffset *packoffset; - const char *register_name; -} MOJOSHADER_astVariableLowLevel; - -typedef struct MOJOSHADER_astStructMembers -{ - MOJOSHADER_astNodeInfo ast; - const MOJOSHADER_astDataType *datatype; - const char *semantic; - MOJOSHADER_astScalarOrArray *details; - MOJOSHADER_astInterpolationModifier interpolation_mod; - struct MOJOSHADER_astStructMembers *next; -} MOJOSHADER_astStructMembers; - -typedef struct MOJOSHADER_astStructDeclaration -{ - MOJOSHADER_astNodeInfo ast; - const MOJOSHADER_astDataType *datatype; - const char *name; - MOJOSHADER_astStructMembers *members; -} MOJOSHADER_astStructDeclaration; - -typedef struct MOJOSHADER_astVariableDeclaration -{ - MOJOSHADER_astNodeInfo ast; - int attributes; - const MOJOSHADER_astDataType *datatype; - MOJOSHADER_astStructDeclaration *anonymous_datatype; - MOJOSHADER_astScalarOrArray *details; - const char *semantic; - MOJOSHADER_astAnnotations *annotations; - MOJOSHADER_astExpression *initializer; - MOJOSHADER_astVariableLowLevel *lowlevel; - struct MOJOSHADER_astVariableDeclaration *next; -} MOJOSHADER_astVariableDeclaration; - -typedef struct MOJOSHADER_astStatement -{ - MOJOSHADER_astNodeInfo ast; - struct MOJOSHADER_astStatement *next; -} MOJOSHADER_astStatement; - -typedef MOJOSHADER_astStatement MOJOSHADER_astEmptyStatement; -typedef MOJOSHADER_astStatement MOJOSHADER_astBreakStatement; -typedef MOJOSHADER_astStatement MOJOSHADER_astContinueStatement; -typedef MOJOSHADER_astStatement MOJOSHADER_astDiscardStatement; - -/* something enclosed in "{}" braces. */ -typedef struct MOJOSHADER_astBlockStatement -{ - MOJOSHADER_astNodeInfo ast; - MOJOSHADER_astStatement *next; - MOJOSHADER_astStatement *statements; /* list of child statements. */ -} MOJOSHADER_astBlockStatement; - -typedef struct MOJOSHADER_astReturnStatement -{ - MOJOSHADER_astNodeInfo ast; - MOJOSHADER_astStatement *next; - MOJOSHADER_astExpression *expr; -} MOJOSHADER_astReturnStatement; - -typedef struct MOJOSHADER_astExpressionStatement -{ - MOJOSHADER_astNodeInfo ast; - MOJOSHADER_astStatement *next; - MOJOSHADER_astExpression *expr; -} MOJOSHADER_astExpressionStatement; - -typedef struct MOJOSHADER_astIfStatement -{ - MOJOSHADER_astNodeInfo ast; - MOJOSHADER_astStatement *next; - int attributes; - MOJOSHADER_astExpression *expr; - MOJOSHADER_astStatement *statement; - MOJOSHADER_astStatement *else_statement; -} MOJOSHADER_astIfStatement; - -typedef struct MOJOSHADER_astSwitchCases -{ - MOJOSHADER_astNodeInfo ast; - MOJOSHADER_astExpression *expr; - MOJOSHADER_astStatement *statement; - struct MOJOSHADER_astSwitchCases *next; -} MOJOSHADER_astSwitchCases; - -typedef struct MOJOSHADER_astSwitchStatement -{ - MOJOSHADER_astNodeInfo ast; - MOJOSHADER_astStatement *next; - int attributes; - MOJOSHADER_astExpression *expr; - MOJOSHADER_astSwitchCases *cases; -} MOJOSHADER_astSwitchStatement; - -typedef struct MOJOSHADER_astWhileStatement -{ - MOJOSHADER_astNodeInfo ast; - MOJOSHADER_astStatement *next; - int unroll; /* # times to unroll, 0 to loop, < 0 == compiler's choice. */ - MOJOSHADER_astExpression *expr; - MOJOSHADER_astStatement *statement; -} MOJOSHADER_astWhileStatement; - -typedef MOJOSHADER_astWhileStatement MOJOSHADER_astDoStatement; - -typedef struct MOJOSHADER_astForStatement -{ - MOJOSHADER_astNodeInfo ast; - MOJOSHADER_astStatement *next; - int unroll; /* # times to unroll, 0 to loop, < 0 == compiler's choice. */ - MOJOSHADER_astVariableDeclaration *var_decl; /* either this ... */ - MOJOSHADER_astExpression *initializer; /* ... or this will used. */ - MOJOSHADER_astExpression *looptest; - MOJOSHADER_astExpression *counter; - MOJOSHADER_astStatement *statement; -} MOJOSHADER_astForStatement; - -typedef struct MOJOSHADER_astTypedef -{ - MOJOSHADER_astNodeInfo ast; - const MOJOSHADER_astDataType *datatype; - int isconst; /* boolean: 1 or 0 */ - MOJOSHADER_astScalarOrArray *details; -} MOJOSHADER_astTypedef; - -typedef struct MOJOSHADER_astTypedefStatement -{ - MOJOSHADER_astNodeInfo ast; - MOJOSHADER_astStatement *next; - MOJOSHADER_astTypedef *type_info; -} MOJOSHADER_astTypedefStatement; - -typedef struct MOJOSHADER_astVarDeclStatement -{ - MOJOSHADER_astNodeInfo ast; - MOJOSHADER_astStatement *next; - MOJOSHADER_astVariableDeclaration *declaration; -} MOJOSHADER_astVarDeclStatement; - -typedef struct MOJOSHADER_astStructStatement -{ - MOJOSHADER_astNodeInfo ast; - MOJOSHADER_astStatement *next; - MOJOSHADER_astStructDeclaration *struct_info; -} MOJOSHADER_astStructStatement; - -typedef struct MOJOSHADER_astCompilationUnitFunction -{ - MOJOSHADER_astNodeInfo ast; - MOJOSHADER_astCompilationUnit *next; - MOJOSHADER_astFunctionSignature *declaration; - MOJOSHADER_astStatement *definition; - int index; /* unique id. Will be 0 until semantic analysis runs. */ -} MOJOSHADER_astCompilationUnitFunction; - -typedef struct MOJOSHADER_astCompilationUnitTypedef -{ - MOJOSHADER_astNodeInfo ast; - MOJOSHADER_astCompilationUnit *next; - MOJOSHADER_astTypedef *type_info; -} MOJOSHADER_astCompilationUnitTypedef; - -typedef struct MOJOSHADER_astCompilationUnitStruct -{ - MOJOSHADER_astNodeInfo ast; - MOJOSHADER_astCompilationUnit *next; - MOJOSHADER_astStructDeclaration *struct_info; -} MOJOSHADER_astCompilationUnitStruct; - -typedef struct MOJOSHADER_astCompilationUnitVariable -{ - MOJOSHADER_astNodeInfo ast; - MOJOSHADER_astCompilationUnit *next; - MOJOSHADER_astVariableDeclaration *declaration; -} MOJOSHADER_astCompilationUnitVariable; - - -/* this is way cleaner than all the nasty typecasting. */ -typedef union MOJOSHADER_astNode -{ - MOJOSHADER_astNodeInfo ast; - MOJOSHADER_astGeneric generic; - MOJOSHADER_astExpression expression; - MOJOSHADER_astArguments arguments; - MOJOSHADER_astExpressionUnary unary; - MOJOSHADER_astExpressionBinary binary; - MOJOSHADER_astExpressionTernary ternary; - MOJOSHADER_astExpressionIdentifier identifier; - MOJOSHADER_astExpressionIntLiteral intliteral; - MOJOSHADER_astExpressionFloatLiteral floatliteral; - MOJOSHADER_astExpressionStringLiteral stringliteral; - MOJOSHADER_astExpressionBooleanLiteral boolliteral; - MOJOSHADER_astExpressionConstructor constructor; - MOJOSHADER_astExpressionDerefStruct derefstruct; - MOJOSHADER_astExpressionCallFunction callfunc; - MOJOSHADER_astExpressionCast cast; - MOJOSHADER_astCompilationUnit compunit; - MOJOSHADER_astFunctionParameters params; - MOJOSHADER_astFunctionSignature funcsig; - MOJOSHADER_astScalarOrArray soa; - MOJOSHADER_astAnnotations annotations; - MOJOSHADER_astPackOffset packoffset; - MOJOSHADER_astVariableLowLevel varlowlevel; - MOJOSHADER_astStructMembers structmembers; - MOJOSHADER_astStructDeclaration structdecl; - MOJOSHADER_astVariableDeclaration vardecl; - MOJOSHADER_astStatement stmt; - MOJOSHADER_astEmptyStatement emptystmt; - MOJOSHADER_astBreakStatement breakstmt; - MOJOSHADER_astContinueStatement contstmt; - MOJOSHADER_astDiscardStatement discardstmt; - MOJOSHADER_astBlockStatement blockstmt; - MOJOSHADER_astReturnStatement returnstmt; - MOJOSHADER_astExpressionStatement exprstmt; - MOJOSHADER_astIfStatement ifstmt; - MOJOSHADER_astSwitchCases cases; - MOJOSHADER_astSwitchStatement switchstmt; - MOJOSHADER_astWhileStatement whilestmt; - MOJOSHADER_astDoStatement dostmt; - MOJOSHADER_astForStatement forstmt; - MOJOSHADER_astTypedef typdef; - MOJOSHADER_astTypedefStatement typedefstmt; - MOJOSHADER_astVarDeclStatement vardeclstmt; - MOJOSHADER_astStructStatement structstmt; - MOJOSHADER_astCompilationUnitFunction funcunit; - MOJOSHADER_astCompilationUnitTypedef typedefunit; - MOJOSHADER_astCompilationUnitStruct structunit; - MOJOSHADER_astCompilationUnitVariable varunit; -} MOJOSHADER_astNode; - - -/* - * Structure used to return data from parsing of a shader into an AST... +/* + * Set a floating-point uniform value (what Direct3D calls a "constant"). + * + * There is a single array of 4-float "registers" shared by all vertex shaders. + * This is the "c" register file in Direct3D (c0, c1, c2, etc...) + * MojoShader will take care of synchronizing this internal array with the + * appropriate variables in the GL shaders. + * + * (idx) is the index into the internal array: 0 is the first four floats, + * 1 is the next four, etc. + * (data) is a pointer to (vec4count*4) floats. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * + * Uniforms are not shared between contexts. */ -/* !!! FIXME: most of these ints should be unsigned. */ -typedef struct MOJOSHADER_astData -{ - /* - * The number of elements pointed to by (errors). - */ - int error_count; +DECLSPEC void MOJOSHADER_glSetVertexShaderUniformF(unsigned int idx, const float *data, + unsigned int vec4count); - /* - * (error_count) elements of data that specify errors that were generated - * by parsing this shader. - * This can be NULL if there were no errors or if (error_count) is zero. - * Note that this will only produce errors for syntax problems. Most of - * the things we expect a compiler to produce errors for--incompatible - * types, unknown identifiers, etc--are not checked at all during - * initial generation of the syntax tree...bogus programs that would - * fail to compile will pass here without error, if they are syntactically - * correct! - */ - MOJOSHADER_error *errors; - - /* - * The name of the source profile used to parse the shader. Will be NULL - * on error. - */ - const char *source_profile; - - /* - * The actual syntax tree. You are responsible for walking it yourself. - * CompilationUnits are always the top of the tree (functions, typedefs, - * global variables, etc). Will be NULL on error. - */ - const MOJOSHADER_astNode *ast; - - /* - * This is the malloc implementation you passed to MOJOSHADER_parse(). - */ - MOJOSHADER_malloc malloc; - - /* - * This is the free implementation you passed to MOJOSHADER_parse(). - */ - MOJOSHADER_free free; - - /* - * This is the pointer you passed as opaque data for your allocator. - */ - void *malloc_data; - - /* - * This is internal data, and not for the application to touch. - */ - void *opaque; -} MOJOSHADER_astData; +/* + * Retrieve a floating-point uniform value (what Direct3D calls a "constant"). + * + * There is a single array of 4-float "registers" shared by all vertex shaders. + * This is the "c" register file in Direct3D (c0, c1, c2, etc...) + * MojoShader will take care of synchronizing this internal array with the + * appropriate variables in the GL shaders. + * + * (idx) is the index into the internal array: 0 is the first four floats, + * 1 is the next four, etc. + * (data) is a pointer to space for (vec4count*4) floats. + * (data) will be filled will current values in the register file. Results + * are undefined if you request data past the end of the register file or + * previously uninitialized registers. + * + * This is a "fast" call; we're just reading from internal memory. We do not + * query the GPU or the GL for this information. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * + * Uniforms are not shared between contexts. + */ +DECLSPEC void MOJOSHADER_glGetVertexShaderUniformF(unsigned int idx, float *data, + unsigned int vec4count); /* - * You almost certainly don't need this function, unless you absolutely know - * why you need it without hesitation. This is almost certainly only good for - * building code analysis tools on top of. + * Set an integer uniform value (what Direct3D calls a "constant"). * - * This is intended to parse HLSL source code, turning it into an abstract - * syntax tree. + * There is a single array of 4-int "registers" shared by all vertex shaders. + * This is the "i" register file in Direct3D (i0, i1, i2, etc...) + * MojoShader will take care of synchronizing this internal array with the + * appropriate variables in the GL shaders. * - * (srcprofile) specifies the source language of the shader. You can specify - * a shader model with this, too. See MOJOSHADER_SRC_PROFILE_* constants. + * (idx) is the index into the internal array: 0 is the first four ints, + * 1 is the next four, etc. + * (data) is a pointer to (ivec4count*4) ints. * - * (filename) is a NULL-terminated UTF-8 filename. It can be NULL. We do not - * actually access this file, as we obtain our data from (source). This - * string is copied when we need to report errors while processing (source), - * as opposed to errors in a file referenced via the #include directive in - * (source). If this is NULL, then errors will report the filename as NULL, - * too. + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. * - * (source) is an UTF-8 string of valid high-level shader source code. - * It does not need to be NULL-terminated. + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). * - * (sourcelen) is the length of the string pointed to by (source), in bytes. + * Uniforms are not shared between contexts. + */ +DECLSPEC void MOJOSHADER_glSetVertexShaderUniformI(unsigned int idx, const int *data, + unsigned int ivec4count); + +/* + * Retrieve an integer uniform value (what Direct3D calls a "constant"). * - * (defines) points to (define_count) preprocessor definitions, and can be - * NULL. These are treated by the preprocessor as if the source code started - * with one #define for each entry you pass in here. + * There is a single array of 4-int "registers" shared by all vertex shaders. + * This is the "i" register file in Direct3D (i0, i1, i2, etc...) + * MojoShader will take care of synchronizing this internal array with the + * appropriate variables in the GL shaders. * - * (include_open) and (include_close) let the app control the preprocessor's - * behaviour for #include statements. Both are optional and can be NULL, but - * both must be specified if either is specified. + * (idx) is the index into the internal array: 0 is the first four ints, + * 1 is the next four, etc. + * (data) is a pointer to space for (ivec4count*4) ints. + * (data) will be filled will current values in the register file. Results + * are undefined if you request data past the end of the register file or + * previously uninitialized registers. * - * This will return a MOJOSHADER_astData. The data supplied here gives the - * application a tree-like structure they can walk to see the layout of - * a given program. When you are done with this data, pass it to - * MOJOSHADER_freeCompileData() to deallocate resources. + * This is a "fast" call; we're just reading from internal memory. We do not + * query the GPU or the GL for this information. * - * This function will never return NULL, even if the system is completely - * out of memory upon entry (in which case, this function returns a static - * MOJOSHADER_astData object, which is still safe to pass to - * MOJOSHADER_freeAstData()). + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. * - * As parsing requires some memory to be allocated, you may provide a - * custom allocator to this function, which will be used to allocate/free - * memory. They function just like malloc() and free(). We do not use - * realloc(). If you don't care, pass NULL in for the allocator functions. - * If your allocator needs instance-specific data, you may supply it with the - * (d) parameter. This pointer is passed as-is to your (m) and (f) functions. + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). * - * This function is thread safe, so long as the various callback functions - * are, too, and that the parameters remains intact for the duration of the - * call. This allows you to parse several shaders on separate CPU cores - * at the same time. + * Uniforms are not shared between contexts. */ -const MOJOSHADER_astData *MOJOSHADER_parseAst(const char *srcprofile, - const char *filename, const char *source, - unsigned int sourcelen, - const MOJOSHADER_preprocessorDefine *defs, - unsigned int define_count, - MOJOSHADER_includeOpen include_open, - MOJOSHADER_includeClose include_close, - MOJOSHADER_malloc m, MOJOSHADER_free f, - void *d); - - -/* !!! FIXME: expose semantic analysis to the public API? */ - +DECLSPEC void MOJOSHADER_glGetVertexShaderUniformI(unsigned int idx, int *data, + unsigned int ivec4count); /* - * Call this to dispose of AST parsing results when you are done with them. - * This will call the MOJOSHADER_free function you provided to - * MOJOSHADER_parseAst() multiple times, if you provided one. - * Passing a NULL here is a safe no-op. + * Set a boolean uniform value (what Direct3D calls a "constant"). * - * This function is thread safe, so long as any allocator you passed into - * MOJOSHADER_parseAst() is, too. + * There is a single array of "registers" shared by all vertex shaders. + * This is the "b" register file in Direct3D (b0, b1, b2, etc...) + * MojoShader will take care of synchronizing this internal array with the + * appropriate variables in the GL shaders. + * + * Unlike the float and int counterparts, booleans are single values, not + * four-element vectors...so idx==1 is the second boolean in the internal + * array, not the fifth. + * + * Non-zero values are considered "true" and zero is considered "false". + * + * (idx) is the index into the internal array. + * (data) is a pointer to (bcount) ints. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * + * Uniforms are not shared between contexts. */ -void MOJOSHADER_freeAstData(const MOJOSHADER_astData *data); - - -/* Intermediate Representation interface... */ -/* !!! FIXME: there is currently no way to access the IR via the public API. */ -typedef enum MOJOSHADER_irNodeType -{ - MOJOSHADER_IR_START_RANGE_EXPR, - MOJOSHADER_IR_CONSTANT, - MOJOSHADER_IR_TEMP, - MOJOSHADER_IR_BINOP, - MOJOSHADER_IR_MEMORY, - MOJOSHADER_IR_CALL, - MOJOSHADER_IR_ESEQ, - MOJOSHADER_IR_ARRAY, - MOJOSHADER_IR_CONVERT, - MOJOSHADER_IR_SWIZZLE, - MOJOSHADER_IR_CONSTRUCT, - MOJOSHADER_IR_END_RANGE_EXPR, - - MOJOSHADER_IR_START_RANGE_STMT, - MOJOSHADER_IR_MOVE, - MOJOSHADER_IR_EXPR_STMT, - MOJOSHADER_IR_JUMP, - MOJOSHADER_IR_CJUMP, - MOJOSHADER_IR_SEQ, - MOJOSHADER_IR_LABEL, - MOJOSHADER_IR_DISCARD, - MOJOSHADER_IR_END_RANGE_STMT, - - MOJOSHADER_IR_START_RANGE_MISC, - MOJOSHADER_IR_EXPRLIST, - MOJOSHADER_IR_END_RANGE_MISC, - - MOJOSHADER_IR_END_RANGE -} MOJOSHADER_irNodeType; - -typedef struct MOJOSHADER_irNodeInfo -{ - MOJOSHADER_irNodeType type; - const char *filename; - unsigned int line; -} MOJOSHADER_irNodeInfo; - -typedef struct MOJOSHADER_irExprList MOJOSHADER_irExprList; +DECLSPEC void MOJOSHADER_glSetVertexShaderUniformB(unsigned int idx, const int *data, + unsigned int bcount); /* - * IR nodes are categorized into Expressions, Statements, and Everything Else. - * You can cast any of them to MOJOSHADER_irGeneric, but this split is - * useful for slightly better type-checking (you can't cleanly assign - * something that doesn't return a value to something that wants one, etc). - * These broader categories are just unions of the simpler types, so the - * real definitions are below all the things they contain (but these - * predeclarations are because the simpler types refer to the broader - * categories). + * Retrieve a boolean uniform value (what Direct3D calls a "constant"). + * + * There is a single array of "registers" shared by all vertex shaders. + * This is the "b" register file in Direct3D (b0, b1, b2, etc...) + * MojoShader will take care of synchronizing this internal array with the + * appropriate variables in the GL shaders. + * + * Unlike the float and int counterparts, booleans are single values, not + * four-element vectors...so idx==1 is the second boolean in the internal + * array, not the fifth. + * + * Non-zero values are considered "true" and zero is considered "false". + * This function will always return true values as 1, regardless of what + * non-zero integer you originally used to set the registers. + * + * (idx) is the index into the internal array. + * (data) is a pointer to space for (bcount) ints. + * (data) will be filled will current values in the register file. Results + * are undefined if you request data past the end of the register file or + * previously uninitialized registers. + * + * This is a "fast" call; we're just reading from internal memory. We do not + * query the GPU or the GL for this information. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * + * Uniforms are not shared between contexts. */ -typedef union MOJOSHADER_irExpression MOJOSHADER_irExpression; /* returns a value. */ -typedef union MOJOSHADER_irStatement MOJOSHADER_irStatement; /* no returned value. */ -typedef union MOJOSHADER_irMisc MOJOSHADER_irMisc; /* Everything Else. */ -typedef union MOJOSHADER_irNode MOJOSHADER_irNode; /* Generic uber-wrapper. */ - -/* You can cast any IR node pointer to this. */ -typedef struct MOJOSHADER_irGeneric -{ - MOJOSHADER_irNodeInfo ir; -} MOJOSHADER_irGeneric; - - -/* These are used for MOJOSHADER_irBinOp */ -typedef enum MOJOSHADER_irBinOpType -{ - MOJOSHADER_IR_BINOP_ADD, - MOJOSHADER_IR_BINOP_SUBTRACT, - MOJOSHADER_IR_BINOP_MULTIPLY, - MOJOSHADER_IR_BINOP_DIVIDE, - MOJOSHADER_IR_BINOP_MODULO, - MOJOSHADER_IR_BINOP_AND, - MOJOSHADER_IR_BINOP_OR, - MOJOSHADER_IR_BINOP_XOR, - MOJOSHADER_IR_BINOP_LSHIFT, - MOJOSHADER_IR_BINOP_RSHIFT, - MOJOSHADER_IR_BINOP_UNKNOWN -} MOJOSHADER_irBinOpType; - -typedef enum MOJOSHADER_irConditionType -{ - MOJOSHADER_IR_COND_EQL, - MOJOSHADER_IR_COND_NEQ, - MOJOSHADER_IR_COND_LT, - MOJOSHADER_IR_COND_GT, - MOJOSHADER_IR_COND_LEQ, - MOJOSHADER_IR_COND_GEQ, - MOJOSHADER_IR_COND_UNKNOWN -} MOJOSHADER_irConditionType; - - -/* MOJOSHADER_irExpression types... */ - -typedef struct MOJOSHADER_irExprInfo -{ - MOJOSHADER_irNodeInfo ir; - MOJOSHADER_astDataTypeType type; - int elements; -} MOJOSHADER_irExprInfo; - -typedef struct MOJOSHADER_irConstant /* Constant value */ -{ - MOJOSHADER_irExprInfo info; /* Always MOJOSHADER_IR_CONSTANT */ - union - { - int ival[16]; - float fval[16]; - } value; -} MOJOSHADER_irConstant; - -typedef struct MOJOSHADER_irTemp /* temp value (not necessarily a register). */ -{ - MOJOSHADER_irExprInfo info; /* Always MOJOSHADER_IR_TEMP */ - int index; -} MOJOSHADER_irTemp; - -typedef struct MOJOSHADER_irBinOp /* binary operator (+, -, etc) */ -{ - MOJOSHADER_irExprInfo info; /* Always MOJOSHADER_IR_BINOP */ - MOJOSHADER_irBinOpType op; - MOJOSHADER_irExpression *left; - MOJOSHADER_irExpression *right; -} MOJOSHADER_irBinOp; - -typedef struct MOJOSHADER_irMemory -{ - MOJOSHADER_irExprInfo info; /* Always MOJOSHADER_IR_MEMORY */ - int index; /* not final addresses, just a unique identifier. */ -} MOJOSHADER_irMemory; - -typedef struct MOJOSHADER_irCall -{ - MOJOSHADER_irExprInfo info; /* Always MOJOSHADER_IR_CALL */ - int index; - MOJOSHADER_irExprList *args; -} MOJOSHADER_irCall; - -typedef struct MOJOSHADER_irESeq /* statement with result */ -{ - MOJOSHADER_irExprInfo info; /* Always MOJOSHADER_IR_ESEQ */ - MOJOSHADER_irStatement *stmt; /* execute this for side-effects, then... */ - MOJOSHADER_irExpression *expr; /* ...use this for the result. */ -} MOJOSHADER_irESeq; - -typedef struct MOJOSHADER_irArray /* Array dereference. */ -{ - MOJOSHADER_irExprInfo info; /* Always MOJOSHADER_IR_ARRAY */ - MOJOSHADER_irExpression *array; - MOJOSHADER_irExpression *element; -} MOJOSHADER_irArray; - -typedef struct MOJOSHADER_irConvert /* casting between datatypes */ -{ - MOJOSHADER_irExprInfo info; /* Always MOJOSHADER_IR_CONVERT */ - MOJOSHADER_irExpression *expr; -} MOJOSHADER_irConvert; - -typedef struct MOJOSHADER_irSwizzle /* vector swizzle */ -{ - MOJOSHADER_irExprInfo info; /* Always MOJOSHADER_IR_SWIZZLE */ - MOJOSHADER_irExpression *expr; - char channels[4]; -} MOJOSHADER_irSwizzle; - -typedef struct MOJOSHADER_irConstruct /* vector construct from discrete items */ -{ - MOJOSHADER_irExprInfo info; /* Always MOJOSHADER_IR_CONTSTRUCT */ - MOJOSHADER_irExprList *args; -} MOJOSHADER_irConstruct; - -/* Wrap the whole category in a union for type "safety." */ -union MOJOSHADER_irExpression -{ - MOJOSHADER_irNodeInfo ir; - MOJOSHADER_irExprInfo info; - MOJOSHADER_irConstant constant; - MOJOSHADER_irTemp temp; - MOJOSHADER_irBinOp binop; - MOJOSHADER_irMemory memory; - MOJOSHADER_irCall call; - MOJOSHADER_irESeq eseq; - MOJOSHADER_irArray array; - MOJOSHADER_irConvert convert; - MOJOSHADER_irSwizzle swizzle; - MOJOSHADER_irConstruct construct; -}; - -/* MOJOSHADER_irStatement types. */ - -typedef struct MOJOSHADER_irMove /* load/store. */ -{ - MOJOSHADER_irNodeInfo ir; /* Always MOJOSHADER_IR_MOVE */ - MOJOSHADER_irExpression *dst; /* must result in a temp or mem! */ - MOJOSHADER_irExpression *src; - int writemask; // for write-masking vector channels. -} MOJOSHADER_irMove; - -typedef struct MOJOSHADER_irExprStmt /* evaluate expression, throw it away. */ -{ - MOJOSHADER_irNodeInfo ir; /* Always MOJOSHADER_IR_EXPR_STMT */ - MOJOSHADER_irExpression *expr; -} MOJOSHADER_irExprStmt; - -typedef struct MOJOSHADER_irJump /* unconditional jump */ -{ - MOJOSHADER_irNodeInfo ir; /* Always MOJOSHADER_IR_JUMP */ - int label; - // !!! FIXME: possible label list, for further optimization passes. -} MOJOSHADER_irJump; - -typedef struct MOJOSHADER_irCJump /* conditional jump */ -{ - MOJOSHADER_irNodeInfo ir; /* Always MOJOSHADER_IR_CJUMP */ - MOJOSHADER_irConditionType cond; - MOJOSHADER_irExpression *left; /* if (left cond right) */ - MOJOSHADER_irExpression *right; - int iftrue; /* label id for true case. */ - int iffalse; /* label id for false case. */ -} MOJOSHADER_irCJump; - -typedef struct MOJOSHADER_irSeq /* statement without side effects */ -{ - MOJOSHADER_irNodeInfo ir; /* Always MOJOSHADER_IR_SEQ */ - MOJOSHADER_irStatement *first; - MOJOSHADER_irStatement *next; -} MOJOSHADER_irSeq; - -typedef struct MOJOSHADER_irLabel /* like a label in assembly language. */ -{ - MOJOSHADER_irNodeInfo ir; /* Always MOJOSHADER_IR_LABEL */ - int index; -} MOJOSHADER_irLabel; - -typedef MOJOSHADER_irGeneric MOJOSHADER_irDiscard; /* discard statement. */ - - -/* Wrap the whole category in a union for type "safety." */ -union MOJOSHADER_irStatement -{ - MOJOSHADER_irNodeInfo ir; - MOJOSHADER_irGeneric generic; - MOJOSHADER_irMove move; - MOJOSHADER_irExprStmt expr; - MOJOSHADER_irJump jump; - MOJOSHADER_irCJump cjump; - MOJOSHADER_irSeq seq; - MOJOSHADER_irLabel label; - MOJOSHADER_irDiscard discard; -}; - -/* MOJOSHADER_irMisc types. */ - -struct MOJOSHADER_irExprList -{ - MOJOSHADER_irNodeInfo ir; /* Always MOJOSHADER_IR_EXPRLIST */ - MOJOSHADER_irExpression *expr; - MOJOSHADER_irExprList *next; -}; - -/* Wrap the whole category in a union for type "safety." */ -union MOJOSHADER_irMisc -{ - MOJOSHADER_irNodeInfo ir; - MOJOSHADER_irGeneric generic; - MOJOSHADER_irExprList exprlist; -}; - -/* This is a catchall for all your needs. :) */ -union MOJOSHADER_irNode -{ - MOJOSHADER_irNodeInfo ir; - MOJOSHADER_irGeneric generic; - MOJOSHADER_irExpression expr; - MOJOSHADER_irStatement stmt; - MOJOSHADER_irMisc misc; -}; +DECLSPEC void MOJOSHADER_glGetVertexShaderUniformB(unsigned int idx, int *data, + unsigned int bcount); +/* + * The equivalent of MOJOSHADER_glSetVertexShaderUniformF() for pixel + * shaders. Other than using a different internal array that is specific + * to pixel shaders, this functions just like its vertex array equivalent. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * + * Uniforms are not shared between contexts. + */ +DECLSPEC void MOJOSHADER_glSetPixelShaderUniformF(unsigned int idx, const float *data, + unsigned int vec4count); -/* Compiler interface... */ /* - * Structure used to return data from parsing of a shader... + * The equivalent of MOJOSHADER_glGetVertexShaderUniformF() for pixel + * shaders. Other than using a different internal array that is specific + * to pixel shaders, this functions just like its vertex array equivalent. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * + * Uniforms are not shared between contexts. */ -/* !!! FIXME: most of these ints should be unsigned. */ -typedef struct MOJOSHADER_compileData -{ - /* - * The number of elements pointed to by (errors). - */ - int error_count; - - /* - * (error_count) elements of data that specify errors that were generated - * by compiling this shader. - * This can be NULL if there were no errors or if (error_count) is zero. - */ - MOJOSHADER_error *errors; - - /* - * The number of elements pointed to by (warnings). - */ - int warning_count; - - /* - * (warning_count) elements of data that specify errors that were - * generated by compiling this shader. - * This can be NULL if there were no errors or if (warning_count) is zero. - */ - MOJOSHADER_error *warnings; - - /* - * The name of the source profile used to compile the shader. Will be NULL - * on error. - */ - const char *source_profile; +DECLSPEC void MOJOSHADER_glGetPixelShaderUniformF(unsigned int idx, float *data, + unsigned int vec4count); - /* - * Bytes of output from compiling. This will be a null-terminated ASCII - * string of D3D assembly source code. - */ - const char *output; - /* - * Byte count for output, not counting any null terminator. - * Will be 0 on error. - */ - int output_len; +/* + * The equivalent of MOJOSHADER_glSetVertexShaderUniformI() for pixel + * shaders. Other than using a different internal array that is specific + * to pixel shaders, this functions just like its vertex array equivalent. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * + * Uniforms are not shared between contexts. + */ +DECLSPEC void MOJOSHADER_glSetPixelShaderUniformI(unsigned int idx, const int *data, + unsigned int ivec4count); - /* - * The number of elements pointed to by (symbols). - */ - int symbol_count; - /* - * (symbol_count) elements of data that specify high-level symbol data - * for the shader. This can be used by MOJOSHADER_assemble() to - * generate a CTAB section in bytecode, which is needed by - * MOJOSHADER_parseData() to handle some shaders. This can be NULL on - * error or if (symbol_count) is zero. - */ - MOJOSHADER_symbol *symbols; +/* + * The equivalent of MOJOSHADER_glGetVertexShaderUniformI() for pixel + * shaders. Other than using a different internal array that is specific + * to pixel shaders, this functions just like its vertex array equivalent. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * + * Uniforms are not shared between contexts. + */ +DECLSPEC void MOJOSHADER_glGetPixelShaderUniformI(unsigned int idx, int *data, + unsigned int ivec4count); - /* - * This is the malloc implementation you passed to MOJOSHADER_parse(). - */ - MOJOSHADER_malloc malloc; +/* + * The equivalent of MOJOSHADER_glSetVertexShaderUniformB() for pixel + * shaders. Other than using a different internal array that is specific + * to pixel shaders, this functions just like its vertex array equivalent. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * + * Uniforms are not shared between contexts. + */ +DECLSPEC void MOJOSHADER_glSetPixelShaderUniformB(unsigned int idx, const int *data, + unsigned int bcount); - /* - * This is the free implementation you passed to MOJOSHADER_parse(). - */ - MOJOSHADER_free free; +/* + * The equivalent of MOJOSHADER_glGetVertexShaderUniformB() for pixel + * shaders. Other than using a different internal array that is specific + * to pixel shaders, this functions just like its vertex array equivalent. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * + * Uniforms are not shared between contexts. + */ +DECLSPEC void MOJOSHADER_glGetPixelShaderUniformB(unsigned int idx, int *data, + unsigned int bcount); - /* - * This is the pointer you passed as opaque data for your allocator. - */ - void *malloc_data; -} MOJOSHADER_compileData; +/* + * Fills register pointers with pointers that are directly used to push uniform + * data to the GL shader context. + * + * This function is really just for the effects API, you should NOT be using + * this unless you know every single line of MojoShader from memory. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + */ +DECLSPEC void MOJOSHADER_glMapUniformBufferMemory(float **vsf, int **vsi, unsigned char **vsb, + float **psf, int **psi, unsigned char **psb); +/* + * Tells the context that you are done with the memory mapped by + * MOJOSHADER_glMapUniformBufferMemory(). + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + */ +DECLSPEC void MOJOSHADER_glUnmapUniformBufferMemory(); /* - * This function is optional. Use this to compile high-level shader programs. + * Set up the vector for the TEXBEM opcode. Most apps can ignore this API. * - * This is intended to turn HLSL source code into D3D assembly code, which - * can then be passed to MOJOSHADER_assemble() to convert it to D3D bytecode - * (which can then be used with MOJOSHADER_parseData() to support other - * shading targets). + * Shader Model 1.1 through 1.3 had an instruction for "fake bump mapping" + * called TEXBEM. To use it, you had to set some sampler states, + * D3DTSS_BUMPENVMATxx, which would be referenced by the opcode. * - * (srcprofile) specifies the source language of the shader. You can specify - * a shader model with this, too. See MOJOSHADER_SRC_PROFILE_* constants. + * This functionality was removed from Shader Model 1.4 and later, because + * it was special-purpose and limited. The functionality could be built on + * more general opcodes, and the sampler state could be supplied in a more + * general uniform. * - * (filename) is a NULL-terminated UTF-8 filename. It can be NULL. We do not - * actually access this file, as we obtain our data from (source). This - * string is copied when we need to report errors while processing (source), - * as opposed to errors in a file referenced via the #include directive in - * (source). If this is NULL, then errors will report the filename as NULL, - * too. + * However, to support this opcode, we supply a way to specify that sampler + * state, and the OpenGL glue code does the right thing to pass that + * information to the shader. * - * (source) is an UTF-8 string of valid high-level shader source code. - * It does not need to be NULL-terminated. + * This call maps to IDirect3DDevice::SetTextureStageState() with the + * D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT01, D3DTSS_BUMPENVMAT10, + * D3DTSS_BUMPENVMAT11, D3DTSS_BUMPENVLSCALE, and D3DTSS_BUMPENVLOFFSET + * targets. This is only useful for Shader Model < 1.4 pixel shaders, if + * they use the TEXBEM or TEXBEML opcode. If you aren't sure, you don't need + * this function. * - * (sourcelen) is the length of the string pointed to by (source), in bytes. + * Like the rest of your uniforms, you must call MOJOSHADER_glProgramReady() + * between setting new values and drawing with them. * - * (defines) points to (define_count) preprocessor definitions, and can be - * NULL. These are treated by the preprocessor as if the source code started - * with one #define for each entry you pass in here. + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. * - * (include_open) and (include_close) let the app control the preprocessor's - * behaviour for #include statements. Both are optional and can be NULL, but - * both must be specified if either is specified. + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). * - * This will return a MOJOSHADER_compileData. The data supplied here is - * sufficient to supply to MOJOSHADER_assemble() for further processing. - * When you are done with this data, pass it to MOJOSHADER_freeCompileData() - * to deallocate resources. + * These values are not shared between contexts. + */ +DECLSPEC void MOJOSHADER_glSetLegacyBumpMapEnv(unsigned int sampler, float mat00, + float mat01, float mat10, float mat11, + float lscale, float loffset); + +/* + * Return the location of a vertex attribute for the currently-bound program. * - * This function will never return NULL, even if the system is completely - * out of memory upon entry (in which case, this function returns a static - * MOJOSHADER_compileData object, which is still safe to pass to - * MOJOSHADER_freeCompileData()). + * (usage) and (index) map to Direct3D vertex declaration values: COLOR1 would + * be MOJOSHADER_USAGE_COLOR and 1. * - * As compiling requires some memory to be allocated, you may provide a - * custom allocator to this function, which will be used to allocate/free - * memory. They function just like malloc() and free(). We do not use - * realloc(). If you don't care, pass NULL in for the allocator functions. - * If your allocator needs instance-specific data, you may supply it with the - * (d) parameter. This pointer is passed as-is to your (m) and (f) functions. + * The return value is the index of the attribute to be sent to + * glVertexAttribPointer, or -1 if the stream is not used. * - * This function is thread safe, so long as the various callback functions - * are, too, and that the parameters remains intact for the duration of the - * call. This allows you to compile several shaders on separate CPU cores - * at the same time. + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). */ -const MOJOSHADER_compileData *MOJOSHADER_compile(const char *srcprofile, - const char *filename, const char *source, - unsigned int sourcelen, - const MOJOSHADER_preprocessorDefine *defs, - unsigned int define_count, - MOJOSHADER_includeOpen include_open, - MOJOSHADER_includeClose include_close, - MOJOSHADER_malloc m, MOJOSHADER_free f, - void *d); - +DECLSPEC int MOJOSHADER_glGetVertexAttribLocation(MOJOSHADER_usage usage, int index); /* - * Call this to dispose of compile results when you are done with them. - * This will call the MOJOSHADER_free function you provided to - * MOJOSHADER_compile() multiple times, if you provided one. - * Passing a NULL here is a safe no-op. + * Connect a client-side array to the currently-bound program. * - * This function is thread safe, so long as any allocator you passed into - * MOJOSHADER_compile() is, too. + * (usage) and (index) map to Direct3D vertex declaration values: COLOR1 would + * be MOJOSHADER_USAGE_COLOR and 1. + * + * The caller should bind VBOs before this call and treat (ptr) as an offset, + * if appropriate. + * + * MojoShader will figure out where to plug this stream into the + * currently-bound program, and enable the appropriate client-side array. + * + * (size), (type), (normalized), (stride), and (ptr) correspond to + * glVertexAttribPointer()'s parameters (in most cases, these get passed + * unmolested to that very entry point during this function). + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * + * Vertex attributes are not shared between contexts. */ -void MOJOSHADER_freeCompileData(const MOJOSHADER_compileData *data); - + /* !!! FIXME: this should probably be "input" and not "attribute" */ + /* !!! FIXME: or maybe "vertex array" or something. */ +DECLSPEC void MOJOSHADER_glSetVertexAttribute(MOJOSHADER_usage usage, + int index, unsigned int size, + MOJOSHADER_attributeType type, + int normalized, unsigned int stride, + const void *ptr); -/* OpenGL interface... */ +/* + * Modify the rate at which this vertex attribute advances during instanced + * rendering. + * + * This should be called alongside glSetVertexAttribute, as this does not flag + * the vertex array as being in use. This just calls glVertexAttribDivisorARB. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * + * Vertex attributes are not shared between contexts. + */ +DECLSPEC void MOJOSHADER_glSetVertexAttribDivisor(MOJOSHADER_usage usage, + int index, unsigned int divisor); /* - * Signature for function lookup callbacks. MojoShader will call a function - * you provide to get OpenGL entry points (both standard functions and - * extensions). Through this, MojoShader never links directly to OpenGL, - * but relies on you to provide the implementation. This means you can - * swap in different drivers, or hook functions (log every GL call MojoShader - * makes, etc). + * Inform MojoShader that it should commit any pending state to the GL. This + * must be called after you bind a program and update any inputs, right + * before you start drawing, so any outstanding changes made to the shared + * constants array (etc) can propagate to the shader during this call. * - * (fnname) is the function name we want the address for ("glBegin" or - * whatever. (data) is a void pointer you provide, if this callback needs - * extra information. If you don't need it, you may specify NULL. + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. * - * Return the entry point on success, NULL if it couldn't be found. - * Note that this could ask for standard entry points like glEnable(), or - * extensions like glProgramLocalParameterI4ivNV(), so you might need - * to check two places to find the desired entry point, depending on your - * platform (Windows might need to look in OpenGL32.dll and use WGL, etc). + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). */ -typedef void *(*MOJOSHADER_glGetProcAddress)(const char *fnname, void *data); +DECLSPEC void MOJOSHADER_glProgramReady(void); +/* + * Provide information about the current viewport to the prepared shader + * program. + * + * There are numerous components of OpenGL and Direct3D where the coordinate + * systems do not match, and so the vertex/pixel shaders have to be modified to + * compensate for these mismatches (for example, gl_FragCoord requires some + * additional math on the Y coordinate to match vPos when rendering to the + * backbuffer). Call this after MOJOSHADER_glProgramReady to apply all of the + * relevant coordinate fixups at once. + * + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + */ +DECLSPEC void MOJOSHADER_glProgramViewportInfo(int viewportW, int viewportH, + int backbufferW, int backbufferH, + int renderTargetBound); /* - * "Contexts" map to OpenGL contexts...you need one per window, or whatever, - * and need to inform MojoShader when you make a new one current. + * Free the resources of a linked program. This will delete the GL object + * and free memory. + * + * If the program is currently bound by MOJOSHADER_glBindProgram(), it will + * be deleted as soon as it becomes unbound. * - * "Shaders" refer to individual vertex or pixel programs, and are created - * by "compiling" Direct3D shader bytecode. A vertex and pixel shader are - * "linked" into a "Program" before you can use them to render. + * This call is NOT thread safe! As most OpenGL implementations are not thread + * safe, you should probably only call this from the same thread that created + * the GL context. * - * To the calling application, these are all opaque handles. + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). */ -typedef struct MOJOSHADER_glContext MOJOSHADER_glContext; -typedef struct MOJOSHADER_glShader MOJOSHADER_glShader; -typedef struct MOJOSHADER_glProgram MOJOSHADER_glProgram; - +DECLSPEC void MOJOSHADER_glDeleteProgram(MOJOSHADER_glProgram *program); /* - * Get a list of available profiles. This will fill in the array (profs) - * with up to (size) pointers of profiles that the current system can handle; - * that is, the profiles are built into MojoShader and the OpenGL extensions - * required for them exist at runtime. This function returns the number of - * available profiles, which may be more, less, or equal to (size). - * - * If there are more than (size) profiles, the (profs) buffer will not - * overflow. You can check the return value for the total number of - * available profiles, allocate more space, and try again if necessary. - * Calling this function with (size) == 0 is legal. - * - * You can only call this AFTER you have successfully built your GL context - * and made it current. This function will lookup the GL functions it needs - * through the callback you supply, via (lookup) and (d). The lookup function - * is neither stored nor used by MojoShader after this function returns, nor - * are the functions it might look up. + * Free the resources of a compiled shader. This will delete the GL object + * and free memory. * - * You should not free any strings returned from this function; they are - * pointers to internal, probably static, memory. + * If the shader is currently referenced by a linked program (or is currently + * bound with MOJOSHADER_glBindShaders()), it will be deleted as soon as all + * referencing programs are deleted and it is no longer bound, too. * * This call is NOT thread safe! As most OpenGL implementations are not thread * safe, you should probably only call this from the same thread that created * the GL context. + * + * This call requires a valid MOJOSHADER_glContext to have been made current, + * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). */ -int MOJOSHADER_glAvailableProfiles(MOJOSHADER_glGetProcAddress lookup, void *d, - const char **profs, const int size); - +DECLSPEC void MOJOSHADER_glDeleteShader(MOJOSHADER_glShader *shader); /* - * Determine the best profile to use for the current system. + * Deinitialize MojoShader's OpenGL shader management. * - * You can only call this AFTER you have successfully built your GL context - * and made it current. This function will lookup the GL functions it needs - * through the callback you supply via (lookup) and (d). The lookup function - * is neither stored nor used by MojoShader after this function returns, nor - * are the functions it might look up. + * You must call this once, while your GL context (not MojoShader context) is + * still current, if you previously had a successful call to + * MOJOSHADER_glCreateContext(). This should be the last MOJOSHADER_gl* + * function you call until you've prepared a context again. * - * Returns the name of the "best" profile on success, NULL if none of the - * available profiles will work on this system. "Best" is a relative term, - * but it generally means the best trade off between feature set and - * performance. The selection algorithm may be arbitrary and complex. + * This will clean up resources previously allocated, and may call into the GL. * - * The returned value is an internal static string, and should not be free()'d - * by the caller. If you get a NULL, calling MOJOSHADER_glGetError() might - * shed some light on why. + * This will not clean up shaders and programs you created! Please call + * MOJOSHADER_glDeleteShader() and MOJOSHADER_glDeleteProgram() to clean + * those up before calling this function! * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * This function destroys the MOJOSHADER_glContext you pass it. If it's the + * current context, then no context will be current upon return. + * + * This call is NOT thread safe! There must not be any other MOJOSHADER_gl* + * functions running when this is called. Also, as most OpenGL implementations + * are not thread safe, you should probably only call this from the same + * thread that created the GL context. */ -const char *MOJOSHADER_glBestProfile(MOJOSHADER_glGetProcAddress lookup, void *d); +DECLSPEC void MOJOSHADER_glDestroyContext(MOJOSHADER_glContext *ctx); + + +/* D3D11 interface... */ +typedef struct MOJOSHADER_d3d11Context MOJOSHADER_d3d11Context; +typedef struct MOJOSHADER_d3d11Shader MOJOSHADER_d3d11Shader; /* - * Prepare MojoShader to manage OpenGL shaders. + * Prepare MojoShader to manage Direct3D 11 shaders. * * You do not need to call this if all you want is MOJOSHADER_parse(). * - * You must call this once AFTER you have successfully built your GL context - * and made it current. This function will lookup the GL functions it needs - * through the callback you supply via (lookup) and (lookup_d), after which - * it may call them at any time up until you call - * MOJOSHADER_glDestroyContext(). The lookup function is neither stored nor - * used by MojoShader after this function returns. - * - * (profile) is an OpenGL-specific MojoShader profile, which decides how - * Direct3D bytecode shaders get turned into OpenGL programs, and how they - * are fed to the GL. - * - * (lookup) is a callback that is used to load GL entry points. This callback - * has to look up base GL functions and extension entry points. The pointer - * you supply in (lookup_d) is passed as-is to the callback. + * You must call this once AFTER you have successfully built your D3D11 context. * * As MojoShader requires some memory to be allocated, you may provide a * custom allocator to this function, which will be used to allocate/free @@ -2602,38 +1827,19 @@ const char *MOJOSHADER_glBestProfile(MOJOSHADER_glGetProcAddress lookup, void *d * (malloc_d) parameter. This pointer is passed as-is to your (m) and (f) * functions. * - * Returns a new context on success, NULL on error. If you get a new context, - * you need to make it current before using it with - * MOJOSHADER_glMakeContextCurrent(). - * - * This call is NOT thread safe! It must return success before you may call - * any other MOJOSHADER_gl* function. Also, as most OpenGL implementations - * are not thread safe, you should probably only call this from the same - * thread that created the GL context. - */ -MOJOSHADER_glContext *MOJOSHADER_glCreateContext(const char *profile, - MOJOSHADER_glGetProcAddress lookup, - void *lookup_d, - MOJOSHADER_malloc m, MOJOSHADER_free f, - void *malloc_d); - -/* - * You must call this before using the context that you got from - * MOJOSHADER_glCreateContext(), and must use it when you switch to a new GL - * context. - * - * You can only have one MOJOSHADER_glContext per actual GL context, or - * undefined behaviour will result. - * - * It is legal to call this with a NULL pointer to make no context current, - * but you need a valid context to be current to use most of MojoShader. + * This call is only as thread safe as your D3D11 context! If you call your + * context from multiple threads, you must protect this call with whatever + * thread synchronization technique you have for your other D3D calls. */ -void MOJOSHADER_glMakeContextCurrent(MOJOSHADER_glContext *ctx); +DECLSPEC MOJOSHADER_d3d11Context *MOJOSHADER_d3d11CreateContext(void *device, + void *deviceContext, + MOJOSHADER_malloc m, + MOJOSHADER_free f, + void *malloc_d); /* - * Get any error state we might have picked up. MojoShader will NOT call - * glGetError() internally, but there are other errors we can pick up, - * such as failed shader compilation, etc. + * Get any error state we might have picked up, such as failed shader + * compilation. * * Returns a human-readable string. This string is for debugging purposes, and * not guaranteed to be localized, coherent, or user-friendly in any way. @@ -2646,590 +1852,1296 @@ void MOJOSHADER_glMakeContextCurrent(MOJOSHADER_glContext *ctx); * Do not free the returned string: it's a pointer to a static internal * buffer. Do not keep the pointer around, either, as it's likely to become * invalid as soon as you call into MojoShader again. + */ +DECLSPEC const char *MOJOSHADER_d3d11GetError(MOJOSHADER_d3d11Context *context); + +/* + * Compile a buffer of Direct3D 9 shader bytecode into a Direct3D 11 shader. + * You still need to link the shader before you may render with it. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * (mainfn) is the name of the shader's main function. + * (tokenbuf) is a buffer of Direct3D shader bytecode. + * (bufsize) is the size, in bytes, of the bytecode buffer. + * (swiz), (swizcount), (smap), and (smapcount) are passed to + * MOJOSHADER_parse() unmolested. * - * This call does NOT require a valid MOJOSHADER_glContext to have been made - * current. The error buffer is shared between contexts, so you can get - * error results from a failed MOJOSHADER_glCreateContext(). + * Returns NULL on error, or a shader handle on success. + * + * This call is only as thread safe as your D3D11 context! If you call your + * context from multiple threads, you must protect this call with whatever + * thread synchronization technique you have for your other D3D calls. */ -const char *MOJOSHADER_glGetError(void); +DECLSPEC MOJOSHADER_d3d11Shader *MOJOSHADER_d3d11CompileShader(MOJOSHADER_d3d11Context *context, + const char *mainfn, + const unsigned char *tokenbuf, + const unsigned int bufsize, + const MOJOSHADER_swizzle *swiz, + const unsigned int swizcount, + const MOJOSHADER_samplerMap *smap, + const unsigned int smapcount); /* - * Get the maximum uniforms a shader can support for the current GL context, - * MojoShader profile, and shader type. You can use this to make decisions - * about what shaders you want to use (for example, a less complicated - * shader may be swapped in for lower-end systems). + * Increments a shader's internal refcount. To decrement the refcount, call + * MOJOSHADER_glDeleteShader(). * - * Returns the number, or -1 on error. + * This call is only as thread safe as your D3D11 context! If you call your + * context from multiple threads, you must protect this call with whatever + * thread synchronization technique you have for your other D3D calls. + */ +DECLSPEC void MOJOSHADER_d3d11ShaderAddRef(MOJOSHADER_d3d11Shader *shader); + +/* + * Get the MOJOSHADER_parseData structure that was produced from the + * call to MOJOSHADER_d3d11CompileShader(). * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * This data is read-only, and you should NOT attempt to free it. This + * pointer remains valid until the shader is deleted. + */ +DECLSPEC const MOJOSHADER_parseData *MOJOSHADER_d3d11GetShaderParseData( + MOJOSHADER_d3d11Shader *shader); + +/* + * This binds individual shaders together, to be linked into a single working + * program once MOJOSHADER_d3d11ProgramReady is called. * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * This call is only as thread safe as your D3D11 context! If you call your + * context from multiple threads, you must protect this call with whatever + * thread synchronization technique you have for your other D3D calls. */ -int MOJOSHADER_glMaxUniforms(MOJOSHADER_shaderType shader_type); +DECLSPEC void MOJOSHADER_d3d11BindShaders(MOJOSHADER_d3d11Context *context, + MOJOSHADER_d3d11Shader *vshader, + MOJOSHADER_d3d11Shader *pshader); /* - * Compile a buffer of Direct3D shader bytecode into an OpenGL shader. - * You still need to link the shader before you may render with it. + * This queries for the shaders currently bound to the active context. * - * (tokenbuf) is a buffer of Direct3D shader bytecode. - * (bufsize) is the size, in bytes, of the bytecode buffer. - * (swiz), (swizcount), (smap), and (smapcount) are passed to - * MOJOSHADER_parse() unmolested. + * This function is only for convenience, specifically for compatibility with + * the effects API. * - * Returns NULL on error, or a shader handle on success. + * This call is only as thread safe as your D3D11 context! If you call your + * context from multiple threads, you must protect this call with whatever + * thread synchronization technique you have for your other D3D calls. + */ +DECLSPEC void MOJOSHADER_d3d11GetBoundShaders(MOJOSHADER_d3d11Context *context, + MOJOSHADER_d3d11Shader **vshader, + MOJOSHADER_d3d11Shader **pshader); + +/* + * Fills register pointers with pointers that are directly used to push uniform + * data to the D3D11 shader context. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * This function is really just for the effects API, you should NOT be using + * this unless you know every single line of MojoShader from memory. * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * This call is only as thread safe as your D3D11 context! If you call your + * context from multiple threads, you must protect this call with whatever + * thread synchronization technique you have for your other D3D calls. + */ +DECLSPEC void MOJOSHADER_d3d11MapUniformBufferMemory(MOJOSHADER_d3d11Context *context, + float **vsf, int **vsi, unsigned char **vsb, + float **psf, int **psi, unsigned char **psb); + +/* + * Tells the context that you are done with the memory mapped by + * MOJOSHADER_d3d11MapUniformBufferMemory(). * - * Compiled shaders from this function may not be shared between contexts. + * This call is only as thread safe as your D3D11 context! If you call your + * context from multiple threads, you must protect this call with whatever + * thread synchronization technique you have for your other D3D calls. */ -MOJOSHADER_glShader *MOJOSHADER_glCompileShader(const unsigned char *tokenbuf, - const unsigned int bufsize, - const MOJOSHADER_swizzle *swiz, - const unsigned int swizcount, - const MOJOSHADER_samplerMap *smap, - const unsigned int smapcount); +DECLSPEC void MOJOSHADER_d3d11UnmapUniformBufferMemory(MOJOSHADER_d3d11Context *context); +/* + * Return the location of a vertex attribute for the given vertex shader. + * + * (usage) and (index) map to Direct3D vertex declaration values: COLOR1 would + * be MOJOSHADER_USAGE_COLOR and 1. + * + * The return value is the index of the attribute to be used when building the + * input layout object. + */ +DECLSPEC int MOJOSHADER_d3d11GetVertexAttribLocation(MOJOSHADER_d3d11Shader *vert, + MOJOSHADER_usage usage, + int index); /* - * Get the MOJOSHADER_parseData structure that was produced from the - * call to MOJOSHADER_glCompileShader(). + * Using the given input layout, compiles the vertex shader with input + * parameters that will be compatible with the incoming vertex data. * - * This data is read-only, and you should NOT attempt to free it. This - * pointer remains valid until the shader is deleted. + * (inputLayoutHash) is an application-defined value to differentiate unique + * vertex declarations that will be passed to the vertex shader. + * (elements) is an array of D3D11_INPUT_ELEMENT_DESCs, with (elementCount) + * entries. (bytecode) and (bytecodeLength) will be filled with the final + * compiled D3D11 vertex shader. + * + * Returns 0 on success, nonzero on error. + * + * This call is only as thread safe as your D3D11 context! If you call your + * context from multiple threads, you must protect this call with whatever + * thread synchronization technique you have for your other D3D calls. */ -const MOJOSHADER_parseData *MOJOSHADER_glGetShaderParseData( - MOJOSHADER_glShader *shader); +DECLSPEC int MOJOSHADER_d3d11CompileVertexShader(MOJOSHADER_d3d11Context *ctx, + unsigned long long inputLayoutHash, + void *elements, int elementCount, + void **bytecode, int *bytecodeLength); + /* - * Link a vertex and pixel shader into an OpenGL program. - * (vshader) or (pshader) can be NULL, to specify that the GL should use the - * fixed-function pipeline instead of the programmable pipeline for that - * portion of the work. You can reuse shaders in various combinations across - * multiple programs, by relinking different pairs. + * Inform MojoShader that it should commit any pending state and prepare the + * final shader program object, linking the input/output parameter data to + * be compatible with the more-strict Shader Model 4 rule set. This must be + * called after you bind shaders and update any inputs, right before you start + * drawing, so any outstanding changes made to the shared constants array (etc) + * can propagate to the shader during this call. * - * It is illegal to give a vertex shader for (pshader) or a pixel shader - * for (vshader). + * Returns 0 on success, nonzero on error. * - * Once you have successfully linked a program, you may render with it. + * This call is only as thread safe as your D3D11 context! If you call your + * context from multiple threads, you must protect this call with whatever + * thread synchronization technique you have for your other D3D calls. + */ +DECLSPEC int MOJOSHADER_d3d11ProgramReady(MOJOSHADER_d3d11Context *context, + unsigned long long inputLayoutHash); + +/* + * Free the resources of a compiled shader. This will delete the shader object + * and free memory. * - * Returns NULL on error, or a program handle on success. + * This call is only as thread safe as your D3D11 context! If you call your + * context from multiple threads, you must protect this call with whatever + * thread synchronization technique you have for your other D3D calls. + */ +DECLSPEC void MOJOSHADER_d3d11DeleteShader(MOJOSHADER_d3d11Context *context, + MOJOSHADER_d3d11Shader *shader); + +/* + * Deinitialize MojoShader's D3D11 shader management. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * This will clean up resources previously allocated for the active context. * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * This will NOT clean up shaders you created! Please destroy all shaders + * before calling this function. + */ +DECLSPEC void MOJOSHADER_d3d11DestroyContext(MOJOSHADER_d3d11Context *context); + + +/* SDL_GPU interface... */ + +typedef struct MOJOSHADER_sdlContext MOJOSHADER_sdlContext; +typedef struct MOJOSHADER_sdlShaderData MOJOSHADER_sdlShaderData; +typedef struct MOJOSHADER_sdlProgram MOJOSHADER_sdlProgram; + +#ifndef SDL_GPU_H +typedef struct SDL_GPUDevice SDL_GPUDevice; +typedef struct SDL_GPUShader SDL_GPUShader; +typedef struct SDL_GPUCommandBuffer SDL_GPUCommandBuffer; +#endif /* SDL_GPU_H */ + +/* + * Call this function to get the 'formatFlags' parameter for + * SDL_CreateGPUDevice. * - * Linked programs from this function may not be shared between contexts. + * Returns the SDL_GPUShaderFormatFlagBits for creating the SDL_GPUDevice. */ -MOJOSHADER_glProgram *MOJOSHADER_glLinkProgram(MOJOSHADER_glShader *vshader, - MOJOSHADER_glShader *pshader); +DECLSPEC unsigned int MOJOSHADER_sdlGetShaderFormats(void); /* - * This binds the program (using, for example, glUseProgramObjectARB()), and - * disables all the client-side arrays so we can reset them with new values - * if appropriate. + * Prepares a context to manage SDL_gpu shaders. * - * Call with NULL to disable the programmable pipeline and all enabled - * client-side arrays. + * You do not need to call this if all you want is MOJOSHADER_parse(). * - * After binding a program, you should update any uniforms you care about - * with MOJOSHADER_glSetVertexShaderUniformF() (etc), set any vertex arrays - * you want to use with MOJOSHADER_glSetVertexAttribute(), and finally call - * MOJOSHADER_glProgramReady() to commit everything to the GL. Then you may - * begin drawing through standard GL entry points. + * (device) refers to the SDL_GPUDevice. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * You can only have one MOJOSHADER_sdlContext per actual SDL_gpu context, or + * undefined behaviour will result. * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * As MojoShader requires some memory to be allocated, you may provide a + * custom allocator to this function, which will be used to allocate/free + * memory. They function just like malloc() and free(). We do not use + * realloc(). If you don't care, pass NULL in for the allocator functions. + * If your allocator needs instance-specific data, you may supply it with the + * (malloc_d) parameter. This pointer is passed as-is to your (m) and (f) + * functions. + * + * Returns a new context on success, NULL on error. */ -void MOJOSHADER_glBindProgram(MOJOSHADER_glProgram *program); +DECLSPEC MOJOSHADER_sdlContext *MOJOSHADER_sdlCreateContext(SDL_GPUDevice *device, + MOJOSHADER_malloc m, + MOJOSHADER_free f, + void *malloc_d); /* - * This binds individual shaders as if you had linked them with - * MOJOSHADER_glLinkProgram(), and used MOJOSHADER_glBindProgram() on the - * linked result. + * Get any error state we might have picked up. * - * MojoShader will handle linking behind the scenes, and keep a cache of - * programs linked here. Programs are removed from this cache when one of the - * invidual shaders in it is deleted, otherwise they remain cached so future - * calls to this function don't need to relink a previously-used shader - * grouping. + * Returns a human-readable string. This string is for debugging purposes, and + * not guaranteed to be localized, coherent, or user-friendly in any way. + * It's for programmers! + * + * The latest error may remain between calls. New errors replace any existing + * error. Don't check this string for a sign that an error happened, check + * return codes instead and use this for explanation when debugging. + * + * Do not free the returned string: it's a pointer to a static internal + * buffer. Do not keep the pointer around, either, as it's likely to become + * invalid as soon as you call into MojoShader again. + * + * This call does NOT require a valid MOJOSHADER_sdlContext to have been made + * current. The error buffer is shared between contexts, so you can get + * error results from a failed MOJOSHADER_sdlCreateContext(). + */ +DECLSPEC const char *MOJOSHADER_sdlGetError(MOJOSHADER_sdlContext *ctx); + +/* + * Deinitialize MojoShader's SDL_gpu shader management. * - * This function is for convenience, as the API is closer to how Direct3D - * works, and retrofitting linking into your app can be difficult; - * frequently, you just end up building your own cache, anyhow. + * You must call this once, while your SDL_GPUDevice is still valid. This should + * be the last MOJOSHADER_sdl* function you call until you've prepared a context + * again. * - * Calling with all shaders set to NULL is equivalent to calling - * MOJOSHADER_glBindProgram(NULL). + * This will clean up resources previously allocated, and may call into SDL_gpu. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * This will not clean up shaders and programs you created! Please call + * MOJOSHADER_sdlDeleteShader() and MOJOSHADER_sdlDeleteProgram() to clean + * those up before calling this function! * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * This function destroys the MOJOSHADER_sdlContext you pass it. */ -void MOJOSHADER_glBindShaders(MOJOSHADER_glShader *vshader, - MOJOSHADER_glShader *pshader); +DECLSPEC void MOJOSHADER_sdlDestroyContext(MOJOSHADER_sdlContext *ctx); /* - * Set a floating-point uniform value (what Direct3D calls a "constant"). + * Compile a buffer of Direct3D shader bytecode into an SDL_gpu shader module. * - * There is a single array of 4-float "registers" shared by all vertex shaders. - * This is the "c" register file in Direct3D (c0, c1, c2, etc...) - * MojoShader will take care of synchronizing this internal array with the - * appropriate variables in the GL shaders. + * (tokenbuf) is a buffer of Direct3D shader bytecode. + * (bufsize) is the size, in bytes, of the bytecode buffer. + * (swiz), (swizcount), (smap), and (smapcount) are passed to + * MOJOSHADER_parse() unmolested. * - * (idx) is the index into the internal array: 0 is the first four floats, - * 1 is the next four, etc. - * (data) is a pointer to (vec4count*4) floats. + * Returns NULL on error, or a shader handle on success. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * Compiled shaders from this function may not be shared between contexts. + */ +DECLSPEC MOJOSHADER_sdlShaderData *MOJOSHADER_sdlCompileShader(MOJOSHADER_sdlContext *ctx, + const char *mainfn, + const unsigned char *tokenbuf, + const unsigned int bufsize, + const MOJOSHADER_swizzle *swiz, + const unsigned int swizcount, + const MOJOSHADER_samplerMap *smap, + const unsigned int smapcount); + +/* + * Increments a shader's internal refcount. * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * To decrement the refcount, call MOJOSHADER_sdlDeleteShader(). + */ +DECLSPEC void MOJOSHADER_sdlShaderAddRef(MOJOSHADER_sdlShaderData *shader); + +/* + * Decrements a shader's internal refcount, and deletes if the refcount is zero. * - * Uniforms are not shared between contexts. + * To increment the refcount, call MOJOSHADER_sdlShaderAddRef(). */ -void MOJOSHADER_glSetVertexShaderUniformF(unsigned int idx, const float *data, - unsigned int vec4count); +DECLSPEC void MOJOSHADER_sdlDeleteShader(MOJOSHADER_sdlContext *ctx, + MOJOSHADER_sdlShaderData *shader); /* - * Retrieve a floating-point uniform value (what Direct3D calls a "constant"). + * Get the MOJOSHADER_parseData structure that was produced from the + * call to MOJOSHADER_sdlCompileShader(). * - * There is a single array of 4-float "registers" shared by all vertex shaders. - * This is the "c" register file in Direct3D (c0, c1, c2, etc...) - * MojoShader will take care of synchronizing this internal array with the - * appropriate variables in the GL shaders. + * This data is read-only, and you should NOT attempt to free it. This + * pointer remains valid until the shader is deleted. + */ +DECLSPEC const MOJOSHADER_parseData *MOJOSHADER_sdlGetShaderParseData( + MOJOSHADER_sdlShaderData *shader); + +/* + * Link bound vertex and pixel shader into a working SDL_gpu shader program. + * (vshader) or (pshader) can NOT be NULL, unlike OpenGL. * - * (idx) is the index into the internal array: 0 is the first four floats, - * 1 is the next four, etc. - * (data) is a pointer to space for (vec4count*4) floats. - * (data) will be filled will current values in the register file. Results - * are undefined if you request data past the end of the register file or - * previously uninitialized registers. + * You can reuse shaders in various combinations across + * multiple programs, by relinking different pairs. * - * This is a "fast" call; we're just reading memory from internal memory. We - * do not query the GPU or the GL for this information. + * Requires vertex element data for patches. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * It is illegal to give a vertex shader for (pshader) or a pixel shader + * for (vshader). * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * Once you have successfully linked a program, you may render with it. * - * Uniforms are not shared between contexts. + * Returns NULL on error, or a program handle on success. */ -void MOJOSHADER_glGetVertexShaderUniformF(unsigned int idx, float *data, - unsigned int vec4count); - +DECLSPEC MOJOSHADER_sdlProgram *MOJOSHADER_sdlLinkProgram(MOJOSHADER_sdlContext *context, + MOJOSHADER_vertexAttribute *vertexAttributes, + int vertexAttributeCount); /* - * Set an integer uniform value (what Direct3D calls a "constant"). - * - * There is a single array of 4-int "registers" shared by all vertex shaders. - * This is the "i" register file in Direct3D (i0, i1, i2, etc...) - * MojoShader will take care of synchronizing this internal array with the - * appropriate variables in the GL shaders. - * - * (idx) is the index into the internal array: 0 is the first four ints, - * 1 is the next four, etc. - * (data) is a pointer to (ivec4count*4) ints. - * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * This binds the program to the active context, and does nothing particularly + * special until you start working with uniform buffers or shader modules. * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * After binding a program, you should update any uniforms you care about + * with MOJOSHADER_sdlMapUniformBufferMemory() (etc), set any vertex arrays + * using MOJOSHADER_sdlGetVertexAttribLocation(), and finally call + * MOJOSHADER_sdlGetShaders() to get the final modules. Then you may + * begin building your pipeline state objects. + */ +DECLSPEC void MOJOSHADER_sdlBindProgram(MOJOSHADER_sdlContext *context, + MOJOSHADER_sdlProgram *program); + +/* + * Free the resources of a linked program. This will delete the shader modules + * and free memory. * - * Uniforms are not shared between contexts. + * If the program is currently bound by MOJOSHADER_sdlBindProgram(), it will + * be deleted as soon as it becomes unbound. */ -void MOJOSHADER_glSetVertexShaderUniformI(unsigned int idx, const int *data, - unsigned int ivec4count); +DECLSPEC void MOJOSHADER_sdlDeleteProgram(MOJOSHADER_sdlContext *context, + MOJOSHADER_sdlProgram *program); /* - * Retrieve an integer uniform value (what Direct3D calls a "constant"). + * This "binds" individual shaders, which effectively means the context + * will store these shaders for later retrieval. No actual binding or + * pipeline creation is performed. * - * There is a single array of 4-int "registers" shared by all vertex shaders. - * This is the "i" register file in Direct3D (i0, i1, i2, etc...) - * MojoShader will take care of synchronizing this internal array with the - * appropriate variables in the GL shaders. + * This function is only for convenience, specifically for compatibility + * with the effects API. + */ +DECLSPEC void MOJOSHADER_sdlBindShaders(MOJOSHADER_sdlContext *ctx, + MOJOSHADER_sdlShaderData *vshader, + MOJOSHADER_sdlShaderData *pshader); + +/* + * This queries for the shaders currently bound to the active context. * - * (idx) is the index into the internal array: 0 is the first four ints, - * 1 is the next four, etc. - * (data) is a pointer to space for (ivec4count*4) ints. - * (data) will be filled will current values in the register file. Results - * are undefined if you request data past the end of the register file or - * previously uninitialized registers. + * This function is only for convenience, specifically for compatibility + * with the effects API. + */ +DECLSPEC void MOJOSHADER_sdlGetBoundShaderData(MOJOSHADER_sdlContext *ctx, + MOJOSHADER_sdlShaderData **vshader, + MOJOSHADER_sdlShaderData **pshader); + +/* + * Fills register pointers with pointers that are directly used to push uniform + * data to the SDL3 shader context. * - * This is a "fast" call; we're just reading memory from internal memory. We - * do not query the GPU or the GL for this information. + * This function is really just for the effects API, you should NOT be using + * this unless you know every single line of MojoShader from memory. + */ +DECLSPEC void MOJOSHADER_sdlMapUniformBufferMemory(MOJOSHADER_sdlContext *ctx, + float **vsf, int **vsi, unsigned char **vsb, + float **psf, int **psi, unsigned char **psb); + +/* + * Tells the context that you are done with the memory mapped by + * MOJOSHADER_sdlMapUniformBufferMemory(). + */ +DECLSPEC void MOJOSHADER_sdlUnmapUniformBufferMemory(MOJOSHADER_sdlContext *ctx); + +/* + * Returns the minimum required size of the uniform buffer for this shader. + * You will need this to fill out the SDL_GPUGraphicsPipelineCreateInfo struct. + */ +DECLSPEC int MOJOSHADER_sdlGetUniformBufferSize(MOJOSHADER_sdlShaderData *shader); + +/* + * Pushes the uniform buffer updates for the currently bound program. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * This function will record calls to SDL_GPUPush*ShaderUniforms into the + * passed command buffer. + */ +DECLSPEC void MOJOSHADER_sdlUpdateUniformBuffers(MOJOSHADER_sdlContext *ctx, + SDL_GPUCommandBuffer *cb); + +/* + * Return the location of a vertex attribute for the given shader. * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * (usage) and (index) map to Direct3D vertex declaration values: COLOR1 would + * be MOJOSHADER_USAGE_COLOR and 1. * - * Uniforms are not shared between contexts. + * The return value is the index of the attribute to be used to create + * an SDL_GPUVertexAttribute, or -1 if the stream is not used. + */ +DECLSPEC int MOJOSHADER_sdlGetVertexAttribLocation(MOJOSHADER_sdlShaderData *vert, + MOJOSHADER_usage usage, + int index); + +/* + * Get the SDL_GPUShaderModules from the currently bound shader program. + */ +DECLSPEC void MOJOSHADER_sdlGetShaders(MOJOSHADER_sdlContext *ctx, + SDL_GPUShader **vshader, + SDL_GPUShader **pshader); + +/* + * Gets the number of sampler slots needed by a given shader module. + */ +DECLSPEC unsigned int MOJOSHADER_sdlGetSamplerSlots(MOJOSHADER_sdlShaderData *shader); + + +/* Effects interface... */ + +#ifdef MOJOSHADER_EFFECT_SUPPORT + +/* MOJOSHADER_effectState types... */ + +typedef enum MOJOSHADER_renderStateType +{ + /* Note that we are NOT using the actual RS values from D3D here. + * For some reason, in the binary data, it's 0-based. + * Even worse, it doesn't even seem to be in order. + * Here is the list of changes compared to the real D3DRS enum: + * - All of the RS_WRAP values are in a row, not separate! + * + * -flibit + */ + MOJOSHADER_RS_ZENABLE, + MOJOSHADER_RS_FILLMODE, + MOJOSHADER_RS_SHADEMODE, + MOJOSHADER_RS_ZWRITEENABLE, + MOJOSHADER_RS_ALPHATESTENABLE, + MOJOSHADER_RS_LASTPIXEL, + MOJOSHADER_RS_SRCBLEND, + MOJOSHADER_RS_DESTBLEND, + MOJOSHADER_RS_CULLMODE, + MOJOSHADER_RS_ZFUNC, + MOJOSHADER_RS_ALPHAREF, + MOJOSHADER_RS_ALPHAFUNC, + MOJOSHADER_RS_DITHERENABLE, + MOJOSHADER_RS_ALPHABLENDENABLE, + MOJOSHADER_RS_FOGENABLE, + MOJOSHADER_RS_SPECULARENABLE, + MOJOSHADER_RS_FOGCOLOR, + MOJOSHADER_RS_FOGTABLEMODE, + MOJOSHADER_RS_FOGSTART, + MOJOSHADER_RS_FOGEND, + MOJOSHADER_RS_FOGDENSITY, + MOJOSHADER_RS_RANGEFOGENABLE, + MOJOSHADER_RS_STENCILENABLE, + MOJOSHADER_RS_STENCILFAIL, + MOJOSHADER_RS_STENCILZFAIL, + MOJOSHADER_RS_STENCILPASS, + MOJOSHADER_RS_STENCILFUNC, + MOJOSHADER_RS_STENCILREF, + MOJOSHADER_RS_STENCILMASK, + MOJOSHADER_RS_STENCILWRITEMASK, + MOJOSHADER_RS_TEXTUREFACTOR, + MOJOSHADER_RS_WRAP0, + MOJOSHADER_RS_WRAP1, + MOJOSHADER_RS_WRAP2, + MOJOSHADER_RS_WRAP3, + MOJOSHADER_RS_WRAP4, + MOJOSHADER_RS_WRAP5, + MOJOSHADER_RS_WRAP6, + MOJOSHADER_RS_WRAP7, + MOJOSHADER_RS_WRAP8, + MOJOSHADER_RS_WRAP9, + MOJOSHADER_RS_WRAP10, + MOJOSHADER_RS_WRAP11, + MOJOSHADER_RS_WRAP12, + MOJOSHADER_RS_WRAP13, + MOJOSHADER_RS_WRAP14, + MOJOSHADER_RS_WRAP15, + MOJOSHADER_RS_CLIPPING, + MOJOSHADER_RS_LIGHTING, + MOJOSHADER_RS_AMBIENT, + MOJOSHADER_RS_FOGVERTEXMODE, + MOJOSHADER_RS_COLORVERTEX, + MOJOSHADER_RS_LOCALVIEWER, + MOJOSHADER_RS_NORMALIZENORMALS, + MOJOSHADER_RS_DIFFUSEMATERIALSOURCE, + MOJOSHADER_RS_SPECULARMATERIALSOURCE, + MOJOSHADER_RS_AMBIENTMATERIALSOURCE, + MOJOSHADER_RS_EMISSIVEMATERIALSOURCE, + MOJOSHADER_RS_VERTEXBLEND, + MOJOSHADER_RS_CLIPPLANEENABLE, + MOJOSHADER_RS_POINTSIZE, + MOJOSHADER_RS_POINTSIZE_MIN, + MOJOSHADER_RS_POINTSPRITEENABLE, + MOJOSHADER_RS_POINTSCALEENABLE, + MOJOSHADER_RS_POINTSCALE_A, + MOJOSHADER_RS_POINTSCALE_B, + MOJOSHADER_RS_POINTSCALE_C, + MOJOSHADER_RS_MULTISAMPLEANTIALIAS, + MOJOSHADER_RS_MULTISAMPLEMASK, + MOJOSHADER_RS_PATCHEDGESTYLE, + MOJOSHADER_RS_DEBUGMONITORTOKEN, + MOJOSHADER_RS_POINTSIZE_MAX, + MOJOSHADER_RS_INDEXEDVERTEXBLENDENABLE, + MOJOSHADER_RS_COLORWRITEENABLE, + MOJOSHADER_RS_TWEENFACTOR, + MOJOSHADER_RS_BLENDOP, + MOJOSHADER_RS_POSITIONDEGREE, + MOJOSHADER_RS_NORMALDEGREE, + MOJOSHADER_RS_SCISSORTESTENABLE, + MOJOSHADER_RS_SLOPESCALEDEPTHBIAS, + MOJOSHADER_RS_ANTIALIASEDLINEENABLE, + MOJOSHADER_RS_MINTESSELLATIONLEVEL, + MOJOSHADER_RS_MAXTESSELLATIONLEVEL, + MOJOSHADER_RS_ADAPTIVETESS_X, + MOJOSHADER_RS_ADAPTIVETESS_Y, + MOJOSHADER_RS_ADAPTIVETESS_Z, + MOJOSHADER_RS_ADAPTIVETESS_W, + MOJOSHADER_RS_ENABLEADAPTIVETESSELLATION, + MOJOSHADER_RS_TWOSIDEDSTENCILMODE, + MOJOSHADER_RS_CCW_STENCILFAIL, + MOJOSHADER_RS_CCW_STENCILZFAIL, + MOJOSHADER_RS_CCW_STENCILPASS, + MOJOSHADER_RS_CCW_STENCILFUNC, + MOJOSHADER_RS_COLORWRITEENABLE1, + MOJOSHADER_RS_COLORWRITEENABLE2, + MOJOSHADER_RS_COLORWRITEENABLE3, + MOJOSHADER_RS_BLENDFACTOR, + MOJOSHADER_RS_SRGBWRITEENABLE, + MOJOSHADER_RS_DEPTHBIAS, + MOJOSHADER_RS_SEPARATEALPHABLENDENABLE, + MOJOSHADER_RS_SRCBLENDALPHA, + MOJOSHADER_RS_DESTBLENDALPHA, + MOJOSHADER_RS_BLENDOPALPHA, + + /* These aren't really "states", but these numbers are + * referred to by MOJOSHADER_effectStateType as such. + */ + MOJOSHADER_RS_VERTEXSHADER = 146, + MOJOSHADER_RS_PIXELSHADER = 147 +} MOJOSHADER_renderStateType; + +typedef enum MOJOSHADER_zBufferType +{ + MOJOSHADER_ZB_FALSE, + MOJOSHADER_ZB_TRUE, + MOJOSHADER_ZB_USEW +} MOJOSHADER_zBufferType; + +typedef enum MOJOSHADER_fillMode +{ + MOJOSHADER_FILL_POINT = 1, + MOJOSHADER_FILL_WIREFRAME = 2, + MOJOSHADER_FILL_SOLID = 3 +} MOJOSHADER_fillMode; + +typedef enum MOJOSHADER_shadeMode +{ + MOJOSHADER_SHADE_FLAT = 1, + MOJOSHADER_SHADE_GOURAUD = 2, + MOJOSHADER_SHADE_PHONG = 3 +} MOJOSHADER_shadeMode; + +typedef enum MOJOSHADER_blendMode +{ + MOJOSHADER_BLEND_ZERO = 1, + MOJOSHADER_BLEND_ONE = 2, + MOJOSHADER_BLEND_SRCCOLOR = 3, + MOJOSHADER_BLEND_INVSRCCOLOR = 4, + MOJOSHADER_BLEND_SRCALPHA = 5, + MOJOSHADER_BLEND_INVSRCALPHA = 6, + MOJOSHADER_BLEND_DESTALPHA = 7, + MOJOSHADER_BLEND_INVDESTALPHA = 8, + MOJOSHADER_BLEND_DESTCOLOR = 9, + MOJOSHADER_BLEND_INVDESTCOLOR = 10, + MOJOSHADER_BLEND_SRCALPHASAT = 11, + MOJOSHADER_BLEND_BOTHSRCALPHA = 12, + MOJOSHADER_BLEND_BOTHINVSRCALPHA = 13, + MOJOSHADER_BLEND_BLENDFACTOR = 14, + MOJOSHADER_BLEND_INVBLENDFACTOR = 15, + MOJOSHADER_BLEND_SRCCOLOR2 = 16, + MOJOSHADER_BLEND_INVSRCCOLOR2 = 17 +} MOJOSHADER_blendMode; + +typedef enum MOJOSHADER_cullMode +{ + MOJOSHADER_CULL_NONE = 1, + MOJOSHADER_CULL_CW = 2, + MOJOSHADER_CULL_CCW = 3 +} MOJOSHADER_cullMode; + +typedef enum MOJOSHADER_compareFunc +{ + MOJOSHADER_CMP_NEVER = 1, + MOJOSHADER_CMP_LESS = 2, + MOJOSHADER_CMP_EQUAL = 3, + MOJOSHADER_CMP_LESSEQUAL = 4, + MOJOSHADER_CMP_GREATER = 5, + MOJOSHADER_CMP_NOTEQUAL = 6, + MOJOSHADER_CMP_GREATEREQUAL = 7, + MOJOSHADER_CMP_ALWAYS = 8 +} MOJOSHADER_compareFunc; + +typedef enum MOJOSHADER_fogMode +{ + MOJOSHADER_FOG_NONE, + MOJOSHADER_FOG_EXP, + MOJOSHADER_FOG_EXP2, + MOJOSHADER_FOG_LINEAR +} MOJOSHADER_fogMode; + +typedef enum MOJOSHADER_stencilOp +{ + MOJOSHADER_STENCILOP_KEEP = 1, + MOJOSHADER_STENCILOP_ZERO = 2, + MOJOSHADER_STENCILOP_REPLACE = 3, + MOJOSHADER_STENCILOP_INCRSAT = 4, + MOJOSHADER_STENCILOP_DECRSAT = 5, + MOJOSHADER_STENCILOP_INVERT = 6, + MOJOSHADER_STENCILOP_INCR = 7, + MOJOSHADER_STENCILOP_DECR = 8 +} MOJOSHADER_stencilOp; + +typedef enum MOJOSHADER_materialColorSource +{ + MOJOSHADER_MCS_MATERIAL, + MOJOSHADER_MCS_COLOR1, + MOJOSHADER_MCS_COLOR2 +} MOJOSHADER_materialColorSource; + +typedef enum MOJOSHADER_vertexBlendFlags +{ + MOJOSHADER_VBF_DISABLE = 0, + MOJOSHADER_VBF_1WEIGHTS = 1, + MOJOSHADER_VBF_2WEIGHTS = 2, + MOJOSHADER_VBF_3WEIGHTS = 3, + MOJOSHADER_VBF_TWEENING = 255, + MOJOSHADER_VBF_0WEIGHTS = 256 +} MOJOSHADER_vertexBlendFlags; + +typedef enum MOJOSHADER_patchedEdgeStyle +{ + MOJOSHADER_PATCHEDGE_DISCRETE, + MOJOSHADER_PATCHEDGE_CONTINUOUS +} MOJOSHADER_patchedEdgeStyle; + +typedef enum MOJOSHADER_debugMonitorTokens +{ + MOJOSHADER_DMT_ENABLE, + MOJOSHADER_DMT_DISABLE +} MOJOSHADER_debugMonitorTokens; + +typedef enum MOJOSHADER_blendOp +{ + MOJOSHADER_BLENDOP_ADD = 1, + MOJOSHADER_BLENDOP_SUBTRACT = 2, + MOJOSHADER_BLENDOP_REVSUBTRACT = 3, + MOJOSHADER_BLENDOP_MIN = 4, + MOJOSHADER_BLENDOP_MAX = 5 +} MOJOSHADER_blendOp; + +typedef enum MOJOSHADER_degreeType +{ + MOJOSHADER_DEGREE_LINEAR = 1, + MOJOSHADER_DEGREE_QUADRATIC = 2, + MOJOSHADER_DEGREE_CUBIC = 3, + MOJOSHADER_DEGREE_QUINTIC = 5 +} MOJOSHADER_degreeType; + + +/* MOJOSHADER_effectSamplerState types... */ + +typedef enum MOJOSHADER_samplerStateType +{ + MOJOSHADER_SAMP_UNKNOWN0 = 0, + MOJOSHADER_SAMP_UNKNOWN1 = 1, + MOJOSHADER_SAMP_UNKNOWN2 = 2, + MOJOSHADER_SAMP_UNKNOWN3 = 3, + MOJOSHADER_SAMP_TEXTURE = 4, + MOJOSHADER_SAMP_ADDRESSU = 5, + MOJOSHADER_SAMP_ADDRESSV = 6, + MOJOSHADER_SAMP_ADDRESSW = 7, + MOJOSHADER_SAMP_BORDERCOLOR = 8, + MOJOSHADER_SAMP_MAGFILTER = 9, + MOJOSHADER_SAMP_MINFILTER = 10, + MOJOSHADER_SAMP_MIPFILTER = 11, + MOJOSHADER_SAMP_MIPMAPLODBIAS = 12, + MOJOSHADER_SAMP_MAXMIPLEVEL = 13, + MOJOSHADER_SAMP_MAXANISOTROPY = 14, + MOJOSHADER_SAMP_SRGBTEXTURE = 15, + MOJOSHADER_SAMP_ELEMENTINDEX = 16, + MOJOSHADER_SAMP_DMAPOFFSET = 17 +} MOJOSHADER_samplerStateType; + +typedef enum MOJOSHADER_textureAddress +{ + MOJOSHADER_TADDRESS_WRAP = 1, + MOJOSHADER_TADDRESS_MIRROR = 2, + MOJOSHADER_TADDRESS_CLAMP = 3, + MOJOSHADER_TADDRESS_BORDER = 4, + MOJOSHADER_TADDRESS_MIRRORONCE = 5 +} MOJOSHADER_textureAddress; + +typedef enum MOJOSHADER_textureFilterType +{ + MOJOSHADER_TEXTUREFILTER_NONE, + MOJOSHADER_TEXTUREFILTER_POINT, + MOJOSHADER_TEXTUREFILTER_LINEAR, + MOJOSHADER_TEXTUREFILTER_ANISOTROPIC, + MOJOSHADER_TEXTUREFILTER_PYRAMIDALQUAD, + MOJOSHADER_TEXTUREFILTER_GAUSSIANQUAD, + MOJOSHADER_TEXTUREFILTER_CONVOLUTIONMONO +} MOJOSHADER_textureFilterType; + + +/* Effect value types... */ + +typedef struct MOJOSHADER_effectSamplerState MOJOSHADER_effectSamplerState; + +typedef struct MOJOSHADER_effectValue +{ + const char *name; + const char *semantic; + MOJOSHADER_symbolTypeInfo type; + unsigned int value_count; + MOJOSHADERNAMELESS union + { + /* Raw value types */ + void *values; + int *valuesI; + float *valuesF; + /* As used by MOJOSHADER_effectState */ + MOJOSHADER_zBufferType *valuesZBT; + MOJOSHADER_fillMode *valuesFiM; + MOJOSHADER_shadeMode *valuesSM; + MOJOSHADER_blendMode *valuesBM; + MOJOSHADER_cullMode *valuesCM; + MOJOSHADER_compareFunc *valuesCF; + MOJOSHADER_fogMode *valuesFoM; + MOJOSHADER_stencilOp *valuesSO; + MOJOSHADER_materialColorSource *valuesMCS; + MOJOSHADER_vertexBlendFlags *valuesVBF; + MOJOSHADER_patchedEdgeStyle *valuesPES; + MOJOSHADER_debugMonitorTokens *valuesDMT; + MOJOSHADER_blendOp *valuesBO; + MOJOSHADER_degreeType *valuesDT; + /* As used by MOJOSHADER_effectSamplerState */ + MOJOSHADER_textureAddress *valuesTA; + MOJOSHADER_textureFilterType *valuesTFT; + /* As used by MOJOSHADER_effectParameter */ + MOJOSHADER_effectSamplerState *valuesSS; + }; +} MOJOSHADER_effectValue; + +typedef struct MOJOSHADER_effectState +{ + MOJOSHADER_renderStateType type; + MOJOSHADER_effectValue value; +} MOJOSHADER_effectState; + +struct MOJOSHADER_effectSamplerState +{ + MOJOSHADER_samplerStateType type; + MOJOSHADER_effectValue value; +}; + +typedef MOJOSHADER_effectValue MOJOSHADER_effectAnnotation; + + +/* Effect interface structures... */ + +typedef struct MOJOSHADER_effectParam +{ + MOJOSHADER_effectValue value; + unsigned int annotation_count; + MOJOSHADER_effectAnnotation *annotations; +} MOJOSHADER_effectParam; + +typedef struct MOJOSHADER_effectPass +{ + const char *name; + unsigned int state_count; + MOJOSHADER_effectState *states; + unsigned int annotation_count; + MOJOSHADER_effectAnnotation* annotations; +} MOJOSHADER_effectPass; + +typedef struct MOJOSHADER_effectTechnique +{ + const char *name; + unsigned int pass_count; + MOJOSHADER_effectPass *passes; + unsigned int annotation_count; + MOJOSHADER_effectAnnotation* annotations; +} MOJOSHADER_effectTechnique; + + +/* Effect "objects"... */ + +/* Defined later in the state change types... */ +typedef struct MOJOSHADER_samplerStateRegister MOJOSHADER_samplerStateRegister; + +typedef struct MOJOSHADER_effectShader +{ + MOJOSHADER_symbolType type; + unsigned int technique; + unsigned int pass; + unsigned int is_preshader; + unsigned int preshader_param_count; + unsigned int *preshader_params; + unsigned int param_count; + unsigned int *params; + unsigned int sampler_count; + MOJOSHADER_samplerStateRegister *samplers; + MOJOSHADERNAMELESS union + { + void *shader; /* glShader, mtlShader, etc. */ + const MOJOSHADER_preshader *preshader; + }; +} MOJOSHADER_effectShader; + +typedef struct MOJOSHADER_effectSamplerMap +{ + MOJOSHADER_symbolType type; + const char *name; +} MOJOSHADER_effectSamplerMap; + +typedef struct MOJOSHADER_effectString +{ + MOJOSHADER_symbolType type; + const char *string; +} MOJOSHADER_effectString; + +typedef struct MOJOSHADER_effectTexture +{ + MOJOSHADER_symbolType type; + /* FIXME: Does this even do anything? */ +} MOJOSHADER_effectTexture; + +typedef union MOJOSHADER_effectObject +{ + MOJOSHADER_symbolType type; + MOJOSHADERNAMELESS union + { + MOJOSHADER_effectShader shader; + MOJOSHADER_effectSamplerMap mapping; + MOJOSHADER_effectString string; + MOJOSHADER_effectTexture texture; + }; +} MOJOSHADER_effectObject; + + +/* Effect state change types... */ + +/* Used to store sampler states with accompanying sampler registers */ +struct MOJOSHADER_samplerStateRegister +{ + const char *sampler_name; + unsigned int sampler_register; + unsigned int sampler_state_count; + const MOJOSHADER_effectSamplerState *sampler_states; +}; + +/* + * Used to acquire the desired render state by the effect pass. + */ +typedef struct MOJOSHADER_effectStateChanges +{ + /* Render state changes caused by effect technique */ + unsigned int render_state_change_count; + const MOJOSHADER_effectState *render_state_changes; + + /* Sampler state changes caused by effect technique */ + unsigned int sampler_state_change_count; + const MOJOSHADER_samplerStateRegister *sampler_state_changes; + + /* Vertex sampler state changes caused by effect technique */ + unsigned int vertex_sampler_state_change_count; + const MOJOSHADER_samplerStateRegister *vertex_sampler_state_changes; +} MOJOSHADER_effectStateChanges; + + +/* + * VTable system for building/running effect shaders... + */ + +typedef void* (MOJOSHADERCALL * MOJOSHADER_compileShaderFunc)( + const void *ctx, + const char *mainfn, + const unsigned char *tokenbuf, + const unsigned int bufsize, + const MOJOSHADER_swizzle *swiz, + const unsigned int swizcount, + const MOJOSHADER_samplerMap *smap, + const unsigned int smapcount +); +typedef void (MOJOSHADERCALL * MOJOSHADER_shaderAddRefFunc)(void* shader); +typedef void (MOJOSHADERCALL * MOJOSHADER_deleteShaderFunc)( + const void *ctx, + void* shader +); +typedef MOJOSHADER_parseData* (MOJOSHADERCALL * MOJOSHADER_getParseDataFunc)( + void *shader +); +typedef void (MOJOSHADERCALL * MOJOSHADER_bindShadersFunc)( + const void *ctx, + void *vshader, + void *pshader +); +typedef void (MOJOSHADERCALL * MOJOSHADER_getBoundShadersFunc)( + const void *ctx, + void **vshader, + void **pshader +); +typedef void (MOJOSHADERCALL * MOJOSHADER_mapUniformBufferMemoryFunc)( + const void *ctx, + float **vsf, int **vsi, unsigned char **vsb, + float **psf, int **psi, unsigned char **psb +); +typedef void (MOJOSHADERCALL * MOJOSHADER_unmapUniformBufferMemoryFunc)( + const void *ctx +); +typedef const char* (MOJOSHADERCALL * MOJOSHADER_getErrorFunc)( + const void *ctx +); + +typedef struct MOJOSHADER_effectShaderContext +{ + /* Shader Backend */ + MOJOSHADER_compileShaderFunc compileShader; + MOJOSHADER_shaderAddRefFunc shaderAddRef; + MOJOSHADER_deleteShaderFunc deleteShader; + MOJOSHADER_getParseDataFunc getParseData; + MOJOSHADER_bindShadersFunc bindShaders; + MOJOSHADER_getBoundShadersFunc getBoundShaders; + MOJOSHADER_mapUniformBufferMemoryFunc mapUniformBufferMemory; + MOJOSHADER_unmapUniformBufferMemoryFunc unmapUniformBufferMemory; + MOJOSHADER_getErrorFunc getError; + + /* Shader context */ + const void *shaderContext; + + /* Allocator */ + MOJOSHADER_malloc m; + MOJOSHADER_free f; + void *malloc_data; +} MOJOSHADER_effectShaderContext; + + +/* + * Structure used to return data from parsing of an effect file... */ -void MOJOSHADER_glGetVertexShaderUniformI(unsigned int idx, int *data, - unsigned int ivec4count); +/* !!! FIXME: most of these ints should be unsigned. */ +typedef struct MOJOSHADER_effect +{ + /* + * Public members. These are the fields your application cares about! + */ + + /* + * The number of elements pointed to by (errors). + */ + int error_count; + + /* + * (error_count) elements of data that specify errors that were generated + * by parsing this shader. + * This can be NULL if there were no errors or if (error_count) is zero. + */ + MOJOSHADER_error *errors; + + /* + * The number of params pointed to by (params). + */ + int param_count; + + /* + * (param_count) elements of data that specify parameter bind points for + * this effect. + * This can be NULL on error or if (param_count) is zero. + */ + MOJOSHADER_effectParam *params; + + /* + * The number of elements pointed to by (techniques). + */ + int technique_count; + + /* + * (technique_count) elements of data that specify techniques used in + * this effect. Each technique contains a series of passes, and each pass + * specifies state and shaders that affect rendering. + * This can be NULL on error or if (technique_count) is zero. + */ + MOJOSHADER_effectTechnique *techniques; + + /* + * The number of elements pointed to by (objects). + */ + int object_count; + + /* + * (object_count) elements of data that specify objects used in + * this effect. + * This can be NULL on error or if (object_count) is zero. + */ + MOJOSHADER_effectObject *objects; + + /* + * Semi-public members. These might be useful, but are better to access from + * a function, not directly. + */ + + /* + * The technique currently being rendered by this effect. + */ + const MOJOSHADER_effectTechnique *current_technique; + + /* + * The index of the current pass being rendered by this effect. + */ + int current_pass; + + /* + * Private Members. Do not touch anything below this line! + */ -/* - * Set a boolean uniform value (what Direct3D calls a "constant"). - * - * There is a single array of "registers" shared by all vertex shaders. - * This is the "b" register file in Direct3D (b0, b1, b2, etc...) - * MojoShader will take care of synchronizing this internal array with the - * appropriate variables in the GL shaders. - * - * Unlike the float and int counterparts, booleans are single values, not - * four-element vectors...so idx==1 is the second boolean in the internal - * array, not the fifth. - * - * Non-zero values are considered "true" and zero is considered "false". - * - * (idx) is the index into the internal array. - * (data) is a pointer to (bcount) ints. + /* + * Value used to determine whether or not to restore the previous shader + * state after rendering an effect, as requested by application. + */ + int restore_shader_state; + + /* + * The structure provided by the appliation to store the state changes. + */ + MOJOSHADER_effectStateChanges *state_changes; + + /* + * Values used to store the current shader state during execution. + */ + MOJOSHADER_effectShader *current_vert_raw; + MOJOSHADER_effectShader *current_pixl_raw; + void *current_vert; + void *current_pixl; + + /* + * Values used to restore shader state after the effect has ended. + */ + void *prev_vertex_shader; + void *prev_pixel_shader; + + /* + * This is the shader implementation you passed to MOJOSHADER_compileEffect(). + */ + MOJOSHADER_effectShaderContext ctx; +} MOJOSHADER_effect; + + +/* Effect compiling interface... */ + +/* Fully compile/link the shaders found within the effect. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * (tokenbuf) is a buffer of Direct3D shader bytecode. + * (bufsize) is the size, in bytes, of the bytecode buffer. + * (swiz), (swizcount), (smap), and (smapcount) are passed to + * MOJOSHADER_parse() unmolested. + * (ctx) contains all the function pointers needed to create and bind shaders + * for a specific backend (OpenGL, Metal, etc). * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * This function returns a MOJOSHADER_effect*, containing effect data which + * includes shaders usable with the provided backend. * - * Uniforms are not shared between contexts. + * This call is only as thread safe as the backend functions! */ -void MOJOSHADER_glSetVertexShaderUniformB(unsigned int idx, const int *data, - unsigned int bcount); +DECLSPEC MOJOSHADER_effect *MOJOSHADER_compileEffect(const unsigned char *tokenbuf, + const unsigned int bufsize, + const MOJOSHADER_swizzle *swiz, + const unsigned int swizcount, + const MOJOSHADER_samplerMap *smap, + const unsigned int smapcount, + const MOJOSHADER_effectShaderContext *ctx); -/* - * Retrieve a boolean uniform value (what Direct3D calls a "constant"). - * - * There is a single array of "registers" shared by all vertex shaders. - * This is the "b" register file in Direct3D (b0, b1, b2, etc...) - * MojoShader will take care of synchronizing this internal array with the - * appropriate variables in the GL shaders. - * - * Unlike the float and int counterparts, booleans are single values, not - * four-element vectors...so idx==1 is the second boolean in the internal - * array, not the fifth. - * - * Non-zero values are considered "true" and zero is considered "false". - * This function will always return true values as 1, regardless of what - * non-zero integer you originally used to set the registers. - * - * (idx) is the index into the internal array. - * (data) is a pointer to space for (bcount) ints. - * (data) will be filled will current values in the register file. Results - * are undefined if you request data past the end of the register file or - * previously uninitialized registers. - * - * This is a "fast" call; we're just reading memory from internal memory. We - * do not query the GPU or the GL for this information. - * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. +/* Delete the shaders that were allocated for an effect. * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * (effect) is a MOJOSHADER_effect* obtained from MOJOSHADER_compileEffect(). * - * Uniforms are not shared between contexts. + * This call is only as thread safe as the backend functions! */ -void MOJOSHADER_glGetVertexShaderUniformB(unsigned int idx, int *data, - unsigned int bcount); +DECLSPEC void MOJOSHADER_deleteEffect(const MOJOSHADER_effect *effect); -/* - * The equivalent of MOJOSHADER_glSetVertexShaderUniformF() for pixel - * shaders. Other than using a different internal array that is specific - * to pixel shaders, this functions just like its vertex array equivalent. +/* Copies an effect, including current parameter/technique data. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * (effect) is a MOJOSHADER_effect* obtained from MOJOSHADER_compileEffect(). * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * This function returns a MOJOSHADER_effect*, containing effect data which + * includes shaders usable with the provided backend. * - * Uniforms are not shared between contexts. + * This call is only as thread safe as the backend functions! */ -void MOJOSHADER_glSetPixelShaderUniformF(unsigned int idx, const float *data, - unsigned int vec4count); +DECLSPEC MOJOSHADER_effect *MOJOSHADER_cloneEffect(const MOJOSHADER_effect *effect); -/* - * The equivalent of MOJOSHADER_glGetVertexShaderUniformF() for pixel - * shaders. Other than using a different internal array that is specific - * to pixel shaders, this functions just like its vertex array equivalent. +/* Effect parameter interface... */ + +/* Set the constant value for the specified effect parameter. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * This function maps to ID3DXEffect::SetRawValue. * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * (parameter) is a parameter obtained from a MOJOSHADER_effect*. + * (data) is the constant values to be applied to the parameter. + * (offset) is the offset, in bytes, of the parameter data being modified. + * (len) is the size, in bytes, of the data buffer being applied. * - * Uniforms are not shared between contexts. + * This function is thread safe. */ -void MOJOSHADER_glGetPixelShaderUniformF(unsigned int idx, float *data, - unsigned int vec4count); - +DECLSPEC void MOJOSHADER_effectSetRawValueHandle(const MOJOSHADER_effectParam *parameter, + const void *data, + const unsigned int offset, + const unsigned int len); -/* - * The equivalent of MOJOSHADER_glSetVertexShaderUniformI() for pixel - * shaders. Other than using a different internal array that is specific - * to pixel shaders, this functions just like its vertex array equivalent. +/* Set the constant value for the effect parameter, specified by name. + * Note: this function is slower than MOJOSHADER_effectSetRawValueHandle(), + * but we still provide it to fully map to ID3DXEffect. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * This function maps to ID3DXEffect::SetRawValue. * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * (effect) is a MOJOSHADER_effect* obtained from MOJOSHADER_compileEffect(). + * (name) is the human-readable name of the parameter being modified. + * (data) is the constant values to be applied to the parameter. + * (offset) is the offset, in bytes, of the parameter data being modified. + * (len) is the size, in bytes, of the data buffer being applied. * - * Uniforms are not shared between contexts. + * This function is thread safe. */ -void MOJOSHADER_glSetPixelShaderUniformI(unsigned int idx, const int *data, - unsigned int ivec4count); +DECLSPEC void MOJOSHADER_effectSetRawValueName(const MOJOSHADER_effect *effect, + const char *name, + const void *data, + const unsigned int offset, + const unsigned int len); -/* - * The equivalent of MOJOSHADER_glGetVertexShaderUniformI() for pixel - * shaders. Other than using a different internal array that is specific - * to pixel shaders, this functions just like its vertex array equivalent. +/* Effect technique interface... */ + +/* Get the current technique in use by an effect. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * This function maps to ID3DXEffect::GetCurrentTechnique. * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * (effect) is a MOJOSHADER_effect* obtained from MOJOSHADER_compileEffect(). * - * Uniforms are not shared between contexts. + * This function returns the technique currently used by the given effect. + * + * This function is thread safe. */ -void MOJOSHADER_glGetPixelShaderUniformI(unsigned int idx, int *data, - unsigned int ivec4count); +DECLSPEC const MOJOSHADER_effectTechnique *MOJOSHADER_effectGetCurrentTechnique(const MOJOSHADER_effect *effect); -/* - * The equivalent of MOJOSHADER_glSetVertexShaderUniformB() for pixel - * shaders. Other than using a different internal array that is specific - * to pixel shaders, this functions just like its vertex array equivalent. +/* Set the current technique to be used an effect. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * This function maps to ID3DXEffect::SetTechnique. * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * (effect) is a MOJOSHADER_effect* obtained from MOJOSHADER_compileEffect(). + * (technique) is the technique to be used by the effect when rendered. * - * Uniforms are not shared between contexts. + * This function is thread safe. */ -void MOJOSHADER_glSetPixelShaderUniformB(unsigned int idx, const int *data, - unsigned int bcount); +DECLSPEC void MOJOSHADER_effectSetTechnique(MOJOSHADER_effect *effect, + const MOJOSHADER_effectTechnique *technique); -/* - * The equivalent of MOJOSHADER_glGetVertexShaderUniformB() for pixel - * shaders. Other than using a different internal array that is specific - * to pixel shaders, this functions just like its vertex array equivalent. +/* Get the next technique in an effect's list. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * This function maps to ID3DXEffect::FindNextValidTechnique. * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * (effect) is a MOJOSHADER_effect* obtained from MOJOSHADER_compileEffect(). + * (technique) can either be a technique found in the given effect, or NULL to + * find the first technique in the given effect. * - * Uniforms are not shared between contexts. + * This function returns either the next technique after the passed technique, + * or the first technique if the passed technique is NULL. + * + * This function is thread safe. */ -void MOJOSHADER_glGetPixelShaderUniformB(unsigned int idx, int *data, - unsigned int bcount); +DECLSPEC const MOJOSHADER_effectTechnique *MOJOSHADER_effectFindNextValidTechnique(const MOJOSHADER_effect *effect, + const MOJOSHADER_effectTechnique *technique); -/* - * Set up the vector for the TEXBEM opcode. Most apps can ignore this API. - * - * Shader Model 1.1 through 1.3 had an instruction for "fake bump mapping" - * called TEXBEM. To use it, you had to set some sampler states, - * D3DTSS_BUMPENVMATxx, which would be referenced by the opcode. - * - * This functionality was removed from Shader Model 1.4 and later, because - * it was special-purpose and limited. The functionality could be built on - * more general opcodes, and the sampler state could be supplied in a more - * general uniform. - * - * However, to support this opcode, we supply a way to specify that sampler - * state, and the OpenGL glue code does the right thing to pass that - * information to the shader. + +/* Effect rendering interface... */ + +/* Prepare the effect for rendering with the currently applied technique. * - * This call maps to IDirect3DDevice::SetTextureStageState() with the - * D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT01, D3DTSS_BUMPENVMAT10, - * D3DTSS_BUMPENVMAT11, D3DTSS_BUMPENVLSCALE, and D3DTSS_BUMPENVLOFFSET - * targets. This is only useful for Shader Model < 1.4 pixel shaders, if - * they use the TEXBEM or TEXBEML opcode. If you aren't sure, you don't need - * this function. + * This function maps to ID3DXEffect::Begin. * - * Like the rest of your uniforms, you must call MOJOSHADER_glProgramReady() - * between setting new values and drawing with them. + * In addition to the expected Begin parameters, we also include a parameter + * to pass in a MOJOSHADER_effectRenderState. Rather than change the render + * state within MojoShader itself we will simply provide what the effect wants + * and allow you to use this information with your own renderer. + * MOJOSHADER_effectBeginPass will update with the render state desired by + * the current effect pass. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * Note that we only provide the ability to preserve the shader state, but NOT + * the ability to preserve the render/sampler states. You are expected to + * track your own GL state and restore these states as needed for your + * application. * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * (effect) is a MOJOSHADER_effect* obtained from MOJOSHADER_compileEffect(). + * (numPasses) will be filled with the number of passes that this technique + * will need to fully render. + * (saveShaderState) is a boolean value informing the effect whether or not to + * restore the shader bindings after calling MOJOSHADER_effectEnd. + * (renderState) will be filled by the effect to inform you of the render state + * changes introduced by the technique and its passes. * - * These values are not shared between contexts. + * This call is only as thread safe as the backend functions! */ -void MOJOSHADER_glSetLegacyBumpMapEnv(unsigned int sampler, float mat00, - float mat01, float mat10, float mat11, - float lscale, float loffset); +DECLSPEC void MOJOSHADER_effectBegin(MOJOSHADER_effect *effect, + unsigned int *numPasses, + int saveShaderState, + MOJOSHADER_effectStateChanges *stateChanges); -/* - * Connect a client-side array to the currently-bound program. +/* Begin an effect pass from the currently applied technique. * - * (usage) and (index) map to Direct3D vertex declaration values: COLOR1 would - * be MOJOSHADER_USAGE_COLOR and 1. - * - * The caller should bind VBOs before this call and treat (ptr) as an offset, - * if appropriate. + * This function maps to ID3DXEffect::BeginPass. * - * MojoShader will figure out where to plug this stream into the - * currently-bound program, and enable the appropriate client-side array. + * (effect) is a MOJOSHADER_effect* obtained from MOJOSHADER_compileEffect(). + * (pass) is the index of the effect pass as found in the current technique. * - * (size), (type), (normalized), (stride), and (ptr) correspond to - * glVertexAttribPointer()'s parameters (in most cases, these get passed - * unmolested to that very entry point during this function). + * This call is only as thread safe as the backend functions! + */ +DECLSPEC void MOJOSHADER_effectBeginPass(MOJOSHADER_effect *effect, + unsigned int pass); + +/* Push render state changes that occurred within an actively rendering pass. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * This function maps to ID3DXEffect::CommitChanges. * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * (effect) is a MOJOSHADER_effect* obtained from MOJOSHADER_compileEffect(). * - * Vertex attributes are not shared between contexts. + * This call is only as thread safe as the backend functions! */ - /* !!! FIXME: this should probably be "input" and not "attribute" */ - /* !!! FIXME: or maybe "vertex array" or something. */ -void MOJOSHADER_glSetVertexAttribute(MOJOSHADER_usage usage, - int index, unsigned int size, - MOJOSHADER_attributeType type, - int normalized, unsigned int stride, - const void *ptr); +DECLSPEC void MOJOSHADER_effectCommitChanges(MOJOSHADER_effect *effect); - - - -/* These below functions are temporary and will be removed from the API once - the real Effects API is written. Do not use! */ -void MOJOSHADER_glSetVertexPreshaderUniformF(unsigned int idx, const float *data, - unsigned int vec4n); -void MOJOSHADER_glGetVertexPreshaderUniformF(unsigned int idx, float *data, - unsigned int vec4n); -void MOJOSHADER_glSetPixelPreshaderUniformF(unsigned int idx, const float *data, - unsigned int vec4n); -void MOJOSHADER_glGetPixelPreshaderUniformF(unsigned int idx, float *data, - unsigned int vec4n); -/* These above functions are temporary and will be removed from the API once - the real Effects API is written. Do not use! */ - - - - -/* - * Inform MojoShader that it should commit any pending state to the GL. This - * must be called after you bind a program and update any inputs, right - * before you start drawing, so any outstanding changes made to the shared - * constants array (etc) can propagate to the shader during this call. +/* End an effect pass from the currently applied technique. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * This function maps to ID3DXEffect::EndPass. * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * (effect) is a MOJOSHADER_effect* obtained from MOJOSHADER_compileEffect(). + * + * This call is only as thread safe as the backend functions! */ -void MOJOSHADER_glProgramReady(void); +DECLSPEC void MOJOSHADER_effectEndPass(MOJOSHADER_effect *effect); -/* - * Free the resources of a linked program. This will delete the GL object - * and free memory. +/* Complete rendering the effect technique, and restore the render state. * - * If the program is currently bound by MOJOSHADER_glBindProgram(), it will - * be deleted as soon as it becomes unbound. + * This function maps to ID3DXEffect::End. * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * (effect) is a MOJOSHADER_effect* obtained from MOJOSHADER_compileEffect(). * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * This call is only as thread safe as the backend functions! */ -void MOJOSHADER_glDeleteProgram(MOJOSHADER_glProgram *program); +DECLSPEC void MOJOSHADER_effectEnd(MOJOSHADER_effect *effect); + + +/* Profile-specific functions... */ /* - * Free the resources of a compiled shader. This will delete the GL object - * and free memory. + * Compile a MTLLibrary that contains all shaders of the given effect. * - * If the shader is currently referenced by a linked program (or is currently - * bound with MOJOSHADER_glBindShaders()), it will be deleted as soon as all - * referencing programs are deleted and it is no longer bound, too. - * - * This call is NOT thread safe! As most OpenGL implementations are not thread - * safe, you should probably only call this from the same thread that created - * the GL context. + * This call requires a valid MOJOSHADER_mtlContext to have been created, + * or it will crash your program. See MOJOSHADER_mtlCreateContext(). * - * This call requires a valid MOJOSHADER_glContext to have been made current, - * or it will crash your program. See MOJOSHADER_glMakeContextCurrent(). + * Returns NULL on error, the generated MTLLibrary on success. */ -void MOJOSHADER_glDeleteShader(MOJOSHADER_glShader *shader); +DECLSPEC void *MOJOSHADER_mtlCompileLibrary(MOJOSHADER_effect *effect); /* - * Deinitialize MojoShader's OpenGL shader management. - * - * You must call this once, while your GL context (not MojoShader context) is - * still current, if you previously had a successful call to - * MOJOSHADER_glCreateContext(). This should be the last MOJOSHADER_gl* - * function you call until you've prepared a context again. - * - * This will clean up resources previously allocated, and may call into the GL. - * - * This will not clean up shaders and programs you created! Please call - * MOJOSHADER_glDeleteShader() and MOJOSHADER_glDeleteProgram() to clean - * those up before calling this function! - * - * This function destroys the MOJOSHADER_glContext you pass it. If it's the - * current context, then no context will be current upon return. - * - * This call is NOT thread safe! There must not be any other MOJOSHADER_gl* - * functions running when this is called. Also, as most OpenGL implementations - * are not thread safe, you should probably only call this from the same - * thread that created the GL context. + * Free the MTLLibrary given by (library). */ -void MOJOSHADER_glDestroyContext(MOJOSHADER_glContext *ctx); +DECLSPEC void MOJOSHADER_mtlDeleteLibrary(void *library); + + +#endif /* MOJOSHADER_EFFECT_SUPPORT */ + #ifdef __cplusplus } diff --git a/mojoshader/mojoshader_assembler.c b/mojoshader/mojoshader_assembler.c deleted file mode 100644 index 24ae275..0000000 --- a/mojoshader/mojoshader_assembler.c +++ /dev/null @@ -1,1770 +0,0 @@ -/** - * MojoShader; generate shader programs from bytecode of compiled - * Direct3D shaders. - * - * Please see the file LICENSE.txt in the source's root directory. - * - * This file written by Ryan C. Gordon. - */ - -// !!! FIXME: this should probably use a formal grammar and not a hand-written -// !!! FIXME: pile of C code. - -#define __MOJOSHADER_INTERNAL__ 1 -#include "mojoshader_internal.h" - -#if !SUPPORT_PROFILE_BYTECODE -#error Shader assembler needs bytecode profile. Fix your build. -#endif - -#if DEBUG_ASSEMBLER_PARSER - #define print_debug_token(token, len, val) \ - MOJOSHADER_print_debug_token("ASSEMBLER", token, len, val) -#else - #define print_debug_token(token, len, val) -#endif - - -typedef struct SourcePos -{ - const char *filename; - uint32 line; -} SourcePos; - - -// Context...this is state that changes as we assemble a shader... -typedef struct Context -{ - int isfail; - int out_of_memory; - MOJOSHADER_malloc malloc; - MOJOSHADER_free free; - void *malloc_data; - const char *current_file; - int current_position; - ErrorList *errors; - Preprocessor *preprocessor; - MOJOSHADER_shaderType shader_type; - uint8 major_ver; - uint8 minor_ver; - int pushedback; - const char *token; // assembler token! - unsigned int tokenlen; // assembler token! - Token tokenval; // assembler token! - uint32 version_token; // bytecode token! - uint32 tokenbuf[16]; // bytecode tokens! - int tokenbufpos; // bytecode tokens! - DestArgInfo dest_arg; - Buffer *output; - Buffer *token_to_source; - Buffer *ctab; -} Context; - - -// !!! FIXME: cut and paste between every damned source file follows... -// !!! FIXME: We need to make some sort of ContextBase that applies to all -// !!! FIXME: files and move this stuff to mojoshader_common.c ... - -// Convenience functions for allocators... - -static inline void out_of_memory(Context *ctx) -{ - ctx->isfail = ctx->out_of_memory = 1; -} // out_of_memory - -static inline void *Malloc(Context *ctx, const size_t len) -{ - void *retval = ctx->malloc((int) len, ctx->malloc_data); - if (retval == NULL) - out_of_memory(ctx); - return retval; -} // Malloc - -static inline char *StrDup(Context *ctx, const char *str) -{ - char *retval = (char *) Malloc(ctx, strlen(str) + 1); - if (retval != NULL) - strcpy(retval, str); - return retval; -} // StrDup - -static inline void Free(Context *ctx, void *ptr) -{ - ctx->free(ptr, ctx->malloc_data); -} // Free - -static void *MallocBridge(int bytes, void *data) -{ - return Malloc((Context *) data, (size_t) bytes); -} // MallocBridge - -static void FreeBridge(void *ptr, void *data) -{ - Free((Context *) data, ptr); -} // FreeBridge - - -static void failf(Context *ctx, const char *fmt, ...) ISPRINTF(2,3); -static void failf(Context *ctx, const char *fmt, ...) -{ - ctx->isfail = 1; - if (ctx->out_of_memory) - return; - - va_list ap; - va_start(ap, fmt); - errorlist_add_va(ctx->errors, ctx->current_file, ctx->current_position, fmt, ap); - va_end(ap); -} // failf - -static inline void fail(Context *ctx, const char *reason) -{ - failf(ctx, "%s", reason); -} // fail - -static inline int isfail(const Context *ctx) -{ - return ctx->isfail; -} // isfail - - -// Shader model version magic... - -static inline uint32 ver_ui32(const uint8 major, const uint8 minor) -{ - return ( (((uint32) major) << 16) | (((minor) == 0xFF) ? 0 : (minor)) ); -} // version_ui32 - -static inline int shader_version_atleast(const Context *ctx, const uint8 maj, - const uint8 min) -{ - return (ver_ui32(ctx->major_ver, ctx->minor_ver) >= ver_ui32(maj, min)); -} // shader_version_atleast - -static inline int shader_is_pixel(const Context *ctx) -{ - return (ctx->shader_type == MOJOSHADER_TYPE_PIXEL); -} // shader_is_pixel - -static inline int shader_is_vertex(const Context *ctx) -{ - return (ctx->shader_type == MOJOSHADER_TYPE_VERTEX); -} // shader_is_vertex - -static inline void pushback(Context *ctx) -{ - #if DEBUG_ASSEMBLER_PARSER - printf("ASSEMBLER PUSHBACK\n"); - #endif - assert(!ctx->pushedback); - ctx->pushedback = 1; -} // pushback - - -static Token nexttoken(Context *ctx) -{ - if (ctx->pushedback) - ctx->pushedback = 0; - else - { - while (1) - { - ctx->token = preprocessor_nexttoken(ctx->preprocessor, - &ctx->tokenlen, - &ctx->tokenval); - - if (preprocessor_outofmemory(ctx->preprocessor)) - { - ctx->tokenval = TOKEN_EOI; - ctx->token = NULL; - ctx->tokenlen = 0; - break; - } // if - - unsigned int line; - ctx->current_file = preprocessor_sourcepos(ctx->preprocessor,&line); - ctx->current_position = (int) line; - - if (ctx->tokenval == TOKEN_BAD_CHARS) - { - fail(ctx, "Bad characters in source file"); - continue; - } // else if - - else if (ctx->tokenval == TOKEN_PREPROCESSING_ERROR) - { - fail(ctx, ctx->token); - continue; - } // else if - - break; - } // while - } // else - - print_debug_token(ctx->token, ctx->tokenlen, ctx->tokenval); - return ctx->tokenval; -} // nexttoken - - -static void output_token_noswap(Context *ctx, const uint32 token) -{ - if (!isfail(ctx)) - { - buffer_append(ctx->output, &token, sizeof (token)); - - // We only need a list of these that grows throughout processing, and - // is flattened for reference at the end of the run, so we use a - // Buffer. It's sneaky! - unsigned int pos = 0; - const char *fname = preprocessor_sourcepos(ctx->preprocessor, &pos); - SourcePos srcpos; - memset(&srcpos, '\0', sizeof (SourcePos)); - srcpos.line = pos; - srcpos.filename = fname; // cached in preprocessor! - buffer_append(ctx->token_to_source, &srcpos, sizeof (SourcePos)); - } // if -} // output_token_noswap - - -static inline void output_token(Context *ctx, const uint32 token) -{ - output_token_noswap(ctx, SWAP32(token)); -} // output_token - - -static void output_comment_bytes(Context *ctx, const uint8 *buf, size_t len) -{ - if (len > (0xFFFF * 4)) // length is stored as token count, in 16 bits. - fail(ctx, "Comment field is too big"); - else if (!isfail(ctx)) - { - const uint32 tokencount = (len / 4) + ((len % 4) ? 1 : 0); - output_token(ctx, 0xFFFE | (tokencount << 16)); - while (len >= 4) - { - output_token_noswap(ctx, *((const uint32 *) buf)); - len -= 4; - buf += 4; - } // while - - if (len > 0) // handle spillover... - { - union { uint8 ui8[4]; uint32 ui32; } overflow; - overflow.ui32 = 0; - memcpy(overflow.ui8, buf, len); - output_token_noswap(ctx, overflow.ui32); - } // if - } // else if -} // output_comment_bytes - - -static inline void output_comment_string(Context *ctx, const char *str) -{ - output_comment_bytes(ctx, (const uint8 *) str, strlen(str)); -} // output_comment_string - - -static int require_comma(Context *ctx) -{ - const Token token = nexttoken(ctx); - if (token != ((Token) ',')) - { - fail(ctx, "Comma expected"); - return 0; - } // if - return 1; -} // require_comma - - -static int check_token_segment(Context *ctx, const char *str) -{ - // !!! FIXME: these are case-insensitive, right? - const size_t len = strlen(str); - if ( (ctx->tokenlen < len) || (strncasecmp(ctx->token, str, len) != 0) ) - return 0; - ctx->token += len; - ctx->tokenlen -= len; - return 1; -} // check_token_segment - - -static int check_token(Context *ctx, const char *str) -{ - const size_t len = strlen(str); - if ( (ctx->tokenlen != len) || (strncasecmp(ctx->token, str, len) != 0) ) - return 0; - ctx->token += len; - ctx->tokenlen = 0; - return 1; -} // check_token - - -static int ui32fromtoken(Context *ctx, uint32 *_val) -{ - unsigned int i; - for (i = 0; i < ctx->tokenlen; i++) - { - if ((ctx->token[i] < '0') || (ctx->token[i] > '9')) - break; - } // for - - if (i == 0) - { - *_val = 0; - return 0; - } // if - - const unsigned int len = i; - uint32 val = 0; - uint32 mult = 1; - while (i--) - { - val += ((uint32) (ctx->token[i] - '0')) * mult; - mult *= 10; - } // while - - ctx->token += len; - ctx->tokenlen -= len; - - *_val = val; - return 1; -} // ui32fromtoken - - -static int parse_register_name(Context *ctx, RegisterType *rtype, int *rnum) -{ - if (nexttoken(ctx) != TOKEN_IDENTIFIER) - { - fail(ctx, "Expected register"); - return 0; - } // if - - int neednum = 1; - int regnum = 0; - RegisterType regtype = REG_TYPE_TEMP; - - // Watch out for substrings! oDepth must be checked before oD, since - // the latter will match either case. - if (check_token_segment(ctx, "oDepth")) - { - regtype = REG_TYPE_DEPTHOUT; - neednum = 0; - } // else if - else if (check_token_segment(ctx, "vFace")) - { - regtype = REG_TYPE_MISCTYPE; - regnum = (int) MISCTYPE_TYPE_FACE; - neednum = 0; - } // else if - else if (check_token_segment(ctx, "vPos")) - { - regtype = REG_TYPE_MISCTYPE; - regnum = (int) MISCTYPE_TYPE_POSITION; - neednum = 0; - } // else if - else if (check_token_segment(ctx, "oPos")) - { - regtype = REG_TYPE_RASTOUT; - regnum = (int) RASTOUT_TYPE_POSITION; - neednum = 0; - } // else if - else if (check_token_segment(ctx, "oFog")) - { - regtype = REG_TYPE_RASTOUT; - regnum = (int) RASTOUT_TYPE_FOG; - neednum = 0; - } // else if - else if (check_token_segment(ctx, "oPts")) - { - regtype = REG_TYPE_RASTOUT; - regnum = (int) RASTOUT_TYPE_POINT_SIZE; - neednum = 0; - } // else if - else if (check_token_segment(ctx, "aL")) - { - regtype = REG_TYPE_LOOP; - neednum = 0; - } // else if - else if (check_token_segment(ctx, "oC")) - regtype = REG_TYPE_COLOROUT; - else if (check_token_segment(ctx, "oT")) - regtype = REG_TYPE_OUTPUT; - else if (check_token_segment(ctx, "oD")) - regtype = REG_TYPE_ATTROUT; - else if (check_token_segment(ctx, "r")) - regtype = REG_TYPE_TEMP; - else if (check_token_segment(ctx, "v")) - regtype = REG_TYPE_INPUT; - else if (check_token_segment(ctx, "c")) - regtype = REG_TYPE_CONST; - else if (check_token_segment(ctx, "i")) - regtype = REG_TYPE_CONSTINT; - else if (check_token_segment(ctx, "b")) - regtype = REG_TYPE_CONSTBOOL; - else if (check_token_segment(ctx, "s")) - regtype = REG_TYPE_SAMPLER; - else if (check_token_segment(ctx, "l")) - regtype = REG_TYPE_LABEL; - else if (check_token_segment(ctx, "p")) - regtype = REG_TYPE_PREDICATE; - else if (check_token_segment(ctx, "o")) - regtype = REG_TYPE_OUTPUT; - else if (check_token_segment(ctx, "a")) - regtype = REG_TYPE_ADDRESS; - else if (check_token_segment(ctx, "t")) - regtype = REG_TYPE_ADDRESS; - - //case REG_TYPE_TEMPFLOAT16: // !!! FIXME: don't know this asm string - - else - { - fail(ctx, "expected register type"); - regtype = REG_TYPE_CONST; - regnum = 0; - neednum = 0; - } // else - - // "c[5]" is the same as "c5", so if the token is done, see if next is '['. - if ((neednum) && (ctx->tokenlen == 0)) - { - const int tlen = ctx->tokenlen; // we need to protect this for later. - if (nexttoken(ctx) == ((Token) '[')) - neednum = 0; // don't need a number on register name itself. - pushback(ctx); - ctx->tokenlen = tlen; - } // if - - if (neednum) - { - uint32 ui32 = 0; - if (!ui32fromtoken(ctx, &ui32)) - fail(ctx, "Invalid register index"); - regnum = (int) ui32; - } // if - - // split up REG_TYPE_CONST - if (regtype == REG_TYPE_CONST) - { - if (regnum < 2048) - { - regtype = REG_TYPE_CONST; - regnum -= 0; - } // if - else if (regnum < 4096) - { - regtype = REG_TYPE_CONST2; - regnum -= 2048; - } // if - else if (regnum < 6144) - { - regtype = REG_TYPE_CONST3; - regnum -= 4096; - } // if - else if (regnum < 8192) - { - regtype = REG_TYPE_CONST4; - regnum -= 6144; - } // if - else - { - fail(ctx, "Invalid const register index"); - } // else - } // if - - *rtype = regtype; - *rnum = regnum; - - return 1; -} // parse_register_name - - -static void set_result_shift(Context *ctx, DestArgInfo *info, const int val) -{ - if (info->result_shift != 0) - fail(ctx, "Multiple result shift modifiers"); - info->result_shift = val; -} // set_result_shift - - -static inline int tokenbuf_overflow(Context *ctx) -{ - if ( ctx->tokenbufpos >= ((int) (STATICARRAYLEN(ctx->tokenbuf))) ) - { - fail(ctx, "Too many tokens"); - return 1; - } // if - - return 0; -} // tokenbuf_overflow - - -static int parse_destination_token(Context *ctx) -{ - DestArgInfo *info = &ctx->dest_arg; - memset(info, '\0', sizeof (DestArgInfo)); - - // parse_instruction_token() sets ctx->token to the end of the instruction - // so we can see if there are destination modifiers on the instruction - // itself... - - int invalid_modifier = 0; - - while ((ctx->tokenlen > 0) && (!invalid_modifier)) - { - if (check_token_segment(ctx, "_x2")) - set_result_shift(ctx, info, 0x1); - else if (check_token_segment(ctx, "_x4")) - set_result_shift(ctx, info, 0x2); - else if (check_token_segment(ctx, "_x8")) - set_result_shift(ctx, info, 0x3); - else if (check_token_segment(ctx, "_d8")) - set_result_shift(ctx, info, 0xD); - else if (check_token_segment(ctx, "_d4")) - set_result_shift(ctx, info, 0xE); - else if (check_token_segment(ctx, "_d2")) - set_result_shift(ctx, info, 0xF); - else if (check_token_segment(ctx, "_sat")) - info->result_mod |= MOD_SATURATE; - else if (check_token_segment(ctx, "_pp")) - info->result_mod |= MOD_PP; - else if (check_token_segment(ctx, "_centroid")) - info->result_mod |= MOD_CENTROID; - else - invalid_modifier = 1; - } // while - - if (invalid_modifier) - fail(ctx, "Invalid destination modifier"); - - // !!! FIXME: predicates. - if (nexttoken(ctx) == ((Token) '(')) - fail(ctx, "Predicates unsupported at this time"); // !!! FIXME: ... - - pushback(ctx); // parse_register_name calls nexttoken(). - - parse_register_name(ctx, &info->regtype, &info->regnum); - // parse_register_name() can't check this: dest regs might have modifiers. - if (ctx->tokenlen > 0) - fail(ctx, "invalid register name"); - - // !!! FIXME: can dest registers do relative addressing? - - int invalid_writemask = 0; - int implicit_writemask = 0; - if (nexttoken(ctx) != ((Token) '.')) - { - implicit_writemask = 1; - info->writemask = 0xF; - info->writemask0 = info->writemask1 = info->writemask2 = info->writemask3 = 1; - pushback(ctx); // no explicit writemask; do full mask. - } // if - - // !!! FIXME: Cg generates code with oDepth.z ... this is a bug, I think. - //else if (scalar_register(ctx->shader_type, info->regtype, info->regnum)) - else if ( (scalar_register(ctx->shader_type, info->regtype, info->regnum)) && (info->regtype != REG_TYPE_DEPTHOUT) ) - fail(ctx, "Writemask specified for scalar register"); - else if (nexttoken(ctx) != TOKEN_IDENTIFIER) - invalid_writemask = 1; - else - { - char tokenbytes[5] = { '\0', '\0', '\0', '\0', '\0' }; - const unsigned int tokenlen = ctx->tokenlen; - memcpy(tokenbytes, ctx->token, ((tokenlen < 4) ? tokenlen : 4)); - char *ptr = tokenbytes; - - if ((*ptr == 'r') || (*ptr == 'x')) { info->writemask0 = 1; ptr++; } - if ((*ptr == 'g') || (*ptr == 'y')) { info->writemask1 = 1; ptr++; } - if ((*ptr == 'b') || (*ptr == 'z')) { info->writemask2 = 1; ptr++; } - if ((*ptr == 'a') || (*ptr == 'w')) { info->writemask3 = 1; ptr++; } - - if (*ptr != '\0') - invalid_writemask = 1; - - info->writemask = ( ((info->writemask0 & 0x1) << 0) | - ((info->writemask1 & 0x1) << 1) | - ((info->writemask2 & 0x1) << 2) | - ((info->writemask3 & 0x1) << 3) ); - } // else - - if (invalid_writemask) - fail(ctx, "Invalid writemask"); - - // !!! FIXME: Cg generates code with oDepth.z ... this is a bug, I think. - if (info->regtype == REG_TYPE_DEPTHOUT) - { - if ( (!implicit_writemask) && ((info->writemask0 + info->writemask1 + - info->writemask2 + info->writemask3) > 1) ) - fail(ctx, "Writemask specified for scalar register"); - } // if - - info->orig_writemask = info->writemask; - - if (tokenbuf_overflow(ctx)) - return 1; - - ctx->tokenbuf[ctx->tokenbufpos++] = - ( ((((uint32) 1)) << 31) | - ((((uint32) info->regnum) & 0x7ff) << 0) | - ((((uint32) info->relative) & 0x1) << 13) | - ((((uint32) info->result_mod) & 0xF) << 20) | - ((((uint32) info->result_shift) & 0xF) << 24) | - ((((uint32) info->writemask) & 0xF) << 16) | - ((((uint32) info->regtype) & 0x7) << 28) | - ((((uint32) info->regtype) & 0x18) << 8) ); - - return 1; -} // parse_destination_token - - -static void set_source_mod(Context *ctx, const int negate, - const SourceMod norm, const SourceMod negated, - SourceMod *srcmod) -{ - if ( (*srcmod != SRCMOD_NONE) || (negate && (negated == SRCMOD_NONE)) ) - fail(ctx, "Incompatible source modifiers"); - else - *srcmod = ((negate) ? negated : norm); -} // set_source_mod - - -static int parse_source_token_maybe_relative(Context *ctx, const int relok) -{ - int retval = 1; - - if (tokenbuf_overflow(ctx)) - return 0; - - // mark this now, so optional relative addressing token is placed second. - uint32 *outtoken = &ctx->tokenbuf[ctx->tokenbufpos++]; - *outtoken = 0; - - SourceMod srcmod = SRCMOD_NONE; - int negate = 0; - Token token = nexttoken(ctx); - - if (token == ((Token) '!')) - srcmod = SRCMOD_NOT; - else if (token == ((Token) '-')) - negate = 1; - else if ( (token == TOKEN_INT_LITERAL) && (check_token(ctx, "1")) ) - { - if (nexttoken(ctx) != ((Token) '-')) - fail(ctx, "Unexpected token"); - else - srcmod = SRCMOD_COMPLEMENT; - } // else - else - { - pushback(ctx); - } // else - - RegisterType regtype; - int regnum; - parse_register_name(ctx, ®type, ®num); - - if (ctx->tokenlen == 0) - { - if (negate) - set_source_mod(ctx, negate, SRCMOD_NONE, SRCMOD_NEGATE, &srcmod); - } // if - else - { - assert(ctx->tokenlen > 0); - if (check_token_segment(ctx, "_bias")) - set_source_mod(ctx, negate, SRCMOD_BIAS, SRCMOD_BIASNEGATE, &srcmod); - else if (check_token_segment(ctx, "_bx2")) - set_source_mod(ctx, negate, SRCMOD_SIGN, SRCMOD_SIGNNEGATE, &srcmod); - else if (check_token_segment(ctx, "_x2")) - set_source_mod(ctx, negate, SRCMOD_X2, SRCMOD_X2NEGATE, &srcmod); - else if (check_token_segment(ctx, "_dz")) - set_source_mod(ctx, negate, SRCMOD_DZ, SRCMOD_NONE, &srcmod); - else if (check_token_segment(ctx, "_db")) - set_source_mod(ctx, negate, SRCMOD_DZ, SRCMOD_NONE, &srcmod); - else if (check_token_segment(ctx, "_dw")) - set_source_mod(ctx, negate, SRCMOD_DW, SRCMOD_NONE, &srcmod); - else if (check_token_segment(ctx, "_da")) - set_source_mod(ctx, negate, SRCMOD_DW, SRCMOD_NONE, &srcmod); - else if (check_token_segment(ctx, "_abs")) - set_source_mod(ctx, negate, SRCMOD_ABS, SRCMOD_ABSNEGATE, &srcmod); - else - fail(ctx, "Invalid source modifier"); - } // else - - uint32 relative = 0; - if (nexttoken(ctx) != ((Token) '[')) - pushback(ctx); // not relative addressing? - else - { - if (!relok) - fail(ctx, "Relative addressing not permitted here."); - else - retval++; - - parse_source_token_maybe_relative(ctx, 0); - relative = 1; - - if (nexttoken(ctx) != ((Token) '+')) - pushback(ctx); - else - { - // !!! FIXME: maybe c3[a0.x + 5] is legal and becomes c[a0.x + 8] ? - if (regnum != 0) - fail(ctx, "Relative addressing with explicit register number."); - - uint32 ui32 = 0; - if ( (nexttoken(ctx) != TOKEN_INT_LITERAL) || - (!ui32fromtoken(ctx, &ui32)) || - (ctx->tokenlen != 0) ) - { - fail(ctx, "Invalid relative addressing offset"); - } // if - regnum += (int) ui32; - } // else - - if (nexttoken(ctx) != ((Token) ']')) - fail(ctx, "Expected ']'"); - } // else - - int invalid_swizzle = 0; - uint32 swizzle = 0; - if (nexttoken(ctx) != ((Token) '.')) - { - swizzle = 0xE4; // 0xE4 == 11100100 ... 0 1 2 3. No swizzle. - pushback(ctx); // no explicit writemask; do full mask. - } // if - else if (scalar_register(ctx->shader_type, regtype, regnum)) - fail(ctx, "Swizzle specified for scalar register"); - else if (nexttoken(ctx) != TOKEN_IDENTIFIER) - invalid_swizzle = 1; - else - { - char tokenbytes[5] = { '\0', '\0', '\0', '\0', '\0' }; - const unsigned int tokenlen = ctx->tokenlen; - memcpy(tokenbytes, ctx->token, ((tokenlen < 4) ? tokenlen : 4)); - - // deal with shortened form (.x = .xxxx, etc). - if (tokenlen == 1) - tokenbytes[1] = tokenbytes[2] = tokenbytes[3] = tokenbytes[0]; - else if (tokenlen == 2) - tokenbytes[2] = tokenbytes[3] = tokenbytes[1]; - else if (tokenlen == 3) - tokenbytes[3] = tokenbytes[2]; - else if (tokenlen != 4) - invalid_swizzle = 1; - tokenbytes[4] = '\0'; - - uint32 val = 0; - int i; - for (i = 0; i < 4; i++) - { - const int component = (int) tokenbytes[i]; - switch (component) - { - case 'r': case 'x': val = 0; break; - case 'g': case 'y': val = 1; break; - case 'b': case 'z': val = 2; break; - case 'a': case 'w': val = 3; break; - default: invalid_swizzle = 1; break; - } // switch - swizzle |= (val << (i * 2)); - } // for - } // else - - if (invalid_swizzle) - fail(ctx, "Invalid swizzle"); - - *outtoken = ( ((((uint32) 1)) << 31) | - ((((uint32) regnum) & 0x7ff) << 0) | - ((((uint32) relative) & 0x1) << 13) | - ((((uint32) swizzle) & 0xFF) << 16) | - ((((uint32) srcmod) & 0xF) << 24) | - ((((uint32) regtype) & 0x7) << 28) | - ((((uint32) regtype) & 0x18) << 8) ); - - return retval; -} // parse_source_token_maybe_relative - - -static inline int parse_source_token(Context *ctx) -{ - return parse_source_token_maybe_relative(ctx, 1); -} // parse_source_token - - -static int parse_args_NULL(Context *ctx) -{ - return 1; -} // parse_args_NULL - - -static int parse_num(Context *ctx, const int floatok, uint32 *value) -{ - union { float f; int32 si32; uint32 ui32; } cvt; - int negative = 0; - Token token = nexttoken(ctx); - - if (token == ((Token) '-')) - { - negative = 1; - token = nexttoken(ctx); - } // if - - if (token == TOKEN_INT_LITERAL) - { - int d = 0; - sscanf(ctx->token, "%d", &d); - if (floatok) - cvt.f = (float) ((negative) ? -d : d); - else - cvt.si32 = (int32) ((negative) ? -d : d); - } // if - else if (token == TOKEN_FLOAT_LITERAL) - { - if (!floatok) - { - fail(ctx, "Expected whole number"); - *value = 0; - return 0; - } // if - sscanf(ctx->token, "%f", &cvt.f); - if (negative) - cvt.f = -cvt.f; - } // if - else - { - fail(ctx, "Expected number"); - *value = 0; - return 0; - } // else - - *value = cvt.ui32; - return 1; -} // parse_num - - -static int parse_args_DEFx(Context *ctx, const int isflt) -{ - parse_destination_token(ctx); - require_comma(ctx); - parse_num(ctx, isflt, &ctx->tokenbuf[ctx->tokenbufpos++]); - require_comma(ctx); - parse_num(ctx, isflt, &ctx->tokenbuf[ctx->tokenbufpos++]); - require_comma(ctx); - parse_num(ctx, isflt, &ctx->tokenbuf[ctx->tokenbufpos++]); - require_comma(ctx); - parse_num(ctx, isflt, &ctx->tokenbuf[ctx->tokenbufpos++]); - return 6; -} // parse_args_DEFx - - -static int parse_args_DEF(Context *ctx) -{ - return parse_args_DEFx(ctx, 1); -} // parse_args_DEF - - -static int parse_args_DEFI(Context *ctx) -{ - return parse_args_DEFx(ctx, 0); -} // parse_args_DEFI - - -static int parse_args_DEFB(Context *ctx) -{ - parse_destination_token(ctx); - require_comma(ctx); - - // !!! FIXME: do a TOKEN_TRUE and TOKEN_FALSE? Is this case-sensitive? - const Token token = nexttoken(ctx); - - int bad = 0; - if (token != TOKEN_IDENTIFIER) - bad = 1; - else if (check_token_segment(ctx, "true")) - ctx->tokenbuf[ctx->tokenbufpos++] = 1; - else if (check_token_segment(ctx, "false")) - ctx->tokenbuf[ctx->tokenbufpos++] = 0; - else - bad = 1; - - if (ctx->tokenlen != 0) - bad = 1; - - if (bad) - fail(ctx, "Expected 'true' or 'false'"); - - return 3; -} // parse_args_DEFB - - -static int parse_dcl_usage(Context *ctx, uint32 *val, int *issampler) -{ - size_t i; - static const char *samplerusagestrs[] = { "_2d", "_cube", "_volume" }; - static const char *usagestrs[] = { - "_position", "_blendweight", "_blendindices", "_normal", "_psize", - "_texcoord", "_tangent", "_binormal", "_tessfactor", "_positiont", - "_color", "_fog", "_depth", "_sample" - }; - - for (i = 0; i < STATICARRAYLEN(usagestrs); i++) - { - if (check_token_segment(ctx, usagestrs[i])) - { - *issampler = 0; - *val = i; - return 1; - } // if - } // for - - for (i = 0; i < STATICARRAYLEN(samplerusagestrs); i++) - { - if (check_token_segment(ctx, samplerusagestrs[i])) - { - *issampler = 1; - *val = i + 2; - return 1; - } // if - } // for - - *issampler = 0; - *val = 0; - return 0; -} // parse_dcl_usage - - -static int parse_args_DCL(Context *ctx) -{ - int issampler = 0; - uint32 usage = 0; - uint32 index = 0; - - ctx->tokenbufpos++; // save a spot for the usage/index token. - ctx->tokenbuf[0] = 0; - - // parse_instruction_token() sets ctx->token to the end of the instruction - // so we can see if there are destination modifiers on the instruction - // itself... - - if (parse_dcl_usage(ctx, &usage, &issampler)) - { - if ((ctx->tokenlen > 0) && (*ctx->token != '_')) - { - if (!ui32fromtoken(ctx, &index)) - fail(ctx, "Expected usage index"); - } // if - } // if - - parse_destination_token(ctx); - - const int samplerreg = (ctx->dest_arg.regtype == REG_TYPE_SAMPLER); - if (issampler != samplerreg) - fail(ctx, "Invalid usage"); - else if (samplerreg) - ctx->tokenbuf[0] = (usage << 27) | 0x80000000; - else - ctx->tokenbuf[0] = usage | (index << 16) | 0x80000000; - - return 3; -} // parse_args_DCL - - -static int parse_args_D(Context *ctx) -{ - int retval = 1; - retval += parse_destination_token(ctx); - return retval; -} // parse_args_D - - -static int parse_args_S(Context *ctx) -{ - int retval = 1; - retval += parse_source_token(ctx); - return retval; -} // parse_args_S - - -static int parse_args_SS(Context *ctx) -{ - int retval = 1; - retval += parse_source_token(ctx); - require_comma(ctx); - retval += parse_source_token(ctx); - return retval; -} // parse_args_SS - - -static int parse_args_DS(Context *ctx) -{ - int retval = 1; - retval += parse_destination_token(ctx); - require_comma(ctx); - retval += parse_source_token(ctx); - return retval; -} // parse_args_DS - - -static int parse_args_DSS(Context *ctx) -{ - int retval = 1; - retval += parse_destination_token(ctx); - require_comma(ctx); - retval += parse_source_token(ctx); - require_comma(ctx); - retval += parse_source_token(ctx); - return retval; -} // parse_args_DSS - - -static int parse_args_DSSS(Context *ctx) -{ - int retval = 1; - retval += parse_destination_token(ctx); - require_comma(ctx); - retval += parse_source_token(ctx); - require_comma(ctx); - retval += parse_source_token(ctx); - require_comma(ctx); - retval += parse_source_token(ctx); - return retval; -} // parse_args_DSSS - - -static int parse_args_DSSSS(Context *ctx) -{ - int retval = 1; - retval += parse_destination_token(ctx); - require_comma(ctx); - retval += parse_source_token(ctx); - require_comma(ctx); - retval += parse_source_token(ctx); - require_comma(ctx); - retval += parse_source_token(ctx); - require_comma(ctx); - retval += parse_source_token(ctx); - return retval; -} // parse_args_DSSSS - - -static int parse_args_SINCOS(Context *ctx) -{ - // this opcode needs extra registers for sm2 and lower. - if (!shader_version_atleast(ctx, 3, 0)) - return parse_args_DSSS(ctx); - return parse_args_DS(ctx); -} // parse_args_SINCOS - - -static int parse_args_TEXCRD(Context *ctx) -{ - // added extra register in ps_1_4. - if (shader_version_atleast(ctx, 1, 4)) - return parse_args_DS(ctx); - return parse_args_D(ctx); -} // parse_args_TEXCRD - - -static int parse_args_TEXLD(Context *ctx) -{ - // different registers in px_1_3, ps_1_4, and ps_2_0! - if (shader_version_atleast(ctx, 2, 0)) - return parse_args_DSS(ctx); - else if (shader_version_atleast(ctx, 1, 4)) - return parse_args_DS(ctx); - return parse_args_D(ctx); -} // parse_args_TEXLD - - - -// one args function for each possible sequence of opcode arguments. -typedef int (*args_function)(Context *ctx); - -// Lookup table for instruction opcodes... -typedef struct -{ - const char *opcode_string; - args_function parse_args; -} Instruction; - - -static const Instruction instructions[] = -{ - #define INSTRUCTION_STATE(op, opstr, s, a, t) { opstr, parse_args_##a }, - #define INSTRUCTION(op, opstr, slots, a, t) { opstr, parse_args_##a }, - #define MOJOSHADER_DO_INSTRUCTION_TABLE 1 - #include "mojoshader_internal.h" - #undef MOJOSHADER_DO_INSTRUCTION_TABLE - #undef INSTRUCTION - #undef INSTRUCTION_STATE -}; - - -static int parse_condition(Context *ctx, uint32 *controls) -{ - static const char *comps[] = { "_gt", "_eq", "_ge", "_lt", "_ne", "_le" }; - size_t i; - - if (ctx->tokenlen >= 3) - { - for (i = 0; i < STATICARRAYLEN(comps); i++) - { - if (check_token_segment(ctx, comps[i])) - { - *controls = (uint32) (i + 1); - return 1; - } // if - } // for - } // if - - return 0; -} // parse_condition - - -static int parse_instruction_token(Context *ctx, Token token) -{ - int coissue = 0; - int predicated = 0; - - if (token == ((Token) '+')) - { - coissue = 1; - token = nexttoken(ctx); - } // if - - if (token != TOKEN_IDENTIFIER) - { - fail(ctx, "Expected instruction"); - return 0; - } // if - - uint32 controls = 0; - uint32 opcode = OPCODE_TEXLD; - const char *origtoken = ctx->token; - const unsigned int origtokenlen = ctx->tokenlen; - - // This might need to be TEXLD instead of TEXLDP. - if (check_token_segment(ctx, "TEXLDP")) - controls = CONTROL_TEXLDP; - - // This might need to be TEXLD instead of TEXLDB. - else if (check_token_segment(ctx, "TEXLDB")) - controls = CONTROL_TEXLDB; - - else // find the instruction. - { - size_t i; - for (i = 0; i < STATICARRAYLEN(instructions); i++) - { - const char *opcode_string = instructions[i].opcode_string; - if (opcode_string == NULL) - continue; // skip this. - else if (!check_token_segment(ctx, opcode_string)) - continue; // not us. - else if ((ctx->tokenlen > 0) && (*ctx->token != '_')) - { - ctx->token = origtoken; - ctx->tokenlen = origtokenlen; - continue; // not the match: TEXLD when we wanted TEXLDL, etc. - } // if - - break; // found it! - } // for - - opcode = (uint32) i; - - // This might need to be IFC instead of IF. - if (opcode == OPCODE_IF) - { - if (parse_condition(ctx, &controls)) - opcode = OPCODE_IFC; - } // if - - // This might need to be BREAKC instead of BREAK. - else if (opcode == OPCODE_BREAK) - { - if (parse_condition(ctx, &controls)) - opcode = OPCODE_BREAKC; - } // else if - - // SETP has a conditional code, always. - else if (opcode == OPCODE_SETP) - { - if (!parse_condition(ctx, &controls)) - fail(ctx, "SETP requires a condition"); - } // else if - } // else - - if ( (opcode == STATICARRAYLEN(instructions)) || - ((ctx->tokenlen > 0) && (ctx->token[0] != '_')) ) - { - char opstr[32]; - const int len = Min(sizeof (opstr) - 1, origtokenlen); - memcpy(opstr, origtoken, len); - opstr[len] = '\0'; - failf(ctx, "Unknown instruction '%s'", opstr); - return 0; - } // if - - const Instruction *instruction = &instructions[opcode]; - - // !!! FIXME: predicated instructions - - ctx->tokenbufpos = 0; - - const int tokcount = instruction->parse_args(ctx); - - // insttoks bits are reserved and should be zero if < SM2. - const uint32 insttoks = shader_version_atleast(ctx, 2, 0) ? tokcount-1 : 0; - - // write out the instruction token. - output_token(ctx, ((opcode & 0xFFFF) << 0) | - ((controls & 0xFF) << 16) | - ((insttoks & 0xF) << 24) | - ((coissue) ? 0x40000000 : 0x00000000) | - ((predicated) ? 0x10000000 : 0x00000000) ); - - // write out the argument tokens. - int i; - for (i = 0; i < (tokcount-1); i++) - output_token(ctx, ctx->tokenbuf[i]); - - return 1; -} // parse_instruction_token - - -static void parse_version_token(Context *ctx) -{ - int bad = 0; - int dot_form = 0; - uint32 shader_type = 0; - - if (nexttoken(ctx) != TOKEN_IDENTIFIER) - bad = 1; - else if (check_token_segment(ctx, "vs")) - { - ctx->shader_type = MOJOSHADER_TYPE_VERTEX; - shader_type = 0xFFFE; - } // if - else if (check_token_segment(ctx, "ps")) - { - ctx->shader_type = MOJOSHADER_TYPE_PIXEL; - shader_type = 0xFFFF; - } // if - else - { - // !!! FIXME: geometry shaders? - bad = 1; - } // else - - dot_form = ((!bad) && (ctx->tokenlen == 0)); // it's in xs.x.x form? - - uint32 major = 0; - uint32 minor = 0; - - if (dot_form) - { - Token t = TOKEN_UNKNOWN; - - if (!bad) - { - t = nexttoken(ctx); - // stupid lexer sees "vs.2.0" and makes the ".2" into a float. - if (t == ((Token) '.')) - t = nexttoken(ctx); - else - { - if ((t != TOKEN_FLOAT_LITERAL) || (ctx->token[0] != '.')) - bad = 1; - else - { - ctx->tokenval = t = TOKEN_INT_LITERAL; - ctx->token++; - ctx->tokenlen--; - } // else - } // else - } // if - - if (!bad) - { - if (t != TOKEN_INT_LITERAL) - bad = 1; - else if (!ui32fromtoken(ctx, &major)) - bad = 1; - } // if - - if (!bad) - { - t = nexttoken(ctx); - // stupid lexer sees "vs.2.0" and makes the ".2" into a float. - if (t == ((Token) '.')) - t = nexttoken(ctx); - else - { - if ((t != TOKEN_FLOAT_LITERAL) || (ctx->token[0] != '.')) - bad = 1; - else - { - ctx->tokenval = t = TOKEN_INT_LITERAL; - ctx->token++; - ctx->tokenlen--; - } // else - } // else - } // if - - if (!bad) - { - if ((t == TOKEN_INT_LITERAL) && (ui32fromtoken(ctx, &minor))) - ; // good to go. - else if ((t == TOKEN_IDENTIFIER) && (check_token_segment(ctx, "x"))) - minor = 1; - else if ((t == TOKEN_IDENTIFIER) && (check_token_segment(ctx, "sw"))) - minor = 255; - else - bad = 1; - } // if - } // if - else - { - if (!check_token_segment(ctx, "_")) - bad = 1; - else if (!ui32fromtoken(ctx, &major)) - bad = 1; - else if (!check_token_segment(ctx, "_")) - bad = 1; - else if (check_token_segment(ctx, "x")) - minor = 1; - else if (check_token_segment(ctx, "sw")) - minor = 255; - else if (!ui32fromtoken(ctx, &minor)) - bad = 1; - } // else - - if ((!bad) && (ctx->tokenlen != 0)) - bad = 1; - - if (bad) - fail(ctx, "Expected valid version string"); - - ctx->major_ver = major; - ctx->minor_ver = minor; - - ctx->version_token = (shader_type << 16) | (major << 8) | (minor << 0); - output_token(ctx, ctx->version_token); -} // parse_version_token - - -static void parse_phase_token(Context *ctx) -{ - output_token(ctx, 0x0000FFFD); // phase token always 0x0000FFFD. -} // parse_phase_token - - -static void parse_end_token(Context *ctx) -{ - // We don't emit the end token bits here, since it's valid for a shader - // to not specify an "end" string at all; it's implicit, in that case. - // Instead, we make sure if we see "end" that it's the last thing we see. - if (nexttoken(ctx) != TOKEN_EOI) - fail(ctx, "Content after END"); -} // parse_end_token - - -static void parse_token(Context *ctx, const Token token) -{ - if (token != TOKEN_IDENTIFIER) - parse_instruction_token(ctx, token); // might be a coissue '+', etc. - else - { - if (check_token(ctx, "end")) - parse_end_token(ctx); - else if (check_token(ctx, "phase")) - parse_phase_token(ctx); - else - parse_instruction_token(ctx, token); - } // if -} // parse_token - - -static void destroy_context(Context *ctx) -{ - if (ctx != NULL) - { - MOJOSHADER_free f = ((ctx->free != NULL) ? ctx->free : MOJOSHADER_internal_free); - void *d = ctx->malloc_data; - preprocessor_end(ctx->preprocessor); - errorlist_destroy(ctx->errors); - buffer_destroy(ctx->ctab); - buffer_destroy(ctx->token_to_source); - buffer_destroy(ctx->output); - f(ctx, d); - } // if -} // destroy_context - - -static Context *build_context(const char *filename, - const char *source, unsigned int sourcelen, - const MOJOSHADER_preprocessorDefine *defines, - unsigned int define_count, - MOJOSHADER_includeOpen include_open, - MOJOSHADER_includeClose include_close, - MOJOSHADER_malloc m, MOJOSHADER_free f, void *d) -{ - if (!m) m = MOJOSHADER_internal_malloc; - if (!f) f = MOJOSHADER_internal_free; - if (!include_open) include_open = MOJOSHADER_internal_include_open; - if (!include_close) include_close = MOJOSHADER_internal_include_close; - - Context *ctx = (Context *) m(sizeof (Context), d); - if (ctx == NULL) - return NULL; - - memset(ctx, '\0', sizeof (Context)); - ctx->malloc = m; - ctx->free = f; - ctx->malloc_data = d; - ctx->current_position = MOJOSHADER_POSITION_BEFORE; - - const size_t outblk = sizeof (uint32) * 4 * 64; // 64 4-token instrs. - ctx->output = buffer_create(outblk, MallocBridge, FreeBridge, ctx); - if (ctx->output == NULL) - goto build_context_failed; - - const size_t mapblk = sizeof (SourcePos) * 4 * 64; // 64 * 4-tokens. - ctx->token_to_source = buffer_create(mapblk, MallocBridge, FreeBridge, ctx); - if (ctx->token_to_source == NULL) - goto build_context_failed; - - ctx->errors = errorlist_create(MallocBridge, FreeBridge, ctx); - if (ctx->errors == NULL) - goto build_context_failed; - - ctx->preprocessor = preprocessor_start(filename, source, sourcelen, - include_open, include_close, - defines, define_count, 1, - MallocBridge, FreeBridge, ctx); - - if (ctx->preprocessor == NULL) - goto build_context_failed; - - return ctx; - -build_context_failed: // ctx is allocated and zeroed before this is called. - destroy_context(ctx); - return NULL; -} // build_context - - -static const MOJOSHADER_parseData *build_failed_assembly(Context *ctx) -{ - assert(isfail(ctx)); - - if (ctx->out_of_memory) - return &MOJOSHADER_out_of_mem_data; - - MOJOSHADER_parseData *retval = NULL; - retval = (MOJOSHADER_parseData*) Malloc(ctx, sizeof(MOJOSHADER_parseData)); - if (retval == NULL) - return &MOJOSHADER_out_of_mem_data; - - memset(retval, '\0', sizeof (MOJOSHADER_parseData)); - retval->malloc = (ctx->malloc == MOJOSHADER_internal_malloc) ? NULL : ctx->malloc; - retval->free = (ctx->free == MOJOSHADER_internal_free) ? NULL : ctx->free; - retval->malloc_data = ctx->malloc_data; - - retval->error_count = errorlist_count(ctx->errors); - retval->errors = errorlist_flatten(ctx->errors); - - if (ctx->out_of_memory) - { - Free(ctx, retval->errors); - Free(ctx, retval); - return &MOJOSHADER_out_of_mem_data; - } // if - - return retval; -} // build_failed_assembly - - -static uint32 add_ctab_bytes(Context *ctx, const uint8 *bytes, const size_t len) -{ - if (isfail(ctx)) - return 0; - - const size_t extra = CTAB_SIZE + sizeof (uint32); - const ssize_t pos = buffer_find(ctx->ctab, extra, bytes, len); - if (pos >= 0) // blob is already in here. - return ((uint32) pos) - sizeof (uint32); - - // add it to the byte pile... - const uint32 retval = ((uint32) buffer_size(ctx->ctab)) - sizeof (uint32); - buffer_append(ctx->ctab, bytes, len); - return retval; -} // add_ctab_bytes - - -static inline uint32 add_ctab_string(Context *ctx, const char *str) -{ - return add_ctab_bytes(ctx, (const uint8 *) str, strlen(str) + 1); -} // add_ctab_string - - -static uint32 add_ctab_typeinfo(Context *ctx, const MOJOSHADER_symbolTypeInfo *info); - -static uint32 add_ctab_members(Context *ctx, const MOJOSHADER_symbolTypeInfo *info) -{ - unsigned int i; - const size_t len = info->member_count * CMEMBERINFO_SIZE; - uint8 *bytes = (uint8 *) Malloc(ctx, len); - if (bytes == NULL) - return 0; - - union { uint8 *ui8; uint16 *ui16; uint32 *ui32; } ptr; - ptr.ui8 = bytes; - for (i = 0; i < info->member_count; i++) - { - const MOJOSHADER_symbolStructMember *member = &info->members[i]; - *(ptr.ui32++) = SWAP32(add_ctab_string(ctx, member->name)); - *(ptr.ui32++) = SWAP32(add_ctab_typeinfo(ctx, &member->info)); - } // for - - const uint32 retval = add_ctab_bytes(ctx, bytes, len); - Free(ctx, bytes); - return retval; -} // add_ctab_members - - -static uint32 add_ctab_typeinfo(Context *ctx, const MOJOSHADER_symbolTypeInfo *info) -{ - uint8 bytes[CTYPEINFO_SIZE]; - union { uint8 *ui8; uint16 *ui16; uint32 *ui32; } ptr; - ptr.ui8 = bytes; - - *(ptr.ui16++) = SWAP16((uint16) info->parameter_class); - *(ptr.ui16++) = SWAP16((uint16) info->parameter_type); - *(ptr.ui16++) = SWAP16((uint16) info->rows); - *(ptr.ui16++) = SWAP16((uint16) info->columns); - *(ptr.ui16++) = SWAP16((uint16) info->elements); - *(ptr.ui16++) = SWAP16((uint16) info->member_count); - *(ptr.ui32++) = SWAP32(add_ctab_members(ctx, info)); - - return add_ctab_bytes(ctx, bytes, sizeof (bytes)); -} // add_ctab_typeinfo - - -static uint32 add_ctab_info(Context *ctx, const MOJOSHADER_symbol *symbols, - const unsigned int symbol_count) -{ - unsigned int i; - const size_t len = symbol_count * CINFO_SIZE; - uint8 *bytes = (uint8 *) Malloc(ctx, len); - if (bytes == NULL) - return 0; - - union { uint8 *ui8; uint16 *ui16; uint32 *ui32; } ptr; - ptr.ui8 = bytes; - for (i = 0; i < symbol_count; i++) - { - const MOJOSHADER_symbol *sym = &symbols[i]; - *(ptr.ui32++) = SWAP32(add_ctab_string(ctx, sym->name)); - *(ptr.ui16++) = SWAP16((uint16) sym->register_set); - *(ptr.ui16++) = SWAP16((uint16) sym->register_index); - *(ptr.ui16++) = SWAP16((uint16) sym->register_count); - *(ptr.ui16++) = SWAP16(0); // reserved - *(ptr.ui32++) = SWAP32(add_ctab_typeinfo(ctx, &sym->info)); - *(ptr.ui32++) = SWAP32(0); // !!! FIXME: default value. - } // for - - const uint32 retval = add_ctab_bytes(ctx, bytes, len); - Free(ctx, bytes); - return retval; -} // add_ctab_info - - -static void output_ctab(Context *ctx, const MOJOSHADER_symbol *symbols, - unsigned int symbol_count, const char *creator) -{ - const size_t tablelen = CTAB_SIZE + sizeof (uint32); - - ctx->ctab = buffer_create(256, MallocBridge, FreeBridge, ctx); - if (ctx->ctab == NULL) - return; // out of memory. - - uint32 *table = (uint32 *) buffer_reserve(ctx->ctab, tablelen); - if (table == NULL) - { - buffer_destroy(ctx->ctab); - ctx->ctab = NULL; - return; // out of memory. - } // if - - *(table++) = SWAP32(CTAB_ID); - *(table++) = SWAP32(CTAB_SIZE); - *(table++) = SWAP32(add_ctab_string(ctx, creator)); - *(table++) = SWAP32(ctx->version_token); - *(table++) = SWAP32(((uint32) symbol_count)); - *(table++) = SWAP32(add_ctab_info(ctx, symbols, symbol_count)); - *(table++) = SWAP32(0); // build flags. - *(table++) = SWAP32(add_ctab_string(ctx, "")); // !!! FIXME: target? - - const size_t ctablen = buffer_size(ctx->ctab); - uint8 *buf = (uint8 *) buffer_flatten(ctx->ctab); - if (buf != NULL) - { - output_comment_bytes(ctx, buf, ctablen); - Free(ctx, buf); - } // if - - buffer_destroy(ctx->ctab); - ctx->ctab = NULL; -} // output_ctab - - -static void output_comments(Context *ctx, const char **comments, - unsigned int comment_count, - const MOJOSHADER_symbol *symbols, - unsigned int symbol_count) -{ - if (isfail(ctx)) - return; - - // make error messages sane if CTAB fails, etc. - const char *prev_fname = ctx->current_file; - const int prev_position = ctx->current_position; - ctx->current_file = NULL; - ctx->current_position = MOJOSHADER_POSITION_BEFORE; - - const char *creator = "MojoShader revision " MOJOSHADER_CHANGESET; - if (symbol_count > 0) - output_ctab(ctx, symbols, symbol_count, creator); - else - output_comment_string(ctx, creator); - - unsigned int i; - for (i = 0; i < comment_count; i++) - output_comment_string(ctx, comments[i]); - - ctx->current_file = prev_fname; - ctx->current_position = prev_position; -} // output_comments - - -static const MOJOSHADER_parseData *build_final_assembly(Context *ctx) -{ - if (isfail(ctx)) - return build_failed_assembly(ctx); - - // get the final bytecode! - const unsigned int output_len = (unsigned int) buffer_size(ctx->output); - unsigned char *bytecode = (unsigned char *) buffer_flatten(ctx->output); - buffer_destroy(ctx->output); - ctx->output = NULL; - - if (bytecode == NULL) - return build_failed_assembly(ctx); - - // This validates the shader; there are lots of things that are - // invalid, but will successfully parse in the assembler, - // generating bad bytecode; this will catch them without us - // having to duplicate most of the validation here. - // It also saves us the trouble of duplicating all the other work, - // like setting up the uniforms list, etc. - MOJOSHADER_parseData *retval = (MOJOSHADER_parseData *) - MOJOSHADER_parse(MOJOSHADER_PROFILE_BYTECODE, - bytecode, output_len, NULL, 0, NULL, 0, - ctx->malloc, ctx->free, ctx->malloc_data); - Free(ctx, bytecode); - - SourcePos *token_to_src = NULL; - if (retval->error_count > 0) - token_to_src = (SourcePos *) buffer_flatten(ctx->token_to_source); - buffer_destroy(ctx->token_to_source); - ctx->token_to_source = NULL; - - if (retval->error_count > 0) - { - if (token_to_src == NULL) - { - assert(ctx->out_of_memory); - MOJOSHADER_freeParseData(retval); - return build_failed_assembly(ctx); - } // if - - // on error, map the bytecode back to a line number. - int i; - for (i = 0; i < retval->error_count; i++) - { - MOJOSHADER_error *error = &retval->errors[i]; - if (error->error_position >= 0) - { - assert(retval != &MOJOSHADER_out_of_mem_data); - assert((error->error_position % sizeof (uint32)) == 0); - - const size_t pos = error->error_position / sizeof(uint32); - if (pos >= output_len) - error->error_position = -1; // oh well. - else - { - const SourcePos *srcpos = &token_to_src[pos]; - Free(ctx, (void *) error->filename); - char *fname = NULL; - if (srcpos->filename != NULL) - fname = StrDup(ctx, srcpos->filename); - error->error_position = srcpos->line; - error->filename = fname; // may be NULL, that's okay. - } // else - } // if - } // for - - Free(ctx, token_to_src); - } // if - - return retval; -} // build_final_assembly - - -// API entry point... - -const MOJOSHADER_parseData *MOJOSHADER_assemble(const char *filename, - const char *source, unsigned int sourcelen, - const char **comments, unsigned int comment_count, - const MOJOSHADER_symbol *symbols, - unsigned int symbol_count, - const MOJOSHADER_preprocessorDefine *defines, - unsigned int define_count, - MOJOSHADER_includeOpen include_open, - MOJOSHADER_includeClose include_close, - MOJOSHADER_malloc m, MOJOSHADER_free f, void *d) -{ - const MOJOSHADER_parseData *retval = NULL; - Context *ctx = NULL; - - if ( ((m == NULL) && (f != NULL)) || ((m != NULL) && (f == NULL)) ) - return &MOJOSHADER_out_of_mem_data; // supply both or neither. - - ctx = build_context(filename, source, sourcelen, defines, define_count, - include_open, include_close, m, f, d); - if (ctx == NULL) - return &MOJOSHADER_out_of_mem_data; - - // Version token always comes first. - parse_version_token(ctx); - output_comments(ctx, comments, comment_count, symbols, symbol_count); - - // parse out the rest of the tokens after the version token... - Token token; - while ((token = nexttoken(ctx)) != TOKEN_EOI) - parse_token(ctx, token); - - ctx->current_file = NULL; - ctx->current_position = MOJOSHADER_POSITION_AFTER; - - output_token(ctx, 0x0000FFFF); // end token always 0x0000FFFF. - - retval = build_final_assembly(ctx); - destroy_context(ctx); - return retval; -} // MOJOSHADER_assemble - -// end of mojoshader_assembler.c ... - diff --git a/mojoshader/mojoshader_common.c b/mojoshader/mojoshader_common.c index 3076550..39cb5c0 100644 --- a/mojoshader/mojoshader_common.c +++ b/mojoshader/mojoshader_common.c @@ -1,5 +1,33 @@ #define __MOJOSHADER_INTERNAL__ 1 #include "mojoshader_internal.h" +#ifndef MOJOSHADER_USE_SDL_STDLIB +#include +#endif /* MOJOSHADER_USE_SDL_STDLIB */ + +// Convenience functions for allocators... +#if !MOJOSHADER_FORCE_ALLOCATOR +static char zeromalloc = 0; +void * MOJOSHADERCALL MOJOSHADER_internal_malloc(int bytes, void *d) +{ + return (bytes == 0) ? &zeromalloc : malloc(bytes); +} // MOJOSHADER_internal_malloc +void MOJOSHADERCALL MOJOSHADER_internal_free(void *ptr, void *d) +{ + if ((ptr != &zeromalloc) && (ptr != NULL)) + free(ptr); +} // MOJOSHADER_internal_free +#endif + +MOJOSHADER_error MOJOSHADER_out_of_mem_error = { + "Out of memory", NULL, MOJOSHADER_POSITION_NONE +}; + +MOJOSHADER_parseData MOJOSHADER_out_of_mem_data = { + 1, &MOJOSHADER_out_of_mem_error, 0, 0, 0, 0, + MOJOSHADER_TYPE_UNKNOWN, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + typedef struct HashItem { @@ -62,7 +90,7 @@ int hash_find(const HashTable *table, const void *key, const void **_value) int hash_iter(const HashTable *table, const void *key, const void **_value, void **iter) { - HashItem *item = (HashItem*)*iter; + HashItem *item = (HashItem *) *iter; if (item == NULL) item = table->table[calc_hash(table, key)]; else @@ -87,8 +115,8 @@ int hash_iter(const HashTable *table, const void *key, int hash_iter_keys(const HashTable *table, const void **_key, void **iter) { - HashItem *item = (HashItem*)*iter; - int idx = 0; + HashItem *item = (HashItem *) *iter; + uint32 idx = 0; if (item != NULL) { @@ -166,7 +194,7 @@ HashTable *hash_create(void *data, const HashTable_HashFn hashfn, return table; } // hash_create -void hash_destroy(HashTable *table) +void hash_destroy(HashTable *table, const void *ctx) { uint32 i; void *data = table->data; @@ -178,7 +206,7 @@ void hash_destroy(HashTable *table) while (item != NULL) { HashItem *next = item->next; - table->nuke(item->key, item->value, data); + table->nuke(ctx, item->key, item->value, data); f(item, d); item = next; } // while @@ -188,7 +216,7 @@ void hash_destroy(HashTable *table) f(table, d); } // hash_destroy -int hash_remove(HashTable *table, const void *key) +int hash_remove(HashTable *table, const void *key, const void *ctx) { HashItem *item = NULL; HashItem *prev = NULL; @@ -203,7 +231,7 @@ int hash_remove(HashTable *table, const void *key) else table->table[hash] = item->next; - table->nuke(item->key, item->value, data); + table->nuke(ctx, item->key, item->value, data); table->f(item, table->d); return 1; } // if @@ -244,9 +272,9 @@ int hash_keymatch_string(const void *a, const void *b, void *data) // string -> string map... -static void stringmap_nuke_noop(const void *key, const void *val, void *d) {} +static void stringmap_nuke_noop(const void *ctx, const void *key, const void *val, void *d) {} -static void stringmap_nuke(const void *key, const void *val, void *d) +static void stringmap_nuke(const void *ctx, const void *key, const void *val, void *d) { StringMap *smap = (StringMap *) d; smap->f((void *) key, smap->d); @@ -266,7 +294,7 @@ StringMap *stringmap_create(const int copy, MOJOSHADER_malloc m, void stringmap_destroy(StringMap *smap) { - hash_destroy(smap); + hash_destroy(smap, NULL); } // stringmap_destroy int stringmap_insert(StringMap *smap, const char *key, const char *value) @@ -299,7 +327,7 @@ int stringmap_insert(StringMap *smap, const char *key, const char *value) int stringmap_remove(StringMap *smap, const char *key) { - return hash_remove(smap, key); + return hash_remove(smap, key, NULL); } // stringmap_remove int stringmap_find(const StringMap *smap, const char *key, const char **_value) @@ -328,13 +356,16 @@ struct StringCache void *d; }; + const char *stringcache(StringCache *cache, const char *str) { return stringcache_len(cache, str, strlen(str)); } // stringcache -const char *stringcache_len(StringCache *cache, const char *str, - const unsigned int len) +static const char *stringcache_len_internal(StringCache *cache, + const char *str, + const unsigned int len, + const int addmissing) { const uint8 hash = hash_string(str, len) & (cache->table_size-1); StringBucket *bucket = cache->hashtable[hash]; @@ -358,23 +389,33 @@ const char *stringcache_len(StringCache *cache, const char *str, bucket = bucket->next; } // while - // no match, add to the table. - bucket = (StringBucket *) cache->m(sizeof (StringBucket), cache->d); - if (bucket == NULL) + // no match! + if (!addmissing) return NULL; - bucket->string = (char *) cache->m(len + 1, cache->d); - if (bucket->string == NULL) - { - cache->f(bucket, cache->d); + + // add to the table. + bucket = (StringBucket *) cache->m(sizeof (StringBucket) + len + 1, cache->d); + if (bucket == NULL) return NULL; - } // if + bucket->string = (char *)(bucket + 1); memcpy(bucket->string, str, len); bucket->string[len] = '\0'; bucket->next = cache->hashtable[hash]; cache->hashtable[hash] = bucket; return bucket->string; +} // stringcache_len_internal + +const char *stringcache_len(StringCache *cache, const char *str, + const unsigned int len) +{ + return stringcache_len_internal(cache, str, len, 1); } // stringcache_len +int stringcache_iscached(StringCache *cache, const char *str) +{ + return (stringcache_len_internal(cache, str, strlen(str), 0) != NULL); +} // stringcache_iscached + const char *stringcache_fmt(StringCache *cache, const char *fmt, ...) { char buf[128]; // use the stack if reasonable. @@ -444,7 +485,6 @@ void stringcache_destroy(StringCache *cache) while (bucket) { StringBucket *next = bucket->next; - f(bucket->string, d); f(bucket, d); bucket = next; } // while @@ -529,9 +569,24 @@ int errorlist_add_va(ErrorList *list, const char *_fname, char scratch[128]; va_list ap; va_copy(ap, va); - const int len = vsnprintf(scratch, sizeof (scratch), fmt, ap); + int len = vsnprintf(scratch, sizeof (scratch), fmt, ap); va_end(ap); + // on some versions of the windows C runtime, vsnprintf() returns -1 + // if the buffer overflows instead of the length the string would have + // been as expected. + // In this case we make another copy of va and fetch the length only + // with another call to _vscprintf + +#if defined(_WIN32) && !defined(MOJOSHADER_USE_SDL_STDLIB) + if (len == -1) + { + va_copy(ap, va); + len = _vscprintf(fmt, ap); + va_end(ap); + } +#endif + char *failstr = (char *) list->m(len + 1, list->d); if (failstr == NULL) { @@ -552,8 +607,6 @@ int errorlist_add_va(ErrorList *list, const char *_fname, va_end(ap); } // else - printf("fail - %s\n", failstr); - error->error.error = failstr; error->error.filename = fname; error->error.error_position = errpos; @@ -623,24 +676,6 @@ void errorlist_destroy(ErrorList *list) } // errorlist_destroy -typedef struct BufferBlock -{ - uint8 *data; - size_t bytes; - struct BufferBlock *next; -} BufferBlock; - -struct Buffer -{ - size_t total_bytes; - BufferBlock *head; - BufferBlock *tail; - size_t block_size; - MOJOSHADER_malloc m; - MOJOSHADER_free f; - void *d; -}; - Buffer *buffer_create(size_t blksz, MOJOSHADER_malloc m, MOJOSHADER_free f, void *d) { @@ -729,7 +764,7 @@ int buffer_append(Buffer *buffer, const void *_data, size_t len) if (len > 0) { - assert((!buffer->tail) || (buffer->tail->bytes == blocksize)); + assert((!buffer->tail) || (buffer->tail->bytes >= blocksize)); const size_t bytecount = len > blocksize ? len : blocksize; const size_t malloc_len = sizeof (BufferBlock) + bytecount; BufferBlock *item = (BufferBlock *) buffer->m(malloc_len, buffer->d); @@ -783,7 +818,7 @@ int buffer_append_va(Buffer *buffer, const char *fmt, va_list va) va_copy(ap, va); vsnprintf(buf, len + 1, fmt, ap); // rebuild it. va_end(ap); - const int retval = buffer_append(buffer, scratch, len); + const int retval = buffer_append(buffer, buf, len); buffer->f(buf, buffer->d); return retval; } // buffer_append_va @@ -891,44 +926,17 @@ void buffer_destroy(Buffer *buffer) } // if } // buffer_destroy -static int blockscmp(BufferBlock *item, const uint8 *data, size_t len) -{ - if (len == 0) - return 1; // "match" - - while (item != NULL) - { - const size_t itemremain = item->bytes; - const size_t avail = len < itemremain ? len : itemremain; - if (memcmp(item->data, data, avail) != 0) - return 0; // not a match. - - if (len == avail) - return 1; // complete match! - - len -= avail; - data += avail; - item = item->next; - } // while - - return 0; // not a complete match. -} // blockscmp - -ssize_t buffer_find(Buffer *buffer, const size_t start, - const void *_data, const size_t len) +void buffer_patch(Buffer *buffer, const size_t start, + const void *_data, const size_t len) { if (len == 0) - return 0; // I guess that's right. - - if (start >= buffer->total_bytes) - return -1; // definitely can't match. + return; // Nothing to do. - if (len > (buffer->total_bytes - start)) - return -1; // definitely can't match. + if ((start + len) > buffer->total_bytes) + return; // definitely can't patch. // Find the start point somewhere in the center of a buffer. BufferBlock *item = buffer->head; - const uint8 *ptr = item->data; size_t pos = 0; if (start > 0) { @@ -936,54 +944,223 @@ ssize_t buffer_find(Buffer *buffer, const size_t start, { assert(item != NULL); if ((pos + item->bytes) > start) // start is in this block. - { - ptr = item->data + (start - pos); break; - } // if pos += item->bytes; item = item->next; } // while } // if - // okay, we're at the origin of the search. - assert(item != NULL); - assert(ptr != NULL); - const uint8 *data = (const uint8 *) _data; - const uint8 first = *data; - while (item != NULL) + size_t write_pos = start - pos; + size_t write_remain = len; + size_t written = 0; + while (write_remain) { - const size_t itemremain = item->bytes - ((size_t)(ptr-item->data)); - ptr = (uint8 *) memchr(ptr, first, itemremain); - while (ptr != NULL) + size_t write_end = write_pos + write_remain; + if (write_end > item->bytes) + write_end = item->bytes; + + size_t to_write = write_end - write_pos; + memcpy(item->data + write_pos, data + written, to_write); + write_remain -= to_write; + written += to_write; + write_pos = 0; + item = item->next; + } // while +} // buffer_patch + +// Based on SDL_string.c's SDL_PrintFloat function +size_t MOJOSHADER_printFloat(char *text, size_t maxlen, float arg) +{ + size_t len; + size_t left = maxlen; + char *textstart = text; + + int precision = 9; + + if (isnan(arg)) + { + if (left > 3) { - const size_t retval = pos + ((size_t) (ptr - item->data)); - if (len == 1) - return retval; // we're done, here it is! + snprintf(text, left, "NaN"); + left -= 3; + } // if + text += 3; + } // if + else if (isinf(arg)) + { + if (left > 3) + { + snprintf(text, left, "inf"); + left -= 3; + } // if + text += 3; + } // else if + else if (arg) + { + /* This isn't especially accurate, but hey, it's easy. :) */ + unsigned long value; - const size_t itemremain = item->bytes - ((size_t)(ptr-item->data)); - const size_t avail = len < itemremain ? len : itemremain; - if ((avail == 0) || (memcmp(ptr, data, avail) == 0)) + if (arg < 0) + { + if (left > 1) { - // okay, we've got a (sub)string match! Move to the next block. - // check all blocks until we get a complete match or a failure. - if (blockscmp(item->next, data+avail, len-avail)) - return (ssize_t) retval; + *text = '-'; + --left; } // if + ++text; + arg = -arg; + } // if + value = (unsigned long) arg; + len = snprintf(text, left, "%lu", value); + text += len; + if (len >= left) + left = (left < 1) ? left : 1; + else + left -= len; + arg -= value; - // try again, further in this block. - ptr = (uint8 *) memchr(ptr + 1, first, itemremain - 1); + int mult = 10; + if (left > 1) + { + *text = '.'; + --left; + } // if + ++text; + while (precision-- > 0) + { + value = (unsigned long) (arg * mult); + len = snprintf(text, left, "%lu", value); + text += len; + if (len >= left) + left = (left < 1) ? left : 1; + else + left -= len; + arg -= (double) value / mult; + if (arg < 0) arg = -arg; // Sometimes that bit gets flipped... + mult *= 10; } // while + } // if + else + { + if (left > 3) + { + snprintf(text, left, "0.0"); + left -= 3; + } // if + text += 3; + } // else - pos += item->bytes; - item = item->next; - if (item != NULL) - ptr = item->data; - } // while + return (text - textstart); +} // MOJOSHADER_printFloat - return -1; // no match found. -} // buffer_find +#if SUPPORT_PROFILE_SPIRV +#include "spirv/spirv.h" +#include "spirv/GLSL.std.450.h" +void MOJOSHADER_spirv_link_attributes(const MOJOSHADER_parseData *vertex, + const MOJOSHADER_parseData *pixel, + int is_glspirv) +{ + int i; + uint32 attr_loc = 0; + uint32 vOffset, pOffset; + int vDataLen = vertex->output_len - sizeof(SpirvPatchTable); + int pDataLen = pixel->output_len - sizeof(SpirvPatchTable); + SpirvPatchTable *vTable = (SpirvPatchTable *) &vertex->output[vDataLen]; + SpirvPatchTable *pTable = (SpirvPatchTable *) &pixel->output[pDataLen]; + const uint32 texcoord0Loc = pTable->attrib_offsets[MOJOSHADER_USAGE_TEXCOORD][0]; + + if (is_glspirv) + { + // We need locations for color outputs first! + for (i = 0; i < pixel->output_count; i++) + { + const MOJOSHADER_attribute* pAttr = &pixel->outputs[i]; + if (pAttr->usage != MOJOSHADER_USAGE_COLOR) + { + // This should be FragDepth, which is builtin + assert(pAttr->usage == MOJOSHADER_USAGE_DEPTH); + continue; + } // if + + // Set the loc for the output declaration... + pOffset = pTable->output_offsets[pAttr->index]; + assert(pOffset > 0); + ((uint32*)pixel->output)[pOffset] = attr_loc; + + // Set the same value for the vertex output/pixel input... + pOffset = pTable->attrib_offsets[pAttr->usage][pAttr->index]; + if (pOffset) + ((uint32*)pixel->output)[pOffset] = attr_loc; + vOffset = vTable->attrib_offsets[pAttr->usage][pAttr->index]; + if (vOffset) + ((uint32*)vertex->output)[vOffset] = attr_loc; + + // ... increment location index, finally. + attr_loc++; + } // for + } + + // Okay, now we can start linking pixel/vertex attributes + for (i = 0; i < pixel->attribute_count; i++) + { + const MOJOSHADER_attribute *pAttr = &pixel->attributes[i]; + if (pAttr->usage == MOJOSHADER_USAGE_UNKNOWN) + continue; // Probably something like VPOS, ignore! + if (pAttr->usage == MOJOSHADER_USAGE_DEPTH) + continue; // This should be FragDepth, which is builtin + if (is_glspirv && pAttr->usage == MOJOSHADER_USAGE_COLOR && pTable->output_offsets[pAttr->index]) + continue; + + // The input may not exist in the output list! + pOffset = pTable->attrib_offsets[pAttr->usage][pAttr->index]; + vOffset = vTable->attrib_offsets[pAttr->usage][pAttr->index]; + ((uint32 *) pixel->output)[pOffset] = attr_loc; + if (vOffset) + ((uint32 *) vertex->output)[vOffset] = attr_loc; + attr_loc++; + } // for + + // There may be outputs not present in the input list! + for (i = 0; i < vertex->output_count; i++) + { + const MOJOSHADER_attribute *vAttr = &vertex->outputs[i]; + assert(vAttr->usage != MOJOSHADER_USAGE_UNKNOWN); + if (vAttr->usage == MOJOSHADER_USAGE_POSITION && vAttr->index == 0) + continue; + if (vAttr->usage == MOJOSHADER_USAGE_POINTSIZE && vAttr->index == 0) + continue; + if (is_glspirv && vAttr->usage == MOJOSHADER_USAGE_COLOR && pTable->output_offsets[vAttr->index]) + continue; + + if (!pTable->attrib_offsets[vAttr->usage][vAttr->index]) + { + vOffset = vTable->attrib_offsets[vAttr->usage][vAttr->index]; + ((uint32 *) vertex->output)[vOffset] = attr_loc++; + } // if + } // for + + // gl_PointCoord support + if (texcoord0Loc) + { + if (vTable->attrib_offsets[MOJOSHADER_USAGE_POINTSIZE][0] > 0) + { + ((uint32 *) pixel->output)[pTable->pointcoord_var_offset + 1] = pTable->tid_pvec2i; + ((uint32 *) pixel->output)[pTable->pointcoord_load_offset + 1] = pTable->tid_vec2; + ((uint32 *) pixel->output)[texcoord0Loc - 1] = SpvDecorationBuiltIn; + ((uint32 *) pixel->output)[texcoord0Loc] = SpvBuiltInPointCoord; + } // if + else + { + ((uint32 *) pixel->output)[pTable->pointcoord_var_offset + 1] = pTable->tid_pvec4i; + ((uint32 *) pixel->output)[pTable->pointcoord_load_offset + 1] = pTable->tid_vec4; + ((uint32 *) pixel->output)[texcoord0Loc - 1] = SpvDecorationLocation; + // texcoord0Loc should already have attr_loc from the above work! + } // else + } // if +} // MOJOSHADER_spirv_link_attributes +#endif // end of mojoshader_common.c ... diff --git a/mojoshader/mojoshader_compiler.c b/mojoshader/mojoshader_compiler.c deleted file mode 100644 index a6ad919..0000000 --- a/mojoshader/mojoshader_compiler.c +++ /dev/null @@ -1,6296 +0,0 @@ -/** - * MojoShader; generate shader programs from bytecode of compiled - * Direct3D shaders. - * - * Please see the file LICENSE.txt in the source's root directory. - * - * This file written by Ryan C. Gordon. - */ - -// !!! FIXME: this needs to be split into separate source files: -// !!! FIXME: parse, AST, IR, etc. The problem is we need to deal with the -// !!! FIXME: "Context" struct being passed around everywhere. - -#define __MOJOSHADER_INTERNAL__ 1 -#include "mojoshader_internal.h" - -#if DEBUG_COMPILER_PARSER -#define LEMON_SUPPORT_TRACING 1 -#endif - -// !!! FIXME: I'd like to lose this. It's really inefficient. Just keep a -// !!! FIXME: (tail) on these list structures instead? -#define REVERSE_LINKED_LIST(typ, head) { \ - if ((head) && (head->next)) { \ - typ *tmp = NULL; \ - typ *tmp1 = NULL; \ - while (head != NULL) { \ - tmp = head; \ - head = head->next; \ - tmp->next = tmp1; \ - tmp1 = tmp; \ - } \ - head = tmp; \ - } \ -} - -static inline int operator_is_unary(const MOJOSHADER_astNodeType op) -{ - return ( (op > MOJOSHADER_AST_OP_START_RANGE_UNARY) && - (op < MOJOSHADER_AST_OP_END_RANGE_UNARY) ); -} // operator_is_unary - -static inline int operator_is_binary(const MOJOSHADER_astNodeType op) -{ - return ( (op > MOJOSHADER_AST_OP_START_RANGE_BINARY) && - (op < MOJOSHADER_AST_OP_END_RANGE_BINARY) ); -} // operator_is_binary - -static inline int operator_is_ternary(const MOJOSHADER_astNodeType op) -{ - return ( (op > MOJOSHADER_AST_OP_START_RANGE_TERNARY) && - (op < MOJOSHADER_AST_OP_END_RANGE_TERNARY) ); -} // operator_is_ternary - - -typedef union TokenData -{ - int64 i64; - double dbl; - const char *string; - const MOJOSHADER_astDataType *datatype; -} TokenData; - - -// This tracks data types and variables, and notes when they enter/leave scope. - -typedef struct SymbolScope -{ - const char *symbol; - const MOJOSHADER_astDataType *datatype; - int index; // unique positive value within a function, negative if global. - int referenced; // non-zero if something looked for this symbol (so we know it's used). - struct SymbolScope *next; -} SymbolScope; - -typedef struct SymbolMap -{ - HashTable *hash; - SymbolScope *scope; -} SymbolMap; - -typedef struct LoopLabels -{ - int start; // loop's start label during IR build. - int end; // loop's end label during IR build. - struct LoopLabels *prev; -} LoopLabels; - -// Compile state, passed around all over the place. - -typedef struct Context -{ - int isfail; - int out_of_memory; - MOJOSHADER_malloc malloc; - MOJOSHADER_free free; - void *malloc_data; - ErrorList *errors; - ErrorList *warnings; - StringCache *strcache; - const char *sourcefile; // current source file that we're parsing. - unsigned int sourceline; // current line in sourcefile that we're parsing. - SymbolMap usertypes; - SymbolMap variables; - MOJOSHADER_astNode *ast; // Abstract Syntax Tree - const char *source_profile; - int is_func_scope; // non-zero if semantic analysis is in function scope. - int loop_count; - int switch_count; - int var_index; // next variable index for current function. - int global_var_index; // next variable index for global scope. - int user_func_index; // next function index for user-defined functions. - int intrinsic_func_index; // next function index for intrinsic functions. - - MOJOSHADER_irStatement **ir; // intermediate representation. - int ir_label_count; // next unused IR label index. - int ir_temp_count; // next unused IR temporary value index. - int ir_end; // current function's end label during IR build. - int ir_ret; // temp that holds current function's retval during IR build. - LoopLabels *ir_loop; // nested loop boundary labels during IR build. - - // Cache intrinsic types for fast lookup and consistent pointer values. - MOJOSHADER_astDataType dt_none; - MOJOSHADER_astDataType dt_bool; - MOJOSHADER_astDataType dt_int; - MOJOSHADER_astDataType dt_uint; - MOJOSHADER_astDataType dt_float; - MOJOSHADER_astDataType dt_float_snorm; - MOJOSHADER_astDataType dt_float_unorm; - MOJOSHADER_astDataType dt_half; - MOJOSHADER_astDataType dt_double; - MOJOSHADER_astDataType dt_string; - MOJOSHADER_astDataType dt_sampler1d; - MOJOSHADER_astDataType dt_sampler2d; - MOJOSHADER_astDataType dt_sampler3d; - MOJOSHADER_astDataType dt_samplercube; - MOJOSHADER_astDataType dt_samplerstate; - MOJOSHADER_astDataType dt_samplercompstate; - MOJOSHADER_astDataType dt_buf_bool; - MOJOSHADER_astDataType dt_buf_int; - MOJOSHADER_astDataType dt_buf_uint; - MOJOSHADER_astDataType dt_buf_half; - MOJOSHADER_astDataType dt_buf_float; - MOJOSHADER_astDataType dt_buf_double; - MOJOSHADER_astDataType dt_buf_float_snorm; - MOJOSHADER_astDataType dt_buf_float_unorm; - - Buffer *garbage; // this is sort of hacky. -} Context; - - -// !!! FIXME: cut and paste between every damned source file follows... -// !!! FIXME: We need to make some sort of ContextBase that applies to all -// !!! FIXME: files and move this stuff to mojoshader_common.c ... - -// Convenience functions for allocators... - -static inline void out_of_memory(Context *ctx) -{ - ctx->isfail = ctx->out_of_memory = 1; -} // out_of_memory - -static inline void *Malloc(Context *ctx, const size_t len) -{ - void *retval = ctx->malloc((int) len, ctx->malloc_data); - if (retval == NULL) - out_of_memory(ctx); - return retval; -} // Malloc - -static inline char *StrDup(Context *ctx, const char *str) -{ - char *retval = (char *) Malloc(ctx, strlen(str) + 1); - if (retval != NULL) - strcpy(retval, str); - return retval; -} // StrDup - -static inline void Free(Context *ctx, void *ptr) -{ - ctx->free(ptr, ctx->malloc_data); -} // Free - -static void *MallocBridge(int bytes, void *data) -{ - return Malloc((Context *) data, (size_t) bytes); -} // MallocBridge - -static void FreeBridge(void *ptr, void *data) -{ - Free((Context *) data, ptr); -} // FreeBridge - -static void failf(Context *ctx, const char *fmt, ...) ISPRINTF(2,3); -static void failf(Context *ctx, const char *fmt, ...) -{ - ctx->isfail = 1; - if (ctx->out_of_memory) - return; - - va_list ap; - va_start(ap, fmt); - errorlist_add_va(ctx->errors, ctx->sourcefile, ctx->sourceline, fmt, ap); - va_end(ap); -} // failf - -static inline void fail(Context *ctx, const char *reason) -{ - failf(ctx, "%s", reason); -} // fail - -static void warnf(Context *ctx, const char *fmt, ...) ISPRINTF(2,3); -static void warnf(Context *ctx, const char *fmt, ...) -{ - if (ctx->out_of_memory) - return; - - va_list ap; - va_start(ap, fmt); - errorlist_add_va(ctx->warnings, ctx->sourcefile, ctx->sourceline, fmt, ap); - va_end(ap); -} // warnf - -static inline void warn(Context *ctx, const char *reason) -{ - warnf(ctx, "%s", reason); -} // warn - -static inline int isfail(const Context *ctx) -{ - return ctx->isfail; -} // isfail - - -static void symbolmap_nuke(const void *k, const void *v, void *d) {/*no-op*/} - -static int create_symbolmap(Context *ctx, SymbolMap *map) -{ - // !!! FIXME: should compare string pointer, with string in cache. - map->scope = NULL; - map->hash = hash_create(ctx, hash_hash_string, hash_keymatch_string, - symbolmap_nuke, 1, MallocBridge, FreeBridge, ctx); - return (map->hash != NULL); -} // create_symbolmap - -static int datatypes_match(const MOJOSHADER_astDataType *a, - const MOJOSHADER_astDataType *b) -{ - int i; - - if (a == b) - return 1; - else if (a->type != b->type) - return 0; - - switch (a->type) - { - case MOJOSHADER_AST_DATATYPE_STRUCT: - if (a->structure.member_count != b->structure.member_count) - return 0; - for (i = 0; i < a->structure.member_count; i++) - { - if (!datatypes_match(a->structure.members[i].datatype, - b->structure.members[i].datatype)) - return 0; - // stringcache'd, pointer compare is safe. - else if (a->structure.members[i].identifier != - b->structure.members[i].identifier) - return 0; - } // for - return 1; - - case MOJOSHADER_AST_DATATYPE_ARRAY: - if (a->array.elements != b->array.elements) - return 0; - else if (!datatypes_match(a->array.base, b->array.base)) - return 0; - return 1; - - case MOJOSHADER_AST_DATATYPE_VECTOR: - if (a->vector.elements != b->vector.elements) - return 0; - else if (!datatypes_match(a->vector.base, b->vector.base)) - return 0; - return 1; - - case MOJOSHADER_AST_DATATYPE_MATRIX: - if (a->matrix.rows != b->matrix.rows) - return 0; - else if (a->matrix.columns != b->matrix.columns) - return 0; - else if (!datatypes_match(a->matrix.base, b->matrix.base)) - return 0; - return 1; - - case MOJOSHADER_AST_DATATYPE_BUFFER: - return datatypes_match(a->buffer.base, b->buffer.base); - - case MOJOSHADER_AST_DATATYPE_FUNCTION: - if (a->function.num_params != b->function.num_params) - return 0; - else if (a->function.intrinsic != b->function.intrinsic) - return 0; - else if (!datatypes_match(a->function.retval, b->function.retval)) - return 0; - for (i = 0; i < a->function.num_params; i++) - { - if (!datatypes_match(a->function.params[i], b->function.params[i])) - return 0; - } // for - return 1; - - case MOJOSHADER_AST_DATATYPE_USER: - return 0; // pointers must match, this clearly didn't. - - default: - assert(0 && "unexpected case"); - return 0; - } // switch - - return 0; -} // datatypes_match - -static void push_symbol(Context *ctx, SymbolMap *map, const char *sym, - const MOJOSHADER_astDataType *dt, const int index, - const int check_dupes) -{ - if (ctx->out_of_memory) - return; - - // Decide if this symbol is defined, and if it's in the current scope. - SymbolScope *item = NULL; - const void *value = NULL; - if ((check_dupes) && (sym != NULL) && (hash_find(map->hash, sym, &value))) - { - // check the current scope for a dupe. - // !!! FIXME: note current scope's starting index, see if found - // !!! FIXME: item is < index (and thus, a previous scope). - item = map->scope; - while ((item) && (item->symbol)) - { - if ( ((const void *) item) == value ) - { - failf(ctx, "Symbol '%s' already defined", sym); - return; - } // if - item = item->next; - } // while - } // if - - // Add the symbol to our map and scope stack. - item = (SymbolScope *) Malloc(ctx, sizeof (SymbolScope)); - if (item == NULL) - return; - - if (sym != NULL) // sym can be NULL if we're pushing a new scope. - { - if (hash_insert(map->hash, sym, item) == -1) - { - Free(ctx, item); - return; - } // if - } // if - - item->symbol = sym; // cached strings, don't copy. - item->index = index; - item->datatype = dt; - item->referenced = 0; - item->next = map->scope; - map->scope = item; -} // push_symbol - -static void push_usertype(Context *ctx, const char *sym, const MOJOSHADER_astDataType *dt) -{ - if (sym != NULL) - { - MOJOSHADER_astDataType *userdt; - userdt = (MOJOSHADER_astDataType *) Malloc(ctx, sizeof (*userdt)); - if (userdt != NULL) - { - // !!! FIXME: this is hacky. - if (!buffer_append(ctx->garbage, &userdt, sizeof (userdt))) - { - Free(ctx, userdt); - return; - } // if - - userdt->type = MOJOSHADER_AST_DATATYPE_USER; - userdt->user.details = dt; - userdt->user.name = sym; - - dt = userdt; - } // if - } // if - - push_symbol(ctx, &ctx->usertypes, sym, dt, 0, 1); -} // push_usertype - -static inline void push_variable(Context *ctx, const char *sym, const MOJOSHADER_astDataType *dt) -{ - int idx = 0; - if (sym != NULL) - { - // leave space for individual member indexes. The IR will need this. - int additional = 0; - if (dt->type == MOJOSHADER_AST_DATATYPE_STRUCT) - additional = dt->structure.member_count; - if (ctx->is_func_scope) - { - idx = ++ctx->var_index; // these are positive. - ctx->var_index += additional; - } // if - else - { - idx = --ctx->global_var_index; // these are negative. - ctx->global_var_index -= additional; - } // else - } // if - - push_symbol(ctx, &ctx->variables, sym, dt, idx, 1); -} // push_variable - -static int push_function(Context *ctx, const char *sym, - const MOJOSHADER_astDataType *dt, - const int just_declare) -{ - // we don't have any reason to support nested functions at the moment, - // so this would be a bug. - assert(!ctx->is_func_scope); - assert(dt->type == MOJOSHADER_AST_DATATYPE_FUNCTION); - - // Functions are always global, so no need to search scopes. - // Functions overload, though, so we have to continue iterating to - // see if it matches anything. - const void *value = NULL; - void *iter = NULL; - while (hash_iter(ctx->variables.hash, sym, &value, &iter)) - { - // !!! FIXME: this breaks if you predeclare a function. - // !!! FIXME: (a declare AFTER defining works, though.) - // there's already something called this. - SymbolScope *item = (SymbolScope *) value; - if (datatypes_match(dt, item->datatype)) - { - if (!just_declare) - failf(ctx, "Function '%s' already defined.", sym); - return item->index; - } // if - } // while - - int idx = 0; - if ((sym != NULL) && (dt != NULL)) - { - if (!dt->function.intrinsic) - idx = ++ctx->user_func_index; // these are positive. - else - idx = --ctx->intrinsic_func_index; // these are negative. - } // if - - // push_symbol() doesn't check dupes, because we just did. - push_symbol(ctx, &ctx->variables, sym, dt, idx, 0); - - return idx; -} // push_function - -static inline void push_scope(Context *ctx) -{ - push_usertype(ctx, NULL, NULL); - push_variable(ctx, NULL, NULL); -} // push_scope - -static void pop_symbol(Context *ctx, SymbolMap *map) -{ - SymbolScope *item = map->scope; - if (!item) - return; - if (item->symbol) - hash_remove(map->hash, item->symbol); - map->scope = item->next; - Free(ctx, item); -} // pop_symbol - -static void pop_symbol_scope(Context *ctx, SymbolMap *map) -{ - while ((map->scope) && (map->scope->symbol)) - pop_symbol(ctx, map); - - assert(map->scope != NULL); - assert(map->scope->symbol == NULL); - pop_symbol(ctx, map); -} // pop_symbol_scope - -static inline void pop_scope(Context *ctx) -{ - pop_symbol_scope(ctx, &ctx->usertypes); - pop_symbol_scope(ctx, &ctx->variables); -} // push_scope - -static const MOJOSHADER_astDataType *find_symbol(Context *ctx, SymbolMap *map, const char *sym, int *_index) -{ - const void *_item = NULL; - hash_find(map->hash, sym, &_item); - SymbolScope *item = (SymbolScope *) _item; - if (item != NULL) - { - item->referenced++; - if (_index != NULL) - *_index = item->index; - } // if - return item ? item->datatype : NULL; -} // find_symbol - -static inline const MOJOSHADER_astDataType *find_usertype(Context *ctx, const char *sym) -{ - return find_symbol(ctx, &ctx->usertypes, sym, NULL); -} // find_usertype - -static inline const MOJOSHADER_astDataType *find_variable(Context *ctx, const char *sym, int *_index) -{ - return find_symbol(ctx, &ctx->variables, sym, _index); -} // find_variable - -static void destroy_symbolmap(Context *ctx, SymbolMap *map) -{ - while (map->scope) - pop_symbol(ctx, map); - hash_destroy(map->hash); -} // destroy_symbolmap - - -static const MOJOSHADER_astDataType *new_datatype_vector(Context *ctx, - const MOJOSHADER_astDataType *dt, - const int columns) -{ - MOJOSHADER_astDataType *retval; - retval = (MOJOSHADER_astDataType *) Malloc(ctx, sizeof (*retval)); - if (retval == NULL) - return NULL; - - // !!! FIXME: this is hacky. - // !!! FIXME: I'd like to cache these anyhow and reuse types. - if (!buffer_append(ctx->garbage, &retval, sizeof (retval))) - { - Free(ctx, retval); - return NULL; - } // if - - if ((columns < 1) || (columns > 4)) - fail(ctx, "Vector must have between 1 and 4 elements"); - - retval->type = MOJOSHADER_AST_DATATYPE_VECTOR; - retval->vector.base = dt; - retval->vector.elements = columns; - return retval; -} // new_datatype_vector - -static const MOJOSHADER_astDataType *new_datatype_matrix(Context *ctx, - const MOJOSHADER_astDataType *dt, - const int rows, const int columns) -{ - MOJOSHADER_astDataType *retval; - // !!! FIXME: allocate enough for a matrix, but we need to cleanup things that copy without checking for subsize. - retval = (MOJOSHADER_astDataType *) Malloc(ctx, sizeof (*retval)); - if (retval == NULL) - return NULL; - - // !!! FIXME: this is hacky. - // !!! FIXME: I'd like to cache these anyhow and reuse types. - if (!buffer_append(ctx->garbage, &retval, sizeof (retval))) - { - Free(ctx, retval); - return NULL; - } // if - - if ((rows < 1) || (rows > 4)) - fail(ctx, "Matrix must have between 1 and 4 rows"); - if ((columns < 1) || (columns > 4)) - fail(ctx, "Matrix must have between 1 and 4 columns"); - - retval->type = MOJOSHADER_AST_DATATYPE_MATRIX; - retval->matrix.base = dt; - retval->matrix.rows = rows; - retval->matrix.columns = columns; - return retval; -} // new_datatype_matrix - - -// !!! FIXME: move this to mojoshader_ast.c -// !!! FIXME: new_* and delete_* should take an allocator, not a context. - -// These functions are mostly for construction and cleanup of nodes in the -// parse tree. Mostly this is simple allocation and initialization, so we -// can do as little in the lemon code as possible, and then sort it all out -// afterwards. - -#define NEW_AST_NODE(retval, cls, typ) \ - cls *retval = (cls *) Malloc(ctx, sizeof (cls)); \ - do { \ - if (retval == NULL) { return NULL; } \ - retval->ast.type = typ; \ - retval->ast.filename = ctx->sourcefile; \ - retval->ast.line = ctx->sourceline; \ - } while (0) - -#define DELETE_AST_NODE(cls) do { \ - if (!cls) return; \ -} while (0) - - -static void delete_compilation_unit(Context*, MOJOSHADER_astCompilationUnit*); -static void delete_statement(Context *ctx, MOJOSHADER_astStatement *stmt); - -static MOJOSHADER_astExpression *new_identifier_expr(Context *ctx, - const char *string) -{ - NEW_AST_NODE(retval, MOJOSHADER_astExpressionIdentifier, - MOJOSHADER_AST_OP_IDENTIFIER); - retval->datatype = NULL; - retval->identifier = string; // cached; don't copy string. - retval->index = 0; - return (MOJOSHADER_astExpression *) retval; -} // new_identifier_expr - -static MOJOSHADER_astExpression *new_callfunc_expr(Context *ctx, - const char *identifier, - MOJOSHADER_astArguments *args) -{ - NEW_AST_NODE(retval, MOJOSHADER_astExpressionCallFunction, - MOJOSHADER_AST_OP_CALLFUNC); - MOJOSHADER_astExpression *expr = new_identifier_expr(ctx, identifier); - retval->datatype = NULL; - retval->identifier = (MOJOSHADER_astExpressionIdentifier *) expr; - retval->args = args; - return (MOJOSHADER_astExpression *) retval; -} // new_callfunc_expr - -static MOJOSHADER_astExpression *new_constructor_expr(Context *ctx, - const MOJOSHADER_astDataType *dt, - MOJOSHADER_astArguments *args) -{ - NEW_AST_NODE(retval, MOJOSHADER_astExpressionConstructor, - MOJOSHADER_AST_OP_CONSTRUCTOR); - retval->datatype = dt; - retval->args = args; - return (MOJOSHADER_astExpression *) retval; -} // new_constructor_expr - -static MOJOSHADER_astExpression *new_cast_expr(Context *ctx, - const MOJOSHADER_astDataType *dt, - MOJOSHADER_astExpression *operand) -{ - NEW_AST_NODE(retval, MOJOSHADER_astExpressionCast, MOJOSHADER_AST_OP_CAST); - retval->datatype = dt; - retval->operand = operand; - return (MOJOSHADER_astExpression *) retval; -} // new_cast_expr - -static MOJOSHADER_astExpression *new_unary_expr(Context *ctx, - const MOJOSHADER_astNodeType op, - MOJOSHADER_astExpression *operand) -{ - NEW_AST_NODE(retval, MOJOSHADER_astExpressionUnary, op); - assert(operator_is_unary(op)); - retval->datatype = NULL; - retval->operand = operand; - return (MOJOSHADER_astExpression *) retval; -} // new_unary_expr - -static MOJOSHADER_astExpression *new_binary_expr(Context *ctx, - const MOJOSHADER_astNodeType op, - MOJOSHADER_astExpression *left, - MOJOSHADER_astExpression *right) -{ - NEW_AST_NODE(retval, MOJOSHADER_astExpressionBinary, op); - assert(operator_is_binary(op)); - retval->datatype = NULL; - retval->left = left; - retval->right = right; - return (MOJOSHADER_astExpression *) retval; -} // new_binary_expr - -static MOJOSHADER_astExpression *new_ternary_expr(Context *ctx, - const MOJOSHADER_astNodeType op, - MOJOSHADER_astExpression *left, - MOJOSHADER_astExpression *center, - MOJOSHADER_astExpression *right) -{ - NEW_AST_NODE(retval, MOJOSHADER_astExpressionTernary, op); - assert(operator_is_ternary(op)); - assert(op == MOJOSHADER_AST_OP_CONDITIONAL); - retval->datatype = &ctx->dt_bool; - retval->left = left; - retval->center = center; - retval->right = right; - return (MOJOSHADER_astExpression *) retval; -} // new_ternary_expr - -static MOJOSHADER_astExpression *new_deref_struct_expr(Context *ctx, - MOJOSHADER_astExpression *identifier, - const char *member) -{ - NEW_AST_NODE(retval, MOJOSHADER_astExpressionDerefStruct, - MOJOSHADER_AST_OP_DEREF_STRUCT); - retval->datatype = NULL; - retval->identifier = identifier; - retval->member = member; // cached; don't copy string. - retval->isswizzle = 0; // may change during semantic analysis. - retval->member_index = 0; // set during semantic analysis. - return (MOJOSHADER_astExpression *) retval; -} // new_deref_struct_expr - -static MOJOSHADER_astExpression *new_literal_int_expr(Context *ctx, - const int value) -{ - NEW_AST_NODE(retval, MOJOSHADER_astExpressionIntLiteral, - MOJOSHADER_AST_OP_INT_LITERAL); - retval->datatype = &ctx->dt_int; - retval->value = value; - return (MOJOSHADER_astExpression *) retval; -} // new_literal_int_expr - -static MOJOSHADER_astExpression *new_literal_float_expr(Context *ctx, - const double dbl) -{ - NEW_AST_NODE(retval, MOJOSHADER_astExpressionFloatLiteral, - MOJOSHADER_AST_OP_FLOAT_LITERAL); - retval->datatype = &ctx->dt_float; - retval->value = dbl; - return (MOJOSHADER_astExpression *) retval; -} // new_literal_float_expr - -static MOJOSHADER_astExpression *new_literal_string_expr(Context *ctx, - const char *string) -{ - NEW_AST_NODE(retval, MOJOSHADER_astExpressionStringLiteral, - MOJOSHADER_AST_OP_STRING_LITERAL); - retval->datatype = &ctx->dt_string; - retval->string = string; // cached; don't copy string. - return (MOJOSHADER_astExpression *) retval; -} // new_literal_string_expr - -static MOJOSHADER_astExpression *new_literal_boolean_expr(Context *ctx, - const int value) -{ - NEW_AST_NODE(retval, MOJOSHADER_astExpressionBooleanLiteral, - MOJOSHADER_AST_OP_BOOLEAN_LITERAL); - retval->datatype = &ctx->dt_bool; - retval->value = value; - return (MOJOSHADER_astExpression *) retval; -} // new_literal_boolean_expr - -static void delete_arguments(Context *ctx, MOJOSHADER_astArguments *args); - -static void delete_expr(Context *ctx, MOJOSHADER_astExpression *_expr) -{ - MOJOSHADER_astNode *expr = (MOJOSHADER_astNode *) _expr; - - DELETE_AST_NODE(expr); - - if (expr->ast.type == MOJOSHADER_AST_OP_CAST) - delete_expr(ctx, expr->cast.operand); - - else if (expr->ast.type == MOJOSHADER_AST_OP_CONSTRUCTOR) - delete_arguments(ctx, expr->constructor.args); - - else if (expr->ast.type == MOJOSHADER_AST_OP_DEREF_STRUCT) - delete_expr(ctx, expr->derefstruct.identifier); - - else if (operator_is_unary(expr->ast.type)) - delete_expr(ctx, expr->unary.operand); - - else if (operator_is_binary(expr->ast.type)) - { - delete_expr(ctx, expr->binary.left); - delete_expr(ctx, expr->binary.right); - } // else if - - else if (operator_is_ternary(expr->ast.type)) - { - delete_expr(ctx, expr->ternary.left); - delete_expr(ctx, expr->ternary.center); - delete_expr(ctx, expr->ternary.right); - } // else if - - else if (expr->ast.type == MOJOSHADER_AST_OP_CALLFUNC) - { - delete_expr(ctx, (MOJOSHADER_astExpression*)expr->callfunc.identifier); - delete_arguments(ctx, expr->callfunc.args); - } // else if - - // rest of operators don't have extra data to free. - - Free(ctx, expr); -} // delete_expr - -static MOJOSHADER_astArguments *new_argument(Context *ctx, - MOJOSHADER_astExpression *arg) -{ - NEW_AST_NODE(retval, MOJOSHADER_astArguments, MOJOSHADER_AST_ARGUMENTS); - retval->argument = arg; - retval->next = NULL; - return retval; -} // new_argument - -static void delete_arguments(Context *ctx, MOJOSHADER_astArguments *args) -{ - DELETE_AST_NODE(args); - delete_arguments(ctx, args->next); - delete_expr(ctx, args->argument); - Free(ctx, args); -} // delete_arguments - -static MOJOSHADER_astFunctionParameters *new_function_param(Context *ctx, - const MOJOSHADER_astInputModifier inputmod, - const MOJOSHADER_astDataType *dt, - const char *identifier, const char *semantic, - const MOJOSHADER_astInterpolationModifier interpmod, - MOJOSHADER_astExpression *initializer) -{ - NEW_AST_NODE(retval, MOJOSHADER_astFunctionParameters, - MOJOSHADER_AST_FUNCTION_PARAMS); - retval->datatype = dt; - retval->input_modifier = inputmod; - retval->identifier = identifier; - retval->semantic = semantic; - retval->interpolation_modifier = interpmod; - retval->initializer = initializer; - retval->next = NULL; - return retval; -} // new_function_param - -static void delete_function_params(Context *ctx, - MOJOSHADER_astFunctionParameters *params) -{ - DELETE_AST_NODE(params); - delete_function_params(ctx, params->next); - delete_expr(ctx, params->initializer); - Free(ctx, params); -} // delete_function_params - -static MOJOSHADER_astFunctionSignature *new_function_signature(Context *ctx, - const MOJOSHADER_astDataType *dt, - const char *identifier, - MOJOSHADER_astFunctionParameters *params) -{ - NEW_AST_NODE(retval, MOJOSHADER_astFunctionSignature, - MOJOSHADER_AST_FUNCTION_SIGNATURE); - retval->datatype = dt; - retval->identifier = identifier; - retval->params = params; - retval->storage_class = MOJOSHADER_AST_FNSTORECLS_NONE; - retval->semantic = NULL; - return retval; -} // new_function_signature - -static void delete_function_signature(Context *ctx, - MOJOSHADER_astFunctionSignature *sig) -{ - DELETE_AST_NODE(sig); - delete_function_params(ctx, sig->params); - Free(ctx, sig); -} // delete_function_signature - -static MOJOSHADER_astCompilationUnit *new_function(Context *ctx, - MOJOSHADER_astFunctionSignature *declaration, - MOJOSHADER_astStatement *definition) -{ - NEW_AST_NODE(retval, MOJOSHADER_astCompilationUnitFunction, - MOJOSHADER_AST_COMPUNIT_FUNCTION); - retval->next = NULL; - retval->declaration = declaration; - retval->definition = definition; - retval->index = 0; - return (MOJOSHADER_astCompilationUnit *) retval; -} // new_function - -static void delete_function(Context *ctx, - MOJOSHADER_astCompilationUnitFunction *unitfn) -{ - DELETE_AST_NODE(unitfn); - delete_compilation_unit(ctx, unitfn->next); - delete_function_signature(ctx, unitfn->declaration); - delete_statement(ctx, unitfn->definition); - Free(ctx, unitfn); -} // delete_function - -static MOJOSHADER_astScalarOrArray *new_scalar_or_array(Context *ctx, - const char *ident, const int isvec, - MOJOSHADER_astExpression *dim) -{ - NEW_AST_NODE(retval, MOJOSHADER_astScalarOrArray, - MOJOSHADER_AST_SCALAR_OR_ARRAY); - retval->identifier = ident; - retval->isarray = isvec; - retval->dimension = dim; - return retval; -} // new_scalar_or_array - -static void delete_scalar_or_array(Context *ctx,MOJOSHADER_astScalarOrArray *s) -{ - DELETE_AST_NODE(s); - delete_expr(ctx, s->dimension); - Free(ctx, s); -} // delete_scalar_or_array - -static MOJOSHADER_astTypedef *new_typedef(Context *ctx, const int isconst, - const MOJOSHADER_astDataType *dt, - MOJOSHADER_astScalarOrArray *soa) -{ - // we correct this datatype to the final version during semantic analysis. - NEW_AST_NODE(retval, MOJOSHADER_astTypedef, MOJOSHADER_AST_TYPEDEF); - retval->datatype = dt; - retval->isconst = isconst; - retval->details = soa; - return retval; -} // new_typedef - -static void delete_typedef(Context *ctx, MOJOSHADER_astTypedef *td) -{ - DELETE_AST_NODE(td); - delete_scalar_or_array(ctx, td->details); - Free(ctx, td); -} // delete_typedef - -static MOJOSHADER_astPackOffset *new_pack_offset(Context *ctx, - const char *a, const char *b) -{ - NEW_AST_NODE(retval, MOJOSHADER_astPackOffset, MOJOSHADER_AST_PACK_OFFSET); - retval->ident1 = a; - retval->ident2 = b; - return retval; -} // new_pack_offset - -static void delete_pack_offset(Context *ctx, MOJOSHADER_astPackOffset *o) -{ - DELETE_AST_NODE(o); - Free(ctx, o); -} // delete_pack_offset - -static MOJOSHADER_astVariableLowLevel *new_variable_lowlevel(Context *ctx, - MOJOSHADER_astPackOffset *po, - const char *reg) -{ - NEW_AST_NODE(retval, MOJOSHADER_astVariableLowLevel, - MOJOSHADER_AST_VARIABLE_LOWLEVEL); - retval->packoffset = po; - retval->register_name = reg; - return retval; -} // new_variable_lowlevel - -static void delete_variable_lowlevel(Context *ctx, - MOJOSHADER_astVariableLowLevel *vll) -{ - DELETE_AST_NODE(vll); - delete_pack_offset(ctx, vll->packoffset); - Free(ctx, vll); -} // delete_variable_lowlevel - -static MOJOSHADER_astAnnotations *new_annotation(Context *ctx, - const MOJOSHADER_astDataType *dt, - MOJOSHADER_astExpression *initializer) -{ - NEW_AST_NODE(retval, MOJOSHADER_astAnnotations, MOJOSHADER_AST_ANNOTATION); - retval->datatype = dt; - retval->initializer = initializer; - retval->next = NULL; - return retval; -} // new_annotation - -static void delete_annotation(Context *ctx, MOJOSHADER_astAnnotations *annos) -{ - DELETE_AST_NODE(annos); - delete_annotation(ctx, annos->next); - delete_expr(ctx, annos->initializer); - Free(ctx, annos); -} // delete_annotation - -static MOJOSHADER_astVariableDeclaration *new_variable_declaration( - Context *ctx, MOJOSHADER_astScalarOrArray *soa, - const char *semantic, - MOJOSHADER_astAnnotations *annotations, - MOJOSHADER_astExpression *init, - MOJOSHADER_astVariableLowLevel *vll) -{ - NEW_AST_NODE(retval, MOJOSHADER_astVariableDeclaration, - MOJOSHADER_AST_VARIABLE_DECLARATION); - retval->datatype = NULL; - retval->attributes = 0; - retval->anonymous_datatype = NULL; - retval->details = soa; - retval->semantic = semantic; - retval->annotations = annotations; - retval->initializer = init; - retval->lowlevel = vll; - retval->next = NULL; - return retval; -} // new_variable_declaration - -static void delete_variable_declaration(Context *ctx, - MOJOSHADER_astVariableDeclaration *dcl) -{ - DELETE_AST_NODE(dcl); - delete_variable_declaration(ctx, dcl->next); - delete_scalar_or_array(ctx, dcl->details); - delete_annotation(ctx, dcl->annotations); - delete_expr(ctx, dcl->initializer); - delete_variable_lowlevel(ctx, dcl->lowlevel); - Free(ctx, dcl); -} // delete_variable_declaration - -static MOJOSHADER_astCompilationUnit *new_global_variable(Context *ctx, - MOJOSHADER_astVariableDeclaration *decl) -{ - NEW_AST_NODE(retval, MOJOSHADER_astCompilationUnitVariable, - MOJOSHADER_AST_COMPUNIT_VARIABLE); - retval->next = NULL; - retval->declaration = decl; - return (MOJOSHADER_astCompilationUnit *) retval; -} // new_global_variable - -static void delete_global_variable(Context *ctx, - MOJOSHADER_astCompilationUnitVariable *var) -{ - DELETE_AST_NODE(var); - delete_compilation_unit(ctx, var->next); - delete_variable_declaration(ctx, var->declaration); - Free(ctx, var); -} // delete_global_variable - -static MOJOSHADER_astCompilationUnit *new_global_typedef(Context *ctx, - MOJOSHADER_astTypedef *td) -{ - NEW_AST_NODE(retval, MOJOSHADER_astCompilationUnitTypedef, - MOJOSHADER_AST_COMPUNIT_TYPEDEF); - retval->next = NULL; - retval->type_info = td; - return (MOJOSHADER_astCompilationUnit *) retval; -} // new_global_typedef - -static void delete_global_typedef(Context *ctx, - MOJOSHADER_astCompilationUnitTypedef *unit) -{ - DELETE_AST_NODE(unit); - delete_compilation_unit(ctx, unit->next); - delete_typedef(ctx, unit->type_info); - Free(ctx, unit); -} // delete_global_typedef - -static MOJOSHADER_astStructMembers *new_struct_member(Context *ctx, - MOJOSHADER_astScalarOrArray *soa, - const char *semantic) -{ - NEW_AST_NODE(retval, MOJOSHADER_astStructMembers, - MOJOSHADER_AST_STRUCT_MEMBER); - retval->datatype = NULL; - retval->semantic = semantic; - retval->details = soa; - retval->interpolation_mod = MOJOSHADER_AST_INTERPMOD_NONE; - retval->next = NULL; - return retval; -} // new_struct_member - -static void delete_struct_member(Context *ctx, - MOJOSHADER_astStructMembers *member) -{ - DELETE_AST_NODE(member); - delete_struct_member(ctx, member->next); - delete_scalar_or_array(ctx, member->details); - Free(ctx, member); -} // delete_struct_member - -static MOJOSHADER_astStructDeclaration *new_struct_declaration(Context *ctx, - const char *name, - MOJOSHADER_astStructMembers *members) -{ - NEW_AST_NODE(retval, MOJOSHADER_astStructDeclaration, - MOJOSHADER_AST_STRUCT_DECLARATION); - retval->datatype = NULL; - retval->name = name; - retval->members = members; - return retval; -} // new_struct_declaration - -static void delete_struct_declaration(Context *ctx, - MOJOSHADER_astStructDeclaration *decl) -{ - DELETE_AST_NODE(decl); - delete_struct_member(ctx, decl->members); - Free(ctx, decl); -} // delete_struct_declaration - -static MOJOSHADER_astCompilationUnit *new_global_struct(Context *ctx, - MOJOSHADER_astStructDeclaration *sd) -{ - NEW_AST_NODE(retval, MOJOSHADER_astCompilationUnitStruct, - MOJOSHADER_AST_COMPUNIT_STRUCT); - retval->next = NULL; - retval->struct_info = sd; - return (MOJOSHADER_astCompilationUnit *) retval; -} // new_global_struct - -static void delete_global_struct(Context *ctx, - MOJOSHADER_astCompilationUnitStruct *unit) -{ - DELETE_AST_NODE(unit); - delete_compilation_unit(ctx, unit->next); - delete_struct_declaration(ctx, unit->struct_info); - Free(ctx, unit); -} // delete_global_struct - -static void delete_compilation_unit(Context *ctx, - MOJOSHADER_astCompilationUnit *unit) -{ - if (!unit) return; - - // it's important to not recurse too deeply here, since you may have - // thousands of items in this linked list (each line of a massive - // function, for example). To avoid this, we iterate the list here, - // deleting all children and making them think they have no reason - // to recurse in their own delete methods. - // Please note that everyone should _try_ to delete their "next" member, - // just in case, but hopefully this cleaned it out. - - MOJOSHADER_astCompilationUnit *i = unit->next; - unit->next = NULL; - while (i) - { - MOJOSHADER_astCompilationUnit *next = i->next; - i->next = NULL; - delete_compilation_unit(ctx, i); - i = next; - } // while - - switch (unit->ast.type) - { - #define DELETE_UNIT(typ, cls, fn) \ - case MOJOSHADER_AST_COMPUNIT_##typ: delete_##fn(ctx, (cls *) unit); break; - DELETE_UNIT(FUNCTION, MOJOSHADER_astCompilationUnitFunction, function); - DELETE_UNIT(TYPEDEF, MOJOSHADER_astCompilationUnitTypedef, global_typedef); - DELETE_UNIT(VARIABLE, MOJOSHADER_astCompilationUnitVariable, global_variable); - DELETE_UNIT(STRUCT, MOJOSHADER_astCompilationUnitStruct, global_struct); - #undef DELETE_UNIT - default: assert(0 && "missing cleanup code"); break; - } // switch - - // don't free (unit) here, the class-specific functions do it. -} // delete_compilation_unit - -static MOJOSHADER_astStatement *new_typedef_statement(Context *ctx, - MOJOSHADER_astTypedef *td) -{ - NEW_AST_NODE(retval, MOJOSHADER_astTypedefStatement, - MOJOSHADER_AST_STATEMENT_TYPEDEF); - retval->next = NULL; - retval->type_info = td; - return (MOJOSHADER_astStatement *) retval; -} // new_typedef_statement - -static void delete_typedef_statement(Context *ctx, - MOJOSHADER_astTypedefStatement *stmt) -{ - DELETE_AST_NODE(stmt); - delete_statement(ctx, stmt->next); - delete_typedef(ctx, stmt->type_info); - Free(ctx, stmt); -} // delete_typedef_statement - -static MOJOSHADER_astStatement *new_return_statement(Context *ctx, - MOJOSHADER_astExpression *expr) -{ - NEW_AST_NODE(retval, MOJOSHADER_astReturnStatement, - MOJOSHADER_AST_STATEMENT_RETURN); - retval->next = NULL; - retval->expr = expr; - return (MOJOSHADER_astStatement *) retval; -} // new_return_statement - -static void delete_return_statement(Context *ctx, - MOJOSHADER_astReturnStatement *stmt) -{ - DELETE_AST_NODE(stmt); - delete_statement(ctx, stmt->next); - delete_expr(ctx, stmt->expr); - Free(ctx, stmt); -} // delete_return_statement - -static MOJOSHADER_astStatement *new_block_statement(Context *ctx, - MOJOSHADER_astStatement *stmts) -{ - NEW_AST_NODE(retval, MOJOSHADER_astBlockStatement, - MOJOSHADER_AST_STATEMENT_BLOCK); - retval->next = NULL; - retval->statements = stmts; - return (MOJOSHADER_astStatement *) retval; -} // new_block_statement - -static void delete_block_statement(Context *ctx, - MOJOSHADER_astBlockStatement *stmt) -{ - DELETE_AST_NODE(stmt); - delete_statement(ctx, stmt->statements); - delete_statement(ctx, stmt->next); - Free(ctx, stmt); -} // delete_statement_block - -static MOJOSHADER_astStatement *new_for_statement(Context *ctx, - MOJOSHADER_astVariableDeclaration *decl, - MOJOSHADER_astExpression *initializer, - MOJOSHADER_astExpression *looptest, - MOJOSHADER_astExpression *counter, - MOJOSHADER_astStatement *statement) -{ - NEW_AST_NODE(retval, MOJOSHADER_astForStatement, - MOJOSHADER_AST_STATEMENT_FOR); - retval->next = NULL; - retval->unroll = -1; - retval->var_decl = decl; - retval->initializer = initializer; - retval->looptest = looptest; - retval->counter = counter; - retval->statement = statement; - return (MOJOSHADER_astStatement *) retval; -} // new_for_statement - -static void delete_for_statement(Context *ctx,MOJOSHADER_astForStatement *stmt) -{ - DELETE_AST_NODE(stmt); - delete_statement(ctx, stmt->next); - delete_variable_declaration(ctx, stmt->var_decl); - delete_expr(ctx, stmt->initializer); - delete_expr(ctx, stmt->looptest); - delete_expr(ctx, stmt->counter); - delete_statement(ctx, stmt->statement); - Free(ctx, stmt); -} // delete_for_statement - -static MOJOSHADER_astStatement *new_do_statement(Context *ctx, - const int unroll, - MOJOSHADER_astStatement *stmt, - MOJOSHADER_astExpression *expr) -{ - NEW_AST_NODE(retval,MOJOSHADER_astDoStatement,MOJOSHADER_AST_STATEMENT_DO); - retval->next = NULL; - retval->unroll = unroll; - retval->expr = expr; - retval->statement = stmt; - return (MOJOSHADER_astStatement *) retval; -} // new_do_statement - -static void delete_do_statement(Context *ctx, MOJOSHADER_astDoStatement *stmt) -{ - DELETE_AST_NODE(stmt); - delete_statement(ctx, stmt->next); - delete_statement(ctx, stmt->statement); - delete_expr(ctx, stmt->expr); - Free(ctx, stmt); -} // delete_do_statement - -static MOJOSHADER_astStatement *new_while_statement(Context *ctx, - const int unroll, - MOJOSHADER_astExpression *expr, - MOJOSHADER_astStatement *stmt) -{ - NEW_AST_NODE(retval, MOJOSHADER_astWhileStatement, - MOJOSHADER_AST_STATEMENT_WHILE); - retval->next = NULL; - retval->unroll = unroll; - retval->expr = expr; - retval->statement = stmt; - return (MOJOSHADER_astStatement *) retval; -} // new_while_statement - -static void delete_while_statement(Context *ctx, - MOJOSHADER_astWhileStatement *stmt) -{ - DELETE_AST_NODE(stmt); - delete_statement(ctx, stmt->next); - delete_statement(ctx, stmt->statement); - delete_expr(ctx, stmt->expr); - Free(ctx, stmt); -} // delete_while_statement - -static MOJOSHADER_astStatement *new_if_statement(Context *ctx, - const int attr, - MOJOSHADER_astExpression *expr, - MOJOSHADER_astStatement *stmt, - MOJOSHADER_astStatement *elsestmt) -{ - NEW_AST_NODE(retval,MOJOSHADER_astIfStatement,MOJOSHADER_AST_STATEMENT_IF); - retval->next = NULL; - retval->attributes = attr; - retval->expr = expr; - retval->statement = stmt; - retval->else_statement = elsestmt; - return (MOJOSHADER_astStatement *) retval; -} // new_if_statement - -static void delete_if_statement(Context *ctx, MOJOSHADER_astIfStatement *stmt) -{ - DELETE_AST_NODE(stmt); - delete_statement(ctx, stmt->next); - delete_expr(ctx, stmt->expr); - delete_statement(ctx, stmt->statement); - delete_statement(ctx, stmt->else_statement); - Free(ctx, stmt); -} // delete_if_statement - -static MOJOSHADER_astSwitchCases *new_switch_case(Context *ctx, - MOJOSHADER_astExpression *expr, - MOJOSHADER_astStatement *stmt) -{ - NEW_AST_NODE(retval, MOJOSHADER_astSwitchCases, MOJOSHADER_AST_SWITCH_CASE); - retval->expr = expr; - retval->statement = stmt; - retval->next = NULL; - return retval; -} // new_switch_case - -static void delete_switch_case(Context *ctx, MOJOSHADER_astSwitchCases *sc) -{ - DELETE_AST_NODE(sc); - delete_switch_case(ctx, sc->next); - delete_expr(ctx, sc->expr); - delete_statement(ctx, sc->statement); - Free(ctx, sc); -} // delete_switch_case - -static MOJOSHADER_astStatement *new_empty_statement(Context *ctx) -{ - NEW_AST_NODE(retval, MOJOSHADER_astEmptyStatement, - MOJOSHADER_AST_STATEMENT_EMPTY); - retval->next = NULL; - return (MOJOSHADER_astStatement *) retval; -} // new_empty_statement - -static void delete_empty_statement(Context *ctx, - MOJOSHADER_astEmptyStatement *stmt) -{ - DELETE_AST_NODE(stmt); - delete_statement(ctx, stmt->next); - Free(ctx, stmt); -} // delete_empty_statement - -static MOJOSHADER_astStatement *new_break_statement(Context *ctx) -{ - NEW_AST_NODE(retval, MOJOSHADER_astBreakStatement, - MOJOSHADER_AST_STATEMENT_BREAK); - retval->next = NULL; - return (MOJOSHADER_astStatement *) retval; -} // new_break_statement - -static void delete_break_statement(Context *ctx, - MOJOSHADER_astBreakStatement *stmt) -{ - DELETE_AST_NODE(stmt); - delete_statement(ctx, stmt->next); - Free(ctx, stmt); -} // delete_break_statement - -static MOJOSHADER_astStatement *new_continue_statement(Context *ctx) -{ - NEW_AST_NODE(retval, MOJOSHADER_astContinueStatement, - MOJOSHADER_AST_STATEMENT_CONTINUE); - retval->next = NULL; - return (MOJOSHADER_astStatement *) retval; -} // new_continue_statement - -static void delete_continue_statement(Context *ctx, - MOJOSHADER_astContinueStatement *stmt) -{ - DELETE_AST_NODE(stmt); - delete_statement(ctx, stmt->next); - Free(ctx, stmt); -} // delete_continue_statement - -static MOJOSHADER_astStatement *new_discard_statement(Context *ctx) -{ - NEW_AST_NODE(retval, MOJOSHADER_astDiscardStatement, - MOJOSHADER_AST_STATEMENT_DISCARD); - retval->next = NULL; - return (MOJOSHADER_astStatement *) retval; -} // new_discard_statement - -static void delete_discard_statement(Context *ctx, - MOJOSHADER_astDiscardStatement *stmt) -{ - DELETE_AST_NODE(stmt); - delete_statement(ctx, stmt->next); - Free(ctx, stmt); -} // delete_discard_statement - -static MOJOSHADER_astStatement *new_expr_statement(Context *ctx, - MOJOSHADER_astExpression *expr) -{ - NEW_AST_NODE(retval, MOJOSHADER_astExpressionStatement, - MOJOSHADER_AST_STATEMENT_EXPRESSION); - retval->next = NULL; - retval->expr = expr; - return (MOJOSHADER_astStatement *) retval; -} // new_expr_statement - -static void delete_expr_statement(Context *ctx, - MOJOSHADER_astExpressionStatement *stmt) -{ - DELETE_AST_NODE(stmt); - delete_statement(ctx, stmt->next); - delete_expr(ctx, stmt->expr); - Free(ctx, stmt); -} // delete_expr_statement - -static MOJOSHADER_astStatement *new_switch_statement(Context *ctx, - const int attr, - MOJOSHADER_astExpression *expr, - MOJOSHADER_astSwitchCases *cases) -{ - NEW_AST_NODE(retval, MOJOSHADER_astSwitchStatement, - MOJOSHADER_AST_STATEMENT_SWITCH); - retval->next = NULL; - retval->attributes = attr; - retval->expr = expr; - retval->cases = cases; - return (MOJOSHADER_astStatement *) retval; -} // new_switch_statement - -static void delete_switch_statement(Context *ctx, - MOJOSHADER_astSwitchStatement *stmt) -{ - DELETE_AST_NODE(stmt); - delete_expr(ctx, stmt->expr); - delete_switch_case(ctx, stmt->cases); - Free(ctx, stmt); -} // delete_switch_statement - -static MOJOSHADER_astStatement *new_struct_statement(Context *ctx, - MOJOSHADER_astStructDeclaration *sd) -{ - NEW_AST_NODE(retval, MOJOSHADER_astStructStatement, - MOJOSHADER_AST_STATEMENT_STRUCT); - retval->next = NULL; - retval->struct_info = sd; - return (MOJOSHADER_astStatement *) retval; -} // new_struct_statement - -static void delete_struct_statement(Context *ctx, - MOJOSHADER_astStructStatement *stmt) -{ - DELETE_AST_NODE(stmt); - delete_statement(ctx, stmt->next); - delete_struct_declaration(ctx, stmt->struct_info); - Free(ctx, stmt); -} // delete_struct_statement - -static MOJOSHADER_astStatement *new_vardecl_statement(Context *ctx, - MOJOSHADER_astVariableDeclaration *vd) -{ - NEW_AST_NODE(retval, MOJOSHADER_astVarDeclStatement, - MOJOSHADER_AST_STATEMENT_VARDECL); - retval->next = NULL; - retval->declaration = vd; - return (MOJOSHADER_astStatement *) retval; -} // new_vardecl_statement - -static void delete_vardecl_statement(Context *ctx, - MOJOSHADER_astVarDeclStatement *stmt) -{ - DELETE_AST_NODE(stmt); - delete_statement(ctx, stmt->next); - delete_variable_declaration(ctx, stmt->declaration); - Free(ctx, stmt); -} // delete_vardecl_statement - -static void delete_statement(Context *ctx, MOJOSHADER_astStatement *stmt) -{ - if (!stmt) return; - - // it's important to not recurse too deeply here, since you may have - // thousands of items in this linked list (each line of a massive - // function, for example). To avoid this, we iterate the list here, - // deleting all children and making them think they have no reason - // to recurse in their own delete methods. - // Please note that everyone should _try_ to delete their "next" member, - // just in case, but hopefully this cleaned it out. - - MOJOSHADER_astStatement *i = stmt->next; - stmt->next = NULL; - while (i) - { - MOJOSHADER_astStatement *next = i->next; - i->next = NULL; - delete_statement(ctx, i); - i = next; - } // while - - switch (stmt->ast.type) - { - #define DELETE_STATEMENT(typ, cls, fn) \ - case MOJOSHADER_AST_STATEMENT_##typ: \ - delete_##fn##_statement(ctx, (cls *) stmt); break; - DELETE_STATEMENT(BLOCK, MOJOSHADER_astBlockStatement, block); - DELETE_STATEMENT(EMPTY, MOJOSHADER_astEmptyStatement, empty); - DELETE_STATEMENT(IF, MOJOSHADER_astIfStatement, if); - DELETE_STATEMENT(SWITCH, MOJOSHADER_astSwitchStatement, switch); - DELETE_STATEMENT(EXPRESSION, MOJOSHADER_astExpressionStatement, expr); - DELETE_STATEMENT(FOR, MOJOSHADER_astForStatement, for); - DELETE_STATEMENT(DO, MOJOSHADER_astDoStatement, do); - DELETE_STATEMENT(WHILE, MOJOSHADER_astWhileStatement, while); - DELETE_STATEMENT(RETURN, MOJOSHADER_astReturnStatement, return); - DELETE_STATEMENT(BREAK, MOJOSHADER_astBreakStatement, break); - DELETE_STATEMENT(CONTINUE, MOJOSHADER_astContinueStatement, continue); - DELETE_STATEMENT(DISCARD, MOJOSHADER_astDiscardStatement, discard); - DELETE_STATEMENT(TYPEDEF, MOJOSHADER_astTypedefStatement, typedef); - DELETE_STATEMENT(STRUCT, MOJOSHADER_astStructStatement, struct); - DELETE_STATEMENT(VARDECL, MOJOSHADER_astVarDeclStatement, vardecl); - #undef DELETE_STATEMENT - default: assert(0 && "missing cleanup code"); break; - } // switch - // don't free (stmt) here, the class-specific functions do it. -} // delete_statement - - -static const MOJOSHADER_astDataType *get_usertype(const Context *ctx, - const char *token) -{ - const void *value; // search all scopes. - if (!hash_find(ctx->usertypes.hash, token, &value)) - return NULL; - return value ? ((SymbolScope *) value)->datatype : NULL; -} // get_usertype - - -// This is where the actual parsing happens. It's Lemon-generated! -#define __MOJOSHADER_HLSL_COMPILER__ 1 -#include "mojoshader_parser_hlsl.h" - - -#if 0 -static int expr_is_constant(MOJOSHADER_astExpression *expr) -{ - const MOJOSHADER_astNodeType op = expr->ast.type; - if (operator_is_unary(op)) - return expr_is_constant(expr->unary.operand); - else if (operator_is_binary(op)) - { - return ( expr_is_constant(expr->binary.left) && - expr_is_constant(expr->binary.right) ); - } // else if - else if (operator_is_ternary(op)) - { - return ( expr_is_constant(expr->ternary.left) && - expr_is_constant(expr->ternary.center) && - expr_is_constant(expr->ternary.right) ); - } // else if - - return ( (op == MOJOSHADER_AST_OP_INT_LITERAL) || - (op == MOJOSHADER_AST_OP_FLOAT_LITERAL) || - (op == MOJOSHADER_AST_OP_STRING_LITERAL) || - (op == MOJOSHADER_AST_OP_BOOLEAN_LITERAL) ); -} // expr_is_constant -#endif - -typedef struct AstCalcData -{ - int isflt; - union - { - double f; - int64 i; - } value; -} AstCalcData; - -// returns 0 if this expression is non-constant, 1 if it is. -// calculation results land in (data). -static int calc_ast_const_expr(Context *ctx, void *_expr, AstCalcData *data) -{ - const MOJOSHADER_astNode *expr = (MOJOSHADER_astNode *) _expr; - const MOJOSHADER_astNodeType op = expr->ast.type; - - ctx->sourcefile = expr->ast.filename; - ctx->sourceline = expr->ast.line; - - if (operator_is_unary(op)) - { - if (!calc_ast_const_expr(ctx, expr->unary.operand, data)) - return 0; - - if (data->isflt) - { - switch (op) - { - case MOJOSHADER_AST_OP_NEGATE: - data->value.f = -data->value.f; - return 1; - case MOJOSHADER_AST_OP_NOT: - data->value.f = !data->value.f; - return 1; - case MOJOSHADER_AST_OP_COMPLEMENT: - fail(ctx, "integer operation on floating point value"); - return 0; - case MOJOSHADER_AST_OP_CAST: - // !!! FIXME: this should work, but it's complicated. - assert(0 && "write me"); - return 0; - default: break; - } // switch - } // if - - else // integer version - { - switch (op) - { - case MOJOSHADER_AST_OP_NEGATE: - data->value.i = -data->value.i; - return 1; - case MOJOSHADER_AST_OP_NOT: - data->value.i = !data->value.i; - return 1; - case MOJOSHADER_AST_OP_COMPLEMENT: - data->value.i = ~data->value.i; - return 1; - case MOJOSHADER_AST_OP_CAST: - // !!! FIXME: this should work, but it's complicated. - assert(0 && "write me"); - return 0; - default: break; - } // switch - } // else - assert(0 && "unhandled operation?"); - return 0; - } // if - - else if (operator_is_binary(op)) - { - AstCalcData subdata2; - if ( (!calc_ast_const_expr(ctx, expr->binary.left, data)) || - (!calc_ast_const_expr(ctx, expr->binary.right, &subdata2)) ) - return 0; - - // upgrade to float if either operand is float. - if ((data->isflt) || (subdata2.isflt)) - { - if (!data->isflt) data->value.f = (double) data->value.i; - if (!subdata2.isflt) subdata2.value.f = (double) subdata2.value.i; - data->isflt = subdata2.isflt = 1; - } // if - - switch (op) - { - // gcc doesn't handle commas here, either (fails to parse!). - case MOJOSHADER_AST_OP_COMMA: - case MOJOSHADER_AST_OP_ASSIGN: - case MOJOSHADER_AST_OP_MULASSIGN: - case MOJOSHADER_AST_OP_DIVASSIGN: - case MOJOSHADER_AST_OP_MODASSIGN: - case MOJOSHADER_AST_OP_ADDASSIGN: - case MOJOSHADER_AST_OP_SUBASSIGN: - case MOJOSHADER_AST_OP_LSHIFTASSIGN: - case MOJOSHADER_AST_OP_RSHIFTASSIGN: - case MOJOSHADER_AST_OP_ANDASSIGN: - case MOJOSHADER_AST_OP_XORASSIGN: - case MOJOSHADER_AST_OP_ORASSIGN: - return 0; // assignment is non-constant. - default: break; - } // switch - - if (data->isflt) - { - switch (op) - { - case MOJOSHADER_AST_OP_MULTIPLY: - data->value.f *= subdata2.value.f; - return 1; - case MOJOSHADER_AST_OP_DIVIDE: - data->value.f /= subdata2.value.f; - return 1; - case MOJOSHADER_AST_OP_ADD: - data->value.f += subdata2.value.f; - return 1; - case MOJOSHADER_AST_OP_SUBTRACT: - data->value.f -= subdata2.value.f; - return 1; - case MOJOSHADER_AST_OP_LESSTHAN: - data->isflt = 0; - data->value.i = data->value.f < subdata2.value.f; - return 1; - case MOJOSHADER_AST_OP_GREATERTHAN: - data->isflt = 0; - data->value.i = data->value.f > subdata2.value.f; - return 1; - case MOJOSHADER_AST_OP_LESSTHANOREQUAL: - data->isflt = 0; - data->value.i = data->value.f <= subdata2.value.f; - return 1; - case MOJOSHADER_AST_OP_GREATERTHANOREQUAL: - data->isflt = 0; - data->value.i = data->value.f >= subdata2.value.f; - return 1; - case MOJOSHADER_AST_OP_EQUAL: - data->isflt = 0; - data->value.i = data->value.f == subdata2.value.f; - return 1; - case MOJOSHADER_AST_OP_NOTEQUAL: - data->isflt = 0; - data->value.i = data->value.f != subdata2.value.f; - return 1; - case MOJOSHADER_AST_OP_LOGICALAND: - data->isflt = 0; - data->value.i = data->value.f && subdata2.value.f; - return 1; - case MOJOSHADER_AST_OP_LOGICALOR: - data->isflt = 0; - data->value.i = data->value.f || subdata2.value.f; - return 1; - - case MOJOSHADER_AST_OP_LSHIFT: - case MOJOSHADER_AST_OP_RSHIFT: - case MOJOSHADER_AST_OP_MODULO: - case MOJOSHADER_AST_OP_BINARYAND: - case MOJOSHADER_AST_OP_BINARYXOR: - case MOJOSHADER_AST_OP_BINARYOR: - fail(ctx, "integer operation on floating point value"); - return 0; - default: break; - } // switch - } // if - - else // integer version. - { - switch (op) - { - case MOJOSHADER_AST_OP_MULTIPLY: - data->value.i *= subdata2.value.i; - return 1; - case MOJOSHADER_AST_OP_DIVIDE: - data->value.i /= subdata2.value.i; - return 1; - case MOJOSHADER_AST_OP_ADD: - data->value.i += subdata2.value.i; - return 1; - case MOJOSHADER_AST_OP_SUBTRACT: - data->value.i -= subdata2.value.i; - return 1; - case MOJOSHADER_AST_OP_LESSTHAN: - data->value.i = data->value.i < subdata2.value.i; - return 1; - case MOJOSHADER_AST_OP_GREATERTHAN: - data->value.i = data->value.i > subdata2.value.i; - return 1; - case MOJOSHADER_AST_OP_LESSTHANOREQUAL: - data->value.i = data->value.i <= subdata2.value.i; - return 1; - case MOJOSHADER_AST_OP_GREATERTHANOREQUAL: - data->value.i = data->value.i >= subdata2.value.i; - return 1; - case MOJOSHADER_AST_OP_EQUAL: - data->value.i = data->value.i == subdata2.value.i; - return 1; - case MOJOSHADER_AST_OP_NOTEQUAL: - data->value.i = data->value.i != subdata2.value.i; - return 1; - case MOJOSHADER_AST_OP_LOGICALAND: - data->value.i = data->value.i && subdata2.value.i; - return 1; - case MOJOSHADER_AST_OP_LOGICALOR: - data->value.i = data->value.i || subdata2.value.i; - return 1; - case MOJOSHADER_AST_OP_LSHIFT: - data->value.i = data->value.i << subdata2.value.i; - return 1; - case MOJOSHADER_AST_OP_RSHIFT: - data->value.i = data->value.i >> subdata2.value.i; - return 1; - case MOJOSHADER_AST_OP_MODULO: - data->value.i = data->value.i % subdata2.value.i; - return 1; - case MOJOSHADER_AST_OP_BINARYAND: - data->value.i = data->value.i & subdata2.value.i; - return 1; - case MOJOSHADER_AST_OP_BINARYXOR: - data->value.i = data->value.i ^ subdata2.value.i; - return 1; - case MOJOSHADER_AST_OP_BINARYOR: - data->value.i = data->value.i | subdata2.value.i; - return 1; - default: break; - } // switch - } // else - - assert(0 && "unhandled operation?"); - return 0; - } // else if - - else if (operator_is_ternary(op)) - { - AstCalcData subdata2; - AstCalcData subdata3; - - assert(op == MOJOSHADER_AST_OP_CONDITIONAL); // only one we have. - - if ( (!calc_ast_const_expr(ctx, expr->ternary.left, data)) || - (!calc_ast_const_expr(ctx, expr->ternary.center, &subdata2)) || - (!calc_ast_const_expr(ctx, expr->ternary.right, &subdata3)) ) - return 0; - - // first operand should be bool (for the one ternary operator we have). - if (data->isflt) - { - data->isflt = 0; - data->value.i = (int64) subdata3.value.f; - } // if - - // upgrade to float if either operand is float. - if ((subdata2.isflt) || (subdata3.isflt)) - { - if (!subdata2.isflt) subdata2.value.f = (double) subdata2.value.i; - if (!subdata3.isflt) subdata3.value.f = (double) subdata3.value.i; - subdata2.isflt = subdata3.isflt = 1; - } // if - - data->isflt = subdata2.isflt; - if (data->isflt) - data->value.f = data->value.i ? subdata2.value.f : subdata3.value.f; - else - data->value.i = data->value.i ? subdata2.value.i : subdata3.value.i; - return 1; - } // else if - - else // not an operator? See if this is a literal value. - { - switch (op) - { - case MOJOSHADER_AST_OP_INT_LITERAL: - data->isflt = 0; - data->value.i = expr->intliteral.value; - return 1; - - case MOJOSHADER_AST_OP_FLOAT_LITERAL: - data->isflt = 1; - data->value.f = expr->floatliteral.value; - return 1; - - case MOJOSHADER_AST_OP_BOOLEAN_LITERAL: - data->isflt = 0; - data->value.i = expr->boolliteral.value ? 1 : 0; - return 1; - - default: break; - } // switch - } // switch - - return 0; // not constant, or unhandled. -} // calc_ast_const_expr - - -static const MOJOSHADER_astDataType *reduce_datatype(Context *ctx, const MOJOSHADER_astDataType *dt) -{ - const MOJOSHADER_astDataType *retval = dt; - while (retval && retval->type == MOJOSHADER_AST_DATATYPE_USER) - { - // !!! FIXME: Ugh, const removal. - MOJOSHADER_astDataTypeUser *user = (MOJOSHADER_astDataTypeUser *) &retval->user; - if (user->details->type == MOJOSHADER_AST_DATATYPE_NONE) - { - // Take this opportunity to fix up some usertype stubs that were - // left over from the parse phase. You HAVE to catch these in the - // right scope, so be aggressive about calling reduce_datatype() - // as soon as things come into view! - user->details = get_usertype(ctx, user->name); - assert(user->details != NULL); - } // if - - retval = user->details; - } // while - - return retval; -} // reduce_datatype - - -static inline const MOJOSHADER_astDataType *sanitize_datatype(Context *ctx, const MOJOSHADER_astDataType *dt) -{ - reduce_datatype(ctx, dt); - return dt; -} // sanitize_datatype - - -static const MOJOSHADER_astDataType *build_function_datatype(Context *ctx, - const MOJOSHADER_astDataType *rettype, - const int paramcount, - const MOJOSHADER_astDataType **params, - const int intrinsic) -{ - if ( ((paramcount > 0) && (params == NULL)) || - ((paramcount == 0) && (params != NULL)) ) - return NULL; - - // !!! FIXME: this is hacky. - const MOJOSHADER_astDataType **dtparams; - void *ptr = Malloc(ctx, sizeof (*params) * paramcount); - if (ptr == NULL) - return NULL; - if (!buffer_append(ctx->garbage, &ptr, sizeof (ptr))) - { - Free(ctx, ptr); - return NULL; - } // if - dtparams = (const MOJOSHADER_astDataType **) ptr; - memcpy(dtparams, params, sizeof (*params) * paramcount); - - ptr = Malloc(ctx, sizeof (MOJOSHADER_astDataType)); - if (ptr == NULL) - return NULL; - if (!buffer_append(ctx->garbage, &ptr, sizeof (ptr))) - { - Free(ctx, ptr); - return NULL; - } // if - - MOJOSHADER_astDataType *dt = (MOJOSHADER_astDataType *) ptr; - dt->type = MOJOSHADER_AST_DATATYPE_FUNCTION; - dt->function.retval = rettype; - dt->function.params = dtparams; - dt->function.num_params = paramcount; - dt->function.intrinsic = intrinsic; - return dt; -} // build_function_datatype - - -static const MOJOSHADER_astDataType *build_datatype(Context *ctx, - const int isconst, - const MOJOSHADER_astDataType *dt, - MOJOSHADER_astScalarOrArray *soa) -{ - MOJOSHADER_astDataType *retval = NULL; - - assert( (soa->isarray && soa->dimension) || - (!soa->isarray && !soa->dimension) ); - - sanitize_datatype(ctx, dt); - - // see if we can just reuse the exist datatype. - if (!soa->isarray) - { - const int c1 = (dt->type & MOJOSHADER_AST_DATATYPE_CONST) != 0; - const int c2 = (isconst != 0); - if (c1 == c2) - return dt; // reuse existing datatype! - } // if - - retval = (MOJOSHADER_astDataType *) Malloc(ctx, sizeof (*retval)); - if (retval == NULL) - return NULL; - - // !!! FIXME: this is hacky. - if (!buffer_append(ctx->garbage, &retval, sizeof (retval))) - { - Free(ctx, retval); - return NULL; - } // if - - if (!soa->isarray) - { - assert(soa->dimension == NULL); - memcpy(retval, dt, sizeof (MOJOSHADER_astDataType)); - if (isconst) - retval->type = (MOJOSHADER_astDataTypeType)(retval->type | MOJOSHADER_AST_DATATYPE_CONST); - else - retval->type = (MOJOSHADER_astDataTypeType)(retval->type & ~MOJOSHADER_AST_DATATYPE_CONST); - return retval; - } // if - - retval->type = MOJOSHADER_AST_DATATYPE_ARRAY; - retval->array.base = dt; - if (soa->dimension == NULL) - { - retval->array.elements = -1; - return retval; - } // if - - // Run the expression to verify it's constant and produces a positive int. - AstCalcData data; - data.isflt = 0; - data.value.i = 0; - retval->array.elements = 16; // sane default for failure. - const int ok = calc_ast_const_expr(ctx, soa->dimension, &data); - - // reset error position. - ctx->sourcefile = soa->ast.filename; - ctx->sourceline = soa->ast.line; - - if (!ok) - fail(ctx, "array dimensions not constant"); - else if (data.isflt) - fail(ctx, "array dimensions not integer"); - else if (data.value.i < 0) - fail(ctx, "array dimensions negative"); - else - retval->array.elements = data.value.i; - - return retval; -} // build_datatype - - -static void require_numeric_datatype(Context *ctx, - const MOJOSHADER_astDataType *datatype) -{ - datatype = reduce_datatype(ctx, datatype); - if (datatype->type == MOJOSHADER_AST_DATATYPE_VECTOR) - datatype = reduce_datatype(ctx, datatype->vector.base); - else if (datatype->type == MOJOSHADER_AST_DATATYPE_MATRIX) - datatype = reduce_datatype(ctx, datatype->matrix.base); - - switch (datatype->type) - { - case MOJOSHADER_AST_DATATYPE_BOOL: - case MOJOSHADER_AST_DATATYPE_INT: - case MOJOSHADER_AST_DATATYPE_UINT: - case MOJOSHADER_AST_DATATYPE_HALF: - case MOJOSHADER_AST_DATATYPE_FLOAT: - case MOJOSHADER_AST_DATATYPE_DOUBLE: - return; - default: break; - } // switch - - fail(ctx, "Expected numeric type"); // !!! FIXME: fmt. - // !!! FIXME: replace AST node with an AST_OP_INT_LITERAL zero, keep going. -} // require_numeric_datatype - -static void require_integer_datatype(Context *ctx, - const MOJOSHADER_astDataType *datatype) -{ - datatype = reduce_datatype(ctx, datatype); - switch (datatype->type) - { - case MOJOSHADER_AST_DATATYPE_INT: - case MOJOSHADER_AST_DATATYPE_UINT: - return; - default: break; - } // switch - - fail(ctx, "Expected integer type"); // !!! FIXME: fmt. - // !!! FIXME: replace AST node with an AST_OP_INT_LITERAL zero, keep going. -} // require_integer_datatype - -static void require_boolean_datatype(Context *ctx, - const MOJOSHADER_astDataType *datatype) -{ - datatype = reduce_datatype(ctx, datatype); - switch (datatype->type) - { - case MOJOSHADER_AST_DATATYPE_BOOL: - case MOJOSHADER_AST_DATATYPE_INT: - case MOJOSHADER_AST_DATATYPE_UINT: - return; - default: break; - } // switch - - fail(ctx, "Expected boolean type"); // !!! FIXME: fmt. - // !!! FIXME: replace AST node with an AST_OP_BOOLEAN_LITERAL false, keep going. -} // require_numeric_datatype - - -static void require_array_datatype(Context *ctx, - const MOJOSHADER_astDataType *datatype) -{ - datatype = reduce_datatype(ctx, datatype); - if (datatype->type == MOJOSHADER_AST_DATATYPE_ARRAY) - return; - - fail(ctx, "expected array"); - // !!! FIXME: delete array dereference for further processing. -} // require_array_datatype - - -static void require_struct_datatype(Context *ctx, - const MOJOSHADER_astDataType *datatype) -{ - datatype = reduce_datatype(ctx, datatype); - if (datatype->type == MOJOSHADER_AST_DATATYPE_STRUCT) - return; - - fail(ctx, "expected struct"); - // !!! FIXME: delete struct dereference for further processing. -} // require_struct_datatype - - -static int require_function_datatype(Context *ctx, - const MOJOSHADER_astDataType *datatype) -{ - datatype = reduce_datatype(ctx, datatype); - if ((!datatype) || (datatype->type != MOJOSHADER_AST_DATATYPE_FUNCTION)) - { - fail(ctx, "expected function"); - return 0; - } // if - - return 1; -} // require_function_datatype - - -// Extract the individual element type from an array datatype. -static const MOJOSHADER_astDataType *array_element_datatype(Context *ctx, - const MOJOSHADER_astDataType *datatype) -{ - datatype = reduce_datatype(ctx, datatype); - assert(datatype->type == MOJOSHADER_AST_DATATYPE_ARRAY); - return datatype->array.base; -} // array_element_datatype - - -// This tests two datatypes to see if they are compatible, and adds cast -// operator nodes to the AST if the program was relying on implicit -// casts between then. Will fail() if the datatypes can't be coerced -// with a cast at all. (left) can be NULL to say that its datatype is -// set in stone (an lvalue, for example). No other NULLs are allowed. -// Returns final datatype used once implicit casting is complete. -// The datatypes must be pointers from the string cache. -static const MOJOSHADER_astDataType *add_type_coercion(Context *ctx, - MOJOSHADER_astExpression **left, - const MOJOSHADER_astDataType *_ldatatype, - MOJOSHADER_astExpression **right, - const MOJOSHADER_astDataType *_rdatatype) -{ - // !!! FIXME: this whole function is probably naive at best. - const MOJOSHADER_astDataType *ldatatype = reduce_datatype(ctx, _ldatatype); - const MOJOSHADER_astDataType *rdatatype = reduce_datatype(ctx, _rdatatype); - - if (ldatatype == rdatatype) - return ldatatype; // they already match, so we're done. - - struct { - const MOJOSHADER_astDataTypeType type; - const int bits; - const int is_unsigned; - const int floating; - } typeinf[] = { - { MOJOSHADER_AST_DATATYPE_BOOL, 1, 1, 0 }, - { MOJOSHADER_AST_DATATYPE_HALF, 16, 0, 1 }, - { MOJOSHADER_AST_DATATYPE_INT, 32, 0, 0 }, - { MOJOSHADER_AST_DATATYPE_UINT, 32, 1, 0 }, - { MOJOSHADER_AST_DATATYPE_FLOAT, 32, 0, 1 }, - { MOJOSHADER_AST_DATATYPE_DOUBLE, 64, 0, 1 }, - }; - - int lvector = 0; - int lmatrix = 0; - int l = STATICARRAYLEN(typeinf); - if (ldatatype != NULL) - { - MOJOSHADER_astDataTypeType type = ldatatype->type; - if (type == MOJOSHADER_AST_DATATYPE_VECTOR) - { - lvector = 1; - type = ldatatype->vector.base->type; - } // if - else if (type == MOJOSHADER_AST_DATATYPE_MATRIX) - { - lmatrix = 1; - type = ldatatype->matrix.base->type; - } // if - - for (l = 0; l < STATICARRAYLEN(typeinf); l++) - { - if (typeinf[l].type == type) - break; - } // for - } // if - - int rvector = 0; - int rmatrix = 0; - int r = STATICARRAYLEN(typeinf); - if (rdatatype != NULL) - { - MOJOSHADER_astDataTypeType type = rdatatype->type; - if (type == MOJOSHADER_AST_DATATYPE_VECTOR) - { - rvector = 1; - type = rdatatype->vector.base->type; - } // if - else if (type == MOJOSHADER_AST_DATATYPE_MATRIX) - { - rmatrix = 1; - type = rdatatype->matrix.base->type; - } // if - - for (r = 0; r < STATICARRAYLEN(typeinf); r++) - { - if (typeinf[r].type == type) - break; - } // for - } // if - - enum { CHOOSE_NEITHER, CHOOSE_LEFT, CHOOSE_RIGHT } choice = CHOOSE_NEITHER; - if ((l < STATICARRAYLEN(typeinf)) && (r < STATICARRAYLEN(typeinf))) - { - if (left == NULL) - choice = CHOOSE_LEFT; // we need to force to the lvalue. - else if (lmatrix && !rmatrix) - choice = CHOOSE_LEFT; - else if (!lmatrix && rmatrix) - choice = CHOOSE_RIGHT; - else if (lvector && !rvector) - choice = CHOOSE_LEFT; - else if (!lvector && rvector) - choice = CHOOSE_RIGHT; - else if (typeinf[l].bits > typeinf[r].bits) - choice = CHOOSE_LEFT; - else if (typeinf[l].bits < typeinf[r].bits) - choice = CHOOSE_RIGHT; - else if (typeinf[l].floating && !typeinf[r].floating) - choice = CHOOSE_LEFT; - else if (!typeinf[l].floating && typeinf[r].floating) - choice = CHOOSE_RIGHT; - else if (typeinf[l].is_unsigned && !typeinf[r].is_unsigned) - choice = CHOOSE_LEFT; - else if (!typeinf[l].is_unsigned && typeinf[r].is_unsigned) - choice = CHOOSE_RIGHT; - } // if - - if (choice == CHOOSE_LEFT) - { - *right = new_cast_expr(ctx, _ldatatype, *right); - return _ldatatype; - } // if - else if (choice == CHOOSE_RIGHT) - { - *left = new_cast_expr(ctx, _rdatatype, *left); - return _rdatatype; - } // else if - - assert(choice == CHOOSE_NEITHER); - fail(ctx, "incompatible data types"); - // Ditch original (*right), force a literal value that matches - // ldatatype, so further processing is normalized. - // !!! FIXME: force (right) to match (left). - delete_expr(ctx, *right); - *right = new_cast_expr(ctx, _ldatatype, new_literal_int_expr(ctx, 0)); - return ldatatype; -} // add_type_coercion - -static int is_swizzle_str(const char *str, const int veclen) -{ - int i; - int is_xyzw = 0; - int is_rgba = 0; - - assert(*str != '\0'); // can this actually happen? - - for (i = 0; i < veclen; i++, str++) - { - const char ch = *str; - if (ch == '\0') - break; - else if ((ch == 'x') || (ch == 'y') || (ch == 'z') || (ch == 'w')) - is_xyzw = 1; - else if ((ch == 'r') || (ch == 'g') || (ch == 'b') || (ch == 'a')) - is_rgba = 1; - } // for - - if (*str != '\0') // must be end of string here. - return 0; // not a swizzle. - return ((is_rgba + is_xyzw) == 1); // can only be one or the other. -} // is_swizzle_str - -static int datatype_size(const MOJOSHADER_astDataType *dt) -{ - switch (dt->type) - { - case MOJOSHADER_AST_DATATYPE_BOOL: return 1; - case MOJOSHADER_AST_DATATYPE_INT: return 4; - case MOJOSHADER_AST_DATATYPE_UINT: return 4; - case MOJOSHADER_AST_DATATYPE_FLOAT: return 4; - case MOJOSHADER_AST_DATATYPE_FLOAT_SNORM: return 4; - case MOJOSHADER_AST_DATATYPE_FLOAT_UNORM: return 4; - case MOJOSHADER_AST_DATATYPE_HALF: return 2; - case MOJOSHADER_AST_DATATYPE_DOUBLE: return 8; - return 1; - default: - assert(0 && "Maybe should have used reduce_datatype()?"); - return 0; - } // switch -} // datatype_size - -static inline int is_scalar_datatype(const MOJOSHADER_astDataType *dt) -{ - switch (dt->type) - { - case MOJOSHADER_AST_DATATYPE_BOOL: - case MOJOSHADER_AST_DATATYPE_INT: - case MOJOSHADER_AST_DATATYPE_UINT: - case MOJOSHADER_AST_DATATYPE_FLOAT: - case MOJOSHADER_AST_DATATYPE_FLOAT_SNORM: - case MOJOSHADER_AST_DATATYPE_FLOAT_UNORM: - case MOJOSHADER_AST_DATATYPE_HALF: - case MOJOSHADER_AST_DATATYPE_DOUBLE: - return 1; - default: - return 0; - } // switch -} // is_scalar_datatype - -static inline int is_float_datatype(const MOJOSHADER_astDataType *dt) -{ - switch (dt->type) - { - case MOJOSHADER_AST_DATATYPE_FLOAT: return 1; - case MOJOSHADER_AST_DATATYPE_FLOAT_SNORM: return 1; - case MOJOSHADER_AST_DATATYPE_FLOAT_UNORM: return 1; - default: return 0; - } // switch -} // is_float_datatype - -static int datatype_elems(Context *ctx, const MOJOSHADER_astDataType *dt) -{ - dt = reduce_datatype(ctx, dt); - switch (dt->type) - { - case MOJOSHADER_AST_DATATYPE_VECTOR: - return dt->vector.elements; - case MOJOSHADER_AST_DATATYPE_MATRIX: - return dt->matrix.rows * dt->matrix.columns; - default: - return 1; - } // switch -} // datatype_elems - -static const MOJOSHADER_astDataType *datatype_base(Context *ctx, const MOJOSHADER_astDataType *dt) -{ - dt = reduce_datatype(ctx, dt); - if (dt == NULL) - return dt; - - switch (dt->type) - { - case MOJOSHADER_AST_DATATYPE_VECTOR: - dt = dt->vector.base; - break; - case MOJOSHADER_AST_DATATYPE_MATRIX: - dt = dt->matrix.base; - break; - case MOJOSHADER_AST_DATATYPE_BUFFER: - dt = dt->buffer.base; - break; - case MOJOSHADER_AST_DATATYPE_ARRAY: - dt = dt->array.base; - break; - default: break; - } // switch - - return dt; -} // datatype_base - -typedef enum -{ - DT_MATCH_INCOMPATIBLE, // flatly incompatible - DT_MATCH_COMPATIBLE_DOWNCAST, // would have to lose precision - DT_MATCH_COMPATIBLE_UPCAST, // would have to gain precision - DT_MATCH_COMPATIBLE, // can cast to without serious change. - DT_MATCH_PERFECT // identical datatype. -} DatatypeMatch; - -static DatatypeMatch compatible_arg_datatype(Context *ctx, - const MOJOSHADER_astDataType *arg, - const MOJOSHADER_astDataType *param) -{ - // The matching rules for HLSL function overloading, as far as I can - // tell from experimenting with Microsoft's compiler, seem to be this: - // - // - All parameters of a function must match what the caller specified - // after possible type promotion via the following rules. - // - If the number of arguments and the number of parameters don't match, - // that overload is immediately rejected. - // - Each overloaded function is given a score that is the sum of the - // "worth" of each parameter vs the caller's arguments - // (see DatatypeMatch). The higher the score, the more favorable this - // function overload would be. - // - If there is a tie for highest score between two or more function - // overloads, we declare that function call to be ambiguous and fail(). - // - Scalars can be promoted to vectors to make a parameter match. - // - Scalars can promote to other scalars (short to int, etc). - // - Datatypes can downcast, but should generate a warning. - // (calling void fn(float x); as fn((double)1.0) should warn). - // - Vectors may NOT be extend (a float2 can't implicity extend to a - // float4). - // - Vectors with the same elements can promote (a half2 can become - // a float2). Downcasting between vectors with the same number of - // elements is allowed. - // - A perfect match of all params will be favored over any functions - // that only match if type promotion is applied (given a perfect match - // of all parameters, we'll stop looking for other matches). - - if (datatypes_match(arg, param)) - return DT_MATCH_PERFECT; // that was easy. - - arg = reduce_datatype(ctx, arg); - param = reduce_datatype(ctx, param); - - int do_base_test = 0; - - if (is_scalar_datatype(arg)) - do_base_test = 1; // we let these all go through for now. - - else if (arg->type == param->type) - { - if (arg->type == MOJOSHADER_AST_DATATYPE_VECTOR) - do_base_test = (arg->vector.elements == param->vector.elements); - else if (arg->type == MOJOSHADER_AST_DATATYPE_MATRIX) - { - do_base_test = - ((arg->matrix.rows == param->matrix.rows) && - (arg->matrix.columns == param->matrix.columns)); - } // if - } // if - - if (do_base_test) - { - arg = datatype_base(ctx, arg); - param = datatype_base(ctx, param); - - const int argsize = datatype_size(arg); - const int paramsize = datatype_size(param); - const int argfloat = is_float_datatype(arg); - const int paramfloat = is_float_datatype(param); - - if (argfloat && !paramfloat) - return DT_MATCH_COMPATIBLE_DOWNCAST; // always loss of precision. - else if (argfloat && !paramfloat) - { - if (argsize < paramsize) - return DT_MATCH_COMPATIBLE_UPCAST; - else - return DT_MATCH_COMPATIBLE_DOWNCAST; // loss of precision. - } // else if - else if (argsize == paramsize) - return DT_MATCH_COMPATIBLE; - else if (argsize < paramsize) - return DT_MATCH_COMPATIBLE_UPCAST; - else /* if (argsize > paramsize) */ - return DT_MATCH_COMPATIBLE_DOWNCAST; - } // if - - return DT_MATCH_INCOMPATIBLE; -} // compatible_arg_datatype - - -static const MOJOSHADER_astDataType *type_check_ast(Context *ctx, void *_ast); - -// !!! FIXME: this function sucks. -static const MOJOSHADER_astDataType *match_func_to_call(Context *ctx, - MOJOSHADER_astExpressionCallFunction *ast) -{ - SymbolScope *best = NULL; // best choice we find. - int best_score = 0; - MOJOSHADER_astExpressionIdentifier *ident = ast->identifier; - const char *sym = ident->identifier; - const void *value = NULL; - void *iter = NULL; - - int argcount = 0; - MOJOSHADER_astArguments *args = ast->args; - while (args != NULL) - { - argcount++; - type_check_ast(ctx, args->argument); - args = args->next; - } // while; - - // we do some tapdancing to handle function overloading here. - int match = 0; - while (hash_iter(ctx->variables.hash, sym, &value, &iter)) - { - SymbolScope *item = (SymbolScope *) value; - const MOJOSHADER_astDataType *dt = item->datatype; - dt = reduce_datatype(ctx, dt); - // there's a locally-scoped symbol with this name? It takes precedence. - if (dt->type != MOJOSHADER_AST_DATATYPE_FUNCTION) - return dt; - - const MOJOSHADER_astDataTypeFunction *dtfn = (MOJOSHADER_astDataTypeFunction *) dt; - const int perfect = argcount * ((int) DT_MATCH_PERFECT); - int score = 0; - - if (argcount == dtfn->num_params) // !!! FIXME: default args. - { - args = ast->args; - int i; - for (i = 0; i < argcount; i++) - { - assert(args != NULL); - dt = args->argument->datatype; - args = args->next; - const DatatypeMatch compatible = compatible_arg_datatype(ctx, dt, dtfn->params[i]); - if (compatible == DT_MATCH_INCOMPATIBLE) - { - args = NULL; - score = 0; - break; - } // if - - score += (int) compatible; - } // for - - if (args != NULL) - score = 0; // too many arguments supplied. No match. - } // else - - if (score == 0) // incompatible. - continue; - - else if (score == perfect) // perfection! stop looking! - { - match = 1; // ignore all other compatible matches. - best = item; - break; - } // if - - else if (score >= best_score) // compatible, but not perfect, match. - { - if (score == best_score) - { - match++; - // !!! FIXME: list each possible function in a fail(), - // !!! FIXME: but you can't actually fail() here, since - // !!! FIXME: this may cease to be ambiguous if we get - // !!! FIXME: a better match on a later overload. - } // if - - else if (score > best_score) - { - match = 1; // reset the ambiguousness count. - best = item; - best_score = score; - } // if - } // else if - } // while - - if (match > 1) - { - assert(best != NULL); - failf(ctx, "Ambiguous function call to '%s'", sym); - } // if - - if (best == NULL) - { - assert(match == 0); - assert(best_score == 0); - // !!! FIXME: ident->datatype = ? - failf(ctx, "No matching function named '%s'", sym); - } // if - else - { - ident->datatype = reduce_datatype(ctx, best->datatype); - ident->index = best->index; - } // else - - return ident->datatype; -} // match_func_to_call - - -static const MOJOSHADER_astDataType *vectype_from_base(Context *ctx, - const MOJOSHADER_astDataType *base, - const int len) -{ - assert(len > 0); - assert(len <= 4); - - if (len == 1) // return "float" and not "float1" - return base; - - const char *typestr = NULL; - switch (base->type) - { - case MOJOSHADER_AST_DATATYPE_BOOL: typestr = "bool"; break; - case MOJOSHADER_AST_DATATYPE_INT: typestr = "int"; break; - case MOJOSHADER_AST_DATATYPE_UINT: typestr = "uint"; break; - case MOJOSHADER_AST_DATATYPE_HALF: typestr = "half"; break; - case MOJOSHADER_AST_DATATYPE_FLOAT: typestr = "float"; break; - case MOJOSHADER_AST_DATATYPE_DOUBLE: typestr = "double"; break; - default: assert(0 && "This shouldn't happen"); break; - } // switch - - char buf[32]; - snprintf(buf, sizeof (buf), "%s%d", typestr, len); - const MOJOSHADER_astDataType *datatype = get_usertype(ctx, buf); - assert(datatype != NULL); - return datatype; -} // vectype_from_base - - -// Go through the AST and make sure all datatypes check out okay. For datatypes -// that are compatible but are relying on an implicit cast, we add explicit -// casts to the AST here, so further processing doesn't have to worry about -// type coercion. -// For things that are incompatible, we generate errors and -// then replace them with reasonable defaults so further processing can -// continue (but code generation will be skipped due to errors). -// This means further processing can assume the AST is sane and not have to -// spend effort verifying it again. -// This stage will also set every AST node's datatype field, if it is -// meaningful to do so. This will allow conversion to IR to know what -// type/size a given node is. -static const MOJOSHADER_astDataType *type_check_ast(Context *ctx, void *_ast) -{ - MOJOSHADER_astNode *ast = (MOJOSHADER_astNode *) _ast; - const MOJOSHADER_astDataType *datatype = NULL; - const MOJOSHADER_astDataType *datatype2 = NULL; - const MOJOSHADER_astDataType *datatype3 = NULL; - - if ((!ast) || (ctx->out_of_memory)) - return NULL; - - // upkeep so we report correct error locations... - ctx->sourcefile = ast->ast.filename; - ctx->sourceline = ast->ast.line; - - switch (ast->ast.type) - { - case MOJOSHADER_AST_OP_POSTINCREMENT: - case MOJOSHADER_AST_OP_POSTDECREMENT: - case MOJOSHADER_AST_OP_PREINCREMENT: - case MOJOSHADER_AST_OP_PREDECREMENT: - case MOJOSHADER_AST_OP_COMPLEMENT: - case MOJOSHADER_AST_OP_NEGATE: - // !!! FIXME: must be lvalue. - // !!! FIXME: bools must type-promote to ...int? - // !!! FIXME: complement must not be float (...right?) - datatype = type_check_ast(ctx, ast->unary.operand); - require_numeric_datatype(ctx, datatype); - ast->unary.datatype = datatype; - return datatype; - - case MOJOSHADER_AST_OP_NOT: - datatype = type_check_ast(ctx, ast->unary.operand); - require_boolean_datatype(ctx, datatype); - // !!! FIXME: coerce to bool here. - ast->unary.datatype = &ctx->dt_bool; - return datatype; - - case MOJOSHADER_AST_OP_DEREF_ARRAY: - datatype = type_check_ast(ctx, ast->binary.left); - datatype2 = type_check_ast(ctx, ast->binary.right); - require_integer_datatype(ctx, datatype2); - add_type_coercion(ctx, NULL, &ctx->dt_int, &ast->binary.right, datatype2); - - datatype = reduce_datatype(ctx, datatype); - if (datatype->type == MOJOSHADER_AST_DATATYPE_VECTOR) - { - // !!! FIXME: if constant int, fail if not 0 >= value <= vecsize. - ast->binary.datatype = datatype->vector.base; - } // if - else if (datatype->type == MOJOSHADER_AST_DATATYPE_MATRIX) - { - // !!! FIXME: if constant int, fail if not 0 >= value <= rowsize (colsize?). - ast->binary.datatype = vectype_from_base(ctx, datatype->matrix.base, datatype->matrix.columns); // !!! FIXME: rows? - } - else - { - require_array_datatype(ctx, datatype); - ast->binary.datatype = array_element_datatype(ctx, datatype); - } // else - - return ast->binary.datatype; - - case MOJOSHADER_AST_OP_DEREF_STRUCT: - { - const char *member = ast->derefstruct.member; - datatype = type_check_ast(ctx, ast->derefstruct.identifier); - const MOJOSHADER_astDataType *reduced = reduce_datatype(ctx, datatype); - - // Is this a swizzle and not a struct deref? - if (reduced->type == MOJOSHADER_AST_DATATYPE_VECTOR) - { - const int veclen = reduced->vector.elements; - ast->derefstruct.isswizzle = 1; - if (!is_swizzle_str(member, veclen)) - { - fail(ctx, "invalid swizzle on vector"); - // force this to be sane for further processing. - const char *sane_swiz = stringcache(ctx->strcache, "xyzw"); - member = ast->derefstruct.member = sane_swiz; - } // if - - const int swizlen = (int) strlen(member); - if (swizlen != veclen) - datatype = vectype_from_base(ctx, reduced->vector.base, swizlen); - - ast->derefstruct.datatype = datatype; - return ast->derefstruct.datatype; - } // if - - // maybe this is an actual struct? - // !!! FIXME: replace with an int or something if not. - require_struct_datatype(ctx, reduced); - - // map member to datatype - assert(ast->derefstruct.datatype == NULL); - const MOJOSHADER_astDataTypeStructMember *mbrs = reduced->structure.members; - int i; - for (i = 0; i < reduced->structure.member_count; i++) - { - if (strcmp(mbrs[i].identifier, member) == 0) - { - ast->derefstruct.datatype = mbrs[i].datatype; - ast->derefstruct.member_index = i; - break; - } // if - } // for - - if (ast->derefstruct.datatype == NULL) - { - // !!! FIXME: replace with an int or something. - failf(ctx, "Struct has no member named '%s'", member); - } // if - - return ast->derefstruct.datatype; - } // case - - case MOJOSHADER_AST_OP_COMMA: - // evaluate and throw away left, return right. - type_check_ast(ctx, ast->binary.left); - ast->binary.datatype = type_check_ast(ctx, ast->binary.right); - return ast->binary.datatype; - - case MOJOSHADER_AST_OP_MULTIPLY: - case MOJOSHADER_AST_OP_DIVIDE: - case MOJOSHADER_AST_OP_ADD: - case MOJOSHADER_AST_OP_SUBTRACT: - datatype = type_check_ast(ctx, ast->binary.left); - datatype2 = type_check_ast(ctx, ast->binary.right); - require_numeric_datatype(ctx, datatype); - require_numeric_datatype(ctx, datatype2); - ast->binary.datatype = add_type_coercion(ctx, &ast->binary.left, - datatype, &ast->binary.right, datatype2); - return ast->binary.datatype; - - case MOJOSHADER_AST_OP_LSHIFT: - case MOJOSHADER_AST_OP_RSHIFT: - case MOJOSHADER_AST_OP_MODULO: - datatype = type_check_ast(ctx, ast->binary.left); - datatype2 = type_check_ast(ctx, ast->binary.right); - require_integer_datatype(ctx, datatype); - require_integer_datatype(ctx, datatype2); - ast->binary.datatype = add_type_coercion(ctx, &ast->binary.left, - datatype, &ast->binary.right, datatype2); - return ast->binary.datatype; - - case MOJOSHADER_AST_OP_LESSTHAN: - case MOJOSHADER_AST_OP_GREATERTHAN: - case MOJOSHADER_AST_OP_LESSTHANOREQUAL: - case MOJOSHADER_AST_OP_GREATERTHANOREQUAL: - case MOJOSHADER_AST_OP_NOTEQUAL: - case MOJOSHADER_AST_OP_EQUAL: - datatype = type_check_ast(ctx, ast->binary.left); - datatype2 = type_check_ast(ctx, ast->binary.right); - add_type_coercion(ctx, &ast->binary.left, datatype, - &ast->binary.right, datatype2); - ast->binary.datatype = &ctx->dt_bool; - return ast->binary.datatype; - - case MOJOSHADER_AST_OP_BINARYAND: - case MOJOSHADER_AST_OP_BINARYXOR: - case MOJOSHADER_AST_OP_BINARYOR: - datatype = type_check_ast(ctx, ast->binary.left); - datatype2 = type_check_ast(ctx, ast->binary.right); - require_integer_datatype(ctx, datatype); - require_integer_datatype(ctx, datatype2); - ast->binary.datatype = add_type_coercion(ctx, &ast->binary.left, - datatype, &ast->binary.right, datatype2); - return ast->binary.datatype; - - case MOJOSHADER_AST_OP_LOGICALAND: - case MOJOSHADER_AST_OP_LOGICALOR: - datatype = type_check_ast(ctx, ast->binary.left); - datatype2 = type_check_ast(ctx, ast->binary.right); - require_boolean_datatype(ctx, datatype); - require_boolean_datatype(ctx, datatype2); - // !!! FIXME: coerce each to bool here, separately. - add_type_coercion(ctx, &ast->binary.left, datatype, - &ast->binary.right, datatype2); - ast->binary.datatype = &ctx->dt_bool; - - case MOJOSHADER_AST_OP_ASSIGN: - case MOJOSHADER_AST_OP_MULASSIGN: - case MOJOSHADER_AST_OP_DIVASSIGN: - case MOJOSHADER_AST_OP_MODASSIGN: - case MOJOSHADER_AST_OP_ADDASSIGN: - case MOJOSHADER_AST_OP_SUBASSIGN: - case MOJOSHADER_AST_OP_LSHIFTASSIGN: - case MOJOSHADER_AST_OP_RSHIFTASSIGN: - case MOJOSHADER_AST_OP_ANDASSIGN: - case MOJOSHADER_AST_OP_XORASSIGN: - case MOJOSHADER_AST_OP_ORASSIGN: - // !!! FIXME: verify binary.left is an lvalue, or fail()! - datatype = type_check_ast(ctx, ast->binary.left); - datatype2 = type_check_ast(ctx, ast->binary.right); - ast->binary.datatype = add_type_coercion(ctx, NULL, datatype, - &ast->binary.right, datatype2); - return ast->binary.datatype; - - case MOJOSHADER_AST_OP_CONDITIONAL: - datatype = type_check_ast(ctx, ast->ternary.left); - datatype2 = type_check_ast(ctx, ast->ternary.center); - datatype3 = type_check_ast(ctx, ast->ternary.right); - require_numeric_datatype(ctx, datatype); - ast->ternary.datatype = add_type_coercion(ctx, &ast->ternary.center, - datatype2, &ast->ternary.right, datatype3); - return ast->ternary.datatype; - - case MOJOSHADER_AST_OP_IDENTIFIER: - datatype = find_variable(ctx, ast->identifier.identifier, &ast->identifier.index); - if (datatype == NULL) - { - fail(ctx, "Unknown identifier"); - // !!! FIXME: replace with a sane default, move on. - datatype = &ctx->dt_int; - } // if - ast->identifier.datatype = datatype; - return ast->identifier.datatype; - - case MOJOSHADER_AST_OP_INT_LITERAL: - case MOJOSHADER_AST_OP_FLOAT_LITERAL: - case MOJOSHADER_AST_OP_STRING_LITERAL: - case MOJOSHADER_AST_OP_BOOLEAN_LITERAL: - assert(ast->expression.datatype != NULL); - return ast->expression.datatype; // already set up during parsing. - - case MOJOSHADER_AST_ARGUMENTS: - assert(0 && "Should be done by MOJOSHADER_AST_OP_CALLFUNC/CONSTRUCTOR"); - return NULL; - - case MOJOSHADER_AST_OP_CALLFUNC: - { - datatype = match_func_to_call(ctx, &ast->callfunc); - const MOJOSHADER_astDataType *reduced = reduce_datatype(ctx, datatype); - // !!! FIXME: replace AST node with an int if this isn't a func. - if (!require_function_datatype(ctx, reduced)) - { - ast->callfunc.datatype = &ctx->dt_int; - return ast->callfunc.datatype; - } // if - - MOJOSHADER_astArguments *arg = ast->callfunc.args; - int i; - for (i = 0; i < reduced->function.num_params; i++) - { - if (arg == NULL) // !!! FIXME: check for default parameters, fill them in. - { - fail(ctx, "Too few arguments"); - // !!! FIXME: replace AST here. - break; - } // if - datatype2 = arg->argument->datatype; // already type-checked. - add_type_coercion(ctx, NULL, reduced->function.params[i], - &arg->argument, datatype2); - arg = arg->next; - } // for - - assert(arg == NULL); // shouldn't have chosen func if too many args. - - ast->callfunc.datatype = reduced->function.retval; - return ast->callfunc.datatype; - } // case - - case MOJOSHADER_AST_OP_CONSTRUCTOR: - { - const MOJOSHADER_astDataType *reduced = reduce_datatype(ctx, ast->constructor.datatype); - const MOJOSHADER_astDataType *base_dt = reduced; - int num_params = 1; - - assert(reduced != NULL); - switch (reduced->type) - { - case MOJOSHADER_AST_DATATYPE_VECTOR: - num_params = reduced->vector.elements; - base_dt = reduced->vector.base; - break; - case MOJOSHADER_AST_DATATYPE_MATRIX: - num_params = reduced->matrix.rows * reduced->matrix.columns; - base_dt = reduced->matrix.base; - break; - - case MOJOSHADER_AST_DATATYPE_BOOL: - case MOJOSHADER_AST_DATATYPE_INT: - case MOJOSHADER_AST_DATATYPE_UINT: - case MOJOSHADER_AST_DATATYPE_FLOAT: - case MOJOSHADER_AST_DATATYPE_FLOAT_SNORM: - case MOJOSHADER_AST_DATATYPE_FLOAT_UNORM: - case MOJOSHADER_AST_DATATYPE_HALF: - case MOJOSHADER_AST_DATATYPE_DOUBLE: - case MOJOSHADER_AST_DATATYPE_STRING: - num_params = 1; - break; - - // !!! FIXME: can you construct a MOJOSHADER_AST_DATATYPE_STRUCT? - // !!! FIXME: can you construct a MOJOSHADER_AST_DATATYPE_ARRAY? - // !!! FIXME: can you construct a MOJOSHADER_AST_DATATYPE_BUFFER? - - default: - fail(ctx, "Invalid type for constructor"); - delete_arguments(ctx, ast->constructor.args); - ast->constructor.args = new_argument(ctx, new_literal_int_expr(ctx, 0)); - ast->constructor.datatype = &ctx->dt_int; - return ast->constructor.datatype; - } // switch - - assert(num_params > 0); - - MOJOSHADER_astArguments *arg = ast->constructor.args; - MOJOSHADER_astArguments *prev = NULL; - int i; - for (i = 0; i < num_params; i++) - { - if (arg == NULL) // !!! FIXME: check for default parameters. - { - fail(ctx, "Too few arguments"); - // !!! FIXME: replace AST here. - break; - } // if - datatype2 = type_check_ast(ctx, arg->argument); - - // "float4(float3(1,2,3),4)" is legal, so we need to see if - // we're a vector, and jump that number of parameters instead - // of doing type coercion. - reduced = reduce_datatype(ctx, datatype2); - if (reduced->type == MOJOSHADER_AST_DATATYPE_VECTOR) - { - // make sure things like float4(half3(1,2,3),1) convert that half3 to float3. - const int count = reduced->vector.elements; - datatype3 = vectype_from_base(ctx, base_dt, count); - add_type_coercion(ctx, NULL, datatype3, &arg->argument, datatype2); - i += count - 1; - } // else - else - { - add_type_coercion(ctx, NULL, base_dt, &arg->argument, datatype2); - } // else - prev = arg; - arg = arg->next; - } // for - - if (arg != NULL) - { - fail(ctx, "Too many arguments"); - // Process extra arguments then chop them out. - MOJOSHADER_astArguments *argi; - for (argi = arg; argi != NULL; argi = argi->next) - type_check_ast(ctx, argi->argument); - if (prev != NULL) - prev->next = NULL; - delete_arguments(ctx, arg); - } // if - - return ast->constructor.datatype; - } // case - - case MOJOSHADER_AST_OP_CAST: - datatype = sanitize_datatype(ctx, ast->cast.datatype); - datatype2 = type_check_ast(ctx, ast->cast.operand); - // you still need type coercion, since you could do a wrong cast, - // like "int x = (short) mychar;" - add_type_coercion(ctx, NULL, datatype, &ast->cast.operand, datatype2); - return datatype; - - case MOJOSHADER_AST_STATEMENT_BREAK: - if ((ctx->loop_count == 0) && (ctx->switch_count == 0)) - fail(ctx, "Break outside loop or switch"); - // !!! FIXME: warn if unreachable statements follow? - type_check_ast(ctx, ast->stmt.next); - return NULL; - - case MOJOSHADER_AST_STATEMENT_CONTINUE: - if (ctx->loop_count == 0) - fail(ctx, "Continue outside loop"); - // !!! FIXME: warn if unreachable statements follow? - type_check_ast(ctx, ast->stmt.next); - return NULL; - - case MOJOSHADER_AST_STATEMENT_DISCARD: - // !!! FIXME: warn if unreachable statements follow? - type_check_ast(ctx, ast->stmt.next); - return NULL; - - case MOJOSHADER_AST_STATEMENT_EMPTY: - type_check_ast(ctx, ast->stmt.next); - return NULL; - - case MOJOSHADER_AST_STATEMENT_EXPRESSION: - // !!! FIXME: warn about expressions without a side-effect here? - type_check_ast(ctx, ast->exprstmt.expr); // !!! FIXME: This is named badly... - type_check_ast(ctx, ast->exprstmt.next); - return NULL; - - case MOJOSHADER_AST_STATEMENT_IF: - push_scope(ctx); // new scope for "if ((int x = blah()) != 0)" - type_check_ast(ctx, ast->ifstmt.expr); - type_check_ast(ctx, ast->ifstmt.statement); - pop_scope(ctx); - type_check_ast(ctx, ast->ifstmt.next); - return NULL; - - case MOJOSHADER_AST_STATEMENT_TYPEDEF: - type_check_ast(ctx, ast->typedefstmt.type_info); - type_check_ast(ctx, ast->typedefstmt.next); - return NULL; - - case MOJOSHADER_AST_STATEMENT_SWITCH: - { - ctx->switch_count++; - MOJOSHADER_astSwitchCases *cases = ast->switchstmt.cases; - // !!! FIXME: expr must be POD (no structs, arrays, etc!). - datatype = type_check_ast(ctx, ast->switchstmt.expr); - while (cases) - { - // !!! FIXME: case must be POD (no structs, arrays, etc!). - datatype2 = type_check_ast(ctx, cases->expr); - add_type_coercion(ctx, NULL, datatype, - &cases->expr, datatype2); - type_check_ast(ctx, cases->statement); - cases = cases->next; - } // while - ctx->switch_count--; - type_check_ast(ctx, ast->switchstmt.next); - return NULL; - } // case - - case MOJOSHADER_AST_SWITCH_CASE: - assert(0 && "Should be done by MOJOSHADER_AST_STATEMENT_SWITCH."); - return NULL; - - case MOJOSHADER_AST_STATEMENT_STRUCT: - type_check_ast(ctx, ast->structstmt.struct_info); - type_check_ast(ctx, ast->structstmt.next); - return NULL; - - case MOJOSHADER_AST_STATEMENT_VARDECL: - type_check_ast(ctx, ast->vardeclstmt.declaration); - type_check_ast(ctx, ast->vardeclstmt.next); - return NULL; - - case MOJOSHADER_AST_STATEMENT_BLOCK: - push_scope(ctx); // new vars declared here live until '}'. - type_check_ast(ctx, ast->blockstmt.statements); - pop_scope(ctx); - type_check_ast(ctx, ast->blockstmt.next); - return NULL; - - case MOJOSHADER_AST_STATEMENT_FOR: - ctx->loop_count++; - push_scope(ctx); // new scope for "for (int x = 0; ...)" - type_check_ast(ctx, ast->forstmt.var_decl); - type_check_ast(ctx, ast->forstmt.initializer); - type_check_ast(ctx, ast->forstmt.looptest); - type_check_ast(ctx, ast->forstmt.counter); - type_check_ast(ctx, ast->forstmt.statement); - pop_scope(ctx); - ctx->loop_count--; - type_check_ast(ctx, ast->forstmt.next); - return NULL; - - case MOJOSHADER_AST_STATEMENT_DO: - ctx->loop_count++; - // !!! FIXME: should there be a push_scope() here? - type_check_ast(ctx, ast->dostmt.statement); - push_scope(ctx); // new scope for "while ((int x = blah()) != 0)" - type_check_ast(ctx, ast->dostmt.expr); - pop_scope(ctx); - ctx->loop_count--; - type_check_ast(ctx, ast->dostmt.next); - return NULL; - - case MOJOSHADER_AST_STATEMENT_WHILE: - ctx->loop_count++; - push_scope(ctx); // new scope for "while ((int x = blah()) != 0)" - type_check_ast(ctx, ast->whilestmt.expr); - type_check_ast(ctx, ast->whilestmt.statement); - pop_scope(ctx); - ctx->loop_count--; - type_check_ast(ctx, ast->whilestmt.next); - return NULL; - - case MOJOSHADER_AST_STATEMENT_RETURN: - // !!! FIXME: type coercion to outer function's return type. - // !!! FIXME: warn if unreachable statements follow? - type_check_ast(ctx, ast->returnstmt.expr); - type_check_ast(ctx, ast->returnstmt.next); - return NULL; - - case MOJOSHADER_AST_COMPUNIT_FUNCTION: - assert(!ctx->is_func_scope); - - // We have to tapdance here to make sure the function is in - // the global scope, but it's parameters are pushed as variables - // in the function's scope. - datatype = type_check_ast(ctx, ast->funcunit.declaration); - ast->funcunit.index = push_function(ctx, - ast->funcunit.declaration->identifier, - datatype, ast->funcunit.definition == NULL); - - // not just a declaration, but a full function definition? - if (ast->funcunit.definition != NULL) - { - assert(ctx->loop_count == 0); - assert(ctx->switch_count == 0); - ctx->is_func_scope = 1; - ctx->var_index = 0; // reset this every function. - push_scope(ctx); // so function params are in function scope. - // repush the parameters before checking the actual function. - MOJOSHADER_astFunctionParameters *param; - for (param = ast->funcunit.declaration->params; param; param = param->next) - push_variable(ctx, param->identifier, param->datatype); - type_check_ast(ctx, ast->funcunit.definition); - pop_scope(ctx); - ctx->is_func_scope = 0; - assert(ctx->loop_count == 0); - assert(ctx->switch_count == 0); - } // else - - type_check_ast(ctx, ast->funcunit.next); - return NULL; - - case MOJOSHADER_AST_COMPUNIT_TYPEDEF: - type_check_ast(ctx, ast->typedefunit.type_info); - type_check_ast(ctx, ast->typedefunit.next); - return NULL; - - case MOJOSHADER_AST_COMPUNIT_STRUCT: - type_check_ast(ctx, ast->structunit.struct_info); - type_check_ast(ctx, ast->structunit.next); - return NULL; - - case MOJOSHADER_AST_COMPUNIT_VARIABLE: - type_check_ast(ctx, ast->varunit.declaration); - type_check_ast(ctx, ast->varunit.next); - return NULL; - - case MOJOSHADER_AST_SCALAR_OR_ARRAY: - assert(0 && "Should be done by other AST nodes."); - return NULL; - - case MOJOSHADER_AST_TYPEDEF: - { - MOJOSHADER_astScalarOrArray *soa = ast->typdef.details; - datatype = get_usertype(ctx, soa->identifier); - if (datatype != NULL) - { - fail(ctx, "typedef already defined"); - ast->typdef.datatype = datatype; - return datatype; - } // if - - datatype = build_datatype(ctx, ast->typdef.isconst, - ast->typdef.datatype, soa); - if (datatype == NULL) - return NULL; // out of memory? - - push_usertype(ctx, soa->identifier, datatype); - ast->typdef.datatype = datatype; - return ast->typdef.datatype; - } // case - - case MOJOSHADER_AST_FUNCTION_PARAMS: - assert(0 && "Should be done by MOJOSHADER_AST_FUNCTION_SIGNATURE"); - - case MOJOSHADER_AST_FUNCTION_SIGNATURE: - { - MOJOSHADER_astFunctionParameters *param; - const MOJOSHADER_astDataType *dtparams[64]; - - int i = 0; - for (param = ast->funcsig.params; param; param = param->next) - { - assert(i <= STATICARRAYLEN(dtparams)); // laziness. - sanitize_datatype(ctx, param->datatype); - if (param->initializer != NULL) - { - datatype2 = type_check_ast(ctx, param->initializer); - add_type_coercion(ctx, NULL, param->datatype, - ¶m->initializer, datatype2); - } // if - dtparams[i] = param->datatype; - i++; - } // for - - ast->funcsig.datatype = build_function_datatype(ctx, - ast->funcsig.datatype, - i, dtparams, 0); - return ast->funcsig.datatype; - } // case - - case MOJOSHADER_AST_STRUCT_DECLARATION: - { - // !!! FIXME: We don't handle struct predeclaration at all right now - // !!! FIXME: (neither does the grammar)...not only does that mean - // !!! FIXME: you need to know the struct definition up front, but - // !!! FIXME: you can't do "struct XXX *next;" for a self-referencing - // !!! FIXME: linked list struct thing. This probably isn't a big - // !!! FIXME: deal, as there aren't (CURRENTLY!) pointers in HLSL, - // !!! FIXME: but you never know. - - const MOJOSHADER_astStructMembers *mbrs; - - // !!! FIXME: count this during parsing? - int count = 0; - mbrs = ast->structdecl.members; - while (mbrs != NULL) - { - count++; - mbrs = mbrs->next; - } // while - - // !!! FIXME: this is hacky. - MOJOSHADER_astDataTypeStructMember *dtmbrs; - void *ptr = Malloc(ctx, sizeof (*dtmbrs) * count); - if (ptr == NULL) - return NULL; - if (!buffer_append(ctx->garbage, &ptr, sizeof (ptr))) - { - Free(ctx, ptr); - return NULL; - } // if - dtmbrs = (MOJOSHADER_astDataTypeStructMember *) ptr; - - ptr = Malloc(ctx, sizeof (MOJOSHADER_astDataType)); - if (ptr == NULL) - return NULL; - if (!buffer_append(ctx->garbage, &ptr, sizeof (ptr))) - { - Free(ctx, ptr); - return NULL; - } // if - MOJOSHADER_astDataType *dt = (MOJOSHADER_astDataType *) ptr; - - mbrs = ast->structdecl.members; - int i; - for (i = 0; i < count; i++) - { - // !!! FIXME: current grammar forbids const keyword on struct members! - dtmbrs[i].datatype = build_datatype(ctx, 0, mbrs->datatype, mbrs->details); - dtmbrs[i].identifier = mbrs->details->identifier; // cached! - mbrs = mbrs->next; - } // for - - dt->structure.type = MOJOSHADER_AST_DATATYPE_STRUCT; - dt->structure.members = dtmbrs; - dt->structure.member_count = count; - ast->structdecl.datatype = dt; - - // !!! FIXME: this shouldn't push for anonymous structs: "struct { int x; } myvar;" - // !!! FIXME: but right now, the grammar is wrong and requires a name for the struct. - push_usertype(ctx, ast->structdecl.name, ast->structdecl.datatype); - return ast->structdecl.datatype; - } // case - - case MOJOSHADER_AST_STRUCT_MEMBER: - assert(0 && "Should be done by MOJOSHADER_AST_STRUCT_DECLARATION."); - return NULL; - - case MOJOSHADER_AST_VARIABLE_DECLARATION: - { - MOJOSHADER_astVariableDeclaration *decl = &ast->vardecl; - - // this is true now, but we'll fill in ->datatype no matter what. - assert((decl->datatype && !decl->anonymous_datatype) || - (!decl->datatype && decl->anonymous_datatype)); - - // An anonymous struct? That AST node does the heavy lifting. - if (decl->anonymous_datatype != NULL) - datatype = type_check_ast(ctx, decl->anonymous_datatype); - else - { - datatype = build_datatype(ctx, (decl->attributes & MOJOSHADER_AST_VARATTR_CONST) != 0, - decl->datatype, decl->details); - } // else - - while (decl != NULL) - { - decl->datatype = datatype; - push_variable(ctx, decl->details->identifier, datatype); - if (decl->initializer != NULL) - { - datatype2 = type_check_ast(ctx, decl->initializer); - add_type_coercion(ctx, NULL, datatype, &decl->initializer, datatype2); - } // if - - type_check_ast(ctx, decl->annotations); - type_check_ast(ctx, decl->lowlevel); - decl = decl->next; - } // while - - return datatype; - } // case - - case MOJOSHADER_AST_ANNOTATION: - { - MOJOSHADER_astAnnotations *anno = &ast->annotations; - while (anno) - { - type_check_ast(ctx, anno->initializer); - anno = anno->next; - } // while - return NULL; - } // case - - case MOJOSHADER_AST_PACK_OFFSET: - case MOJOSHADER_AST_VARIABLE_LOWLEVEL: - return NULL; // no-op (for now, at least). - - default: - assert(0 && "unexpected type"); - } // switch - - return NULL; -} // type_check_ast - - -static inline void semantic_analysis(Context *ctx) -{ - type_check_ast(ctx, ctx->ast); -} // semantic_analysis - -// !!! FIXME: isn't this a cut-and-paste of somewhere else? -static inline int64 strtoi64(const char *str, unsigned int len) -{ - int64 retval = 0; - int64 mult = 1; - int i = 0; - - while ((len) && (*str == ' ')) - { - str++; - len--; - } // while - - if ((len) && (*str == '-')) - { - mult = -1; - str++; - len--; - } // if - - while (i < len) - { - const char ch = str[i]; - if ((ch < '0') || (ch > '9')) - break; - i++; - } // while - - while (--i >= 0) - { - const char ch = str[i]; - retval += ((int64) (ch - '0')) * mult; - mult *= 10; - } // while - - return retval; -} // strtoi64 - -// !!! FIXME: isn't this a cut-and-paste of somewhere else? -static inline double strtodouble(const char *_str, unsigned int len) -{ - // !!! FIXME: laziness prevails. - char *str = (char *) alloca(len+1); - memcpy(str, _str, len); - str[len] = '\0'; - return strtod(str, NULL); -} // strtodouble - -#if 0 -// This does not check correctness (POSITIONT993842 passes, etc). -static int is_semantic(const Context *ctx, const char *token, - const unsigned int tokenlen) -{ - static const char *names[] = { - "BINORMAL", "BLENDINDICES", "BLENDWEIGHT", - "COLOR", "NORMAL", "POSITION", "POSITIONT", "PSIZE", "TANGENT", - "TEXCOORD", "FOG", "TESSFACTOR", "TEXCOORD", "VFACE", "VPOS", - "DEPTH", NULL - }; - - // !!! FIXME: DX10 has SV_* ("System Value Semantics"). - const char **i; - for (i = names; *i; i++) - { - const char *name = *i; - const size_t namelen = strlen(name); - if (tokenlen < namelen) - continue; - else if (memcmp(token, name, namelen) != 0) - continue; - - for (name += namelen; *name; name++) - { - if ((*name < '0') || (*name > '9')) - break; - } // for - - if (*name == '\0') - return 1; - } // for - - return 0; -} // is_semantic -#endif - -static int convert_to_lemon_token(Context *ctx, const char *token, - unsigned int tokenlen, const Token tokenval) -{ - switch (tokenval) - { - case ((Token) ','): return TOKEN_HLSL_COMMA; - case ((Token) '='): return TOKEN_HLSL_ASSIGN; - case ((Token) TOKEN_ADDASSIGN): return TOKEN_HLSL_ADDASSIGN; - case ((Token) TOKEN_SUBASSIGN): return TOKEN_HLSL_SUBASSIGN; - case ((Token) TOKEN_MULTASSIGN): return TOKEN_HLSL_MULASSIGN; - case ((Token) TOKEN_DIVASSIGN): return TOKEN_HLSL_DIVASSIGN; - case ((Token) TOKEN_MODASSIGN): return TOKEN_HLSL_MODASSIGN; - case ((Token) TOKEN_LSHIFTASSIGN): return TOKEN_HLSL_LSHIFTASSIGN; - case ((Token) TOKEN_RSHIFTASSIGN): return TOKEN_HLSL_RSHIFTASSIGN; - case ((Token) TOKEN_ANDASSIGN): return TOKEN_HLSL_ANDASSIGN; - case ((Token) TOKEN_ORASSIGN): return TOKEN_HLSL_ORASSIGN; - case ((Token) TOKEN_XORASSIGN): return TOKEN_HLSL_XORASSIGN; - case ((Token) '?'): return TOKEN_HLSL_QUESTION; - case ((Token) TOKEN_OROR): return TOKEN_HLSL_OROR; - case ((Token) TOKEN_ANDAND): return TOKEN_HLSL_ANDAND; - case ((Token) '|'): return TOKEN_HLSL_OR; - case ((Token) '^'): return TOKEN_HLSL_XOR; - case ((Token) '&'): return TOKEN_HLSL_AND; - case ((Token) TOKEN_EQL): return TOKEN_HLSL_EQL; - case ((Token) TOKEN_NEQ): return TOKEN_HLSL_NEQ; - case ((Token) '<'): return TOKEN_HLSL_LT; - case ((Token) TOKEN_LEQ): return TOKEN_HLSL_LEQ; - case ((Token) '>'): return TOKEN_HLSL_GT; - case ((Token) TOKEN_GEQ): return TOKEN_HLSL_GEQ; - case ((Token) TOKEN_LSHIFT): return TOKEN_HLSL_LSHIFT; - case ((Token) TOKEN_RSHIFT): return TOKEN_HLSL_RSHIFT; - case ((Token) '+'): return TOKEN_HLSL_PLUS; - case ((Token) '-'): return TOKEN_HLSL_MINUS; - case ((Token) '*'): return TOKEN_HLSL_STAR; - case ((Token) '/'): return TOKEN_HLSL_SLASH; - case ((Token) '%'): return TOKEN_HLSL_PERCENT; - case ((Token) '!'): return TOKEN_HLSL_EXCLAMATION; - case ((Token) '~'): return TOKEN_HLSL_COMPLEMENT; - case ((Token) TOKEN_DECREMENT): return TOKEN_HLSL_MINUSMINUS; - case ((Token) TOKEN_INCREMENT): return TOKEN_HLSL_PLUSPLUS; - case ((Token) '.'): return TOKEN_HLSL_DOT; - case ((Token) '['): return TOKEN_HLSL_LBRACKET; - case ((Token) ']'): return TOKEN_HLSL_RBRACKET; - case ((Token) '('): return TOKEN_HLSL_LPAREN; - case ((Token) ')'): return TOKEN_HLSL_RPAREN; - case ((Token) TOKEN_INT_LITERAL): return TOKEN_HLSL_INT_CONSTANT; - case ((Token) TOKEN_FLOAT_LITERAL): return TOKEN_HLSL_FLOAT_CONSTANT; - case ((Token) TOKEN_STRING_LITERAL): return TOKEN_HLSL_STRING_LITERAL; - case ((Token) ':'): return TOKEN_HLSL_COLON; - case ((Token) ';'): return TOKEN_HLSL_SEMICOLON; - case ((Token) '{'): return TOKEN_HLSL_LBRACE; - case ((Token) '}'): return TOKEN_HLSL_RBRACE; - //case ((Token) TOKEN_PP_PRAGMA): return TOKEN_HLSL_PRAGMA; - //case ((Token) '\n'): return TOKEN_HLSL_NEWLINE; - - case ((Token) TOKEN_IDENTIFIER): - #define tokencmp(t) ((tokenlen == strlen(t)) && (memcmp(token, t, tokenlen) == 0)) - //case ((Token) ''): return TOKEN_HLSL_TYPECAST - //if (tokencmp("")) return TOKEN_HLSL_TYPE_NAME - //if (tokencmp("...")) return TOKEN_HLSL_ELIPSIS - if (tokencmp("else")) return TOKEN_HLSL_ELSE; - if (tokencmp("inline")) return TOKEN_HLSL_INLINE; - if (tokencmp("void")) return TOKEN_HLSL_VOID; - if (tokencmp("in")) return TOKEN_HLSL_IN; - if (tokencmp("inout")) return TOKEN_HLSL_INOUT; - if (tokencmp("out")) return TOKEN_HLSL_OUT; - if (tokencmp("uniform")) return TOKEN_HLSL_UNIFORM; - if (tokencmp("linear")) return TOKEN_HLSL_LINEAR; - if (tokencmp("centroid")) return TOKEN_HLSL_CENTROID; - if (tokencmp("nointerpolation")) return TOKEN_HLSL_NOINTERPOLATION; - if (tokencmp("noperspective")) return TOKEN_HLSL_NOPERSPECTIVE; - if (tokencmp("sample")) return TOKEN_HLSL_SAMPLE; - if (tokencmp("struct")) return TOKEN_HLSL_STRUCT; - if (tokencmp("typedef")) return TOKEN_HLSL_TYPEDEF; - if (tokencmp("const")) return TOKEN_HLSL_CONST; - if (tokencmp("packoffset")) return TOKEN_HLSL_PACKOFFSET; - if (tokencmp("register")) return TOKEN_HLSL_REGISTER; - if (tokencmp("extern")) return TOKEN_HLSL_EXTERN; - if (tokencmp("shared")) return TOKEN_HLSL_SHARED; - if (tokencmp("static")) return TOKEN_HLSL_STATIC; - if (tokencmp("volatile")) return TOKEN_HLSL_VOLATILE; - if (tokencmp("row_major")) return TOKEN_HLSL_ROWMAJOR; - if (tokencmp("column_major")) return TOKEN_HLSL_COLUMNMAJOR; - if (tokencmp("bool")) return TOKEN_HLSL_BOOL; - if (tokencmp("int")) return TOKEN_HLSL_INT; - if (tokencmp("uint")) return TOKEN_HLSL_UINT; - if (tokencmp("half")) return TOKEN_HLSL_HALF; - if (tokencmp("float")) return TOKEN_HLSL_FLOAT; - if (tokencmp("double")) return TOKEN_HLSL_DOUBLE; - if (tokencmp("string")) return TOKEN_HLSL_STRING; - if (tokencmp("snorm")) return TOKEN_HLSL_SNORM; - if (tokencmp("unorm")) return TOKEN_HLSL_UNORM; - if (tokencmp("buffer")) return TOKEN_HLSL_BUFFER; - if (tokencmp("vector")) return TOKEN_HLSL_VECTOR; - if (tokencmp("matrix")) return TOKEN_HLSL_MATRIX; - if (tokencmp("break")) return TOKEN_HLSL_BREAK; - if (tokencmp("continue")) return TOKEN_HLSL_CONTINUE; - if (tokencmp("discard")) return TOKEN_HLSL_DISCARD; - if (tokencmp("return")) return TOKEN_HLSL_RETURN; - if (tokencmp("while")) return TOKEN_HLSL_WHILE; - if (tokencmp("for")) return TOKEN_HLSL_FOR; - if (tokencmp("unroll")) return TOKEN_HLSL_UNROLL; - if (tokencmp("loop")) return TOKEN_HLSL_LOOP; - if (tokencmp("do")) return TOKEN_HLSL_DO; - if (tokencmp("if")) return TOKEN_HLSL_IF; - if (tokencmp("branch")) return TOKEN_HLSL_BRANCH; - if (tokencmp("flatten")) return TOKEN_HLSL_FLATTEN; - if (tokencmp("switch")) return TOKEN_HLSL_SWITCH; - if (tokencmp("forcecase")) return TOKEN_HLSL_FORCECASE; - if (tokencmp("call")) return TOKEN_HLSL_CALL; - if (tokencmp("case")) return TOKEN_HLSL_CASE; - if (tokencmp("default")) return TOKEN_HLSL_DEFAULT; - if (tokencmp("sampler")) return TOKEN_HLSL_SAMPLER; - if (tokencmp("sampler1D")) return TOKEN_HLSL_SAMPLER1D; - if (tokencmp("sampler2D")) return TOKEN_HLSL_SAMPLER2D; - if (tokencmp("sampler3D")) return TOKEN_HLSL_SAMPLER3D; - if (tokencmp("samplerCUBE")) return TOKEN_HLSL_SAMPLERCUBE; - if (tokencmp("sampler_state")) return TOKEN_HLSL_SAMPLER_STATE; - if (tokencmp("SamplerState")) return TOKEN_HLSL_SAMPLERSTATE; - if (tokencmp("true")) return TOKEN_HLSL_TRUE; - if (tokencmp("false")) return TOKEN_HLSL_FALSE; - if (tokencmp("SamplerComparisonState")) return TOKEN_HLSL_SAMPLERCOMPARISONSTATE; - if (tokencmp("isolate")) return TOKEN_HLSL_ISOLATE; - if (tokencmp("maxInstructionCount")) return TOKEN_HLSL_MAXINSTRUCTIONCOUNT; - if (tokencmp("noExpressionOptimizations")) return TOKEN_HLSL_NOEXPRESSIONOPTIMIZATIONS; - if (tokencmp("unused")) return TOKEN_HLSL_UNUSED; - if (tokencmp("xps")) return TOKEN_HLSL_XPS; - #undef tokencmp - - // get a canonical copy of the string now, as we'll need it. - token = stringcache_len(ctx->strcache, token, tokenlen); - if (get_usertype(ctx, token) != NULL) - return TOKEN_HLSL_USERTYPE; - return TOKEN_HLSL_IDENTIFIER; - - case TOKEN_EOI: return 0; - default: assert(0 && "unexpected token from lexer\n"); return 0; - } // switch - - return 0; -} // convert_to_lemon_token - - -static void delete_ir(Context *ctx, void *_ir); // !!! FIXME: move this code around. - -static void destroy_context(Context *ctx) -{ - if (ctx != NULL) - { - MOJOSHADER_free f = ((ctx->free != NULL) ? ctx->free : MOJOSHADER_internal_free); - void *d = ctx->malloc_data; - size_t i = 0; - - // !!! FIXME: this is kinda hacky. - const size_t count = buffer_size(ctx->garbage) / sizeof (void *); - if (count > 0) - { - void **garbage = (void **) buffer_flatten(ctx->garbage); - if (garbage != NULL) - { - for (i = 0; i < count; i++) - f(garbage[i], d); - f(garbage, d); - } // if - } // if - buffer_destroy(ctx->garbage); - - delete_compilation_unit(ctx, (MOJOSHADER_astCompilationUnit*)ctx->ast); - destroy_symbolmap(ctx, &ctx->usertypes); - destroy_symbolmap(ctx, &ctx->variables); - stringcache_destroy(ctx->strcache); - errorlist_destroy(ctx->errors); - errorlist_destroy(ctx->warnings); - - if (ctx->ir != NULL) - { - for (i = 0; i <= ctx->user_func_index; i++) - delete_ir(ctx, ctx->ir[i]); - f(ctx->ir, d); - } // if - - // !!! FIXME: more to clean up here, now. - - f(ctx, d); - } // if -} // destroy_context - -static Context *build_context(MOJOSHADER_malloc m, MOJOSHADER_free f, void *d) -{ - if (!m) m = MOJOSHADER_internal_malloc; - if (!f) f = MOJOSHADER_internal_free; - - Context *ctx = (Context *) m(sizeof (Context), d); - if (ctx == NULL) - return NULL; - - memset(ctx, '\0', sizeof (Context)); - ctx->malloc = m; - ctx->free = f; - ctx->malloc_data = d; - //ctx->parse_phase = MOJOSHADER_PARSEPHASE_NOTSTARTED; - create_symbolmap(ctx, &ctx->usertypes); // !!! FIXME: check for failure. - create_symbolmap(ctx, &ctx->variables); // !!! FIXME: check for failure. - ctx->strcache = stringcache_create(MallocBridge, FreeBridge, ctx); // !!! FIXME: check for failure. - ctx->errors = errorlist_create(MallocBridge, FreeBridge, ctx); // !!! FIXME: check for failure. - ctx->warnings = errorlist_create(MallocBridge, FreeBridge, ctx); // !!! FIXME: check for failure. - - // !!! FIXME: this feels hacky. - ctx->garbage = buffer_create(256*sizeof(void*),MallocBridge,FreeBridge,ctx); // !!! FIXME: check for failure. - - ctx->dt_none.type = MOJOSHADER_AST_DATATYPE_NONE; - ctx->dt_bool.type = MOJOSHADER_AST_DATATYPE_BOOL; - ctx->dt_int.type = MOJOSHADER_AST_DATATYPE_INT; - ctx->dt_uint.type = MOJOSHADER_AST_DATATYPE_UINT; - ctx->dt_float.type = MOJOSHADER_AST_DATATYPE_FLOAT; - ctx->dt_float_snorm.type = MOJOSHADER_AST_DATATYPE_FLOAT_SNORM; - ctx->dt_float_unorm.type = MOJOSHADER_AST_DATATYPE_FLOAT_UNORM; - ctx->dt_half.type = MOJOSHADER_AST_DATATYPE_HALF; - ctx->dt_double.type = MOJOSHADER_AST_DATATYPE_DOUBLE; - ctx->dt_string.type = MOJOSHADER_AST_DATATYPE_STRING; - ctx->dt_sampler1d.type = MOJOSHADER_AST_DATATYPE_SAMPLER_1D; - ctx->dt_sampler2d.type = MOJOSHADER_AST_DATATYPE_SAMPLER_2D; - ctx->dt_sampler3d.type = MOJOSHADER_AST_DATATYPE_SAMPLER_3D; - ctx->dt_samplercube.type = MOJOSHADER_AST_DATATYPE_SAMPLER_CUBE; - ctx->dt_samplerstate.type = MOJOSHADER_AST_DATATYPE_SAMPLER_STATE; - ctx->dt_samplercompstate.type = MOJOSHADER_AST_DATATYPE_SAMPLER_COMPARISON_STATE; - - #define INIT_DT_BUFFER(t) \ - ctx->dt_buf_##t.type = MOJOSHADER_AST_DATATYPE_BUFFER; \ - ctx->dt_buf_##t.buffer.base = &ctx->dt_##t; - INIT_DT_BUFFER(bool); - INIT_DT_BUFFER(int); - INIT_DT_BUFFER(uint); - INIT_DT_BUFFER(half); - INIT_DT_BUFFER(float); - INIT_DT_BUFFER(double); - INIT_DT_BUFFER(float_snorm); - INIT_DT_BUFFER(float_unorm); - #undef INIT_DT_BUFFER - - return ctx; -} // build_context - - -// This macro salsa is kinda nasty, but it's the smallest, least error-prone -// way I can find to do this well in C. :/ - -#define ADD_INTRINSIC(fn, ret, params) do { \ - push_function(ctx, fn, \ - build_function_datatype(ctx, ret, STATICARRAYLEN(params), params, 1), \ - 0); \ -} while (0) - -#define ADD_INTRINSIC_VECTOR(typestr, code) do { \ - const MOJOSHADER_astDataType *dt; \ - dt = get_usertype(ctx, typestr "1"); code; \ - dt = get_usertype(ctx, typestr "2"); code; \ - dt = get_usertype(ctx, typestr "3"); code; \ - dt = get_usertype(ctx, typestr "4"); code; \ -} while (0) - -#define ADD_INTRINSIC_VECTOR_FLOAT(code) { \ - ADD_INTRINSIC_VECTOR("float", code); \ - ADD_INTRINSIC_VECTOR("half", code); \ - ADD_INTRINSIC_VECTOR("double", code); \ -} -#define ADD_INTRINSIC_VECTOR_INT(code) { \ - ADD_INTRINSIC_VECTOR("int", code); \ - ADD_INTRINSIC_VECTOR("uint", code); \ -} -#define ADD_INTRINSIC_VECTOR_BOOL(code) { \ - ADD_INTRINSIC_VECTOR("bool", code); \ -} - -#define ADD_INTRINSIC_MATRIX(typestr, code) do { \ - const MOJOSHADER_astDataType *dt; \ - dt = get_usertype(ctx, typestr "1x1"); code; \ - dt = get_usertype(ctx, typestr "1x2"); code; \ - dt = get_usertype(ctx, typestr "1x3"); code; \ - dt = get_usertype(ctx, typestr "1x4"); code; \ - dt = get_usertype(ctx, typestr "2x1"); code; \ - dt = get_usertype(ctx, typestr "2x2"); code; \ - dt = get_usertype(ctx, typestr "2x3"); code; \ - dt = get_usertype(ctx, typestr "2x4"); code; \ - dt = get_usertype(ctx, typestr "3x1"); code; \ - dt = get_usertype(ctx, typestr "3x2"); code; \ - dt = get_usertype(ctx, typestr "3x3"); code; \ - dt = get_usertype(ctx, typestr "3x4"); code; \ - dt = get_usertype(ctx, typestr "4x1"); code; \ - dt = get_usertype(ctx, typestr "4x2"); code; \ - dt = get_usertype(ctx, typestr "4x3"); code; \ - dt = get_usertype(ctx, typestr "4x4"); code; \ -} while (0) - -#define ADD_INTRINSIC_MATRIX_FLOAT(code) { \ - ADD_INTRINSIC_MATRIX("float", code); \ - ADD_INTRINSIC_MATRIX("half", code); \ - ADD_INTRINSIC_MATRIX("double", code); \ -} -#define ADD_INTRINSIC_MATRIX_INT(code) { \ - ADD_INTRINSIC_MATRIX("int", code); \ - ADD_INTRINSIC_MATRIX("uint", code); \ -} -#define ADD_INTRINSIC_MATRIX_BOOL(code) { \ - ADD_INTRINSIC_MATRIX("bool", code); \ -} - -#define ADD_INTRINSIC_ANY(scalar, typestr, code) do { \ - { const MOJOSHADER_astDataType *dt = scalar; code; } \ - ADD_INTRINSIC_VECTOR(typestr, code); \ - ADD_INTRINSIC_MATRIX(typestr, code); \ -} while (0) - -#define ADD_INTRINSIC_ANY_FLOAT(code) do { \ - ADD_INTRINSIC_ANY(&ctx->dt_double, "double", code); \ - ADD_INTRINSIC_ANY(&ctx->dt_half, "half", code); \ - ADD_INTRINSIC_ANY(&ctx->dt_float, "float", code); \ -} while (0) -#define ADD_INTRINSIC_ANY_INT(code) do { \ - ADD_INTRINSIC_ANY(&ctx->dt_uint, "uint", code); \ - ADD_INTRINSIC_ANY(&ctx->dt_int, "int", code); \ -} while (0) - -#define ADD_INTRINSIC_ANY_BOOL(code) ADD_INTRINSIC_ANY(&ctx->dt_bool, "bool", code) - -static void add_intrinsic1(Context *ctx, const char *fn, - const MOJOSHADER_astDataType *ret, - const MOJOSHADER_astDataType *dt1) -{ - const MOJOSHADER_astDataType *params[] = { dt1 }; - ADD_INTRINSIC(fn, ret, params); -} // add_intrinsic1 - -static void add_intrinsic2(Context *ctx, const char *fn, - const MOJOSHADER_astDataType *ret, - const MOJOSHADER_astDataType *dt1, - const MOJOSHADER_astDataType *dt2) -{ - const MOJOSHADER_astDataType *params[] = { dt1, dt2 }; - ADD_INTRINSIC(fn, ret, params); -} // add_intrinsic2 - -static void add_intrinsic3(Context *ctx, const char *fn, - const MOJOSHADER_astDataType *ret, - const MOJOSHADER_astDataType *dt1, - const MOJOSHADER_astDataType *dt2, - const MOJOSHADER_astDataType *dt3) -{ - const MOJOSHADER_astDataType *params[] = { dt1, dt2, dt3 }; - ADD_INTRINSIC(fn, ret, params); -} // add_intrinsic3 - -static void add_intrinsic4(Context *ctx, const char *fn, - const MOJOSHADER_astDataType *ret, - const MOJOSHADER_astDataType *dt1, - const MOJOSHADER_astDataType *dt2, - const MOJOSHADER_astDataType *dt3, - const MOJOSHADER_astDataType *dt4) -{ - const MOJOSHADER_astDataType *params[] = { dt1, dt2, dt3, dt4 }; - ADD_INTRINSIC(fn, ret, params); -} // add_intrinsic4 - -// PLEASE NOTE that add_intrinsic*() is called AFTER the various -// ADD_INTRINSIC_* macros, even though these look like functions that -// should be called first. They might be called multiple times by the macro. -// The variable "dt" is defined by the macro for use by your code. -static void add_intrinsic_SAME1_ANYf(Context *ctx, const char *fn) -{ - ADD_INTRINSIC_ANY_FLOAT(add_intrinsic1(ctx, fn, dt, dt)); -} // add_intrinsic_SAME1_ANYf - -static void add_intrinsic_SAME1_ANYfi(Context *ctx, const char *fn) -{ - ADD_INTRINSIC_ANY_INT(add_intrinsic1(ctx, fn, dt, dt)); - add_intrinsic_SAME1_ANYf(ctx, fn); -} // add_intrinsic_SAME1_ANYfi - -static void add_intrinsic_BOOL_ANYf(Context *ctx, const char *fn) -{ - ADD_INTRINSIC_ANY_FLOAT(add_intrinsic1(ctx, fn, &ctx->dt_bool, dt)); -} // add_intrinsic_BOOL_ANYf - -static void add_intrinsic_BOOL_ANYfib(Context *ctx, const char *fn) -{ - ADD_INTRINSIC_ANY_BOOL(add_intrinsic1(ctx, fn, &ctx->dt_bool, dt)); - ADD_INTRINSIC_ANY_INT(add_intrinsic1(ctx, fn, &ctx->dt_bool, dt)); - add_intrinsic_BOOL_ANYf(ctx, fn); -} // add_intrinsic_BOOL_ANYfib - -static void add_intrinsic_SAME1_ANYf_SAME1(Context *ctx, const char *fn) -{ - ADD_INTRINSIC_ANY_FLOAT(add_intrinsic2(ctx, fn, dt, dt, dt)); -} // add_intrinsic_SAME1_ANYf_SAME1 - -static void add_intrinsic_SAME1_ANYfi_SAME1(Context *ctx, const char *fn) -{ - ADD_INTRINSIC_ANY_INT(add_intrinsic2(ctx, fn, dt, dt, dt)); - add_intrinsic_SAME1_ANYf_SAME1(ctx, fn); -} // add_intrinsic_SAME1_ANYfi_SAME1 - -static void add_intrinsic_SAME1_ANYf_SAME1_SAME1(Context *ctx, const char *fn) -{ - ADD_INTRINSIC_ANY_FLOAT(add_intrinsic3(ctx, fn, dt, dt, dt, dt)); -} // add_intrinsic_SAME1_ANYf_SAME1_SAME1 - -static void add_intrinsic_SAME1_ANYfi_SAME1_SAME1(Context *ctx, const char *fn) -{ - ADD_INTRINSIC_ANY_INT(add_intrinsic3(ctx, fn, dt, dt, dt, dt)); - add_intrinsic_SAME1_ANYf_SAME1_SAME1(ctx, fn); -} // add_intrinsic_SAME1_ANYfi_SAME1_SAME1 - -static void add_intrinsic_SAME1_Mfib(Context *ctx, const char *fn) -{ - ADD_INTRINSIC_MATRIX_BOOL(add_intrinsic1(ctx, fn, dt, dt)); - ADD_INTRINSIC_MATRIX_INT(add_intrinsic1(ctx, fn, dt, dt)); - ADD_INTRINSIC_MATRIX_FLOAT(add_intrinsic1(ctx, fn, dt, dt)); -} // add_intrinsic_SAME1_Mfib - -static void add_intrinsic_SAME1_Vf(Context *ctx, const char *fn) -{ - ADD_INTRINSIC_VECTOR_FLOAT(add_intrinsic1(ctx, fn, dt, dt)); -} // add_intrinsic_SAME1_Vf - -static void add_intrinsic_SAME1_Vf_SAME1_SAME1(Context *ctx, const char *fn) -{ - ADD_INTRINSIC_VECTOR_FLOAT(add_intrinsic3(ctx, fn, dt, dt, dt, dt)); -} // add_intrinsic_SAME1_Vf_SAME1_SAME1 - -static void add_intrinsic_SAME1_Vf_SAME1_f(Context *ctx, const char *fn) -{ - ADD_INTRINSIC_VECTOR_FLOAT(add_intrinsic3(ctx, fn, dt, dt, dt, dt->user.details->vector.base)); -} // add_intrinsic_SAME1_Vf_SAME1_f - -static void add_intrinsic_VOID_ANYf(Context *ctx, const char *fn) -{ - ADD_INTRINSIC_ANY_FLOAT(add_intrinsic1(ctx, fn, NULL, dt)); -} // add_intrinsic_VOID_ANYf - -static void add_intrinsic_VOID_ANYf_SAME1_SAME1(Context *ctx, const char *fn) -{ - ADD_INTRINSIC_ANY_FLOAT(add_intrinsic3(ctx, fn, NULL, dt, dt, dt)); -} // add_intrinsic_VOID_ANYf_SAME1_SAME1 - -static void add_intrinsic_f_SQUAREMATRIXf(Context *ctx, const char *fn) -{ - add_intrinsic1(ctx, fn, &ctx->dt_float, get_usertype(ctx, "float1x1")); - add_intrinsic1(ctx, fn, &ctx->dt_float, get_usertype(ctx, "float2x2")); - add_intrinsic1(ctx, fn, &ctx->dt_float, get_usertype(ctx, "float3x3")); - add_intrinsic1(ctx, fn, &ctx->dt_float, get_usertype(ctx, "float4x4")); -} // add_intrinsic_f_SQUAREMATRIXf - -static void add_intrinsic_f_Vf(Context *ctx, const char *fn) -{ - ADD_INTRINSIC_VECTOR_FLOAT(add_intrinsic1(ctx, fn, dt->user.details->vector.base, dt)); -} // add_intrinsic_f_Vf - -static void add_intrinsic_fi_Vfi_SAME1(Context *ctx, const char *fn) -{ - ADD_INTRINSIC_VECTOR_INT(add_intrinsic2(ctx, fn, dt->user.details->vector.base, dt, dt)); - ADD_INTRINSIC_VECTOR_FLOAT(add_intrinsic2(ctx, fn, dt->user.details->vector.base, dt, dt)); -} // add_intrinsic_fi_Vfi_SAME1 - -static void add_intrinsic_f_Vf_SAME1(Context *ctx, const char *fn) -{ - ADD_INTRINSIC_VECTOR_FLOAT(add_intrinsic2(ctx, fn, dt->user.details->vector.base, dt, dt)); -} // add_intrinsic_f_Vf_SAME1 - -static void add_intrinsic_3f_3f_3f(Context *ctx, const char *fn) -{ - const MOJOSHADER_astDataType *dt = get_usertype(ctx, "float3"); - add_intrinsic2(ctx, fn, dt, dt, dt); -} // add_intrinsic_3f_3f_3f - -static void add_intrinsic_4f_f_f_f(Context *ctx, const char *fn) -{ - const MOJOSHADER_astDataType *f4 = get_usertype(ctx, "float4"); - const MOJOSHADER_astDataType *f = &ctx->dt_float; - add_intrinsic3(ctx, fn, f4, f, f, f); -} // add_intrinsic_4f_f_f_f - -static void add_intrinsic_4f_s1_4f(Context *ctx, const char *fn) -{ - const MOJOSHADER_astDataType *dt = get_usertype(ctx, "float4"); - add_intrinsic2(ctx, fn, dt, &ctx->dt_sampler1d, dt); -} // add_intrinsic_4f_s1_4f - -static void add_intrinsic_4f_s1_f(Context *ctx, const char *fn) -{ - const MOJOSHADER_astDataType *dt = get_usertype(ctx, "float4"); - add_intrinsic2(ctx, fn, dt, &ctx->dt_sampler1d, &ctx->dt_float); -} // add_intrinsic_4f_s1_f - -static void add_intrinsic_4f_s1_f_f_f(Context *ctx, const char *fn) -{ - const MOJOSHADER_astDataType *dt = get_usertype(ctx, "float4"); - const MOJOSHADER_astDataType *f = &ctx->dt_float; - add_intrinsic4(ctx, fn, dt, &ctx->dt_sampler1d, f, f, f); -} // add_intrinsic_4f_s1_f_f_f - -static void add_intrinsic_4f_s2_2f(Context *ctx, const char *fn) -{ - const MOJOSHADER_astDataType *f4 = get_usertype(ctx, "float4"); - const MOJOSHADER_astDataType *f2 = get_usertype(ctx, "float2"); - add_intrinsic2(ctx, fn, f4, &ctx->dt_sampler2d, f2); -} // add_intrinsic_4f_s2_2f - -static void add_intrinsic_4f_s2_2f_2f_2f(Context *ctx, const char *fn) -{ - const MOJOSHADER_astDataType *f4 = get_usertype(ctx, "float4"); - const MOJOSHADER_astDataType *f2 = get_usertype(ctx, "float2"); - add_intrinsic4(ctx, fn, f4, &ctx->dt_sampler2d, f2, f2, f2); -} // add_intrinsic_4f_s2_2f_2f_2f - -static void add_intrinsic_4f_s2_4f(Context *ctx, const char *fn) -{ - const MOJOSHADER_astDataType *f4 = get_usertype(ctx, "float4"); - add_intrinsic2(ctx, fn, f4, &ctx->dt_sampler2d, f4); -} // add_intrinsic_4f_s2_4f - -static void add_intrinsic_4f_s3_3f(Context *ctx, const char *fn) -{ - const MOJOSHADER_astDataType *f4 = get_usertype(ctx, "float4"); - const MOJOSHADER_astDataType *f3 = get_usertype(ctx, "float3"); - add_intrinsic2(ctx, fn, f4, &ctx->dt_sampler3d, f3); -} // add_intrinsic_4f_s3_3f - -static void add_intrinsic_4f_s3_3f_3f_3f(Context *ctx, const char *fn) -{ - const MOJOSHADER_astDataType *f4 = get_usertype(ctx, "float4"); - const MOJOSHADER_astDataType *f3 = get_usertype(ctx, "float3"); - add_intrinsic4(ctx, fn, f4, &ctx->dt_sampler3d, f3, f3, f3); -} // add_intrinsic_4f_s3_3f_3f_3f - -static void add_intrinsic_4f_s3_4f(Context *ctx, const char *fn) -{ - const MOJOSHADER_astDataType *f4 = get_usertype(ctx, "float4"); - add_intrinsic2(ctx, fn, f4, &ctx->dt_sampler3d, f4); -} // add_intrinsic_4f_s3_4f - -static void add_intrinsic_4f_sc_3f(Context *ctx, const char *fn) -{ - const MOJOSHADER_astDataType *f4 = get_usertype(ctx, "float4"); - const MOJOSHADER_astDataType *f3 = get_usertype(ctx, "float3"); - add_intrinsic2(ctx, fn, f4, &ctx->dt_samplercube, f3); -} // add_intrinsic_4f_sc_3f - -static void add_intrinsic_4f_sc_3f_3f_3f(Context *ctx, const char *fn) -{ - const MOJOSHADER_astDataType *f4 = get_usertype(ctx, "float4"); - const MOJOSHADER_astDataType *f3 = get_usertype(ctx, "float3"); - add_intrinsic4(ctx, fn, f4, &ctx->dt_samplercube, f3, f3, f3); -} // add_intrinsic_4f_sc_3f_3f_3f - -static void add_intrinsic_4f_sc_4f(Context *ctx, const char *fn) -{ - const MOJOSHADER_astDataType *f4 = get_usertype(ctx, "float4"); - add_intrinsic2(ctx, fn, f4, &ctx->dt_samplercube, f4); -} // add_intrinsic_4f_sc_4f - -static void add_intrinsic_4i_4f(Context *ctx, const char *fn) -{ - const MOJOSHADER_astDataType *i4 = get_usertype(ctx, "int4"); - const MOJOSHADER_astDataType *f4 = get_usertype(ctx, "float4"); - add_intrinsic1(ctx, fn, i4, f4); -} // add_intrinsic_4i_4f - -static void add_intrinsic_mul(Context *ctx, const char *fn) -{ - // mul() is nasty, since there's a bunch of overloads that aren't just - // related to vector size. - // !!! FIXME: needs half, double, uint... - const MOJOSHADER_astDataType *dtf = &ctx->dt_float; - const MOJOSHADER_astDataType *dti = &ctx->dt_int; - const MOJOSHADER_astDataType *f1 = get_usertype(ctx, "float1"); - const MOJOSHADER_astDataType *f2 = get_usertype(ctx, "float2"); - const MOJOSHADER_astDataType *f3 = get_usertype(ctx, "float3"); - const MOJOSHADER_astDataType *f4 = get_usertype(ctx, "float4"); - const MOJOSHADER_astDataType *i1 = get_usertype(ctx, "int1"); - const MOJOSHADER_astDataType *i2 = get_usertype(ctx, "int2"); - const MOJOSHADER_astDataType *i3 = get_usertype(ctx, "int3"); - const MOJOSHADER_astDataType *i4 = get_usertype(ctx, "int4"); - const MOJOSHADER_astDataType *f1x1 = get_usertype(ctx, "float1x1"); - const MOJOSHADER_astDataType *f1x2 = get_usertype(ctx, "float1x2"); - const MOJOSHADER_astDataType *f1x3 = get_usertype(ctx, "float1x3"); - const MOJOSHADER_astDataType *f1x4 = get_usertype(ctx, "float1x4"); - const MOJOSHADER_astDataType *f2x1 = get_usertype(ctx, "float2x1"); - const MOJOSHADER_astDataType *f2x2 = get_usertype(ctx, "float2x2"); - const MOJOSHADER_astDataType *f2x3 = get_usertype(ctx, "float2x3"); - const MOJOSHADER_astDataType *f2x4 = get_usertype(ctx, "float2x4"); - const MOJOSHADER_astDataType *f3x1 = get_usertype(ctx, "float3x1"); - const MOJOSHADER_astDataType *f3x2 = get_usertype(ctx, "float3x2"); - const MOJOSHADER_astDataType *f3x3 = get_usertype(ctx, "float3x3"); - const MOJOSHADER_astDataType *f3x4 = get_usertype(ctx, "float3x4"); - const MOJOSHADER_astDataType *f4x1 = get_usertype(ctx, "float4x1"); - const MOJOSHADER_astDataType *f4x2 = get_usertype(ctx, "float4x2"); - const MOJOSHADER_astDataType *f4x3 = get_usertype(ctx, "float4x3"); - const MOJOSHADER_astDataType *f4x4 = get_usertype(ctx, "float4x4"); - const MOJOSHADER_astDataType *i1x1 = get_usertype(ctx, "int1x1"); - const MOJOSHADER_astDataType *i1x2 = get_usertype(ctx, "int1x2"); - const MOJOSHADER_astDataType *i1x3 = get_usertype(ctx, "int1x3"); - const MOJOSHADER_astDataType *i1x4 = get_usertype(ctx, "int1x4"); - const MOJOSHADER_astDataType *i2x1 = get_usertype(ctx, "int2x1"); - const MOJOSHADER_astDataType *i2x2 = get_usertype(ctx, "int2x2"); - const MOJOSHADER_astDataType *i2x3 = get_usertype(ctx, "int2x3"); - const MOJOSHADER_astDataType *i2x4 = get_usertype(ctx, "int2x4"); - const MOJOSHADER_astDataType *i3x1 = get_usertype(ctx, "int3x1"); - const MOJOSHADER_astDataType *i3x2 = get_usertype(ctx, "int3x2"); - const MOJOSHADER_astDataType *i3x3 = get_usertype(ctx, "int3x3"); - const MOJOSHADER_astDataType *i3x4 = get_usertype(ctx, "int3x4"); - const MOJOSHADER_astDataType *i4x1 = get_usertype(ctx, "int4x1"); - const MOJOSHADER_astDataType *i4x2 = get_usertype(ctx, "int4x2"); - const MOJOSHADER_astDataType *i4x3 = get_usertype(ctx, "int4x3"); - const MOJOSHADER_astDataType *i4x4 = get_usertype(ctx, "int4x4"); - - // scalar * scalar - add_intrinsic2(ctx, fn, dti, dti, dti); - add_intrinsic2(ctx, fn, dtf, dtf, dtf); - - // scalar * vector - ADD_INTRINSIC_VECTOR_INT(add_intrinsic2(ctx, fn, dt, dti, dt)); - ADD_INTRINSIC_VECTOR_FLOAT(add_intrinsic2(ctx, fn, dt, dtf, dt)); - - // scalar * matrix - ADD_INTRINSIC_MATRIX_INT(add_intrinsic2(ctx, fn, dt, dti, dt)); - ADD_INTRINSIC_MATRIX_FLOAT(add_intrinsic2(ctx, fn, dt, dtf, dt)); - - // vector * scalar - ADD_INTRINSIC_VECTOR_INT(add_intrinsic2(ctx, fn, dt, dt, dti)); - ADD_INTRINSIC_VECTOR_FLOAT(add_intrinsic2(ctx, fn, dt, dt, dtf)); - - // vector * vector - ADD_INTRINSIC_VECTOR_INT(add_intrinsic2(ctx, fn, dti, dt, dt)); - ADD_INTRINSIC_VECTOR_FLOAT(add_intrinsic2(ctx, fn, dtf, dt, dt)); - - // vector * matrix - add_intrinsic2(ctx, fn, i1, i1, i1x1); - add_intrinsic2(ctx, fn, i2, i1, i1x2); - add_intrinsic2(ctx, fn, i3, i1, i1x3); - add_intrinsic2(ctx, fn, i4, i1, i1x4); - add_intrinsic2(ctx, fn, i1, i2, i2x1); - add_intrinsic2(ctx, fn, i2, i2, i2x2); - add_intrinsic2(ctx, fn, i3, i2, i2x3); - add_intrinsic2(ctx, fn, i4, i2, i2x4); - add_intrinsic2(ctx, fn, i1, i3, i3x1); - add_intrinsic2(ctx, fn, i2, i3, i3x2); - add_intrinsic2(ctx, fn, i3, i3, i3x3); - add_intrinsic2(ctx, fn, i4, i3, i3x4); - add_intrinsic2(ctx, fn, i1, i4, i4x1); - add_intrinsic2(ctx, fn, i2, i4, i4x2); - add_intrinsic2(ctx, fn, i3, i4, i4x3); - add_intrinsic2(ctx, fn, i4, i4, i4x4); - add_intrinsic2(ctx, fn, f1, f1, f1x1); - add_intrinsic2(ctx, fn, f2, f1, f1x2); - add_intrinsic2(ctx, fn, f3, f1, f1x3); - add_intrinsic2(ctx, fn, f4, f1, f1x4); - add_intrinsic2(ctx, fn, f1, f2, f2x1); - add_intrinsic2(ctx, fn, f2, f2, f2x2); - add_intrinsic2(ctx, fn, f3, f2, f2x3); - add_intrinsic2(ctx, fn, f4, f2, f2x4); - add_intrinsic2(ctx, fn, f1, f3, f3x1); - add_intrinsic2(ctx, fn, f2, f3, f3x2); - add_intrinsic2(ctx, fn, f3, f3, f3x3); - add_intrinsic2(ctx, fn, f4, f3, f3x4); - add_intrinsic2(ctx, fn, f1, f4, f4x1); - add_intrinsic2(ctx, fn, f2, f4, f4x2); - add_intrinsic2(ctx, fn, f3, f4, f4x3); - add_intrinsic2(ctx, fn, f4, f4, f4x4); - - // matrix * scalar - ADD_INTRINSIC_MATRIX_INT(add_intrinsic2(ctx, fn, dt, dt, dti)); - ADD_INTRINSIC_MATRIX_FLOAT(add_intrinsic2(ctx, fn, dt, dt, dtf)); - - // matrix * vector - add_intrinsic2(ctx, fn, i1, i1x1, i1); - add_intrinsic2(ctx, fn, i1, i1x2, i2); - add_intrinsic2(ctx, fn, i1, i1x3, i3); - add_intrinsic2(ctx, fn, i1, i1x4, i4); - add_intrinsic2(ctx, fn, i2, i2x1, i1); - add_intrinsic2(ctx, fn, i2, i2x2, i2); - add_intrinsic2(ctx, fn, i2, i2x3, i3); - add_intrinsic2(ctx, fn, i2, i2x4, i4); - add_intrinsic2(ctx, fn, i3, i3x1, i1); - add_intrinsic2(ctx, fn, i3, i3x2, i2); - add_intrinsic2(ctx, fn, i3, i3x3, i3); - add_intrinsic2(ctx, fn, i3, i3x4, i4); - add_intrinsic2(ctx, fn, i4, i4x1, i1); - add_intrinsic2(ctx, fn, i4, i4x2, i2); - add_intrinsic2(ctx, fn, i4, i4x3, i3); - add_intrinsic2(ctx, fn, i4, i4x4, i4); - add_intrinsic2(ctx, fn, f1, f1x1, f1); - add_intrinsic2(ctx, fn, f1, f1x2, f2); - add_intrinsic2(ctx, fn, f1, f1x3, f3); - add_intrinsic2(ctx, fn, f1, f1x4, f4); - add_intrinsic2(ctx, fn, f2, f2x1, f1); - add_intrinsic2(ctx, fn, f2, f2x2, f2); - add_intrinsic2(ctx, fn, f2, f2x3, f3); - add_intrinsic2(ctx, fn, f2, f2x4, f4); - add_intrinsic2(ctx, fn, f3, f3x1, f1); - add_intrinsic2(ctx, fn, f3, f3x2, f2); - add_intrinsic2(ctx, fn, f3, f3x3, f3); - add_intrinsic2(ctx, fn, f3, f3x4, f4); - add_intrinsic2(ctx, fn, f4, f4x1, f1); - add_intrinsic2(ctx, fn, f4, f4x2, f2); - add_intrinsic2(ctx, fn, f4, f4x3, f3); - add_intrinsic2(ctx, fn, f4, f4x4, f4); - - // matrix * matrix - add_intrinsic2(ctx, fn, i1x1, i1x1, i1x1); - add_intrinsic2(ctx, fn, i1x2, i1x1, i1x2); - add_intrinsic2(ctx, fn, i1x3, i1x1, i1x3); - add_intrinsic2(ctx, fn, i1x4, i1x1, i1x4); - add_intrinsic2(ctx, fn, i1x1, i1x2, i2x1); - add_intrinsic2(ctx, fn, i1x2, i1x2, i2x2); - add_intrinsic2(ctx, fn, i1x3, i1x2, i2x3); - add_intrinsic2(ctx, fn, i1x4, i1x2, i2x4); - add_intrinsic2(ctx, fn, i1x1, i1x3, i3x1); - add_intrinsic2(ctx, fn, i1x2, i1x3, i3x2); - add_intrinsic2(ctx, fn, i1x3, i1x3, i3x3); - add_intrinsic2(ctx, fn, i1x4, i1x3, i3x4); - add_intrinsic2(ctx, fn, i1x1, i1x4, i4x1); - add_intrinsic2(ctx, fn, i1x2, i1x4, i4x2); - add_intrinsic2(ctx, fn, i1x3, i1x4, i4x3); - add_intrinsic2(ctx, fn, i1x4, i1x4, i4x4); - add_intrinsic2(ctx, fn, i2x1, i2x1, i1x1); - add_intrinsic2(ctx, fn, i2x2, i2x1, i1x2); - add_intrinsic2(ctx, fn, i2x3, i2x1, i1x3); - add_intrinsic2(ctx, fn, i2x4, i2x1, i1x4); - add_intrinsic2(ctx, fn, i2x1, i2x2, i2x1); - add_intrinsic2(ctx, fn, i2x2, i2x2, i2x2); - add_intrinsic2(ctx, fn, i2x3, i2x2, i2x3); - add_intrinsic2(ctx, fn, i2x4, i2x2, i2x4); - add_intrinsic2(ctx, fn, i2x1, i2x3, i3x1); - add_intrinsic2(ctx, fn, i2x2, i2x3, i3x2); - add_intrinsic2(ctx, fn, i2x3, i2x3, i3x3); - add_intrinsic2(ctx, fn, i2x4, i2x3, i3x4); - add_intrinsic2(ctx, fn, i2x1, i2x4, i4x1); - add_intrinsic2(ctx, fn, i2x2, i2x4, i4x2); - add_intrinsic2(ctx, fn, i2x3, i2x4, i4x3); - add_intrinsic2(ctx, fn, i2x4, i2x4, i4x4); - add_intrinsic2(ctx, fn, i3x1, i3x1, i1x1); - add_intrinsic2(ctx, fn, i3x2, i3x1, i1x2); - add_intrinsic2(ctx, fn, i3x3, i3x1, i1x3); - add_intrinsic2(ctx, fn, i3x4, i3x1, i1x4); - add_intrinsic2(ctx, fn, i3x1, i3x2, i2x1); - add_intrinsic2(ctx, fn, i3x2, i3x2, i2x2); - add_intrinsic2(ctx, fn, i3x3, i3x2, i2x3); - add_intrinsic2(ctx, fn, i3x4, i3x2, i2x4); - add_intrinsic2(ctx, fn, i3x1, i3x3, i3x1); - add_intrinsic2(ctx, fn, i3x2, i3x3, i3x2); - add_intrinsic2(ctx, fn, i3x3, i3x3, i3x3); - add_intrinsic2(ctx, fn, i3x4, i3x3, i3x4); - add_intrinsic2(ctx, fn, i3x1, i3x4, i4x1); - add_intrinsic2(ctx, fn, i3x2, i3x4, i4x2); - add_intrinsic2(ctx, fn, i3x3, i3x4, i4x3); - add_intrinsic2(ctx, fn, i3x4, i3x4, i4x4); - add_intrinsic2(ctx, fn, i4x1, i4x1, i1x1); - add_intrinsic2(ctx, fn, i4x2, i4x1, i1x2); - add_intrinsic2(ctx, fn, i4x3, i4x1, i1x3); - add_intrinsic2(ctx, fn, i4x4, i4x1, i1x4); - add_intrinsic2(ctx, fn, i4x1, i4x2, i2x1); - add_intrinsic2(ctx, fn, i4x2, i4x2, i2x2); - add_intrinsic2(ctx, fn, i4x3, i4x2, i2x3); - add_intrinsic2(ctx, fn, i4x4, i4x2, i2x4); - add_intrinsic2(ctx, fn, i4x1, i4x3, i3x1); - add_intrinsic2(ctx, fn, i4x2, i4x3, i3x2); - add_intrinsic2(ctx, fn, i4x3, i4x3, i3x3); - add_intrinsic2(ctx, fn, i4x4, i4x3, i3x4); - add_intrinsic2(ctx, fn, i4x1, i4x4, i4x1); - add_intrinsic2(ctx, fn, i4x2, i4x4, i4x2); - add_intrinsic2(ctx, fn, i4x3, i4x4, i4x3); - add_intrinsic2(ctx, fn, i4x4, i4x4, i4x4); - add_intrinsic2(ctx, fn, f1x1, f1x1, f1x1); - add_intrinsic2(ctx, fn, f1x2, f1x1, f1x2); - add_intrinsic2(ctx, fn, f1x3, f1x1, f1x3); - add_intrinsic2(ctx, fn, f1x4, f1x1, f1x4); - add_intrinsic2(ctx, fn, f1x1, f1x2, f2x1); - add_intrinsic2(ctx, fn, f1x2, f1x2, f2x2); - add_intrinsic2(ctx, fn, f1x3, f1x2, f2x3); - add_intrinsic2(ctx, fn, f1x4, f1x2, f2x4); - add_intrinsic2(ctx, fn, f1x1, f1x3, f3x1); - add_intrinsic2(ctx, fn, f1x2, f1x3, f3x2); - add_intrinsic2(ctx, fn, f1x3, f1x3, f3x3); - add_intrinsic2(ctx, fn, f1x4, f1x3, f3x4); - add_intrinsic2(ctx, fn, f1x1, f1x4, f4x1); - add_intrinsic2(ctx, fn, f1x2, f1x4, f4x2); - add_intrinsic2(ctx, fn, f1x3, f1x4, f4x3); - add_intrinsic2(ctx, fn, f1x4, f1x4, f4x4); - add_intrinsic2(ctx, fn, f2x1, f2x1, f1x1); - add_intrinsic2(ctx, fn, f2x2, f2x1, f1x2); - add_intrinsic2(ctx, fn, f2x3, f2x1, f1x3); - add_intrinsic2(ctx, fn, f2x4, f2x1, f1x4); - add_intrinsic2(ctx, fn, f2x1, f2x2, f2x1); - add_intrinsic2(ctx, fn, f2x2, f2x2, f2x2); - add_intrinsic2(ctx, fn, f2x3, f2x2, f2x3); - add_intrinsic2(ctx, fn, f2x4, f2x2, f2x4); - add_intrinsic2(ctx, fn, f2x1, f2x3, f3x1); - add_intrinsic2(ctx, fn, f2x2, f2x3, f3x2); - add_intrinsic2(ctx, fn, f2x3, f2x3, f3x3); - add_intrinsic2(ctx, fn, f2x4, f2x3, f3x4); - add_intrinsic2(ctx, fn, f2x1, f2x4, f4x1); - add_intrinsic2(ctx, fn, f2x2, f2x4, f4x2); - add_intrinsic2(ctx, fn, f2x3, f2x4, f4x3); - add_intrinsic2(ctx, fn, f2x4, f2x4, f4x4); - add_intrinsic2(ctx, fn, f3x1, f3x1, f1x1); - add_intrinsic2(ctx, fn, f3x2, f3x1, f1x2); - add_intrinsic2(ctx, fn, f3x3, f3x1, f1x3); - add_intrinsic2(ctx, fn, f3x4, f3x1, f1x4); - add_intrinsic2(ctx, fn, f3x1, f3x2, f2x1); - add_intrinsic2(ctx, fn, f3x2, f3x2, f2x2); - add_intrinsic2(ctx, fn, f3x3, f3x2, f2x3); - add_intrinsic2(ctx, fn, f3x4, f3x2, f2x4); - add_intrinsic2(ctx, fn, f3x1, f3x3, f3x1); - add_intrinsic2(ctx, fn, f3x2, f3x3, f3x2); - add_intrinsic2(ctx, fn, f3x3, f3x3, f3x3); - add_intrinsic2(ctx, fn, f3x4, f3x3, f3x4); - add_intrinsic2(ctx, fn, f3x1, f3x4, f4x1); - add_intrinsic2(ctx, fn, f3x2, f3x4, f4x2); - add_intrinsic2(ctx, fn, f3x3, f3x4, f4x3); - add_intrinsic2(ctx, fn, f3x4, f3x4, f4x4); - add_intrinsic2(ctx, fn, f4x1, f4x1, f1x1); - add_intrinsic2(ctx, fn, f4x2, f4x1, f1x2); - add_intrinsic2(ctx, fn, f4x3, f4x1, f1x3); - add_intrinsic2(ctx, fn, f4x4, f4x1, f1x4); - add_intrinsic2(ctx, fn, f4x1, f4x2, f2x1); - add_intrinsic2(ctx, fn, f4x2, f4x2, f2x2); - add_intrinsic2(ctx, fn, f4x3, f4x2, f2x3); - add_intrinsic2(ctx, fn, f4x4, f4x2, f2x4); - add_intrinsic2(ctx, fn, f4x1, f4x3, f3x1); - add_intrinsic2(ctx, fn, f4x2, f4x3, f3x2); - add_intrinsic2(ctx, fn, f4x3, f4x3, f3x3); - add_intrinsic2(ctx, fn, f4x4, f4x3, f3x4); - add_intrinsic2(ctx, fn, f4x1, f4x4, f4x1); - add_intrinsic2(ctx, fn, f4x2, f4x4, f4x2); - add_intrinsic2(ctx, fn, f4x3, f4x4, f4x3); - add_intrinsic2(ctx, fn, f4x4, f4x4, f4x4); -} // add_intrinsic_mul - -static void init_builtins(Context *ctx) -{ - // add in standard typedefs... - const struct - { - const char *str; - const MOJOSHADER_astDataType *datatype; - } types[] = { - { "bool", &ctx->dt_bool }, - { "int", &ctx->dt_int }, - { "uint", &ctx->dt_uint }, - { "half", &ctx->dt_half }, - { "float", &ctx->dt_float }, - { "double", &ctx->dt_double }, - }; - - int i, j, k; - for (i = 0; i < STATICARRAYLEN(types); i++) - { - char buf[32]; - int len; - const MOJOSHADER_astDataType *dt; - - for (j = 1; j <= 4; j++) - { - // "float2" - dt = new_datatype_vector(ctx, types[i].datatype, j); - len = snprintf(buf, sizeof (buf), "%s%d", types[i].str, j); - push_usertype(ctx, stringcache_len(ctx->strcache, buf, len), dt); - for (k = 1; k <= 4; k++) - { - // "float2x2" - dt = new_datatype_matrix(ctx, types[i].datatype, j, k); - len = snprintf(buf, sizeof (buf), "%s%dx%d", types[i].str,j,k); - push_usertype(ctx, stringcache_len(ctx->strcache,buf,len), dt); - } // for - } // for - } // for - - // !!! FIXME: block these out by pixel/vertex/etc shader. - // !!! FIXME: calculate actual shader model (or maybe just let bytecode verifier throw up?). - const int shader_model = 3; - if (shader_model >= 1) - { - add_intrinsic_SAME1_ANYfi(ctx, stringcache(ctx->strcache, "abs")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "acos")); - add_intrinsic_BOOL_ANYfib(ctx, stringcache(ctx->strcache, "all")); - add_intrinsic_BOOL_ANYfib(ctx, stringcache(ctx->strcache, "any")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "asin")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "atan")); - add_intrinsic_SAME1_ANYf_SAME1(ctx, stringcache(ctx->strcache, "atan2")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "ceil")); - add_intrinsic_SAME1_ANYfi_SAME1_SAME1(ctx, stringcache(ctx->strcache, "clamp")); - add_intrinsic_VOID_ANYf(ctx, stringcache(ctx->strcache, "clip")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "cos")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "cosh")); - add_intrinsic_3f_3f_3f(ctx, stringcache(ctx->strcache, "cross")); - add_intrinsic_4i_4f(ctx, stringcache(ctx->strcache, "D3DCOLORtoUBYTE4")); - add_intrinsic_f_Vf_SAME1(ctx, stringcache(ctx->strcache, "distance")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "degrees")); - add_intrinsic_f_SQUAREMATRIXf(ctx, stringcache(ctx->strcache, "determinant")); - add_intrinsic_fi_Vfi_SAME1(ctx, stringcache(ctx->strcache, "dot")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "exp")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "exp2")); - add_intrinsic_SAME1_Vf_SAME1_SAME1(ctx, stringcache(ctx->strcache, "faceforward")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "floor")); - add_intrinsic_SAME1_ANYf_SAME1(ctx, stringcache(ctx->strcache, "fmod")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "frac")); - add_intrinsic_BOOL_ANYf(ctx, stringcache(ctx->strcache, "isfinite")); - add_intrinsic_BOOL_ANYf(ctx, stringcache(ctx->strcache, "isinf")); - add_intrinsic_BOOL_ANYf(ctx, stringcache(ctx->strcache, "isnan")); - add_intrinsic_SAME1_ANYf_SAME1(ctx, stringcache(ctx->strcache, "ldexp")); - add_intrinsic_f_Vf(ctx, stringcache(ctx->strcache, "length")); - add_intrinsic_SAME1_ANYf_SAME1_SAME1(ctx, stringcache(ctx->strcache, "lerp")); - add_intrinsic_4f_f_f_f(ctx, stringcache(ctx->strcache, "lit")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "log")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "log10")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "log2")); - add_intrinsic_SAME1_ANYfi_SAME1(ctx, stringcache(ctx->strcache, "max")); - add_intrinsic_SAME1_ANYfi_SAME1(ctx, stringcache(ctx->strcache, "min")); - add_intrinsic_SAME1_ANYfi_SAME1(ctx, stringcache(ctx->strcache, "modf")); // !!! FIXME: out var? - add_intrinsic_mul(ctx, stringcache(ctx->strcache, "mul")); - add_intrinsic_f_Vf(ctx, stringcache(ctx->strcache, "noise")); - add_intrinsic_SAME1_Vf(ctx, stringcache(ctx->strcache, "normalize")); - add_intrinsic_SAME1_ANYf_SAME1(ctx, stringcache(ctx->strcache, "pow")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "radians")); - add_intrinsic_SAME1_ANYfi_SAME1(ctx, stringcache(ctx->strcache, "reflect")); - add_intrinsic_SAME1_Vf_SAME1_f(ctx, stringcache(ctx->strcache, "refract")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "round")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "rsqrt")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "saturate")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "sign")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "sin")); - add_intrinsic_VOID_ANYf_SAME1_SAME1(ctx, stringcache(ctx->strcache, "sincos")); // !!! FIXME: out var? - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "sinh")); - add_intrinsic_SAME1_ANYf_SAME1_SAME1(ctx, stringcache(ctx->strcache, "smoothstep")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "sqrt")); - add_intrinsic_SAME1_ANYf_SAME1(ctx, stringcache(ctx->strcache, "step")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "tan")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "tanh")); - add_intrinsic_4f_s1_f(ctx, stringcache(ctx->strcache, "tex1D")); - add_intrinsic_4f_s2_2f(ctx, stringcache(ctx->strcache, "tex2D")); - add_intrinsic_4f_s3_3f(ctx, stringcache(ctx->strcache, "tex3D")); - add_intrinsic_4f_sc_3f(ctx, stringcache(ctx->strcache, "texCUBE")); - add_intrinsic_SAME1_Mfib(ctx, stringcache(ctx->strcache, "transpose")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "trunc")); - } // if - - if (shader_model >= 2) - { - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "ddx")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "ddy")); - add_intrinsic_SAME1_ANYf_SAME1(ctx, stringcache(ctx->strcache, "frexp")); - add_intrinsic_SAME1_ANYf(ctx, stringcache(ctx->strcache, "fwidth")); - add_intrinsic_4f_s1_f_f_f(ctx, stringcache(ctx->strcache, "tex1D")); - add_intrinsic_4f_s1_4f(ctx, stringcache(ctx->strcache, "tex1Dbias")); - add_intrinsic_4f_s1_f_f_f(ctx, stringcache(ctx->strcache, "tex1Dgrad")); - add_intrinsic_4f_s1_4f(ctx, stringcache(ctx->strcache, "tex1Dproj")); - add_intrinsic_4f_s2_2f_2f_2f(ctx, stringcache(ctx->strcache, "tex2D")); - add_intrinsic_4f_s2_4f(ctx, stringcache(ctx->strcache, "tex2Dbias")); - add_intrinsic_4f_s2_2f_2f_2f(ctx, stringcache(ctx->strcache, "tex2Dgrad")); - add_intrinsic_4f_s2_4f(ctx, stringcache(ctx->strcache, "tex2Dproj")); - add_intrinsic_4f_s3_3f_3f_3f(ctx, stringcache(ctx->strcache, "tex3D")); - add_intrinsic_4f_s3_4f(ctx, stringcache(ctx->strcache, "tex3Dbias")); - add_intrinsic_4f_s3_3f_3f_3f(ctx, stringcache(ctx->strcache, "tex3Dgrad")); - add_intrinsic_4f_s3_4f(ctx, stringcache(ctx->strcache, "tex3Dproj")); - add_intrinsic_4f_sc_3f_3f_3f(ctx, stringcache(ctx->strcache, "texCUBE")); - add_intrinsic_4f_sc_4f(ctx, stringcache(ctx->strcache, "texCUBEbias")); - add_intrinsic_4f_sc_3f_3f_3f(ctx, stringcache(ctx->strcache, "texCUBEgrad")); - add_intrinsic_4f_sc_4f(ctx, stringcache(ctx->strcache, "texCUBEproj")); - } // if - - if (shader_model >= 3) - { - add_intrinsic_4f_s1_4f(ctx, stringcache(ctx->strcache, "tex1Dlod")); - add_intrinsic_4f_s2_4f(ctx, stringcache(ctx->strcache, "tex2Dlod")); - add_intrinsic_4f_s3_4f(ctx, stringcache(ctx->strcache, "tex3Dlod")); - add_intrinsic_4f_sc_4f(ctx, stringcache(ctx->strcache, "texCUBElod")); - } // if -} // init_builtins - - -// parse the source code into an AST. -static void parse_source(Context *ctx, const char *filename, - const char *source, unsigned int sourcelen, - const MOJOSHADER_preprocessorDefine *defines, - unsigned int define_count, - MOJOSHADER_includeOpen include_open, - MOJOSHADER_includeClose include_close) -{ - TokenData data; - unsigned int tokenlen; - Token tokenval; - const char *token; - int lemon_token; - const char *fname; - Preprocessor *pp; - void *parser; - - if (!include_open) include_open = MOJOSHADER_internal_include_open; - if (!include_close) include_close = MOJOSHADER_internal_include_close; - - pp = preprocessor_start(filename, source, sourcelen, include_open, - include_close, defines, define_count, 0, - MallocBridge, FreeBridge, ctx); - if (pp == NULL) - { - assert(ctx->out_of_memory); // shouldn't fail for any other reason. - return; - } // if - - parser = ParseHLSLAlloc(ctx->malloc, ctx->malloc_data); - if (parser == NULL) - { - assert(ctx->out_of_memory); // shouldn't fail for any other reason. - preprocessor_end(pp); - return; - } // if - - // !!! FIXME: check if (parser == NULL)... - - init_builtins(ctx); - - SymbolScope *start_scope = ctx->usertypes.scope; - - #if DEBUG_COMPILER_PARSER - ParseHLSLTrace(stdout, "COMPILER: "); - #endif - - // Run the preprocessor/lexer/parser... - int is_pragma = 0; // !!! FIXME: remove this later when we can parse #pragma. - int skipping = 0; // !!! FIXME: remove this later when we can parse #pragma. - do { - token = preprocessor_nexttoken(pp, &tokenlen, &tokenval); - - if (ctx->out_of_memory) - break; - - fname = preprocessor_sourcepos(pp, &ctx->sourceline); - ctx->sourcefile = fname ? stringcache(ctx->strcache, fname) : 0; - - if ((tokenval == TOKEN_HASH) || (tokenval == TOKEN_HASHHASH)) - tokenval = TOKEN_BAD_CHARS; - - if (tokenval == TOKEN_BAD_CHARS) - { - fail(ctx, "Bad characters in source file"); - continue; - } // else if - - else if (tokenval == TOKEN_PREPROCESSING_ERROR) - { - fail(ctx, token); // this happens to be null-terminated. - continue; - } // else if - - else if (tokenval == TOKEN_PP_PRAGMA) - { - assert(!is_pragma); - is_pragma = 1; - skipping = 1; - continue; - } - - else if (tokenval == ((Token) '\n')) - { - assert(is_pragma); - is_pragma = 0; - skipping = 0; - continue; - } - - else if (skipping) - { - continue; - } - - // !!! FIXME: this is a mess, decide who should be doing this stuff, and only do it once. - lemon_token = convert_to_lemon_token(ctx, token, tokenlen, tokenval); - switch (lemon_token) - { - case TOKEN_HLSL_INT_CONSTANT: - data.i64 = strtoi64(token, tokenlen); - break; - - case TOKEN_HLSL_FLOAT_CONSTANT: - data.dbl = strtodouble(token, tokenlen); - break; - - case TOKEN_HLSL_USERTYPE: - data.string = stringcache_len(ctx->strcache, token, tokenlen); - data.datatype = get_usertype(ctx, data.string); // !!! FIXME: do we need this? It's kind of useless during parsing. - assert(data.datatype != NULL); - break; - - case TOKEN_HLSL_STRING_LITERAL: - case TOKEN_HLSL_IDENTIFIER: - data.string = stringcache_len(ctx->strcache, token, tokenlen); - break; - - default: - data.i64 = 0; - break; - } // switch - - ParseHLSL(parser, lemon_token, data, ctx); - - // this probably isn't perfect, but it's good enough for surviving - // the parse. We'll sort out correctness once we have a tree. - if (lemon_token == TOKEN_HLSL_LBRACE) - push_scope(ctx); - else if (lemon_token == TOKEN_HLSL_RBRACE) - pop_scope(ctx); - } while (tokenval != TOKEN_EOI); - - // Clean out extra usertypes; they are dummies until semantic analysis. - while (ctx->usertypes.scope != start_scope) - pop_symbol(ctx, &ctx->usertypes); - - ParseHLSLFree(parser, ctx->free, ctx->malloc_data); - preprocessor_end(pp); -} // parse_source - - -/* Intermediate representation... */ - -static inline int generate_ir_label(Context *ctx) -{ - return ctx->ir_label_count++; -} // generate_ir_label - -static inline int generate_ir_temp(Context *ctx) -{ - return ctx->ir_temp_count++; -} // generate_ir_temp - -static const LoopLabels *push_ir_loop(Context *ctx, const int isswitch) -{ - // !!! FIXME: cache these allocations? - LoopLabels *retval = (LoopLabels*)Malloc(ctx, sizeof (LoopLabels)); - if (retval) - { - retval->start = (isswitch) ? -1 : generate_ir_label(ctx); - retval->end = generate_ir_label(ctx); - retval->prev = ctx->ir_loop; - ctx->ir_loop = retval; - } // if - - return retval; -} // push_ir_loop - -static void pop_ir_loop(Context *ctx) -{ - assert(ctx->ir_loop != NULL); - LoopLabels *labels = ctx->ir_loop; - ctx->ir_loop = ctx->ir_loop->prev; - Free(ctx, labels); -} // pop_ir_loop - - -#define NEW_IR_NODE(retval, cls, typ) \ - cls *retval = (cls *) Malloc(ctx, sizeof (cls)); \ - do { \ - if (retval == NULL) { return NULL; } \ - retval->ir.type = typ; \ - retval->ir.filename = ctx->sourcefile; \ - retval->ir.line = ctx->sourceline; \ - } while (0) - -#define NEW_IR_EXPR(retval, cls, typ, dt, numelems) \ - cls *retval = (cls *) Malloc(ctx, sizeof (cls)); \ - do { \ - if (retval == NULL) { return NULL; } \ - retval->info.ir.type = typ; \ - retval->info.ir.filename = ctx->sourcefile; \ - retval->info.ir.line = ctx->sourceline; \ - retval->info.type = dt; \ - retval->info.elements = numelems; \ - } while (0) - -// syntactic sugar. -static inline MOJOSHADER_irNode *build_ir(Context *ctx, void *_ast); -static inline MOJOSHADER_irExpression *build_ir_expr(Context *ctx, void *_ast) -{ - MOJOSHADER_irNode *retval = build_ir(ctx, _ast); - assert(!retval || (retval->ir.type > MOJOSHADER_IR_START_RANGE_EXPR)); - assert(!retval || (retval->ir.type < MOJOSHADER_IR_END_RANGE_EXPR)); - return (MOJOSHADER_irExpression *) retval; -} // build_ir_expr - -static inline MOJOSHADER_irStatement *build_ir_stmt(Context *ctx, void *_ast) -{ - MOJOSHADER_irNode *retval = build_ir(ctx, _ast); - assert(!retval || (retval->ir.type > MOJOSHADER_IR_START_RANGE_STMT)); - assert(!retval || (retval->ir.type < MOJOSHADER_IR_END_RANGE_STMT)); - return (MOJOSHADER_irStatement *) retval; -} // build_ir_stmt - - -static MOJOSHADER_irExpression *new_ir_binop(Context *ctx, - const MOJOSHADER_irBinOpType op, - MOJOSHADER_irExpression *left, - MOJOSHADER_irExpression *right) -{ - if ((!left) || (!right)) return NULL; - NEW_IR_EXPR(retval, MOJOSHADER_irBinOp, MOJOSHADER_IR_BINOP, left->info.type, left->info.elements); - assert(left->info.type == right->info.type); - assert(left->info.elements == right->info.elements); - retval->op = op; - retval->left = left; - retval->right = right; - return (MOJOSHADER_irExpression *) retval; -} // new_ir_binop - -static MOJOSHADER_irExpression *new_ir_eseq(Context *ctx, - MOJOSHADER_irStatement *stmt, - MOJOSHADER_irExpression *expr) -{ - if (!expr) return NULL; - NEW_IR_EXPR(retval, MOJOSHADER_irESeq, MOJOSHADER_IR_ESEQ, expr->info.type, expr->info.elements); - retval->stmt = stmt; - retval->expr = expr; - return (MOJOSHADER_irExpression *) retval; -} // new_ir_eseq - -static MOJOSHADER_irExpression *new_ir_temp(Context *ctx, const int index, - const MOJOSHADER_astDataTypeType type, - const int elements) -{ - NEW_IR_EXPR(retval, MOJOSHADER_irTemp, MOJOSHADER_IR_TEMP, type, elements); - retval->index = index; - return (MOJOSHADER_irExpression *) retval; -} // new_ir_temp - - - -#define NEW_IR_BINOP(op,l,r) new_ir_binop(ctx, MOJOSHADER_IR_BINOP_##op, l, r) -#define EASY_IR_BINOP(op) \ - NEW_IR_BINOP(op, build_ir_expr(ctx, ast->binary.left), \ - build_ir_expr(ctx, ast->binary.right)) - -// You have to fill in ->value yourself! -static MOJOSHADER_irExpression *new_ir_constant(Context *ctx, - const MOJOSHADER_astDataTypeType type, - const int elements) -{ - NEW_IR_EXPR(retval, MOJOSHADER_irConstant, MOJOSHADER_IR_CONSTANT, type, elements); - return (MOJOSHADER_irExpression *) retval; -} // new_ir_constant - -static MOJOSHADER_irExpression *new_ir_constint(Context *ctx, const int val) -{ - NEW_IR_EXPR(retval, MOJOSHADER_irConstant, MOJOSHADER_IR_CONSTANT, MOJOSHADER_AST_DATATYPE_INT, 1); - retval->value.ival[0] = val; - return (MOJOSHADER_irExpression *) retval; -} // new_ir_constint - -static MOJOSHADER_irExpression *new_ir_constfloat(Context *ctx, const float val) -{ - NEW_IR_EXPR(retval, MOJOSHADER_irConstant, MOJOSHADER_IR_CONSTANT, MOJOSHADER_AST_DATATYPE_FLOAT, 1); - retval->value.fval[0] = val; - return (MOJOSHADER_irExpression *) retval; -} // new_ir_constfloat - -static MOJOSHADER_irExpression *new_ir_constbool(Context *ctx, const int val) -{ - // !!! FIXME: cache true and false in (ctx), ignore in delete_ir(). - NEW_IR_EXPR(retval, MOJOSHADER_irConstant, MOJOSHADER_IR_CONSTANT, MOJOSHADER_AST_DATATYPE_BOOL, 1); - retval->value.ival[0] = val; - return (MOJOSHADER_irExpression *) retval; -} // new_ir_constbool - -static MOJOSHADER_irExpression *new_ir_convert(Context *ctx, MOJOSHADER_irExpression *expr, - const MOJOSHADER_astDataTypeType type, - const int elements) -{ - NEW_IR_EXPR(retval, MOJOSHADER_irConvert, MOJOSHADER_IR_CONVERT, type, elements); - retval->expr = expr; - return (MOJOSHADER_irExpression *) retval; -} // new_ir_convert - -static MOJOSHADER_irExpression *new_ir_construct(Context *ctx, MOJOSHADER_irExprList *args, - const MOJOSHADER_astDataTypeType type, - const int elements) -{ - NEW_IR_EXPR(retval, MOJOSHADER_irConstruct, MOJOSHADER_IR_CONSTRUCT, type, elements); - retval->args = args; - return (MOJOSHADER_irExpression *) retval; -} // new_ir_construct - -static MOJOSHADER_irExpression *new_ir_call(Context *ctx, const int index, - MOJOSHADER_irExprList *args, - const MOJOSHADER_astDataTypeType type, - const int elements) -{ - NEW_IR_EXPR(retval, MOJOSHADER_irCall, MOJOSHADER_IR_CALL, type, elements); - retval->args = args; - retval->index = index; - return (MOJOSHADER_irExpression *) retval; -} // new_ir_call - -static MOJOSHADER_irExpression *new_ir_swizzle(Context *ctx, - MOJOSHADER_irExpression *expr, - const char *channels, - const MOJOSHADER_astDataTypeType type, - const int elements) -{ - NEW_IR_EXPR(retval, MOJOSHADER_irSwizzle, MOJOSHADER_IR_SWIZZLE, type, elements); - retval->expr = expr; - memcpy(retval->channels, channels, sizeof (retval->channels)); - return (MOJOSHADER_irExpression *) retval; -} // new_ir_swizzle - -static MOJOSHADER_irExpression *new_ir_memory(Context *ctx, const int index, - const MOJOSHADER_astDataTypeType type, - const int elements) -{ - NEW_IR_EXPR(retval, MOJOSHADER_irMemory, MOJOSHADER_IR_MEMORY, type, elements); - retval->index = index; - return (MOJOSHADER_irExpression *) retval; -} // new_ir_memory - -static MOJOSHADER_irExpression *new_ir_array(Context *ctx, - MOJOSHADER_irExpression *array, - MOJOSHADER_irExpression *element, - const MOJOSHADER_astDataTypeType type, - const int elements) -{ - NEW_IR_EXPR(retval, MOJOSHADER_irArray, MOJOSHADER_IR_ARRAY, type, elements); - retval->array = array; - retval->element = element; - return (MOJOSHADER_irExpression *) retval; -} // new_ir_array - -static MOJOSHADER_irStatement *new_ir_seq(Context *ctx, - MOJOSHADER_irStatement *first, - MOJOSHADER_irStatement *next) -{ - assert((first != NULL) || (next != NULL)); - if (first == NULL) // don't generate a SEQ if unnecessary. - return next; - else if (next == NULL) - return first; - - NEW_IR_NODE(retval, MOJOSHADER_irSeq, MOJOSHADER_IR_SEQ); - retval->first = first; - retval->next = next; - return (MOJOSHADER_irStatement *) retval; -} // new_ir_seq - -static MOJOSHADER_irStatement *new_ir_jump(Context *ctx, const int label) -{ - NEW_IR_NODE(retval, MOJOSHADER_irJump, MOJOSHADER_IR_JUMP); - retval->label = label; - return (MOJOSHADER_irStatement *) retval; -} // new_ir_jump - -static MOJOSHADER_irStatement *new_ir_cjump(Context *ctx, - const MOJOSHADER_irConditionType cond, - MOJOSHADER_irExpression *left, - MOJOSHADER_irExpression *right, - const int iftrue, const int iffalse) -{ - NEW_IR_NODE(retval, MOJOSHADER_irCJump, MOJOSHADER_IR_CJUMP); - retval->cond = cond; - retval->left = left; - retval->right = right; - retval->iftrue = iftrue; - retval->iffalse = iffalse; - return (MOJOSHADER_irStatement *) retval; -} // new_ir_cjump - -static MOJOSHADER_irStatement *new_ir_label(Context *ctx, const int index) -{ - NEW_IR_NODE(retval, MOJOSHADER_irLabel, MOJOSHADER_IR_LABEL); - retval->index = index; - return (MOJOSHADER_irStatement *) retval; -} // new_ir_label - -static MOJOSHADER_irStatement *new_ir_move(Context *ctx, - MOJOSHADER_irExpression *dst, - MOJOSHADER_irExpression *src, - const int writemask) -{ - NEW_IR_NODE(retval, MOJOSHADER_irMove, MOJOSHADER_IR_MOVE); - assert(dst && src && (dst->info.type == src->info.type)); - assert(dst && src && (dst->info.elements == src->info.elements)); - retval->dst = dst; - retval->src = src; - retval->writemask = writemask; - return (MOJOSHADER_irStatement *) retval; -} // new_ir_move - -static MOJOSHADER_irStatement *new_ir_expr_stmt(Context *ctx, MOJOSHADER_irExpression *expr) -{ - NEW_IR_NODE(retval, MOJOSHADER_irExprStmt, MOJOSHADER_IR_EXPR_STMT); - retval->expr = expr; - return (MOJOSHADER_irStatement *) retval; -} // new_ir_expr_stmt - -static MOJOSHADER_irStatement *new_ir_discard(Context *ctx) -{ - NEW_IR_NODE(retval, MOJOSHADER_irDiscard, MOJOSHADER_IR_DISCARD); - return (MOJOSHADER_irStatement *) retval; -} // new_ir_discard - -static MOJOSHADER_irExprList *new_ir_exprlist(Context *ctx, MOJOSHADER_irExpression *expr) -{ - NEW_IR_NODE(retval, MOJOSHADER_irExprList, MOJOSHADER_IR_EXPRLIST); - retval->expr = expr; - retval->next = NULL; - return (MOJOSHADER_irExprList *) retval; -} // new_ir_exprlist - - -// This handles most comparison operators (less-than, equals, etc...) -static MOJOSHADER_irExpression *build_ir_compare(Context *ctx, - const MOJOSHADER_irConditionType operation, - MOJOSHADER_irExpression *left, - MOJOSHADER_irExpression *right, - MOJOSHADER_irExpression *tval, - MOJOSHADER_irExpression *fval) -{ - /* The gist... - cjump x < y, t, f // '<' is whatever operation - t: - move tmp, tval - jump join - f: - move tmp, fval - join: - */ - - const int t = generate_ir_label(ctx); - const int f = generate_ir_label(ctx); - const int join = generate_ir_label(ctx); - const int tmp = generate_ir_temp(ctx); - - assert(tval && fval && (tval->info.type == fval->info.type)); - assert(tval && fval && (tval->info.elements == fval->info.elements)); - - const MOJOSHADER_astDataTypeType dt = tval->info.type; - const int elements = tval->info.elements; - - return new_ir_eseq(ctx, - new_ir_seq(ctx, new_ir_cjump(ctx, operation, left, right, t, f), - new_ir_seq(ctx, new_ir_label(ctx, t), - new_ir_seq(ctx, new_ir_move(ctx, new_ir_temp(ctx, tmp, dt, elements), tval, -1), - new_ir_seq(ctx, new_ir_jump(ctx, join), - new_ir_seq(ctx, new_ir_label(ctx, f), - new_ir_seq(ctx, new_ir_move(ctx, new_ir_temp(ctx, tmp, dt, elements), fval, -1), - new_ir_label(ctx, join))))))), - new_ir_temp(ctx, tmp, dt, elements)); -} // build_ir_compare - -#define EASY_IR_COMPARE(op) \ - build_ir_compare(ctx, MOJOSHADER_IR_COND_##op, \ - build_ir_expr(ctx, ast->binary.left), \ - build_ir_expr(ctx, ast->binary.right), \ - new_ir_constbool(ctx, 1), \ - new_ir_constbool(ctx, 0)) - - -// This handles && and || operators. -static MOJOSHADER_irExpression *build_ir_logical_and_or(Context *ctx, - const MOJOSHADER_astExpressionBinary *ast, - const int left_testval) -{ - /* The gist... - cjump left == left_testval, maybe, f - maybe: - cjump right == true, t, f - t: - move tmp, 1 - jump join - f: - move tmp, 0 - join: - */ - - assert(ast->left->datatype->type == MOJOSHADER_AST_DATATYPE_BOOL); - assert(ast->right->datatype->type == MOJOSHADER_AST_DATATYPE_BOOL); - - const int t = generate_ir_label(ctx); - const int f = generate_ir_label(ctx); - const int maybe = generate_ir_label(ctx); - const int join = generate_ir_label(ctx); - const int tmp = generate_ir_temp(ctx); - - return new_ir_eseq(ctx, - new_ir_seq(ctx, new_ir_cjump(ctx, MOJOSHADER_IR_COND_EQL, build_ir_expr(ctx, ast->left), new_ir_constbool(ctx, left_testval), maybe, f), - new_ir_seq(ctx, new_ir_label(ctx, maybe), - new_ir_seq(ctx, new_ir_cjump(ctx, MOJOSHADER_IR_COND_EQL, build_ir_expr(ctx, ast->right), new_ir_constbool(ctx, 1), t, f), - new_ir_seq(ctx, new_ir_label(ctx, t), - new_ir_seq(ctx, new_ir_move(ctx, new_ir_temp(ctx, tmp, MOJOSHADER_AST_DATATYPE_BOOL, 1), new_ir_constbool(ctx, 1), -1), - new_ir_seq(ctx, new_ir_jump(ctx, join), - new_ir_seq(ctx, new_ir_label(ctx, f), - new_ir_seq(ctx, new_ir_move(ctx, new_ir_temp(ctx, tmp, MOJOSHADER_AST_DATATYPE_BOOL, 1), new_ir_constbool(ctx, 0), -1), - new_ir_label(ctx, join))))))))), - new_ir_temp(ctx, tmp, MOJOSHADER_AST_DATATYPE_BOOL, 1)); -} // build_ir_logical_and_or - -static inline MOJOSHADER_irExpression *build_ir_logical_and(Context *ctx, - const MOJOSHADER_astExpressionBinary *ast) -{ - // this needs to not evaluate (right) if (left) is false! - return build_ir_logical_and_or(ctx, ast, 1); -} // build_ir_logical_and - -static inline MOJOSHADER_irExpression *build_ir_logical_or(Context *ctx, - const MOJOSHADER_astExpressionBinary *ast) -{ - // this needs to not evaluate (right) if (left) is true! - return build_ir_logical_and_or(ctx, ast, 0); -} // build_ir_logical_or - -static inline MOJOSHADER_irStatement *build_ir_no_op(Context *ctx) -{ - return new_ir_label(ctx, generate_ir_label(ctx)); -} // build_ir_no_op - -static MOJOSHADER_irStatement *build_ir_ifstmt(Context *ctx, - const MOJOSHADER_astIfStatement *ast) -{ - assert(ast->expr->datatype->type == MOJOSHADER_AST_DATATYPE_BOOL); - - // !!! FIXME: ast->attributes? - - // IF statement without an ELSE. - if (ast->else_statement == NULL) - { - /* The gist... - cjump expr, t, join - t: - statement - join: - */ - - const int t = generate_ir_label(ctx); - const int join = generate_ir_label(ctx); - - return new_ir_seq(ctx, new_ir_cjump(ctx, MOJOSHADER_IR_COND_EQL, build_ir_expr(ctx, ast->expr), new_ir_constbool(ctx, 1), t, join), - new_ir_seq(ctx, new_ir_label(ctx, t), - new_ir_seq(ctx, build_ir_stmt(ctx, ast->statement), - new_ir_seq(ctx, new_ir_label(ctx, join), - build_ir_stmt(ctx, ast->next))))); - } // if - - // IF statement _with_ an ELSE. - /* The gist... - cjump expr, t, f - t: - statement - jump join - f: - elsestatement - join: - */ - - const int t = generate_ir_label(ctx); - const int f = generate_ir_label(ctx); - const int join = generate_ir_label(ctx); - - return new_ir_seq(ctx, new_ir_cjump(ctx, MOJOSHADER_IR_COND_EQL, build_ir_expr(ctx, ast->expr), new_ir_constbool(ctx, 1), t, f), - new_ir_seq(ctx, new_ir_label(ctx, t), - new_ir_seq(ctx, build_ir_stmt(ctx, ast->statement), - new_ir_seq(ctx, new_ir_jump(ctx, join), - new_ir_seq(ctx, new_ir_label(ctx, f), - new_ir_seq(ctx, build_ir_stmt(ctx, ast->else_statement), - new_ir_seq(ctx, new_ir_label(ctx, join), - build_ir_stmt(ctx, ast->next)))))))); -} // build_ir_ifstmt - - -static MOJOSHADER_irStatement *build_ir_forstmt(Context *ctx, - const MOJOSHADER_astForStatement *ast) -{ - // !!! FIXME: ast->unroll - - assert(ast->looptest->datatype->type == MOJOSHADER_AST_DATATYPE_BOOL); - - /* The gist... - initializer // (or var_decl->initializer!) - test: - cjump looptest == true, loop, join - loop: - statement - increment: // needs to be here; this is where "continue" jumps! - counter - jump test - join: - */ - - const int test = generate_ir_label(ctx); - const int loop = generate_ir_label(ctx); - - const LoopLabels *labels = push_ir_loop(ctx, 0); - if (labels == NULL) - return NULL; // out of memory... - - const int increment = labels->start; - const int join = labels->end; - - assert( (ast->var_decl && !ast->initializer) || - (!ast->var_decl && ast->initializer) ); - - MOJOSHADER_irStatement *init = NULL; - if (ast->var_decl != NULL) - { -//sdfsdf - // !!! FIXME: map the initializer to the variable? Need fix to var_decl parsing. -// new_ir_move(ctx, FIXME MAP TO REGISTER ast->var_decl->index, build_ir_expr(ctx, ast->fsdf)); -// FIXME -// init = build_ir_vardecl(ctx, ast->var_decl); - } // if - else - { -// init = build_ir_expr(ctx, ast->initializer); - } // else - - MOJOSHADER_irStatement *retval = - new_ir_seq(ctx, init, - new_ir_seq(ctx, new_ir_label(ctx, test), - new_ir_seq(ctx, new_ir_cjump(ctx, MOJOSHADER_IR_COND_EQL, build_ir_expr(ctx, ast->looptest), new_ir_constbool(ctx, 1), loop, join), - new_ir_seq(ctx, new_ir_label(ctx, loop), - new_ir_seq(ctx, build_ir_stmt(ctx, ast->statement), - new_ir_seq(ctx, new_ir_label(ctx, increment), - new_ir_seq(ctx, new_ir_expr_stmt(ctx, build_ir_expr(ctx, ast->counter)), - new_ir_seq(ctx, new_ir_jump(ctx, test), - new_ir_label(ctx, join))))))))); - - pop_ir_loop(ctx); - - return new_ir_seq(ctx, retval, build_ir_stmt(ctx, ast->next)); -} // build_ir_forstmt - -static MOJOSHADER_irStatement *build_ir_whilestmt(Context *ctx, - const MOJOSHADER_astWhileStatement *ast) -{ - // !!! FIXME: ast->unroll - - assert(ast->expr->datatype->type == MOJOSHADER_AST_DATATYPE_BOOL); - - /* The gist... - loop: - cjump expr == true, t, join - t: - statement - jump loop - join: - */ - - const LoopLabels *labels = push_ir_loop(ctx, 0); - if (labels == NULL) - return NULL; // out of memory... - - const int loop = labels->start; - const int t = generate_ir_label(ctx); - const int join = labels->end; - - MOJOSHADER_irStatement *retval = - new_ir_seq(ctx, new_ir_label(ctx, loop), - new_ir_seq(ctx, new_ir_cjump(ctx, MOJOSHADER_IR_COND_EQL, build_ir_expr(ctx, ast->expr), new_ir_constbool(ctx, 1), t, join), - new_ir_seq(ctx, new_ir_label(ctx, t), - new_ir_seq(ctx, build_ir_stmt(ctx, ast->statement), - new_ir_seq(ctx, new_ir_jump(ctx, loop), - new_ir_label(ctx, join)))))); - - pop_ir_loop(ctx); - - return new_ir_seq(ctx, retval, build_ir_stmt(ctx, ast->next)); -} // build_ir_whilestmt - -static MOJOSHADER_irStatement *build_ir_dostmt(Context *ctx, - const MOJOSHADER_astDoStatement *ast) -{ - // !!! FIXME: ast->unroll - - assert(ast->expr->datatype->type == MOJOSHADER_AST_DATATYPE_BOOL); - - /* The gist... - loop: - statement - cjump expr == true, loop, join - join: - */ - - const LoopLabels *labels = push_ir_loop(ctx, 0); - if (labels == NULL) - return NULL; // out of memory... - - const int loop = labels->start; - const int join = labels->end; - - MOJOSHADER_irStatement *retval = - new_ir_seq(ctx, new_ir_label(ctx, loop), - new_ir_seq(ctx, build_ir_stmt(ctx, ast->statement), - new_ir_seq(ctx, new_ir_cjump(ctx, MOJOSHADER_IR_COND_EQL, build_ir_expr(ctx, ast->expr), new_ir_constbool(ctx, 1), loop, join), - new_ir_label(ctx, join)))); - - pop_ir_loop(ctx); - - return new_ir_seq(ctx, retval, build_ir_stmt(ctx, ast->next)); -} // build_ir_dostmt - -static MOJOSHADER_irStatement *build_ir_switch(Context *ctx, const MOJOSHADER_astSwitchStatement *ast) -{ - // Dithering down to a list of if-statements in all cases - // isn't ideal, but we can't do jumptables in D3D bytecode. - - // !!! FIXME: attributes? - - /* The gist... - move tmp, expr - cjump tmp == case1expr, case1, testcase2 - testcase2: // etc - cjump tmp == case2expr, case2, join - case1: - case1stmt // might have a break in it somewhere. - case2: - case2stmt - join: - */ - - const LoopLabels *labels = push_ir_loop(ctx, 1); - if (labels == NULL) - return NULL; // out of memory... - - const int join = labels->end; - const int elems = datatype_elems(ctx, ast->expr->datatype); - const MOJOSHADER_astDataTypeType dt = datatype_base(ctx, ast->expr->datatype)->type; - - const MOJOSHADER_astSwitchCases *cases = ast->cases; - const int tmp = generate_ir_temp(ctx); - MOJOSHADER_irStatement *startseqs = new_ir_move(ctx, new_ir_temp(ctx, tmp, dt, elems), build_ir_expr(ctx, ast->expr), -1); - MOJOSHADER_irStatement *testseqs = startseqs; - MOJOSHADER_irStatement *startcaseseqs = NULL; - MOJOSHADER_irStatement *caseseqs = NULL; - while (cases) - { - const int t = generate_ir_label(ctx); - const int f = (cases->next == NULL) ? join : generate_ir_label(ctx); - MOJOSHADER_irStatement *cjump = new_ir_cjump(ctx, MOJOSHADER_IR_COND_EQL, build_ir_expr(ctx, cases->expr), new_ir_temp(ctx, tmp, dt, elems), t, f); - - if (cases->next == NULL) // last one, do the join label. - { - testseqs = new_ir_seq(ctx, testseqs, cjump); - caseseqs = new_ir_seq(ctx, caseseqs, new_ir_seq(ctx, new_ir_label(ctx, t), build_ir_stmt(ctx, cases->statement))); - caseseqs = new_ir_seq(ctx, caseseqs, new_ir_label(ctx, f)); - } // if - else - { - testseqs = new_ir_seq(ctx, testseqs, new_ir_seq(ctx, cjump, new_ir_label(ctx, f))); - caseseqs = new_ir_seq(ctx, caseseqs, new_ir_seq(ctx, new_ir_label(ctx, t), build_ir_stmt(ctx, cases->statement))); - } // else - - if (startcaseseqs == NULL) - startcaseseqs = caseseqs; - - cases = cases->next; - } // while - - pop_ir_loop(ctx); - - return new_ir_seq(ctx, startseqs, new_ir_seq(ctx, startcaseseqs, build_ir_stmt(ctx, ast->next))); -} // build_ir_switch - -static MOJOSHADER_irExpression *build_ir_increxpr(Context *ctx, const MOJOSHADER_astDataType *_dt, - const int val) -{ - const MOJOSHADER_astDataType *dt = reduce_datatype(ctx, _dt); - const MOJOSHADER_astDataTypeType type = datatype_base(ctx, dt)->type; - const int elems = datatype_elems(ctx, dt); - MOJOSHADER_irConstant *retval = (MOJOSHADER_irConstant *) new_ir_constant(ctx, type, elems); - int i; - - switch (type) - { - case MOJOSHADER_AST_DATATYPE_BOOL: - case MOJOSHADER_AST_DATATYPE_INT: - case MOJOSHADER_AST_DATATYPE_UINT: - for (i = 0; i < elems; i++) - retval->value.ival[i] = (int) val; - break; - - case MOJOSHADER_AST_DATATYPE_FLOAT: - case MOJOSHADER_AST_DATATYPE_FLOAT_SNORM: - case MOJOSHADER_AST_DATATYPE_FLOAT_UNORM: - case MOJOSHADER_AST_DATATYPE_HALF: - case MOJOSHADER_AST_DATATYPE_DOUBLE: - for (i = 0; i < elems; i++) - retval->value.fval[i] = (float) val; - break; - - default: - assert(0 && "Semantic analysis should have caught this!"); - } // switch - - return (MOJOSHADER_irExpression *) retval; -} // build_ir_increxpr - -static MOJOSHADER_irExpression *build_ir_preincdec(Context *ctx, MOJOSHADER_astExpressionUnary *ast, const MOJOSHADER_irBinOpType binop) -{ - /* The gist... - move expr, expr + 1 - return expr - */ - // !!! FIXME: can you writemask an increment operator? - MOJOSHADER_irExpression *constant = build_ir_increxpr(ctx, ast->datatype, 1); - return new_ir_eseq(ctx, - new_ir_move(ctx, - build_ir_expr(ctx, ast->operand), - new_ir_binop(ctx, binop, build_ir_expr(ctx, ast->operand), constant), -1), - build_ir_expr(ctx, ast->operand)); -} // build_ir_preincdec - -static MOJOSHADER_irExpression *build_ir_postincdec(Context *ctx, MOJOSHADER_astExpressionUnary *ast, const MOJOSHADER_irBinOpType binop) -{ - /* The gist... - move tmp, expr - move expr, expr + 1 - return tmp - */ - - // !!! FIXME: can you writemask an increment operator? - MOJOSHADER_irExpression *constant = build_ir_increxpr(ctx, ast->datatype, 1); - const int tmp = generate_ir_temp(ctx); - return new_ir_eseq(ctx, - new_ir_seq(ctx, - new_ir_move(ctx, new_ir_temp(ctx, tmp, constant->info.type, constant->info.elements), build_ir_expr(ctx, ast->operand), -1), - new_ir_move(ctx, build_ir_expr(ctx, ast->operand), - new_ir_binop(ctx, binop, build_ir_expr(ctx, ast->operand), constant), -1)), - new_ir_temp(ctx, tmp, constant->info.type, constant->info.elements)); -} // build_ir_postincdec - -static MOJOSHADER_irExpression *build_ir_convert(Context *ctx, const MOJOSHADER_astExpressionCast *ast) -{ - const MOJOSHADER_astDataType *dt = reduce_datatype(ctx, ast->datatype); - const MOJOSHADER_astDataTypeType type = datatype_base(ctx, dt)->type; - const int elems = datatype_elems(ctx, dt); - return new_ir_convert(ctx, build_ir_expr(ctx, ast->operand), type, elems); -} // build_ir_convert - -static MOJOSHADER_irExprList *build_ir_exprlist(Context *ctx, MOJOSHADER_astArguments *args) -{ - MOJOSHADER_irExprList *retval = NULL; - MOJOSHADER_irExprList *prev = NULL; - - while (args != NULL) - { - assert((retval && prev) || ((!retval) && (!prev))); - - MOJOSHADER_irExprList *item = new_ir_exprlist(ctx, build_ir_expr(ctx, args->argument)); - if (prev == NULL) - prev = retval = item; - else - prev->next = item; - - args = args->next; - } // while - - return retval; -} // build_ir_exprlist - -static MOJOSHADER_irExpression *build_ir_constructor(Context *ctx, const MOJOSHADER_astExpressionConstructor *ast) -{ - const MOJOSHADER_astDataType *dt = reduce_datatype(ctx, ast->datatype); - const MOJOSHADER_astDataTypeType type = datatype_base(ctx, dt)->type; - const int elems = datatype_elems(ctx, dt); - assert(elems <= 16); // just in case (matrix4x4 constructor is largest). - return new_ir_construct(ctx, build_ir_exprlist(ctx, ast->args), type, elems); -} // build_ir_constructor - -static MOJOSHADER_irExpression *build_ir_call(Context *ctx, const MOJOSHADER_astExpressionCallFunction *ast) -{ - const MOJOSHADER_astDataType *dt = reduce_datatype(ctx, ast->datatype); - const MOJOSHADER_astDataTypeType type = datatype_base(ctx, dt)->type; - const int elems = datatype_elems(ctx, dt); - return new_ir_call(ctx, ast->identifier->index, build_ir_exprlist(ctx, ast->args), type, elems); -} // build_ir_call - -static char swiz_to_channel(const char swiz) -{ - if ((swiz == 'r') || (swiz == 'x')) return 0; - if ((swiz == 'g') || (swiz == 'y')) return 1; - if ((swiz == 'b') || (swiz == 'z')) return 2; - if ((swiz == 'a') || (swiz == 'w')) return 3; - assert(0 && "Should have been caught by semantic analysis."); - return 0; -} // swiz_to_channel - -static MOJOSHADER_irExpression *build_ir_swizzle(Context *ctx, const MOJOSHADER_astExpressionDerefStruct *ast) -{ - const MOJOSHADER_astDataType *dt = reduce_datatype(ctx, ast->datatype); - const MOJOSHADER_astDataTypeType type = datatype_base(ctx, dt)->type; - const int elems = datatype_elems(ctx, dt); - char chans[4] = { 0, 0, 0, 0 }; - const char *swizstr = ast->member; - int i; - - for (i = 0; swizstr[i]; i++) - chans[i] = swiz_to_channel(swizstr[i]); - - return new_ir_swizzle(ctx, build_ir_expr(ctx, ast->identifier), chans, type, elems); -} // build_ir_swizzle - -static MOJOSHADER_irExpression *build_ir_identifier(Context *ctx, const MOJOSHADER_astExpressionIdentifier *ast) -{ - const MOJOSHADER_astDataType *dt = reduce_datatype(ctx, ast->datatype); - const MOJOSHADER_astDataTypeType type = datatype_base(ctx, dt)->type; - const int elems = datatype_elems(ctx, dt); - return new_ir_memory(ctx, ast->index, type, elems); -} // build_ir_identifier - -static MOJOSHADER_irExpression *build_ir_derefstruct(Context *ctx, const MOJOSHADER_astExpressionDerefStruct *ast) -{ - // There are only three possible IR nodes that contain a struct: - // an irTemp, an irMemory, or an irESeq that results in a temp or memory. - // As such, we figure out which it is, and offset appropriately for the - // member. - const MOJOSHADER_astDataType *dt = reduce_datatype(ctx, ast->datatype); - const MOJOSHADER_astDataTypeType type = datatype_base(ctx, dt)->type; - const int elems = datatype_elems(ctx, dt); - MOJOSHADER_irExpression *expr = build_ir_expr(ctx, ast->identifier); - MOJOSHADER_irExpression *finalexpr = expr; - - if (expr == NULL) - return NULL; - - assert(!ast->isswizzle); - - while (finalexpr->ir.type == MOJOSHADER_IR_ESEQ) - finalexpr = finalexpr->eseq.expr; - - if (finalexpr->ir.type == MOJOSHADER_IR_TEMP) - finalexpr->temp.index += ast->member_index; - else if (finalexpr->ir.type == MOJOSHADER_IR_MEMORY) - finalexpr->memory.index += ast->member_index; - else - assert(0 && "Unexpected condition"); - - // Replace the struct type with the type of the member. - expr->info.type = type; - expr->info.elements = elems; - - return expr; -} // build_ir_derefstruct - -static MOJOSHADER_irExpression *build_ir_derefarray(Context *ctx, const MOJOSHADER_astExpressionBinary *ast) -{ - // In most compilers, arrays dither down to offsets into memory, but - // they're somewhat special in D3D, since they might have to deal with - // vectors, etc...so we keep them as first-class citizens of the IR, - // and let the optimizer/codegen sort it out. - // !!! FIXME: this might be the wrong move. Maybe remove this IR node type? - const MOJOSHADER_astDataType *dt = reduce_datatype(ctx, ast->datatype); - const MOJOSHADER_astDataTypeType type = datatype_base(ctx, dt)->type; - const int elems = datatype_elems(ctx, dt); - - // !!! FIXME: Array dereference of a vector can become a simple swizzle operation, if we have a constant index. - // !!! FIXME: Matrix dereference of a vector can become a simple reference to a temp/memory, if we have a constant index. - return new_ir_array(ctx, build_ir_expr(ctx, ast->left), build_ir_expr(ctx, ast->right), type, elems); -} // build_ir_derefarray - -static MOJOSHADER_irExpression *build_ir_assign_binop(Context *ctx, - const MOJOSHADER_irBinOpType op, - const MOJOSHADER_astExpressionBinary *ast) -{ - MOJOSHADER_irExpression *lvalue = build_ir_expr(ctx, ast->left); - MOJOSHADER_irExpression *rvalue = build_ir_expr(ctx, ast->right); - const MOJOSHADER_astDataTypeType type = lvalue->info.type; - const int elems = lvalue->info.elements; - const int tmp = generate_ir_temp(ctx); - - // Semantic analysis should have inserted casts if necessary. - assert(type == rvalue->info.type); - assert(elems == rvalue->info.elements); - - // The destination must eventually be lvalue, which means memory or temp. - MOJOSHADER_irExpression *dst = lvalue; - while (dst->ir.type == MOJOSHADER_IR_ESEQ) - dst = dst->eseq.expr; - - if (dst->ir.type == MOJOSHADER_IR_TEMP) - dst = new_ir_temp(ctx, dst->temp.index, dst->info.type, dst->info.elements); - else if (dst->ir.type == MOJOSHADER_IR_MEMORY) - dst = new_ir_memory(ctx, dst->memory.index, dst->info.type, dst->info.elements); - else - assert(0 && "Unexpected condition"); - - // !!! FIXME: write masking! - return new_ir_eseq(ctx, - new_ir_seq(ctx, - new_ir_move(ctx, new_ir_temp(ctx, tmp, type, elems), new_ir_binop(ctx, op, lvalue, rvalue), -1), - new_ir_move(ctx, dst, new_ir_temp(ctx, tmp, type, elems), -1)), - new_ir_temp(ctx, tmp, type, elems)); -} // build_ir_assign_binop - -static MOJOSHADER_irExpression *build_ir_assign(Context *ctx, - const MOJOSHADER_astExpressionBinary *ast) -{ - MOJOSHADER_irExpression *lvalue = build_ir_expr(ctx, ast->left); - MOJOSHADER_irExpression *rvalue = build_ir_expr(ctx, ast->right); - const MOJOSHADER_astDataTypeType type = lvalue->info.type; - const int elems = lvalue->info.elements; - const int tmp = generate_ir_temp(ctx); - - // Semantic analysis should have inserted casts if necessary. - assert(type == rvalue->info.type); - assert(elems == rvalue->info.elements); - - // !!! FIXME: write masking! - // !!! FIXME: whole array/struct assignments need to become a sequence of moves. - return new_ir_eseq(ctx, - new_ir_seq(ctx, - new_ir_move(ctx, new_ir_temp(ctx, tmp, type, elems), rvalue, -1), - new_ir_move(ctx, lvalue, new_ir_temp(ctx, tmp, type, elems), -1)), - new_ir_temp(ctx, tmp, type, elems)); -} // build_ir_assign - - -// The AST must be perfect and normalized and sane here. If there are any -// strange corner cases, you should strive to handle them in semantic -// analysis, so conversion to IR can proceed with a minimum of drama. -static void *build_ir_internal(Context *ctx, void *_ast); -static inline MOJOSHADER_irNode *build_ir(Context *ctx, void *_ast) -{ - return (MOJOSHADER_irNode *) build_ir_internal(ctx, _ast); -} // build_ir - -static void *build_ir_internal(Context *ctx, void *_ast) -{ - if ((_ast == NULL) || (ctx->out_of_memory)) - return NULL; - - MOJOSHADER_astNode *ast = (MOJOSHADER_astNode *) _ast; - - // upkeep so we report correct error locations... - ctx->sourcefile = ast->ast.filename; - ctx->sourceline = ast->ast.line; - - switch (ast->ast.type) - { - case MOJOSHADER_AST_OP_PREINCREMENT: // !!! FIXME: sequence points? - return build_ir_preincdec(ctx, &ast->unary, MOJOSHADER_IR_BINOP_ADD); - - case MOJOSHADER_AST_OP_POSTINCREMENT: // !!! FIXME: sequence points? - return build_ir_postincdec(ctx, &ast->unary, MOJOSHADER_IR_BINOP_ADD); - - case MOJOSHADER_AST_OP_PREDECREMENT: // !!! FIXME: sequence points? - return build_ir_preincdec(ctx, &ast->unary, MOJOSHADER_IR_BINOP_SUBTRACT); - - case MOJOSHADER_AST_OP_POSTDECREMENT: // !!! FIXME: sequence points? - return build_ir_postincdec(ctx, &ast->unary, MOJOSHADER_IR_BINOP_SUBTRACT); - - case MOJOSHADER_AST_OP_COMPLEMENT: - return NEW_IR_BINOP(XOR, build_ir_expr(ctx, ast->unary.operand), - new_ir_constint(ctx, 0xFFFFFFFF)); - - case MOJOSHADER_AST_OP_NEGATE: // !!! FIXME: -0.0f != +0.0f - return NEW_IR_BINOP(SUBTRACT, build_ir_increxpr(ctx, ast->unary.datatype, -1), - build_ir_expr(ctx, ast->unary.operand)); - - case MOJOSHADER_AST_OP_NOT: // operand must be bool here! - assert(ast->unary.operand->datatype->type == MOJOSHADER_AST_DATATYPE_BOOL); - return NEW_IR_BINOP(XOR, build_ir_expr(ctx, ast->unary.operand), - new_ir_constint(ctx, 1)); - - case MOJOSHADER_AST_OP_DEREF_ARRAY: - return build_ir_derefarray(ctx, &ast->binary); - - case MOJOSHADER_AST_OP_DEREF_STRUCT: - if (ast->derefstruct.isswizzle) - return build_ir_swizzle(ctx, &ast->derefstruct); - return build_ir_derefstruct(ctx, &ast->derefstruct); - - case MOJOSHADER_AST_OP_COMMA: - // evaluate and throw away left, return right. - return new_ir_eseq(ctx, new_ir_expr_stmt(ctx, build_ir_expr(ctx, ast->binary.left)), - build_ir_expr(ctx, ast->binary.right)); - - case MOJOSHADER_AST_OP_LESSTHAN: return EASY_IR_COMPARE(LT); - case MOJOSHADER_AST_OP_GREATERTHAN: return EASY_IR_COMPARE(GT); - case MOJOSHADER_AST_OP_LESSTHANOREQUAL: return EASY_IR_COMPARE(LEQ); - case MOJOSHADER_AST_OP_GREATERTHANOREQUAL: return EASY_IR_COMPARE(GEQ); - case MOJOSHADER_AST_OP_NOTEQUAL: return EASY_IR_COMPARE(NEQ); - case MOJOSHADER_AST_OP_EQUAL: return EASY_IR_COMPARE(EQL); - - case MOJOSHADER_AST_OP_MULTIPLY: return EASY_IR_BINOP(MULTIPLY); - case MOJOSHADER_AST_OP_DIVIDE: return EASY_IR_BINOP(DIVIDE); - case MOJOSHADER_AST_OP_MODULO: return EASY_IR_BINOP(MODULO); - case MOJOSHADER_AST_OP_ADD: return EASY_IR_BINOP(ADD); - case MOJOSHADER_AST_OP_SUBTRACT: return EASY_IR_BINOP(SUBTRACT); - case MOJOSHADER_AST_OP_LSHIFT: return EASY_IR_BINOP(LSHIFT); - case MOJOSHADER_AST_OP_RSHIFT: return EASY_IR_BINOP(RSHIFT); - case MOJOSHADER_AST_OP_BINARYAND: return EASY_IR_BINOP(AND); - case MOJOSHADER_AST_OP_BINARYXOR: return EASY_IR_BINOP(XOR); - case MOJOSHADER_AST_OP_BINARYOR: return EASY_IR_BINOP(OR); - - case MOJOSHADER_AST_OP_LOGICALAND: - return build_ir_logical_and(ctx, &ast->binary); - - case MOJOSHADER_AST_OP_LOGICALOR: - return build_ir_logical_or(ctx, &ast->binary); - - case MOJOSHADER_AST_OP_ASSIGN: - return build_ir_assign(ctx, &ast->binary); - - case MOJOSHADER_AST_OP_MULASSIGN: return build_ir_assign_binop(ctx, MOJOSHADER_IR_BINOP_MULTIPLY, &ast->binary); - case MOJOSHADER_AST_OP_DIVASSIGN: return build_ir_assign_binop(ctx, MOJOSHADER_IR_BINOP_DIVIDE, &ast->binary); - case MOJOSHADER_AST_OP_MODASSIGN: return build_ir_assign_binop(ctx, MOJOSHADER_IR_BINOP_MODULO, &ast->binary); - case MOJOSHADER_AST_OP_ADDASSIGN: return build_ir_assign_binop(ctx, MOJOSHADER_IR_BINOP_ADD, &ast->binary); - case MOJOSHADER_AST_OP_SUBASSIGN: return build_ir_assign_binop(ctx, MOJOSHADER_IR_BINOP_SUBTRACT, &ast->binary); - case MOJOSHADER_AST_OP_LSHIFTASSIGN: return build_ir_assign_binop(ctx, MOJOSHADER_IR_BINOP_LSHIFT, &ast->binary); - case MOJOSHADER_AST_OP_RSHIFTASSIGN: return build_ir_assign_binop(ctx, MOJOSHADER_IR_BINOP_RSHIFT, &ast->binary); - case MOJOSHADER_AST_OP_ANDASSIGN: return build_ir_assign_binop(ctx, MOJOSHADER_IR_BINOP_AND, &ast->binary); - case MOJOSHADER_AST_OP_XORASSIGN: return build_ir_assign_binop(ctx, MOJOSHADER_IR_BINOP_XOR, &ast->binary); - case MOJOSHADER_AST_OP_ORASSIGN: return build_ir_assign_binop(ctx, MOJOSHADER_IR_BINOP_OR, &ast->binary); - - case MOJOSHADER_AST_OP_CONDITIONAL: - assert(ast->binary.left->datatype->type == MOJOSHADER_AST_DATATYPE_BOOL); - return build_ir_compare(ctx, MOJOSHADER_IR_COND_EQL, - build_ir_expr(ctx, ast->ternary.left), - new_ir_constbool(ctx, 1), - build_ir_expr(ctx, ast->ternary.center), - build_ir_expr(ctx, ast->ternary.right)); - - case MOJOSHADER_AST_OP_IDENTIFIER: - return build_ir_identifier(ctx, &ast->identifier); - - case MOJOSHADER_AST_OP_INT_LITERAL: - return new_ir_constint(ctx, ast->intliteral.value); - - case MOJOSHADER_AST_OP_FLOAT_LITERAL: - return new_ir_constfloat(ctx, ast->floatliteral.value); - - case MOJOSHADER_AST_OP_BOOLEAN_LITERAL: - return new_ir_constbool(ctx, ast->boolliteral.value); - - case MOJOSHADER_AST_OP_CALLFUNC: - return build_ir_call(ctx, &ast->callfunc); - - case MOJOSHADER_AST_OP_CONSTRUCTOR: - return build_ir_constructor(ctx, &ast->constructor); - - case MOJOSHADER_AST_OP_CAST: - return build_ir_convert(ctx, &ast->cast); - - case MOJOSHADER_AST_STATEMENT_BREAK: - { - const LoopLabels *labels = ctx->ir_loop; - assert(labels != NULL); // semantic analysis should catch this. - return new_ir_jump(ctx, labels->end); - } // case - - case MOJOSHADER_AST_STATEMENT_CONTINUE: - { - const LoopLabels *labels = ctx->ir_loop; - assert(labels != NULL); // semantic analysis should catch this. - return new_ir_jump(ctx, labels->start); - } // case - - case MOJOSHADER_AST_STATEMENT_DISCARD: - return new_ir_seq(ctx, new_ir_discard(ctx), build_ir_stmt(ctx, ast->discardstmt.next)); - - case MOJOSHADER_AST_STATEMENT_EMPTY: - return build_ir(ctx, ast->stmt.next); // skip it, do next thing. - - case MOJOSHADER_AST_STATEMENT_EXPRESSION: - return new_ir_seq(ctx, new_ir_expr_stmt(ctx, build_ir_expr(ctx, ast->exprstmt.expr)), build_ir_stmt(ctx, ast->exprstmt.next)); - - case MOJOSHADER_AST_STATEMENT_IF: - return build_ir_ifstmt(ctx, &ast->ifstmt); - - case MOJOSHADER_AST_STATEMENT_TYPEDEF: // ignore this, move on. - return build_ir(ctx, ast->typedefstmt.next); - - case MOJOSHADER_AST_STATEMENT_SWITCH: - return build_ir_switch(ctx, &ast->switchstmt); - - case MOJOSHADER_AST_STATEMENT_STRUCT: // ignore this, move on. - return build_ir(ctx, ast->structstmt.next); - - case MOJOSHADER_AST_STATEMENT_VARDECL: // ignore this, move on. - return build_ir(ctx, ast->vardeclstmt.next); - - case MOJOSHADER_AST_STATEMENT_BLOCK: - return new_ir_seq(ctx, build_ir_stmt(ctx, ast->blockstmt.statements), build_ir_stmt(ctx, ast->blockstmt.next)); - - case MOJOSHADER_AST_STATEMENT_FOR: - return build_ir_forstmt(ctx, &ast->forstmt); - - case MOJOSHADER_AST_STATEMENT_DO: - return build_ir_dostmt(ctx, &ast->dostmt); - - case MOJOSHADER_AST_STATEMENT_WHILE: - return build_ir_whilestmt(ctx, &ast->whilestmt); - - case MOJOSHADER_AST_STATEMENT_RETURN: - { - const int label = ctx->ir_end; - assert(label >= 0); // parser should have caught this! - MOJOSHADER_irStatement *retval = NULL; - if (ast->returnstmt.expr != NULL) - { - // !!! FIXME: whole array/struct returns need to move more into the temp. - const MOJOSHADER_astDataType *dt = reduce_datatype(ctx, ast->returnstmt.expr->datatype); - const MOJOSHADER_astDataTypeType type = datatype_base(ctx, dt)->type; - const int elems = datatype_elems(ctx, dt); - assert(ctx->ir_ret >= 0); - retval = new_ir_move(ctx, new_ir_temp(ctx, ctx->ir_ret, type, elems), build_ir_expr(ctx, ast->returnstmt.expr), -1); - } // if - return new_ir_seq(ctx, retval, new_ir_jump(ctx, label)); - } // case - - case MOJOSHADER_AST_COMPUNIT_TYPEDEF: - case MOJOSHADER_AST_COMPUNIT_STRUCT: - case MOJOSHADER_AST_COMPUNIT_VARIABLE: - case MOJOSHADER_AST_COMPUNIT_FUNCTION: - case MOJOSHADER_AST_ARGUMENTS: - case MOJOSHADER_AST_OP_STRING_LITERAL: - case MOJOSHADER_AST_SWITCH_CASE: - case MOJOSHADER_AST_SCALAR_OR_ARRAY: - case MOJOSHADER_AST_TYPEDEF: - case MOJOSHADER_AST_FUNCTION_PARAMS: - case MOJOSHADER_AST_FUNCTION_SIGNATURE: - case MOJOSHADER_AST_STRUCT_DECLARATION: - case MOJOSHADER_AST_STRUCT_MEMBER: - case MOJOSHADER_AST_VARIABLE_DECLARATION: - case MOJOSHADER_AST_ANNOTATION: - case MOJOSHADER_AST_PACK_OFFSET: - case MOJOSHADER_AST_VARIABLE_LOWLEVEL: - assert(0 && "Shouldn't hit this in build_ir."); - return NULL; - - default: - assert(0 && "unexpected type"); - return NULL; - } // switch -} // build_ir - -static void print_ir(FILE *io, unsigned int depth, void *_ir) -{ - MOJOSHADER_irNode *ir = (MOJOSHADER_irNode *) _ir; - if (ir == NULL) - return; - - const char *fname = strrchr(ir->ir.filename, '/'); - if (fname != NULL) - fname++; - else - { - fname = strrchr(ir->ir.filename, '\\'); - if (fname != NULL) - fname++; - else - fname = ir->ir.filename; - } // else - - int i; - for (i = 0; i < depth; i++) - fprintf(io, " "); - depth++; - - fprintf(io, "[ %s:%d ", fname, ir->ir.line); - - switch (ir->ir.type) - { - case MOJOSHADER_IR_LABEL: - fprintf(io, "LABEL %d ]\n", ir->stmt.label.index); - break; - - case MOJOSHADER_IR_CONSTANT: - fprintf(io, "CONSTANT "); - switch (ir->expr.constant.info.type) - { - case MOJOSHADER_AST_DATATYPE_BOOL: - case MOJOSHADER_AST_DATATYPE_INT: - case MOJOSHADER_AST_DATATYPE_UINT: - for (i = 0; i < ir->expr.constant.info.elements-1; i++) - fprintf(io, "%d, ", ir->expr.constant.value.ival[i]); - if (ir->expr.constant.info.elements > 0) - fprintf(io, "%d", ir->expr.constant.value.ival[i]); - break; - - case MOJOSHADER_AST_DATATYPE_FLOAT: - case MOJOSHADER_AST_DATATYPE_FLOAT_SNORM: - case MOJOSHADER_AST_DATATYPE_FLOAT_UNORM: - case MOJOSHADER_AST_DATATYPE_HALF: - case MOJOSHADER_AST_DATATYPE_DOUBLE: - for (i = 0; i < ir->expr.constant.info.elements-1; i++) - fprintf(io, "%ff, ", ir->expr.constant.value.fval[i]); - if (ir->expr.constant.info.elements > 0) - fprintf(io, "%ff", ir->expr.constant.value.fval[i]); - break; - - default: assert(0 && "shouldn't happen"); - } // switch - fprintf(io, " ]\n"); - break; - - case MOJOSHADER_IR_TEMP: - fprintf(io, "TEMP %d ]\n", ir->expr.temp.index); - break; - - case MOJOSHADER_IR_DISCARD: - fprintf(io, "DISCARD ]\n"); - break; - - case MOJOSHADER_IR_SWIZZLE: - fprintf(io, "SWIZZLE"); - for (i = 0; i < ir->expr.swizzle.info.elements-1; i++) - fprintf(io, " %d", (int) ir->expr.swizzle.channels[i]); - fprintf(io, " ]\n"); - print_ir(io, depth, ir->expr.swizzle.expr); - break; - - case MOJOSHADER_IR_CONSTRUCT: - fprintf(io, "CONSTRUCT ]\n"); - print_ir(io, depth, ir->expr.construct.args); - break; - - case MOJOSHADER_IR_CONVERT: - fprintf(io, "CONVERT ]\n"); - print_ir(io, depth, ir->expr.convert.expr); - break; - - case MOJOSHADER_IR_BINOP: - fprintf(io, "BINOP "); - switch (ir->expr.binop.op) - { - #define PRINT_IR_BINOP(x) \ - case MOJOSHADER_IR_BINOP_##x: fprintf(io, #x); break; - PRINT_IR_BINOP(ADD) - PRINT_IR_BINOP(SUBTRACT) - PRINT_IR_BINOP(MULTIPLY) - PRINT_IR_BINOP(DIVIDE) - PRINT_IR_BINOP(MODULO) - PRINT_IR_BINOP(AND) - PRINT_IR_BINOP(OR) - PRINT_IR_BINOP(XOR) - PRINT_IR_BINOP(LSHIFT) - PRINT_IR_BINOP(RSHIFT) - PRINT_IR_BINOP(UNKNOWN) - #undef PRINT_IR_BINOP - default: assert(0 && "unexpected case"); break; - } // switch - fprintf(io, " ]\n"); - print_ir(io, depth, ir->expr.binop.left); - print_ir(io, depth, ir->expr.binop.right); - break; - - case MOJOSHADER_IR_MEMORY: - fprintf(io, "MEMORY %d ]\n", ir->expr.memory.index); - break; - - case MOJOSHADER_IR_CALL: - fprintf(io, "CALL %d ]\n", ir->expr.call.index); - print_ir(io, depth, ir->expr.call.args); - break; - - case MOJOSHADER_IR_ESEQ: - fprintf(io, "ESEQ ]\n"); - print_ir(io, depth, ir->expr.eseq.stmt); - break; - - case MOJOSHADER_IR_ARRAY: - fprintf(io, "ARRAY ]\n"); - print_ir(io, depth, ir->expr.array.array); - print_ir(io, depth, ir->expr.array.element); - break; - - case MOJOSHADER_IR_MOVE: - fprintf(io, "MOVE ]\n"); - print_ir(io, depth, ir->stmt.move.dst); - print_ir(io, depth, ir->stmt.move.src); - break; - - case MOJOSHADER_IR_EXPR_STMT: - fprintf(io, "EXPRSTMT ]\n"); - print_ir(io, depth, ir->stmt.expr.expr); - break; - - case MOJOSHADER_IR_JUMP: - fprintf(io, "JUMP %d ]\n", ir->stmt.jump.label); - break; - - case MOJOSHADER_IR_CJUMP: - fprintf(io, "CJUMP "); - switch (ir->stmt.cjump.cond) - { - #define PRINT_IR_COND(x) \ - case MOJOSHADER_IR_COND_##x: fprintf(io, #x); break; - PRINT_IR_COND(EQL) - PRINT_IR_COND(NEQ) - PRINT_IR_COND(LT) - PRINT_IR_COND(GT) - PRINT_IR_COND(LEQ) - PRINT_IR_COND(GEQ) - PRINT_IR_COND(UNKNOWN) - #undef PRINT_IR_COND - default: assert(0 && "unexpected case"); break; - } // switch - fprintf(io, " %d %d ]\n", ir->stmt.cjump.iftrue, ir->stmt.cjump.iffalse); - print_ir(io, depth, ir->stmt.cjump.left); - print_ir(io, depth, ir->stmt.cjump.right); - break; - - case MOJOSHADER_IR_SEQ: - fprintf(io, "SEQ ]\n"); - print_ir(io, depth, ir->stmt.seq.first); - print_ir(io, depth, ir->stmt.seq.next); // !!! FIXME: don't recurse? - break; - - case MOJOSHADER_IR_EXPRLIST: - fprintf(io, "EXPRLIST ]\n"); - print_ir(io, depth, ir->misc.exprlist.expr); - print_ir(io, depth, ir->misc.exprlist.next); // !!! FIXME: don't recurse? - break; - - default: assert(0 && "unexpected IR node"); break; - } // switch -} // print_ir - -static void print_whole_ir(Context *ctx, FILE *io) -{ - if (ctx->ir != NULL) - { - int i; - for (i = 0; i <= ctx->user_func_index; i++) - { - printf("[FUNCTION %d ]\n", i); - print_ir(io, 1, ctx->ir[i]); - } // for - } // if -} // print_whole_ir - -static void delete_ir(Context *ctx, void *_ir) -{ - MOJOSHADER_irNode *ir = (MOJOSHADER_irNode *) _ir; - if (ir == NULL) - return; - - switch (ir->ir.type) - { - case MOJOSHADER_IR_JUMP: - case MOJOSHADER_IR_LABEL: - case MOJOSHADER_IR_CONSTANT: - case MOJOSHADER_IR_TEMP: - case MOJOSHADER_IR_DISCARD: - case MOJOSHADER_IR_MEMORY: - break; // nothing extra to free here. - - case MOJOSHADER_IR_BINOP: - delete_ir(ctx, ir->expr.binop.left); - delete_ir(ctx, ir->expr.binop.right); - break; - - case MOJOSHADER_IR_CALL: - delete_ir(ctx, ir->expr.call.args); - break; - - case MOJOSHADER_IR_ESEQ: - delete_ir(ctx, ir->expr.eseq.stmt); - delete_ir(ctx, ir->expr.eseq.expr); - break; - - case MOJOSHADER_IR_ARRAY: - delete_ir(ctx, ir->expr.array.array); - delete_ir(ctx, ir->expr.array.element); - break; - - case MOJOSHADER_IR_MOVE: - delete_ir(ctx, ir->stmt.move.dst); - delete_ir(ctx, ir->stmt.move.src); - break; - - case MOJOSHADER_IR_EXPR_STMT: - delete_ir(ctx, ir->stmt.expr.expr); - break; - - case MOJOSHADER_IR_CJUMP: - delete_ir(ctx, ir->stmt.cjump.left); - delete_ir(ctx, ir->stmt.cjump.right); - break; - - case MOJOSHADER_IR_SEQ: - delete_ir(ctx, ir->stmt.seq.first); - delete_ir(ctx, ir->stmt.seq.next); // !!! FIXME: don't recurse? - break; - - case MOJOSHADER_IR_EXPRLIST: - delete_ir(ctx, ir->misc.exprlist.expr); - delete_ir(ctx, ir->misc.exprlist.next); // !!! FIXME: don't recurse? - break; - - case MOJOSHADER_IR_SWIZZLE: - delete_ir(ctx, ir->expr.swizzle.expr); - break; - - case MOJOSHADER_IR_CONSTRUCT: - delete_ir(ctx, ir->expr.construct.args); - break; - - case MOJOSHADER_IR_CONVERT: - delete_ir(ctx, ir->expr.convert.expr); - break; - - default: assert(0 && "unexpected IR node"); break; - } // switch - - Free(ctx, ir); -} // delete_ir - -static void intermediate_representation(Context *ctx) -{ - const MOJOSHADER_astCompilationUnit *ast = NULL; - const MOJOSHADER_astCompilationUnitFunction *astfn = NULL; - const size_t arraylen = (ctx->user_func_index+1) * sizeof (MOJOSHADER_irStatement *); - - ctx->ir = (MOJOSHADER_irStatement**)Malloc(ctx, arraylen); - if (ctx->ir == NULL) - return; - memset(ctx->ir, '\0', arraylen); - - ctx->ir_end = -1; - ctx->ir_ret = -1; - - for (ast = &ctx->ast->compunit; ast != NULL; ast = ast->next) - { - assert(ast->ast.type > MOJOSHADER_AST_COMPUNIT_START_RANGE); - assert(ast->ast.type < MOJOSHADER_AST_COMPUNIT_END_RANGE); - if (ast->ast.type != MOJOSHADER_AST_COMPUNIT_FUNCTION) - continue; // only care about functions right now. - - astfn = (MOJOSHADER_astCompilationUnitFunction *) ast; - if (astfn->definition == NULL) // just a predeclare; skip. - continue; - - assert(ctx->ir_loop == NULL); // parser should have caught this! - assert(ctx->ir_end < 0); // parser should have caught this! - assert(ctx->ir_ret < 0); // parser should have caught this! - const int start = generate_ir_label(ctx); // !!! FIXME: store somewhere. - const int end = generate_ir_label(ctx); - ctx->ir_end = end; - - if (astfn->declaration->datatype != NULL) - ctx->ir_ret = generate_ir_temp(ctx); - - MOJOSHADER_irStatement *funcseq = new_ir_seq(ctx, new_ir_label(ctx, start), build_ir_stmt(ctx, astfn->definition)); - funcseq = new_ir_seq(ctx, funcseq, new_ir_label(ctx, end)); - assert(ctx->ir_loop == NULL); // parser should have caught this! - ctx->ir_end = -1; - ctx->ir_ret = -1; - - assert(astfn->index <= ctx->user_func_index); - assert(ctx->ir[astfn->index] == NULL); - ctx->ir[astfn->index] = funcseq; - } // for - - print_whole_ir(ctx, stdout); - - // done with the AST, nuke it. - // !!! FIXME: we're going to need CTAB data from this at some point. - delete_compilation_unit(ctx, (MOJOSHADER_astCompilationUnit *) ctx->ast); - ctx->ast = NULL; -} // intermediate_representation - - - -static MOJOSHADER_astData MOJOSHADER_out_of_mem_ast_data = { - 1, &MOJOSHADER_out_of_mem_error, 0, 0, 0, 0, 0, 0 -}; - - -// !!! FIXME: cut and paste from assembler. -static const MOJOSHADER_astData *build_failed_ast(Context *ctx) -{ - assert(isfail(ctx)); - - if (ctx->out_of_memory) - return &MOJOSHADER_out_of_mem_ast_data; - - MOJOSHADER_astData *retval = NULL; - retval = (MOJOSHADER_astData *) Malloc(ctx, sizeof (MOJOSHADER_astData)); - if (retval == NULL) - return &MOJOSHADER_out_of_mem_ast_data; - - memset(retval, '\0', sizeof (MOJOSHADER_astData)); - retval->source_profile = ctx->source_profile; - retval->malloc = (ctx->malloc == MOJOSHADER_internal_malloc) ? NULL : ctx->malloc; - retval->free = (ctx->free == MOJOSHADER_internal_free) ? NULL : ctx->free; - retval->malloc_data = ctx->malloc_data; - retval->error_count = errorlist_count(ctx->errors); - retval->errors = errorlist_flatten(ctx->errors); - - if (ctx->out_of_memory) - { - Free(ctx, retval); - return &MOJOSHADER_out_of_mem_ast_data; - } // if - - return retval; -} // build_failed_ast - - -static const MOJOSHADER_astData *build_astdata(Context *ctx) -{ - MOJOSHADER_astData *retval = NULL; - - if (ctx->out_of_memory) - return &MOJOSHADER_out_of_mem_ast_data; - - retval = (MOJOSHADER_astData *) Malloc(ctx, sizeof (MOJOSHADER_astData)); - if (retval == NULL) - return &MOJOSHADER_out_of_mem_ast_data; - - memset(retval, '\0', sizeof (MOJOSHADER_astData)); - retval->malloc = (ctx->malloc == MOJOSHADER_internal_malloc) ? NULL : ctx->malloc; - retval->free = (ctx->free == MOJOSHADER_internal_free) ? NULL : ctx->free; - retval->malloc_data = ctx->malloc_data; - - if (!isfail(ctx)) - { - retval->source_profile = ctx->source_profile; - retval->ast = ctx->ast; - } // if - - retval->error_count = errorlist_count(ctx->errors); - retval->errors = errorlist_flatten(ctx->errors); - if (ctx->out_of_memory) - { - Free(ctx, retval); - return &MOJOSHADER_out_of_mem_ast_data; - } // if - - retval->opaque = ctx; - - return retval; -} // build_astdata - - -static void choose_src_profile(Context *ctx, const char *srcprofile) -{ - ctx->source_profile = srcprofile; - - #define TEST_PROFILE(x) if (strcmp(srcprofile, x) == 0) { return; } - - TEST_PROFILE(MOJOSHADER_SRC_PROFILE_HLSL_VS_1_1); - TEST_PROFILE(MOJOSHADER_SRC_PROFILE_HLSL_VS_2_0); - TEST_PROFILE(MOJOSHADER_SRC_PROFILE_HLSL_VS_3_0); - TEST_PROFILE(MOJOSHADER_SRC_PROFILE_HLSL_PS_1_1); - TEST_PROFILE(MOJOSHADER_SRC_PROFILE_HLSL_PS_1_2); - TEST_PROFILE(MOJOSHADER_SRC_PROFILE_HLSL_PS_1_3); - TEST_PROFILE(MOJOSHADER_SRC_PROFILE_HLSL_PS_1_4); - TEST_PROFILE(MOJOSHADER_SRC_PROFILE_HLSL_PS_2_0); - TEST_PROFILE(MOJOSHADER_SRC_PROFILE_HLSL_PS_3_0); - - #undef TEST_PROFILE - - fail(ctx, "Unknown profile"); -} // choose_src_profile - - -static MOJOSHADER_compileData MOJOSHADER_out_of_mem_compile_data = { - 1, &MOJOSHADER_out_of_mem_error, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - - -// !!! FIXME: cut and paste from assembler. -static const MOJOSHADER_compileData *build_failed_compile(Context *ctx) -{ - assert(isfail(ctx)); - - MOJOSHADER_compileData *retval = NULL; - retval = (MOJOSHADER_compileData *) Malloc(ctx, sizeof (MOJOSHADER_compileData)); - if (retval == NULL) - return &MOJOSHADER_out_of_mem_compile_data; - - memset(retval, '\0', sizeof (MOJOSHADER_compileData)); - retval->malloc = (ctx->malloc == MOJOSHADER_internal_malloc) ? NULL : ctx->malloc; - retval->free = (ctx->free == MOJOSHADER_internal_free) ? NULL : ctx->free; - retval->malloc_data = ctx->malloc_data; - retval->source_profile = ctx->source_profile; - retval->error_count = errorlist_count(ctx->errors); - retval->errors = errorlist_flatten(ctx->errors); - retval->warning_count = errorlist_count(ctx->warnings); - retval->warnings = errorlist_flatten(ctx->warnings); - - if (ctx->out_of_memory) // in case something failed up there. - { - MOJOSHADER_freeCompileData(retval); - return &MOJOSHADER_out_of_mem_compile_data; - } // if - - return retval; -} // build_failed_compile - - -static const MOJOSHADER_compileData *build_compiledata(Context *ctx) -{ - assert(!isfail(ctx)); - - MOJOSHADER_compileData *retval = NULL; - - retval = (MOJOSHADER_compileData *) Malloc(ctx, sizeof (MOJOSHADER_compileData)); - if (retval == NULL) - return &MOJOSHADER_out_of_mem_compile_data; - - memset(retval, '\0', sizeof (MOJOSHADER_compileData)); - retval->malloc = (ctx->malloc == MOJOSHADER_internal_malloc) ? NULL : ctx->malloc; - retval->free = (ctx->free == MOJOSHADER_internal_free) ? NULL : ctx->free; - retval->malloc_data = ctx->malloc_data; - retval->source_profile = ctx->source_profile; - - if (!isfail(ctx)) - { - // !!! FIXME: build output and output_len here. - } // if - - if (!isfail(ctx)) - { - // !!! FIXME: build symbols and symbol_count here. - } // if - - retval->error_count = errorlist_count(ctx->errors); - retval->errors = errorlist_flatten(ctx->errors); - retval->warning_count = errorlist_count(ctx->warnings); - retval->warnings = errorlist_flatten(ctx->warnings); - - if (ctx->out_of_memory) // in case something failed up there. - { - MOJOSHADER_freeCompileData(retval); - return &MOJOSHADER_out_of_mem_compile_data; - } // if - - return retval; -} // build_compiledata - - -// API entry point... - -// !!! FIXME: move this (and a lot of other things) to mojoshader_ast.c. -const MOJOSHADER_astData *MOJOSHADER_parseAst(const char *srcprofile, - const char *filename, const char *source, - unsigned int sourcelen, - const MOJOSHADER_preprocessorDefine *defs, - unsigned int define_count, - MOJOSHADER_includeOpen include_open, - MOJOSHADER_includeClose include_close, - MOJOSHADER_malloc m, MOJOSHADER_free f, - void *d) -{ - const MOJOSHADER_astData *retval = NULL; - Context *ctx = NULL; - - if ( ((m == NULL) && (f != NULL)) || ((m != NULL) && (f == NULL)) ) - return &MOJOSHADER_out_of_mem_ast_data; // supply both or neither. - - ctx = build_context(m, f, d); - if (ctx == NULL) - return &MOJOSHADER_out_of_mem_ast_data; - - choose_src_profile(ctx, srcprofile); - - if (!isfail(ctx)) - { - parse_source(ctx, filename, source, sourcelen, defs, define_count, - include_open, include_close); - } // if - - if (!isfail(ctx)) - retval = build_astdata(ctx); // ctx isn't destroyed yet! - else - { - retval = (MOJOSHADER_astData *) build_failed_ast(ctx); - destroy_context(ctx); - } // else - - return retval; -} // MOJOSHADER_parseAst - - -void MOJOSHADER_freeAstData(const MOJOSHADER_astData *_data) -{ - MOJOSHADER_astData *data = (MOJOSHADER_astData *) _data; - if ((data == NULL) || (data == &MOJOSHADER_out_of_mem_ast_data)) - return; // no-op. - - // !!! FIXME: this needs to live for deleting the stringcache and the ast. - Context *ctx = (Context *) data->opaque; - MOJOSHADER_free f = (data->free == NULL) ? MOJOSHADER_internal_free : data->free; - void *d = data->malloc_data; - int i; - - // we don't f(data->source_profile), because that's internal static data. - - for (i = 0; i < data->error_count; i++) - { - f((void *) data->errors[i].error, d); - f((void *) data->errors[i].filename, d); - } // for - f((void *) data->errors, d); - - // don't delete data->ast (it'll delete with the context). - f(data, d); - - destroy_context(ctx); // finally safe to destroy this. -} // MOJOSHADER_freeAstData - - -const MOJOSHADER_compileData *MOJOSHADER_compile(const char *srcprofile, - const char *filename, const char *source, - unsigned int sourcelen, - const MOJOSHADER_preprocessorDefine *defs, - unsigned int define_count, - MOJOSHADER_includeOpen include_open, - MOJOSHADER_includeClose include_close, - MOJOSHADER_malloc m, MOJOSHADER_free f, - void *d) -{ - // !!! FIXME: cut and paste from MOJOSHADER_parseAst(). - MOJOSHADER_compileData *retval = NULL; - Context *ctx = NULL; - - if ( ((m == NULL) && (f != NULL)) || ((m != NULL) && (f == NULL)) ) - return &MOJOSHADER_out_of_mem_compile_data; // supply both or neither. - - ctx = build_context(m, f, d); - if (ctx == NULL) - return &MOJOSHADER_out_of_mem_compile_data; - - choose_src_profile(ctx, srcprofile); - - if (!isfail(ctx)) - { - parse_source(ctx, filename, source, sourcelen, defs, define_count, - include_open, include_close); - } // if - - if (!isfail(ctx)) - semantic_analysis(ctx); - - if (!isfail(ctx)) - intermediate_representation(ctx); - - if (isfail(ctx)) - retval = (MOJOSHADER_compileData *) build_failed_compile(ctx); - else - retval = (MOJOSHADER_compileData *) build_compiledata(ctx); - - destroy_context(ctx); - return retval; -} // MOJOSHADER_compile - - -void MOJOSHADER_freeCompileData(const MOJOSHADER_compileData *_data) -{ - MOJOSHADER_compileData *data = (MOJOSHADER_compileData *) _data; - if ((data == NULL) || (data == &MOJOSHADER_out_of_mem_compile_data)) - return; // no-op. - - MOJOSHADER_free f = (data->free == NULL) ? MOJOSHADER_internal_free : data->free; - void *d = data->malloc_data; - int i; - - // we don't f(data->source_profile), because that's internal static data. - - for (i = 0; i < data->error_count; i++) - { - f((void *) data->errors[i].error, d); - f((void *) data->errors[i].filename, d); - } // for - f((void *) data->errors, d); - - for (i = 0; i < data->warning_count; i++) - { - f((void *) data->warnings[i].error, d); - f((void *) data->warnings[i].filename, d); - } // for - f((void *) data->warnings, d); - - for (i = 0; i < data->symbol_count; i++) - { - f((void *) data->symbols[i].name, d); - // !!! FIXME: this is missing stuff (including freeing substructs). - } // for - f((void *) data->symbols, d); - - f((void *) data->output, d); - f(data, d); -} // MOJOSHADER_freeCompileData - -// end of mojoshader_compiler.c ... - diff --git a/mojoshader/mojoshader_d3d11.c b/mojoshader/mojoshader_d3d11.c new file mode 100644 index 0000000..be39b7c --- /dev/null +++ b/mojoshader/mojoshader_d3d11.c @@ -0,0 +1,1088 @@ +/** + * MojoShader; generate shader programs from bytecode of compiled + * Direct3D shaders. + * + * Please see the file LICENSE.txt in the source's root directory. + * + * This file written by Ryan C. Gordon. + */ + +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN 1 +#include // Include this early to avoid SDL conflicts +#endif + +#define __MOJOSHADER_INTERNAL__ 1 +#include "mojoshader_internal.h" + +#if SUPPORT_PROFILE_HLSL + +#define D3D11_NO_HELPERS +#define CINTERFACE +#define COBJMACROS +#include + +/* d3dcompiler DLL */ + +#ifndef WINAPI_FAMILY_WINRT +#define WINAPI_FAMILY_WINRT 0 +#endif +#if WINAPI_FAMILY_WINRT +#include +#elif defined(_WIN32) +#define LOAD_D3DCOMPILER LoadLibrary("d3dcompiler_47.dll") +#define UNLOAD_D3DCOMPILER(d) FreeLibrary(d) +#define LOAD_D3DCOMPILE(d) GetProcAddress(d, "D3DCompile") +#else +#define USING_VKD3D +#if defined(__APPLE__) +#define LOAD_D3DCOMPILER dlopen("libvkd3d-utils.1.dylib", RTLD_NOW|RTLD_LOCAL) +#else +#define LOAD_D3DCOMPILER dlopen("libvkd3d-utils.so.1", RTLD_NOW|RTLD_LOCAL) +#endif +#define UNLOAD_D3DCOMPILER(d) dlclose(d) +#define LOAD_D3DCOMPILE(d) dlsym(d, "D3DCompile") +#endif + +/* __stdcall declaration, largely taken from vkd3d_windows.h */ + +#ifdef _WIN32 +#define D3DCOMPILER_API WINAPI +#else +# ifdef __stdcall +# undef __stdcall +# endif +# ifdef __x86_64__ +# define __stdcall __attribute__((ms_abi)) +# else +# if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2)) || defined(__APPLE__) +# define __stdcall __attribute__((__stdcall__)) __attribute__((__force_align_arg_pointer__)) +# else +# define __stdcall __attribute__((__stdcall__)) +# endif +# endif +# define D3DCOMPILER_API __stdcall +#endif + +/* vkd3d uses stdcall for its ID3D10Blob implementation */ + +#ifdef USING_VKD3D +typedef struct VKD3DBlob VKD3DBlob; +typedef struct VKD3DBlobVtbl +{ + HRESULT (__stdcall *QueryInterface)( + VKD3DBlob *This, + REFIID riid, + void **ppvObject); + ULONG (__stdcall *AddRef)(VKD3DBlob *This); + ULONG (__stdcall *Release)(VKD3DBlob *This); + void * (__stdcall *GetBufferPointer)(VKD3DBlob *This); + SIZE_T (__stdcall *GetBufferSize)(VKD3DBlob *This); +} VKD3DBlobVtbl; +struct VKD3DBlob +{ + const VKD3DBlobVtbl *lpVtbl; +}; +#define ID3D10Blob VKD3DBlob +#define ID3DBlob VKD3DBlob +#endif // USING_VKD3D + +/* D3DCompile signature */ + +typedef HRESULT(D3DCOMPILER_API *PFN_D3DCOMPILE)( + LPCVOID pSrcData, + SIZE_T SrcDataSize, + LPCSTR pSourceName, + const D3D_SHADER_MACRO *pDefines, + ID3DInclude *pInclude, + LPCSTR pEntrypoint, + LPCSTR pTarget, + UINT Flags1, + UINT Flags2, + ID3DBlob **ppCode, + ID3DBlob **ppErrorMsgs +); + +// D3DCompile optimization can be overzealous and cause very visible bugs, +// so we disable it when compiling shaders to preserve correctness. +#define D3D_SKIP_OPT (1 << 2) + +/* Error state */ + +static char error_buffer[1024] = { '\0' }; + +static void set_error(const char *str) +{ + snprintf(error_buffer, sizeof (error_buffer), "%s", str); +} // set_error + +static inline void out_of_memory(void) +{ + set_error("out of memory"); +} // out_of_memory + +/* Structs */ + +typedef struct d3d11ShaderMap +{ + void *val; + union + { + struct + { + uint64 layoutHash; + ID3D10Blob *blob; + } vertex; + struct + { + MOJOSHADER_d3d11Shader *vshader; + } pixel; + }; +} d3d11ShaderMap; + +typedef struct MOJOSHADER_d3d11Shader +{ + const MOJOSHADER_parseData *parseData; + uint32 refcount; + ID3D11Buffer *ubo; + size_t buflen; + unsigned char *constantData; + unsigned int mapCapacity; + unsigned int numMaps; + d3d11ShaderMap *shaderMaps; +} MOJOSHADER_d3d11Shader; + +// Max entries for each register file type... +#define MAX_REG_FILE_F 8192 +#define MAX_REG_FILE_I 2047 +#define MAX_REG_FILE_B 2047 + +typedef struct MOJOSHADER_d3d11Context +{ + // Allocators... + MOJOSHADER_malloc malloc_fn; + MOJOSHADER_free free_fn; + void *malloc_data; + + // The constant register files... + // !!! FIXME: Man, it kills me how much memory this takes... + // !!! FIXME: ... make this dynamically allocated on demand. + float vs_reg_file_f[MAX_REG_FILE_F * 4]; + int vs_reg_file_i[MAX_REG_FILE_I * 4]; + uint8 vs_reg_file_b[MAX_REG_FILE_B]; + float ps_reg_file_f[MAX_REG_FILE_F * 4]; + int ps_reg_file_i[MAX_REG_FILE_I * 4]; + uint8 ps_reg_file_b[MAX_REG_FILE_B]; + + // Pointer to the active ID3D11Device. + ID3D11Device *device; + + // Pointer to the ID3D11DeviceContext. + ID3D11DeviceContext *deviceContext; + + // Currently bound vertex and pixel shaders. + MOJOSHADER_d3d11Shader *vertexShader; + MOJOSHADER_d3d11Shader *pixelShader; + int vertexNeedsBound; + int pixelNeedsBound; + + // D3DCompile function pointer. + PFN_D3DCOMPILE D3DCompileFunc; +#if !WINAPI_FAMILY_WINRT + HMODULE d3dcompilerDLL; +#endif +} MOJOSHADER_d3d11Context; + +/* Uniform buffer utilities */ + +static inline int next_highest_alignment(int n) +{ + const int align = 16; + return align * ((n + align - 1) / align); +} // next_highest_alignment + +static inline void *get_uniform_buffer(MOJOSHADER_d3d11Shader *shader) +{ + return (shader == NULL || shader->ubo == NULL) ? NULL : shader->ubo; +} // get_uniform_buffer + +static void update_uniform_buffer( + MOJOSHADER_d3d11Context *ctx, + MOJOSHADER_d3d11Shader *shader +) { + int i, j; + float *regF; int *regI; uint8 *regB; + int needsUpdate; + size_t offset; + int idx; + int arrayCount; + void *src, *dst; + size_t size; + int *vecDst; + + if (shader == NULL || shader->ubo == NULL) + return; + + if (shader->parseData->shader_type == MOJOSHADER_TYPE_VERTEX) + { + regF = ctx->vs_reg_file_f; + regI = ctx->vs_reg_file_i; + regB = ctx->vs_reg_file_b; + } // if + else + { + regF = ctx->ps_reg_file_f; + regI = ctx->ps_reg_file_i; + regB = ctx->ps_reg_file_b; + } // else + + // Update the buffer contents + needsUpdate = 0; + offset = 0; + for (i = 0; i < shader->parseData->uniform_count; i++) + { + if (shader->parseData->uniforms[i].constant) + continue; + + idx = shader->parseData->uniforms[i].index; + arrayCount = shader->parseData->uniforms[i].array_count; + + src = NULL; + dst = NULL; + size = arrayCount ? (arrayCount * 16) : 16; + + switch (shader->parseData->uniforms[i].type) + { + case MOJOSHADER_UNIFORM_FLOAT: + src = ®F[4 * idx]; + dst = shader->constantData + offset; + break; + + case MOJOSHADER_UNIFORM_INT: + src = ®I[4 * idx]; + dst = shader->constantData + offset; + break; + + case MOJOSHADER_UNIFORM_BOOL: + // bool registers are a whole other mess, thanks to alignment. + // The bool field is an int4 in HLSL 4+, so we have to cast the + // bool to an int, then skip 3 ints. Super efficient, right? + vecDst = (int*) (shader->constantData + offset); + j = 0; + do + { + if (vecDst[j * 4] != regB[idx + j]) + { + needsUpdate = 1; + vecDst[j * 4] = regB[idx + j]; + } // if + } while (++j < arrayCount); + + offset += size; + continue; // Skip the rest, do NOT break! + + default: + assert(0); // This should never happen. + break; + } // switch + + if (memcmp(dst, src, size) != 0) + { + memcpy(dst, src, size); + needsUpdate = 1; + } // if + + offset += size; + } // for + + if (needsUpdate) + { + // Map the buffer + D3D11_MAPPED_SUBRESOURCE res; + ID3D11DeviceContext_Map((ID3D11DeviceContext*) ctx->deviceContext, + (ID3D11Resource*) shader->ubo, 0, + D3D11_MAP_WRITE_DISCARD, 0, &res); + + // Copy the contents + memcpy(res.pData, shader->constantData, shader->buflen); + + // Unmap the buffer + ID3D11DeviceContext_Unmap( + (ID3D11DeviceContext*) ctx->deviceContext, + (ID3D11Resource*) shader->ubo, + 0 + ); + } // if +} // update_uniform_buffer + +static inline void expand_map( + MOJOSHADER_d3d11Context *ctx, + MOJOSHADER_d3d11Shader *shader +) { + if (shader->numMaps == shader->mapCapacity) + { + d3d11ShaderMap *newMap = (d3d11ShaderMap *) ctx->malloc_fn( + sizeof(d3d11ShaderMap) * shader->mapCapacity * 2, + ctx->malloc_data + ); + memcpy(newMap, shader->shaderMaps, + sizeof(d3d11ShaderMap) * shader->mapCapacity); + shader->mapCapacity *= 2; + ctx->free_fn(shader->shaderMaps, ctx->malloc_data); + shader->shaderMaps = newMap; + newMap = NULL; + } // if +} // expand_map + +static inline int element_is_uint(DXGI_FORMAT format) +{ + return format == DXGI_FORMAT_R32G32B32A32_UINT || + format == DXGI_FORMAT_R32G32B32_UINT || + format == DXGI_FORMAT_R16G16B16A16_UINT || + format == DXGI_FORMAT_R32G32_UINT || + format == DXGI_FORMAT_R10G10B10A2_UINT || + format == DXGI_FORMAT_R8G8B8A8_UINT || + format == DXGI_FORMAT_R16G16_UINT || + format == DXGI_FORMAT_R32_UINT || + format == DXGI_FORMAT_R8G8_UINT || + format == DXGI_FORMAT_R16_UINT || + format == DXGI_FORMAT_R8_UINT; +} // element_is_uint + +static inline int element_is_int(DXGI_FORMAT format) +{ + return format == DXGI_FORMAT_R32G32B32A32_SINT || + format == DXGI_FORMAT_R32G32B32_SINT || + format == DXGI_FORMAT_R16G16B16A16_SINT || + format == DXGI_FORMAT_R32G32_SINT || + format == DXGI_FORMAT_R8G8B8A8_SINT || + format == DXGI_FORMAT_R16G16_SINT || + format == DXGI_FORMAT_R32_SINT || + format == DXGI_FORMAT_R8G8_SINT || + format == DXGI_FORMAT_R16_SINT || + format == DXGI_FORMAT_R8_SINT; +} // element_is_int + +/* Shader Compilation Utilities */ + +static ID3D11VertexShader *compileVertexShader( + MOJOSHADER_d3d11Context *ctx, + MOJOSHADER_d3d11Shader *shader, + const char *src, + int src_len, + ID3D10Blob **blob +) { + const MOJOSHADER_parseData *pd = shader->parseData; + HRESULT result = ctx->D3DCompileFunc(src, src_len, pd->mainfn, + NULL, NULL, pd->mainfn, "vs_4_0", + D3D_SKIP_OPT, 0, blob, blob); + + if (result < 0) + { + set_error((const char *) ID3D10Blob_GetBufferPointer(*blob)); + ID3D10Blob_Release(*blob); + return NULL; + } // if + + void *bytecode = ID3D10Blob_GetBufferPointer(*blob); + int bytecodeLength = ID3D10Blob_GetBufferSize(*blob); + ID3D11VertexShader *ret = NULL; + ID3D11Device_CreateVertexShader(ctx->device, bytecode, bytecodeLength, + NULL, &ret); + return ret; +} // compileVertexShader + +static void replaceVarname( + MOJOSHADER_d3d11Context *ctx, + const char *find, + const char *replace, + const char **source +) { + const char *srcbuf = *source; + size_t find_len = strlen(find); + size_t replace_len = strlen(replace); + + #define IS_PARTIAL_TOKEN(token) \ + (isalnum(*(token + find_len)) || isalnum(*(token-1))) + + // How many times does `find` occur in the source buffer? + int count = 0; + char *ptr = (char *) strstr(srcbuf, find); + while (ptr != NULL) + { + if (!IS_PARTIAL_TOKEN(ptr)) + count++; + ptr = strstr(ptr + find_len, find); + } // while + + // How big should we make the new text buffer? + size_t oldlen = strlen(srcbuf) + 1; + size_t newlen = oldlen + (count * (replace_len - find_len)); + + // Easy case; just find/replace in the original buffer + if (newlen == oldlen) + { + ptr = (char *) strstr(srcbuf, find); + while (ptr != NULL) + { + if (!IS_PARTIAL_TOKEN(ptr)) + memcpy(ptr, replace, replace_len); + ptr = strstr(ptr + find_len, find); + } // while + return; + } // if + + // Allocate a new buffer + char *newbuf = (char *) ctx->malloc_fn(newlen, ctx->malloc_data); + memset(newbuf, '\0', newlen); + + // Find + replace + char *prev_ptr = (char *) srcbuf; + char *curr_ptr = (char *) newbuf; + ptr = (char*) strstr(srcbuf, find); + while (ptr != NULL) + { + memcpy(curr_ptr, prev_ptr, ptr - prev_ptr); + curr_ptr += ptr - prev_ptr; + + if (!IS_PARTIAL_TOKEN(ptr)) + { + memcpy(curr_ptr, replace, replace_len); + curr_ptr += replace_len; + } // if + else + { + // Don't accidentally eat partial tokens... + memcpy(curr_ptr, find, find_len); + curr_ptr += find_len; + } // else + + prev_ptr = ptr + find_len; + ptr = strstr(prev_ptr, find); + } // while + + #undef IS_PARTIAL_TOKEN + + // Copy the remaining part of the source buffer + memcpy(curr_ptr, prev_ptr, (srcbuf + oldlen) - prev_ptr); + + // Free the source buffer + ctx->free_fn((void *) srcbuf, ctx->malloc_data); + + // Point the source parameter to the new buffer + *source = newbuf; +} // replaceVarname + +static char *rewritePixelShader( + MOJOSHADER_d3d11Context *ctx, + MOJOSHADER_d3d11Shader *vshader, + MOJOSHADER_d3d11Shader *pshader +) { + const MOJOSHADER_parseData *vpd = vshader->parseData; + const MOJOSHADER_parseData *ppd = pshader->parseData; + const char *_Output = "_Output" ENDLINE_STR "{" ENDLINE_STR; + const char *_Input = "_Input" ENDLINE_STR "{" ENDLINE_STR; + const char *vsrc = vpd->output; + const char *psrc = ppd->output; + const char *a, *b, *vout, *pstart, *vface, *pend; + size_t substr_len; + char *pfinal; + + #define MAKE_STRBUF(buf) \ + substr_len = b - a; \ + buf = (const char *) ctx->malloc_fn(substr_len + 1, ctx->malloc_data); \ + memset((void *) buf, '\0', substr_len + 1); \ + memcpy((void *) buf, a, substr_len); + + // Copy the vertex function's output struct into a buffer + a = strstr(vsrc, _Output) + strlen(_Output); + b = a; + while (*(b++) != '}'); + b--; + MAKE_STRBUF(vout) + + // Split up the pixel shader text... + + // ...everything up to the input contents... + a = psrc; + b = strstr(psrc, _Input) + strlen(_Input); + MAKE_STRBUF(pstart) + + // ...everything after the input contents. + a = b; + while (*(a++) != '}'); + a--; + while (*(b++) != '\0'); + MAKE_STRBUF(pend) + + // Find matching semantics + int i, j; + int vfaceidx = -1; + const char *pvarname, *vvarname; + for (i = 0; i < ppd->attribute_count; i++) + { + int found_matching_vs_output_for_ps_input = 0; + for (j = 0; j < vpd->output_count; j++) + { + if (ppd->attributes[i].usage == vpd->outputs[j].usage && + ppd->attributes[i].index == vpd->outputs[j].index) + { + found_matching_vs_output_for_ps_input = 1; + pvarname = ppd->attributes[i].name; + vvarname = vpd->outputs[j].name; + if (strcmp(pvarname, vvarname) != 0) + replaceVarname(ctx, pvarname, vvarname, &pend); + } // if + else if (strcmp(ppd->attributes[i].name, "vPos") == 0 && + vpd->outputs[j].usage == MOJOSHADER_USAGE_POSITION && + vpd->outputs[j].index == 0) + { + found_matching_vs_output_for_ps_input = 1; + pvarname = ppd->attributes[i].name; + vvarname = vpd->outputs[j].name; + if (strcmp(pvarname, vvarname) != 0) + replaceVarname(ctx, pvarname, vvarname, &pend); + } // else if + } // for + + if (strcmp(ppd->attributes[i].name, "vFace") == 0) + vfaceidx = i; + + // A vertex shader that doesn't properly initialize all its outputs + // can produce a situation where vpd->outputs is missing a matching + // entry for the PS's inputs, even though fxc will happily compile + // both shaders together as a technique in FX mode + // I don't know how to fix this yet, but a workaround is to + // correct your shader to zero-initialize all its outputs -kg + assert(found_matching_vs_output_for_ps_input); + } // for + + // Special handling for VFACE + vface = (vfaceidx != -1) ? "\tbool m_vFace : SV_IsFrontFace;\n" : ""; + + // Concatenate the shader pieces together + substr_len = strlen(pstart) + strlen(vout) + strlen(vface) + strlen(pend); + pfinal = (char *) ctx->malloc_fn(substr_len + 1, ctx->malloc_data); + memset((void *) pfinal, '\0', substr_len + 1); + memcpy(pfinal, pstart, strlen(pstart)); + memcpy(pfinal + strlen(pstart), vout, strlen(vout)); + memcpy(pfinal + strlen(pstart) + strlen(vout), vface, strlen(vface)); + memcpy(pfinal + strlen(pstart) + strlen(vout) + strlen(vface), pend, strlen(pend)); + + // Free the temporary buffers + ctx->free_fn((void *) vout, ctx->malloc_data); + ctx->free_fn((void *) pstart, ctx->malloc_data); + ctx->free_fn((void *) pend, ctx->malloc_data); + + #undef MAKE_STRBUF + + return pfinal; +} // spliceVertexShaderInput + +static ID3D11PixelShader *compilePixelShader( + MOJOSHADER_d3d11Context *ctx, + MOJOSHADER_d3d11Shader *vshader, + MOJOSHADER_d3d11Shader *pshader +) { + ID3D11PixelShader *retval = NULL; + const char *source; + ID3DBlob *blob; + HRESULT result; + int needs_free; + + if (pshader->parseData->attribute_count > 0) + { + source = rewritePixelShader(ctx, vshader, pshader); + needs_free = 1; + } // if + else + { + source = pshader->parseData->output; + needs_free = 0; + } // else + + result = ctx->D3DCompileFunc(source, strlen(source), + pshader->parseData->mainfn, NULL, NULL, + pshader->parseData->mainfn, "ps_4_0", + D3D_SKIP_OPT, 0, &blob, &blob); + + if (needs_free) + ctx->free_fn((void *) source, ctx->malloc_data); + + if (result < 0) + { + set_error((const char *) ID3D10Blob_GetBufferPointer(blob)); + return NULL; + } // if + + ID3D11Device_CreatePixelShader(ctx->device, + ID3D10Blob_GetBufferPointer(blob), + ID3D10Blob_GetBufferSize(blob), + NULL, &retval); + + ID3D10Blob_Release(blob); + return retval; +} // compilePixelShader + +/* Public API */ + +MOJOSHADER_d3d11Context* MOJOSHADER_d3d11CreateContext( + void *device, + void *deviceContext, + MOJOSHADER_malloc m, + MOJOSHADER_free f, + void *malloc_d +) { + MOJOSHADER_d3d11Context *ctx; + PFN_D3DCOMPILE compileFunc; + +#if WINAPI_FAMILY_WINRT + compileFunc = D3DCompile; +#else + HMODULE compileDLL; + compileDLL = LOAD_D3DCOMPILER; + if (compileDLL == NULL) + return NULL; + compileFunc = (PFN_D3DCOMPILE) LOAD_D3DCOMPILE(compileDLL); + if (compileFunc == NULL) + { + UNLOAD_D3DCOMPILER(compileDLL); + return NULL; + } // if +#ifdef USING_VKD3D + unsigned int major, minor; + const char *(*vkd3d_shader_get_version)(unsigned int *, unsigned int *); + vkd3d_shader_get_version = (const char *(*)(unsigned int *, unsigned int *)) dlsym(compileDLL, "vkd3d_shader_get_version"); + if (vkd3d_shader_get_version == NULL) + { + UNLOAD_D3DCOMPILER(compileDLL); + return NULL; + } + vkd3d_shader_get_version(&major, &minor); + if (!((major > 1) || (major == 1 && minor >= 10))) + { + UNLOAD_D3DCOMPILER(compileDLL); + return NULL; + } +#endif +#endif + + if (m == NULL) m = MOJOSHADER_internal_malloc; + if (f == NULL) f = MOJOSHADER_internal_free; + + ctx = (MOJOSHADER_d3d11Context *) m(sizeof(MOJOSHADER_d3d11Context), malloc_d); + if (ctx == NULL) + { + out_of_memory(); + goto init_fail; + } // if + + memset(ctx, '\0', sizeof (MOJOSHADER_d3d11Context)); + ctx->malloc_fn = m; + ctx->free_fn = f; + ctx->malloc_data = malloc_d; + + // Store references to the D3D device and immediate context + ctx->device = (ID3D11Device*) device; + ctx->deviceContext = (ID3D11DeviceContext*) deviceContext; + + // Store the d3dcompiler info + ctx->D3DCompileFunc = compileFunc; +#if !WINAPI_FAMILY_WINRT + ctx->d3dcompilerDLL = compileDLL; +#endif + + return ctx; + +init_fail: + if (ctx != NULL) + f(ctx, malloc_d); + return NULL; +} // MOJOSHADER_d3d11CreateContext + +void MOJOSHADER_d3d11DestroyContext(MOJOSHADER_d3d11Context *ctx) +{ +#if !WINAPI_FAMILY_WINRT + UNLOAD_D3DCOMPILER(ctx->d3dcompilerDLL); +#endif + ctx->free_fn(ctx, ctx->malloc_data); +} // MOJOSHADER_d3d11DestroyContext + +MOJOSHADER_d3d11Shader *MOJOSHADER_d3d11CompileShader(MOJOSHADER_d3d11Context *ctx, + const char *mainfn, + const unsigned char *tokenbuf, + const unsigned int bufsize, + const MOJOSHADER_swizzle *swiz, + const unsigned int swizcount, + const MOJOSHADER_samplerMap *smap, + const unsigned int smapcount) +{ + MOJOSHADER_malloc m = ctx->malloc_fn; + MOJOSHADER_free f = ctx->free_fn; + void *d = ctx->malloc_data; + int i; + + const MOJOSHADER_parseData *pd = MOJOSHADER_parse("hlsl", mainfn, tokenbuf, + bufsize, swiz, swizcount, + smap, smapcount, m, f, d); + + if (pd->error_count > 0) + { + // !!! FIXME: put multiple errors in the buffer? Don't use + // !!! FIXME: MOJOSHADER_d3d11GetError() for this? + set_error(pd->errors[0].error); + goto compile_shader_fail; + } // if + + MOJOSHADER_d3d11Shader *retval = (MOJOSHADER_d3d11Shader *) m(sizeof(MOJOSHADER_d3d11Shader), d); + if (retval == NULL) + goto compile_shader_fail; + + retval->parseData = pd; + retval->refcount = 1; + retval->ubo = NULL; + retval->constantData = NULL; + retval->buflen = 0; + retval->numMaps = 0; + + // Allocate shader maps + retval->mapCapacity = 4; // arbitrary! + retval->shaderMaps = (d3d11ShaderMap *) m(retval->mapCapacity * sizeof(d3d11ShaderMap), d); + if (retval->shaderMaps == NULL) + goto compile_shader_fail; + + memset(retval->shaderMaps, '\0', retval->mapCapacity * sizeof(d3d11ShaderMap)); + + // Create the uniform buffer, if needed + if (pd->uniform_count > 0) + { + // Calculate how big we need to make the buffer + for (i = 0; i < pd->uniform_count; i++) + { + const int arrayCount = pd->uniforms[i].array_count; + retval->buflen += (arrayCount ? arrayCount : 1) * 16; + } // for + + D3D11_BUFFER_DESC bdesc; + bdesc.ByteWidth = next_highest_alignment(retval->buflen); + bdesc.Usage = D3D11_USAGE_DYNAMIC; + bdesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + bdesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + bdesc.MiscFlags = 0; + bdesc.StructureByteStride = 0; + ID3D11Device_CreateBuffer((ID3D11Device*) ctx->device, &bdesc, NULL, + (ID3D11Buffer**) &retval->ubo); + + // Additionally allocate a CPU-side staging buffer + retval->constantData = (unsigned char *) m(retval->buflen, d); + memset(retval->constantData, '\0', retval->buflen); + } // if + + return retval; + +compile_shader_fail: + MOJOSHADER_freeParseData(pd); + return NULL; +} // MOJOSHADER_d3d11CompileShader + +void MOJOSHADER_d3d11ShaderAddRef(MOJOSHADER_d3d11Shader *shader) +{ + if (shader != NULL) + shader->refcount++; +} // MOJOSHADER_d3d11ShaderAddRef + +void MOJOSHADER_d3d11DeleteShader( + MOJOSHADER_d3d11Context *ctx, + MOJOSHADER_d3d11Shader *shader +) { + if (shader != NULL) + { + if (shader->refcount > 1) + shader->refcount--; + else + { + if (shader->ubo != NULL) + { + ID3D11Buffer_Release((ID3D11Buffer*) shader->ubo); + ctx->free_fn(shader->constantData, ctx->malloc_data); + } // if + + if (shader->parseData->shader_type == MOJOSHADER_TYPE_VERTEX) + { + for (int i = 0; i < shader->numMaps; i++) + { + ID3D11VertexShader_Release((ID3D11VertexShader *) shader->shaderMaps[i].val); + ID3D10Blob_Release(shader->shaderMaps[i].vertex.blob); + } // for + } // if + else if (shader->parseData->shader_type == MOJOSHADER_TYPE_PIXEL) + { + for (int i = 0; i < shader->numMaps; i++) + ID3D11PixelShader_Release((ID3D11PixelShader *) shader->shaderMaps[i].val); + } // else if + + ctx->free_fn(shader->shaderMaps, ctx->malloc_data); + shader->shaderMaps = NULL; + MOJOSHADER_freeParseData(shader->parseData); + ctx->free_fn(shader, ctx->malloc_data); + } // else + } // if +} // MOJOSHADER_d3d11DeleteShader + +const MOJOSHADER_parseData *MOJOSHADER_d3d11GetShaderParseData( + MOJOSHADER_d3d11Shader *shader) +{ + return (shader != NULL) ? shader->parseData : NULL; +} // MOJOSHADER_d3d11GetParseData + +void MOJOSHADER_d3d11BindShaders( + MOJOSHADER_d3d11Context *ctx, + MOJOSHADER_d3d11Shader *vshader, + MOJOSHADER_d3d11Shader *pshader +) { + // Use the last bound shaders in case of NULL + if (vshader != NULL) + { + ctx->vertexShader = vshader; + ctx->vertexNeedsBound = 1; + } // if + + if (pshader != NULL) + { + ctx->pixelShader = pshader; + ctx->pixelNeedsBound = 1; + } // if +} // MOJOSHADER_d3d11BindShaders + +void MOJOSHADER_d3d11GetBoundShaders( + MOJOSHADER_d3d11Context *ctx, + MOJOSHADER_d3d11Shader **vshader, + MOJOSHADER_d3d11Shader **pshader +) { + *vshader = ctx->vertexShader; + *pshader = ctx->pixelShader; +} // MOJOSHADER_d3d11GetBoundShaders + +void MOJOSHADER_d3d11MapUniformBufferMemory( + MOJOSHADER_d3d11Context *ctx, + float **vsf, int **vsi, unsigned char **vsb, + float **psf, int **psi, unsigned char **psb +) { + *vsf = ctx->vs_reg_file_f; + *vsi = ctx->vs_reg_file_i; + *vsb = ctx->vs_reg_file_b; + *psf = ctx->ps_reg_file_f; + *psi = ctx->ps_reg_file_i; + *psb = ctx->ps_reg_file_b; +} // MOJOSHADER_d3d11MapUniformBufferMemory + +void MOJOSHADER_d3d11UnmapUniformBufferMemory(MOJOSHADER_d3d11Context *ctx) +{ + /* This has nothing to do with unmapping memory + * and everything to do with updating uniform + * buffers with the latest parameter contents. + */ + MOJOSHADER_d3d11Shader *vs, *ps; + MOJOSHADER_d3d11GetBoundShaders(ctx, &vs, &ps); + update_uniform_buffer(ctx, vs); + update_uniform_buffer(ctx, ps); +} // MOJOSHADER_d3d11UnmapUniformBufferMemory + +int MOJOSHADER_d3d11GetVertexAttribLocation(MOJOSHADER_d3d11Shader *vert, + MOJOSHADER_usage usage, int index) +{ + if (vert == NULL) + return -1; + + for (int i = 0; i < vert->parseData->attribute_count; i++) + { + if (vert->parseData->attributes[i].usage == usage && + vert->parseData->attributes[i].index == index) + { + return i; + } // if + } // for + + // failure, couldn't find requested attribute + return -1; +} // MOJOSHADER_d3d11GetVertexAttribLocation + +int MOJOSHADER_d3d11CompileVertexShader( + MOJOSHADER_d3d11Context *ctx, + unsigned long long inputLayoutHash, + void* elements, + int elementCount, + void **bytecode, + int *bytecodeLength +) { + MOJOSHADER_d3d11Shader *vshader = ctx->vertexShader; + ID3D11VertexShader *vs; + ID3D10Blob *blob; + + // Don't compile if there's already a mapping for this layout. + for (int i = 0; i < vshader->numMaps; i++) + { + if (inputLayoutHash == vshader->shaderMaps[i].vertex.layoutHash) + { + blob = vshader->shaderMaps[i].vertex.blob; + *bytecode = ID3D10Blob_GetBufferPointer(blob); + *bytecodeLength = ID3D10Blob_GetBufferSize(blob); + return 0; + } // if + } // for + + // Check for and replace non-float types + D3D11_INPUT_ELEMENT_DESC *d3dElements = (D3D11_INPUT_ELEMENT_DESC*) elements; + const char *origSource = vshader->parseData->output; + int srcLength = vshader->parseData->output_len; + char *newSource = (char*) origSource; + for (int i = 0; i < elementCount; i += 1) + { + D3D11_INPUT_ELEMENT_DESC e = d3dElements[i]; + + const char *replace; + if (element_is_uint(e.Format)) + replace = " uint4"; + else if (element_is_int(e.Format)) + replace = " int4"; + else + replace = NULL; + + if (replace != NULL) + { + char sem[16]; + memset(sem, '\0', sizeof(sem)); + snprintf(sem, sizeof(sem), "%s%d", e.SemanticName, e.SemanticIndex); + // !!! FIXME: POSITIONT has no index. What to do? -caleb + + if (newSource == origSource) + { + newSource = (char *) ctx->malloc_fn(srcLength + 1, + ctx->malloc_data); + strcpy(newSource, origSource); + } // if + + char *ptr = strstr(newSource, sem); + assert(ptr != NULL && "Could not find semantic in shader source!"); + + int spaces = 0; + while (spaces < 3) + if (*(--ptr) == ' ') spaces++; + memcpy(ptr - strlen("float4"), replace, strlen(replace)); + } // if + } // for + + vs = compileVertexShader(ctx, vshader, newSource, srcLength, &blob); + if (newSource != origSource) + { + ctx->free_fn((void *) newSource, ctx->malloc_data); + } // if + if (vs == NULL) + { + // Error was already set, just return + return -1; + } // if + + // Expand the map array, if needed + expand_map(ctx, vshader); + + // Add the new mapping + vshader->shaderMaps[vshader->numMaps].vertex.layoutHash = inputLayoutHash; + vshader->shaderMaps[ctx->vertexShader->numMaps].val = vs; + vshader->shaderMaps[ctx->vertexShader->numMaps].vertex.blob = blob; + ctx->vertexShader->numMaps++; + + // Return the bytecode info + *bytecode = ID3D10Blob_GetBufferPointer(blob); + *bytecodeLength = ID3D10Blob_GetBufferSize(blob); + return 0; +} // MOJOSHADER_d3d11CompileVertexShader + +int MOJOSHADER_d3d11ProgramReady( + MOJOSHADER_d3d11Context *ctx, + unsigned long long inputLayoutHash +) { + MOJOSHADER_d3d11Shader *vshader = ctx->vertexShader; + MOJOSHADER_d3d11Shader *pshader = ctx->pixelShader; + ID3D11VertexShader *realVS = NULL; + ID3D11PixelShader *realPS = NULL; + + // Vertex shader... + if (ctx->vertexNeedsBound) + { + for (int i = 0; i < vshader->numMaps; i++) + { + if (inputLayoutHash == vshader->shaderMaps[i].vertex.layoutHash) + { + realVS = (ID3D11VertexShader *) vshader->shaderMaps[i].val; + break; + } // if + } // for + + if (realVS == NULL) + { + set_error("Vertex shader was not found, did you call d3d11CompileVertexShader?"); + return -1; + } // if + + ctx->vertexNeedsBound = 0; + } // if + + // Pixel shader... + if (ctx->pixelNeedsBound) + { + // Is there already a mapping for the current vertex shader? + for (int i = 0; i < pshader->numMaps; i++) + { + if (pshader->shaderMaps[i].pixel.vshader == vshader) + { + realPS = (ID3D11PixelShader *) pshader->shaderMaps[i].val; + break; + } // if + } // for + + // We have to create a new vertex/pixel shader mapping... + if (realPS == NULL) + { + realPS = compilePixelShader(ctx, vshader, pshader); + + if (realPS == NULL) + { + // Error already set by compilePixelShader, just return + return -1; + } // if + + // Expand the map array, if needed + expand_map(ctx, pshader); + + // Add the new mapping + pshader->shaderMaps[pshader->numMaps].pixel.vshader = vshader; + pshader->shaderMaps[pshader->numMaps].val = realPS; + pshader->numMaps++; + } // if + } // if + + // Set shader state at the end, in case of errors above + if (realVS != NULL) + { + ID3D11DeviceContext_VSSetShader(ctx->deviceContext, realVS, NULL, 0); + ID3D11DeviceContext_VSSetConstantBuffers(ctx->deviceContext, 0, 1, + &vshader->ubo); + } // if + if (realPS != NULL) + { + ID3D11DeviceContext_PSSetShader(ctx->deviceContext, realPS, NULL, 0); + ID3D11DeviceContext_PSSetConstantBuffers(ctx->deviceContext, 0, 1, + &pshader->ubo); + } // if + return 0; +} // MOJOSHADER_d3d11ProgramReady + +const char *MOJOSHADER_d3d11GetError(MOJOSHADER_d3d11Context *ctx) +{ + return error_buffer; +} // MOJOSHADER_d3d11GetError + +#endif /* SUPPORT_PROFILE_HLSL */ + +// end of mojoshader_d3d11.c ... diff --git a/mojoshader/mojoshader_effects.c b/mojoshader/mojoshader_effects.c index d1a4b16..036f18d 100644 --- a/mojoshader/mojoshader_effects.c +++ b/mojoshader/mojoshader_effects.c @@ -10,12 +10,17 @@ #define __MOJOSHADER_INTERNAL__ 1 #include "mojoshader_internal.h" +#ifdef MOJOSHADER_EFFECT_SUPPORT + +#ifndef MOJOSHADER_USE_SDL_STDLIB #include +#endif /* MOJOSHADER_USE_SDL_STDLIB */ -DLLEXPORT -void MOJOSHADER_runPreshader(const MOJOSHADER_preshader *preshader, - const float *inregs, float *outregs) +static void run_preshader(const MOJOSHADER_preshader *preshader, + float *outregs) { + const float *inregs = preshader->registers; + // this is fairly straightforward, as there aren't any branching // opcodes in the preshader instruction set (at the moment, at least). const int scalarstart = (int) MOJOSHADER_PRESHADEROP_SCALAR_OPS; @@ -36,6 +41,17 @@ void MOJOSHADER_runPreshader(const MOJOSHADER_preshader *preshader, MOJOSHADER_preshaderInstruction *inst = preshader->instructions; int instit; +#if 0 // FIXME: Do we need to do this or is the compiler smart enough? + // Clear preshader output registers first! + for (instit = 0; instit < preshader->instruction_count; instit++, inst++) + { + const MOJOSHADER_preshaderOperand *operand = &inst->operands[inst->operand_count - 1]; + if (operand->type == MOJOSHADER_PRESHADEROPERAND_OUTPUT) + memset(&outregs[operand->index], '\0', sizeof(float) * 4); + } // for + inst = preshader->instructions; +#endif + for (instit = 0; instit < preshader->instruction_count; instit++, inst++) { const MOJOSHADER_preshaderOperand *operand = inst->operands; @@ -51,29 +67,37 @@ void MOJOSHADER_runPreshader(const MOJOSHADER_preshader *preshader, for (opiter = 0; opiter < inst->operand_count-1; opiter++, operand++) { const int isscalar = ((isscalarop) && (opiter == 0)); - unsigned int index = operand->index; + const unsigned int index = operand->index; switch (operand->type) { case MOJOSHADER_PRESHADEROPERAND_LITERAL: { - const double *lit = &preshader->literals[index]; - assert((index + elems) <= preshader->literal_count); if (!isscalar) - memcpy(&src[opiter][0], lit, elemsbytes); + { + assert((index + elems) <= preshader->literal_count); + memcpy(&src[opiter][0], &preshader->literals[index], elemsbytes); + } // if else { - const double val = *lit; for (elemiter = 0; elemiter < elems; elemiter++) - src[opiter][elemiter] = val; + src[opiter][elemiter] = preshader->literals[index]; } // else break; } // case case MOJOSHADER_PRESHADEROPERAND_INPUT: - if (operand->indexingType == 2) { - index = index+inregs[operand->indexingIndex]*4; - } - if (isscalar) + if (operand->array_register_count > 0) + { + int i; + const int *regsi = (const int *) inregs; + int arrIndex = regsi[((index >> 4) * 4) + ((index >> 2) & 3)]; + for (i = 0; i < operand->array_register_count; i++) + { + arrIndex = regsi[operand->array_registers[i] + arrIndex]; + } + src[opiter][0] = arrIndex; + } // if + else if (isscalar) src[opiter][0] = inregs[index]; else { @@ -162,6 +186,7 @@ void MOJOSHADER_runPreshader(const MOJOSHADER_preshader *preshader, final += src0[i] * src1[i]; for (i = 0; i < elems; i++) dst[i] = final; // !!! FIXME: is this right? + break; } // case default: @@ -183,11 +208,48 @@ void MOJOSHADER_runPreshader(const MOJOSHADER_preshader *preshader, outregs[operand->index + i] = (float) dst[i]; } // else } // for -} // MOJOSHADER_runPreshader +} // run_preshader static MOJOSHADER_effect MOJOSHADER_out_of_mem_effect = { 1, &MOJOSHADER_out_of_mem_error, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; +static MOJOSHADER_error MOJOSHADER_need_a_backend_error = { + "Need a MOJOSHADER_effectShaderContext", NULL, MOJOSHADER_POSITION_NONE +}; +static MOJOSHADER_effect MOJOSHADER_need_a_backend_effect = { + 1, &MOJOSHADER_need_a_backend_error, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; +static MOJOSHADER_error MOJOSHADER_unexpected_eof_error = { + "Unexpected EOF", NULL, MOJOSHADER_POSITION_NONE +}; +static MOJOSHADER_effect MOJOSHADER_unexpected_eof_effect = { + 1, &MOJOSHADER_unexpected_eof_error, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; +static MOJOSHADER_error MOJOSHADER_not_an_effect_error = { + "Not an Effects Framework binary", NULL, MOJOSHADER_POSITION_NONE +}; +static MOJOSHADER_effect MOJOSHADER_not_an_effect_effect = { + 1, &MOJOSHADER_not_an_effect_error, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static void push_errors(ErrorList *list, MOJOSHADER_error *errors, int len) +{ + int i; + for (i = 0; i < len; i += 1) + errorlist_add(list, errors[i].filename, errors[i].error_position, errors[i].error); +} // push_errors + +static void read_version_token(const uint8 **_ptr, uint32 *_len, uint16 *magic, uint8 *version_major, uint8 *version_minor) +{ + const uint32 *ptr = (const uint32 *) *_ptr; + const uint32 token = SWAP32(*ptr); + *_ptr += sizeof (token); + *_len -= sizeof (token); + + *magic = ((token >> 16) & 0xFFFF); + *version_major = (uint8) ((token >> 8) & 0xFF); + *version_minor = (uint8) (token & 0xFF); +} // read_version_token static uint32 readui32(const uint8 **_ptr, uint32 *_len) { @@ -204,424 +266,1704 @@ static uint32 readui32(const uint8 **_ptr, uint32 *_len) return retval; } // readui32 -// !!! FIXME: this is sort of a big, ugly function. -const MOJOSHADER_effect *MOJOSHADER_parseEffect(const char *profile, - const unsigned char *buf, - const unsigned int _len, - const MOJOSHADER_swizzle *swiz, - const unsigned int swizcount, - const MOJOSHADER_samplerMap *smap, - const unsigned int smapcount, - MOJOSHADER_malloc m, - MOJOSHADER_free f, - void *d) -{ - if ( ((m == NULL) && (f != NULL)) || ((m != NULL) && (f == NULL)) ) - return &MOJOSHADER_out_of_mem_effect; // supply both or neither. - - if (m == NULL) m = MOJOSHADER_internal_malloc; - if (f == NULL) f = MOJOSHADER_internal_free; - - MOJOSHADER_effect *retval = (MOJOSHADER_effect*)m(sizeof (MOJOSHADER_effect), d); - if (retval == NULL) - return &MOJOSHADER_out_of_mem_effect; // supply both or neither. - memset(retval, '\0', sizeof (*retval)); +static char *readstring(const uint8 *base, + const uint32 offset, + MOJOSHADER_malloc m, + void *d) +{ + // !!! FIXME: sanity checks! + // !!! FIXME: verify this doesn't go past EOF looking for a null. + uint8 *pair = (uint8 *) (base + offset); + const uint32 *lenptr = (const uint32 *) pair; + char *strptr = (char *) (pair + sizeof(uint32)); - retval->malloc = m; - retval->free = f; - retval->malloc_data = d; + const uint32 len = SWAP32(*lenptr); + char *result = NULL; - const uint8 *ptr = (const uint8 *) buf; - uint32 len = (uint32) _len; - size_t siz = 0; + if (len == 0) return NULL; /* No length? No string. */ + + result = (char *) m(len, d); + memcpy(result, strptr, len); + return result; +} // readstring + +static int findparameter(const MOJOSHADER_effectParam *params, + const uint32 param_count, + const char *name) +{ + int i; + for (i = 0; i < param_count; i++) + if (strcmp(name, params[i].value.name) == 0) + return i; + assert(0 && "Parameter not found!"); + return -1; +} + +static void readvalue(const uint8 *base, + const uint32 typeoffset, + const uint32 valoffset, + MOJOSHADER_effectValue *value, + MOJOSHADER_effectObject *objects, + MOJOSHADER_malloc m, + void *d) +{ int i, j, k; + const uint8 *typeptr = base + typeoffset; + const uint8 *valptr = base + valoffset; + unsigned int typelen = 9999999; // !!! FIXME + const uint32 type = readui32(&typeptr, &typelen); + const uint32 valclass = readui32(&typeptr, &typelen); + const uint32 name = readui32(&typeptr, &typelen); + const uint32 semantic = readui32(&typeptr, &typelen); + const uint32 numelements = readui32(&typeptr, &typelen); + + value->type.parameter_type = (MOJOSHADER_symbolType) type; + value->type.parameter_class = (MOJOSHADER_symbolClass) valclass; + value->name = readstring(base, name, m, d); + value->semantic = readstring(base, semantic, m, d); + value->type.elements = numelements; + + /* Class sanity check */ + assert(valclass >= MOJOSHADER_SYMCLASS_SCALAR && valclass <= MOJOSHADER_SYMCLASS_STRUCT); + + if (valclass == MOJOSHADER_SYMCLASS_SCALAR + || valclass == MOJOSHADER_SYMCLASS_VECTOR + || valclass == MOJOSHADER_SYMCLASS_MATRIX_ROWS + || valclass == MOJOSHADER_SYMCLASS_MATRIX_COLUMNS) + { + /* These classes only ever contain scalar values */ + assert(type >= MOJOSHADER_SYMTYPE_BOOL && type <= MOJOSHADER_SYMTYPE_FLOAT); + + const uint32 columncount = readui32(&typeptr, &typelen); + const uint32 rowcount = readui32(&typeptr, &typelen); + + value->type.columns = columncount; + value->type.rows = rowcount; + + uint32 siz = 4 * rowcount; + if (numelements > 0) + siz *= numelements; + value->value_count = siz; + siz *= 4; + value->values = m(siz, d); + memset(value->values, '\0', siz); + siz /= 16; + for (i = 0; i < siz; i++) + memcpy(value->valuesF + (i << 2), valptr + ((columncount << 2) * i), columncount << 2); + } // if + else if (valclass == MOJOSHADER_SYMCLASS_OBJECT) + { + /* This class contains either samplers or "objects" */ + assert(type >= MOJOSHADER_SYMTYPE_STRING && type <= MOJOSHADER_SYMTYPE_VERTEXSHADER); + + if (type == MOJOSHADER_SYMTYPE_SAMPLER + || type == MOJOSHADER_SYMTYPE_SAMPLER1D + || type == MOJOSHADER_SYMTYPE_SAMPLER2D + || type == MOJOSHADER_SYMTYPE_SAMPLER3D + || type == MOJOSHADER_SYMTYPE_SAMPLERCUBE) + { + unsigned int vallen = 9999999; // !!! FIXME + const uint32 numstates = readui32(&valptr, &vallen); - if (len < 8) - goto parseEffect_unexpectedEOF; + value->value_count = numstates; - const uint8 *base = NULL; - if (readui32(&ptr, &len) != 0xFEFF0901) // !!! FIXME: is this always magic? - goto parseEffect_notAnEffectsFile; - else + const uint32 siz = sizeof(MOJOSHADER_effectSamplerState) * numstates; + value->values = m(siz, d); + memset(value->values, '\0', siz); + + for (i = 0; i < numstates; i++) + { + MOJOSHADER_effectSamplerState *state = &value->valuesSS[i]; + const uint32 stype = readui32(&valptr, &vallen) & ~0xA0; + /*const uint32 FIXME =*/ readui32(&valptr, &vallen); + const uint32 statetypeoffset = readui32(&valptr, &vallen); + const uint32 statevaloffset = readui32(&valptr, &vallen); + + state->type = (MOJOSHADER_samplerStateType) stype; + readvalue(base, statetypeoffset, statevaloffset, + &state->value, objects, + m, d); + if (stype == MOJOSHADER_SAMP_TEXTURE) + objects[state->value.valuesI[0]].type = (MOJOSHADER_symbolType) type; + } // for + } // if + else + { + uint32 numobjects = 1; + if (numelements > 0) + numobjects = numelements; + + value->value_count = numobjects; + + const uint32 siz = 4 * numobjects; + value->values = m(siz, d); + memcpy(value->values, valptr, siz); + #if MOJOSHADER_BIG_ENDIAN + int valI; + for (valI=0;valI < (value->value_count);valI++) { + value->valuesI[valI] = SWAP32(value->valuesI[valI]); + } + #endif + for (i = 0; i < value->value_count; i++) + objects[value->valuesI[i]].type = (MOJOSHADER_symbolType) type; + } // else + } // else if + else if (valclass == MOJOSHADER_SYMCLASS_STRUCT) { - const uint32 offset = readui32(&ptr, &len); - base = ptr; -//printf("base offset == %u\n", offset); - if (offset > len) - goto parseEffect_unexpectedEOF; - ptr += offset; - len -= offset; - } // else + uint32 siz; - // params... + value->type.member_count = readui32(&typeptr, &typelen); + siz = value->type.member_count * sizeof (MOJOSHADER_symbolStructMember); + value->type.members = (MOJOSHADER_symbolStructMember *) m(siz, d); - if (len < 16) - goto parseEffect_unexpectedEOF; + uint32 structsize = 0; + for (i = 0; i < value->type.member_count; i++) + { + MOJOSHADER_symbolStructMember *mem = &value->type.members[i]; + + mem->info.parameter_type = (MOJOSHADER_symbolType) readui32(&typeptr, &typelen); + mem->info.parameter_class = (MOJOSHADER_symbolClass) readui32(&typeptr, &typelen); + + const uint32 memname = readui32(&typeptr, &typelen); + /*const uint32 memsemantic =*/ readui32(&typeptr, &typelen); + mem->name = readstring(base, memname, m, d); + + mem->info.elements = readui32(&typeptr, &typelen); + mem->info.columns = readui32(&typeptr, &typelen); + mem->info.rows = readui32(&typeptr, &typelen); + + // !!! FIXME: Nested structs! -flibit + assert(mem->info.parameter_class >= MOJOSHADER_SYMCLASS_SCALAR + && mem->info.parameter_class <= MOJOSHADER_SYMCLASS_MATRIX_COLUMNS); + assert(mem->info.parameter_type >= MOJOSHADER_SYMTYPE_BOOL + && mem->info.parameter_type <= MOJOSHADER_SYMTYPE_FLOAT); + mem->info.member_count = 0; + mem->info.members = NULL; + + uint32 memsize = 4 * mem->info.rows; + if (mem->info.elements > 0) + memsize *= mem->info.elements; + structsize += memsize; + } // for - const uint32 numparams = readui32(&ptr, &len); - const uint32 numtechniques = readui32(&ptr, &len); + value->type.columns = structsize; + value->type.rows = 1; + value->value_count = structsize; + if (numelements > 0) + value->value_count *= numelements; + + siz = value->value_count * 4; + value->values = m(siz, d); + memset(value->values, '\0', siz); + int dst_offset = 0, src_offset = 0; + i = 0; + do + { + for (j = 0; j < value->type.member_count; j++) + { + siz = value->type.members[j].info.rows * value->type.members[j].info.elements; + for (k = 0; k < siz; k++) + { + memcpy(value->valuesF + dst_offset, + typeptr + src_offset, /* Yes, typeptr. -flibit */ + value->type.members[j].info.columns << 2); + dst_offset += 4; + src_offset += value->type.members[j].info.columns << 2; + } // for + } + } while (++i < numelements); + } // else if +} // readvalue + +static void readannotations(const uint32 numannos, + const uint8 *base, + const uint8 **ptr, + uint32 *len, + MOJOSHADER_effectAnnotation **annotations, + MOJOSHADER_effectObject *objects, + MOJOSHADER_malloc m, + void *d) +{ + int i; + if (numannos == 0) return; - readui32(&ptr, &len); // !!! FIXME: there are 8 unknown bytes here. Annotations? - /*const uint32 numobjects = */ readui32(&ptr, &len); + const uint32 siz = sizeof(MOJOSHADER_effectAnnotation) * numannos; + *annotations = (MOJOSHADER_effectAnnotation *) m(siz, d); + memset(*annotations, '\0', siz); - if (numparams > 0) + for (i = 0; i < numannos; i++) { - siz = sizeof (MOJOSHADER_effectParam) * numparams; - retval->params = (MOJOSHADER_effectParam *) m(siz, d); - if (retval->params == NULL) - goto parseEffect_outOfMemory; - memset(retval->params, '\0', siz); + MOJOSHADER_effectAnnotation *anno = &(*annotations)[i]; - retval->param_count = numparams; + const uint32 typeoffset = readui32(ptr, len); + const uint32 valoffset = readui32(ptr, len); - for (i = 0; i < numparams; i++) - { - if (len < 16) - goto parseEffect_unexpectedEOF; + readvalue(base, typeoffset, valoffset, + anno, objects, + m, d); + } // for +} // readannotation + +static void readparameters(const uint32 numparams, + const uint8 *base, + const uint8 **ptr, + uint32 *len, + MOJOSHADER_effectParam **params, + MOJOSHADER_effectObject *objects, + MOJOSHADER_malloc m, + void *d) +{ + int i; + if (numparams == 0) return; - const uint32 typeoffset = readui32(&ptr, &len); - /*const uint32 valoffset =*/ readui32(&ptr, &len); - /*const uint32 flags =*/ readui32(&ptr, &len); - const uint32 numannos = readui32(&ptr, &len); - for (j = 0; j < numannos; j++) - { - if (len < 8) - goto parseEffect_unexpectedEOF; - // !!! FIXME: parse annotations. - readui32(&ptr, &len); - readui32(&ptr, &len); - } // for + uint32 siz = sizeof(MOJOSHADER_effectParam) * numparams; + *params = (MOJOSHADER_effectParam *) m(siz, d); + memset(*params, '\0', siz); - const uint8 *typeptr = base + typeoffset; - unsigned int typelen = 9999999; // !!! FIXME - /*const uint32 paramtype =*/ readui32(&typeptr, &typelen); - /*const uint32 paramclass =*/ readui32(&typeptr, &typelen); - const uint32 paramname = readui32(&typeptr, &typelen); - const uint32 paramsemantic = readui32(&typeptr, &typelen); - - // !!! FIXME: sanity checks! - const char *namestr = ((const char *) base) + paramname; - const char *semstr = ((const char *) base) + paramsemantic; - uint32 len; - char *strptr; - len = *((const uint32 *) namestr); - strptr = (char *) m(len + 1, d); - memcpy(strptr, namestr + 4, len); - strptr[len] = '\0'; - retval->params[i].name = strptr; - len = *((const uint32 *) semstr); - strptr = (char *) m(len + 1, d); - memcpy(strptr, semstr + 4, len); - strptr[len] = '\0'; - retval->params[i].semantic = strptr; - } // for - } // if + for (i = 0; i < numparams; i++) + { + MOJOSHADER_effectParam *param = &(*params)[i]; + + const uint32 typeoffset = readui32(ptr, len); + const uint32 valoffset = readui32(ptr, len); + /*const uint32 flags =*/ readui32(ptr, len); + const uint32 numannos = readui32(ptr, len); + + param->annotation_count = numannos; + readannotations(numannos, base, ptr, len, + ¶m->annotations, objects, + m, d); - uint32 numshaders = 0; // we'll calculate this later. + readvalue(base, typeoffset, valoffset, + ¶m->value, objects, + m, d); + } // for +} // readparameters + +static void readstates(const uint32 numstates, + const uint8 *base, + const uint8 **ptr, + uint32 *len, + MOJOSHADER_effectState **states, + MOJOSHADER_effectObject *objects, + MOJOSHADER_malloc m, + void *d) +{ + int i; + if (numstates == 0) return; - // techniques... + const uint32 siz = sizeof (MOJOSHADER_effectState) * numstates; + *states = (MOJOSHADER_effectState *) m(siz, d); + memset(*states, '\0', siz); - if (numtechniques > 0) + for (i = 0; i < numstates; i++) { - siz = sizeof (MOJOSHADER_effectTechnique) * numtechniques; - retval->techniques = (MOJOSHADER_effectTechnique *) m(siz, d); - if (retval->techniques == NULL) - goto parseEffect_outOfMemory; - memset(retval->techniques, '\0', siz); + MOJOSHADER_effectState *state = &(*states)[i]; - retval->technique_count = numtechniques; + const uint32 type = readui32(ptr, len); + /*const uint32 FIXME =*/ readui32(ptr, len); + const uint32 typeoffset = readui32(ptr, len); + const uint32 valoffset = readui32(ptr, len); - for (i = 0; i < numtechniques; i++) - { - if (len < 12) - goto parseEffect_unexpectedEOF; - - MOJOSHADER_effectTechnique *technique = &retval->techniques[i]; + state->type = (MOJOSHADER_renderStateType) type; + readvalue(base, typeoffset, valoffset, + &state->value, objects, + m, d); + } // for +} // readstates + +static void readpasses(const uint32 numpasses, + const uint8 *base, + const uint8 **ptr, + uint32 *len, + MOJOSHADER_effectPass **passes, + MOJOSHADER_effectObject *objects, + MOJOSHADER_malloc m, + void *d) +{ + int i; + if (numpasses == 0) return; + + const uint32 siz = sizeof (MOJOSHADER_effectPass) * numpasses; + *passes = (MOJOSHADER_effectPass *) m(siz, d); + memset(*passes, '\0', siz); + + for (i = 0; i < numpasses; i++) + { + MOJOSHADER_effectPass *pass = &(*passes)[i]; + + const uint32 passnameoffset = readui32(ptr, len); + const uint32 numannos = readui32(ptr, len); + const uint32 numstates = readui32(ptr, len); - const uint32 nameoffset = readui32(&ptr, &len); - const uint32 numannos = readui32(&ptr, &len); - const uint32 numpasses = readui32(&ptr, &len); + pass->name = readstring(base, passnameoffset, m, d); - if (nameoffset >= _len) - goto parseEffect_unexpectedEOF; + pass->annotation_count = numannos; + readannotations(numannos, base, ptr, len, + &pass->annotations, objects, + m, d); - if (numannos > 0) + pass->state_count = numstates; + readstates(numstates, base, ptr, len, + &pass->states, objects, + m, d); + } // for +} // readpasses + +static void readtechniques(const uint32 numtechniques, + const uint8 *base, + const uint8 **ptr, + uint32 *len, + MOJOSHADER_effectTechnique **techniques, + MOJOSHADER_effectObject *objects, + MOJOSHADER_malloc m, + void *d) +{ + int i; + if (numtechniques == 0) return; + + const uint32 siz = sizeof (MOJOSHADER_effectTechnique) * numtechniques; + *techniques = (MOJOSHADER_effectTechnique *) m(siz, d); + memset(*techniques, '\0', siz); + + for (i = 0; i < numtechniques; i++) + { + MOJOSHADER_effectTechnique *technique = &(*techniques)[i]; + + const uint32 nameoffset = readui32(ptr, len); + const uint32 numannos = readui32(ptr, len); + const uint32 numpasses = readui32(ptr, len); + + technique->name = readstring(base, nameoffset, m, d); + + technique->annotation_count = numannos; + readannotations(numannos, base, ptr, len, + &technique->annotations, objects, + m, d); + + technique->pass_count = numpasses; + readpasses(numpasses, base, ptr, len, + &technique->passes, objects, + m, d); + } // for +} // readtechniques + +static void readsmallobjects(const uint32 numsmallobjects, + const uint8 **ptr, + uint32 *len, + MOJOSHADER_effect *effect, + const MOJOSHADER_swizzle *swiz, + const unsigned int swizcount, + const MOJOSHADER_samplerMap *smap, + const unsigned int smapcount, + ErrorList *errors) +{ + int i, j; + MOJOSHADER_parseData *pd; + MOJOSHADER_malloc m = effect->ctx.m; + void *d = effect->ctx.malloc_data; + + if (numsmallobjects == 0) return; + + for (i = 1; i < numsmallobjects + 1; i++) + { + const uint32 index = readui32(ptr, len); + const uint32 length = readui32(ptr, len); + + MOJOSHADER_effectObject *object = &effect->objects[index]; + if (object->type == MOJOSHADER_SYMTYPE_STRING) + { + if (length > 0) { - // !!! FIXME: expose these to the caller? - for (j = 0; j < numannos; j++) + char *str = (char *) m(length, d); + memcpy(str, *ptr, length); + object->string.string = str; + } // if + } // if + else if (object->type == MOJOSHADER_SYMTYPE_TEXTURE + || object->type == MOJOSHADER_SYMTYPE_TEXTURE1D + || object->type == MOJOSHADER_SYMTYPE_TEXTURE2D + || object->type == MOJOSHADER_SYMTYPE_TEXTURE3D + || object->type == MOJOSHADER_SYMTYPE_TEXTURECUBE + || object->type == MOJOSHADER_SYMTYPE_SAMPLER + || object->type == MOJOSHADER_SYMTYPE_SAMPLER1D + || object->type == MOJOSHADER_SYMTYPE_SAMPLER2D + || object->type == MOJOSHADER_SYMTYPE_SAMPLER3D + || object->type == MOJOSHADER_SYMTYPE_SAMPLERCUBE) + { + if (length > 0) + { + char *str = (char *) m(length, d); + memcpy(str, *ptr, length); + object->mapping.name = str; + } // if + } // else if + else if (object->type == MOJOSHADER_SYMTYPE_PIXELSHADER + || object->type == MOJOSHADER_SYMTYPE_VERTEXSHADER) + { + char mainfn[32]; + snprintf(mainfn, sizeof(mainfn), "ShaderFunction%u", (unsigned int) index); + object->shader.technique = -1; + object->shader.pass = -1; + object->shader.shader = effect->ctx.compileShader(effect->ctx.shaderContext, + mainfn, *ptr, length, + swiz, swizcount, + smap, smapcount); + if (object->shader.shader == NULL) + { + // Bail ASAP, so we can get the error to the application + errorlist_add(errors, NULL, 0, effect->ctx.getError(effect->ctx.shaderContext)); + return; + } // if + pd = effect->ctx.getParseData(object->shader.shader); + if (pd->error_count > 0) + { + // Bail ASAP, so we can get the error to the application + push_errors(errors, pd->errors, pd->error_count); + return; + } // if + + for (j = 0; j < pd->symbol_count; j++) + if (pd->symbols[j].register_set == MOJOSHADER_SYMREGSET_SAMPLER) + object->shader.sampler_count++; + object->shader.param_count = pd->symbol_count; + object->shader.params = (uint32 *) m(object->shader.param_count * sizeof (uint32), d); + object->shader.samplers = (MOJOSHADER_samplerStateRegister *) m(object->shader.sampler_count * sizeof (MOJOSHADER_samplerStateRegister), d); + uint32 curSampler = 0; + for (j = 0; j < pd->symbol_count; j++) + { + int par = findparameter(effect->params, + effect->param_count, + pd->symbols[j].name); + object->shader.params[j] = par; + if (pd->symbols[j].register_set == MOJOSHADER_SYMREGSET_SAMPLER) + { + object->shader.samplers[curSampler].sampler_name = effect->params[par].value.name; + object->shader.samplers[curSampler].sampler_register = pd->symbols[j].register_index; + object->shader.samplers[curSampler].sampler_state_count = effect->params[par].value.value_count; + object->shader.samplers[curSampler].sampler_states = effect->params[par].value.valuesSS; + curSampler++; + } // if + } // for + if (pd->preshader) + { + object->shader.preshader_param_count = pd->preshader->symbol_count; + object->shader.preshader_params = (uint32 *) m(object->shader.preshader_param_count * sizeof (uint32), d); + for (j = 0; j < pd->preshader->symbol_count; j++) { - if (len < 8) - goto parseEffect_unexpectedEOF; - readui32(&ptr, &len); // typedef offset - readui32(&ptr, &len); // value offset + object->shader.preshader_params[j] = findparameter(effect->params, + effect->param_count, + pd->preshader->symbols[j].name); } // for } // if + } // else if + else + { + assert(0 && "Small object type unknown!"); + } // else - // !!! FIXME: verify this doesn't go past EOF looking for a null. + /* Object block is always a multiple of four */ + const uint32 blocklen = (length + 3) - ((length - 1) % 4); + *ptr += blocklen; + *len -= blocklen; + } // for +} // readstrings + +static void readlargeobjects(const uint32 numlargeobjects, + const uint32 numsmallobjects, + const uint8 **ptr, + uint32 *len, + MOJOSHADER_effect *effect, + const MOJOSHADER_swizzle *swiz, + const unsigned int swizcount, + const MOJOSHADER_samplerMap *smap, + const unsigned int smapcount, + ErrorList *errors) +{ + int i, j; + MOJOSHADER_parseData *pd; + MOJOSHADER_malloc m = effect->ctx.m; + MOJOSHADER_free f = effect->ctx.f; + void *d = effect->ctx.malloc_data; + + if (numlargeobjects == 0) return; + + int numobjects = numsmallobjects + numlargeobjects + 1; + for (i = numsmallobjects + 1; i < numobjects; i++) + { + const uint32 technique = readui32(ptr, len); + const uint32 index = readui32(ptr, len); + /*const uint32 FIXME =*/ readui32(ptr, len); + const uint32 state = readui32(ptr, len); + const uint32 type = readui32(ptr, len); + const uint32 length = readui32(ptr, len); + + uint32 objectIndex; + if (technique == -1) + objectIndex = effect->params[index].value.valuesSS[state].value.valuesI[0]; + else + objectIndex = effect->techniques[technique].passes[index].states[state].value.valuesI[0]; + + MOJOSHADER_effectObject *object = &effect->objects[objectIndex]; + if (object->type == MOJOSHADER_SYMTYPE_PIXELSHADER + || object->type == MOJOSHADER_SYMTYPE_VERTEXSHADER) + { + object->shader.technique = technique; + object->shader.pass = index; + + if (type == 2) + { + /* This is a standalone preshader! + * It exists solely for effect passes that do not use a single + * vertex/fragment shader. + */ + object->shader.is_preshader = 1; + const uint32 start = *((uint32 *) *ptr) + 4; + const char *array = readstring(*ptr, 0, m, d); + object->shader.param_count = 1; + object->shader.params = (uint32 *) m(sizeof (uint32), d); + object->shader.params[0] = findparameter(effect->params, + effect->param_count, + array); + f((void *) array, d); + object->shader.preshader = MOJOSHADER_parsePreshader(*ptr + start, length, + m, f, d); + // !!! FIXME: check for errors. + object->shader.preshader_param_count = object->shader.preshader->symbol_count; + object->shader.preshader_params = (uint32 *) m(object->shader.preshader_param_count * sizeof (uint32), d); + for (j = 0; j < object->shader.preshader->symbol_count; j++) + { + object->shader.preshader_params[j] = findparameter(effect->params, + effect->param_count, + object->shader.preshader->symbols[j].name); + } // for + } // if + else { - const char *namestr = ((char *) base) + nameoffset; - uint32 len = *((const uint32 *) namestr); - char *strptr = (char *) m(len + 1, d); - memcpy(strptr, namestr + 4, len); - strptr[len] = '\0'; - technique->name = strptr; + char mainfn[32]; + snprintf(mainfn, sizeof (mainfn), "ShaderFunction%u", (unsigned int) objectIndex); + object->shader.shader = effect->ctx.compileShader(effect->ctx.shaderContext, + mainfn, *ptr, length, + swiz, swizcount, + smap, smapcount); + if (object->shader.shader == NULL) + { + // Bail ASAP, so we can get the error to the application + errorlist_add(errors, NULL, 0, effect->ctx.getError(effect->ctx.shaderContext)); + return; + } // if + pd = effect->ctx.getParseData(object->shader.shader); + if (pd->error_count > 0) + { + // Bail ASAP, so we can get the error to the application + push_errors(errors, pd->errors, pd->error_count); + return; + } // if + + for (j = 0; j < pd->symbol_count; j++) + if (pd->symbols[j].register_set == MOJOSHADER_SYMREGSET_SAMPLER) + object->shader.sampler_count++; + object->shader.param_count = pd->symbol_count; + object->shader.params = (uint32 *) m(object->shader.param_count * sizeof (uint32), d); + object->shader.samplers = (MOJOSHADER_samplerStateRegister *) m(object->shader.sampler_count * sizeof (MOJOSHADER_samplerStateRegister), d); + uint32 curSampler = 0; + for (j = 0; j < pd->symbol_count; j++) + { + int par = findparameter(effect->params, + effect->param_count, + pd->symbols[j].name); + object->shader.params[j] = par; + if (pd->symbols[j].register_set == MOJOSHADER_SYMREGSET_SAMPLER) + { + object->shader.samplers[curSampler].sampler_name = effect->params[par].value.name; + object->shader.samplers[curSampler].sampler_register = pd->symbols[j].register_index; + object->shader.samplers[curSampler].sampler_state_count = effect->params[par].value.value_count; + object->shader.samplers[curSampler].sampler_states = effect->params[par].value.valuesSS; + curSampler++; + } // if + } // for + if (pd->preshader) + { + object->shader.preshader_param_count = pd->preshader->symbol_count; + object->shader.preshader_params = (uint32 *) m(object->shader.preshader_param_count * sizeof (uint32), d); + for (j = 0; j < pd->preshader->symbol_count; j++) + { + object->shader.preshader_params[j] = findparameter(effect->params, + effect->param_count, + pd->preshader->symbols[j].name); + } // for + } // if } - - if (numpasses > 0) + } // if + else if (object->type == MOJOSHADER_SYMTYPE_TEXTURE + || object->type == MOJOSHADER_SYMTYPE_TEXTURE1D + || object->type == MOJOSHADER_SYMTYPE_TEXTURE2D + || object->type == MOJOSHADER_SYMTYPE_TEXTURE3D + || object->type == MOJOSHADER_SYMTYPE_TEXTURECUBE + || object->type == MOJOSHADER_SYMTYPE_SAMPLER + || object->type == MOJOSHADER_SYMTYPE_SAMPLER1D + || object->type == MOJOSHADER_SYMTYPE_SAMPLER2D + || object->type == MOJOSHADER_SYMTYPE_SAMPLER3D + || object->type == MOJOSHADER_SYMTYPE_SAMPLERCUBE) + { + if (length > 0) { - technique->pass_count = numpasses; + char *str = (char *) m(length, d); + memcpy(str, *ptr, length); + object->mapping.name = str; + } // if + } // else if + else if (object->type != MOJOSHADER_SYMTYPE_VOID) // FIXME: Why? -flibit + { + assert(0 && "Large object type unknown!"); + } // else - siz = sizeof (MOJOSHADER_effectPass) * numpasses; - technique->passes = (MOJOSHADER_effectPass *) m(siz, d); - if (technique->passes == NULL) - goto parseEffect_outOfMemory; - memset(technique->passes, '\0', siz); + /* Object block is always a multiple of four */ + const uint32 blocklen = (length + 3) - ((length - 1) % 4); + *ptr += blocklen; + *len -= blocklen; + } // for +} // readobjects + +MOJOSHADER_effect *MOJOSHADER_compileEffect(const unsigned char *buf, + const unsigned int _len, + const MOJOSHADER_swizzle *swiz, + const unsigned int swizcount, + const MOJOSHADER_samplerMap *smap, + const unsigned int smapcount, + const MOJOSHADER_effectShaderContext *ctx) +{ + const uint8 *ptr = (const uint8 *) buf; + uint32 len = (uint32) _len; + ErrorList *errors; + MOJOSHADER_malloc m; + MOJOSHADER_free f; + void *d; + + /* Need a backend! */ + if (ctx == NULL) + return &MOJOSHADER_need_a_backend_effect; + + /* Supply both m and f, or neither */ + if ( ((ctx->m == NULL) && (ctx->f != NULL)) + || ((ctx->m != NULL) && (ctx->f == NULL)) ) + return &MOJOSHADER_out_of_mem_effect; + + /* Use default malloc/free if m/f were not passed */ + if (ctx->m == NULL) + m = MOJOSHADER_internal_malloc; + else + m = ctx->m; + if (ctx->f == NULL) + f = MOJOSHADER_internal_free; + else + f = ctx->f; + d = ctx->malloc_data; - for (j = 0; j < numpasses; j++) - { - if (len < 12) - goto parseEffect_unexpectedEOF; + /* malloc base effect structure */ + MOJOSHADER_effect *retval = (MOJOSHADER_effect *) m(sizeof (MOJOSHADER_effect), + ctx->malloc_data); + if (retval == NULL) + return &MOJOSHADER_out_of_mem_effect; + memset(retval, '\0', sizeof (*retval)); - MOJOSHADER_effectPass *pass = &technique->passes[j]; + /* Store ctx in effect structure */ + memcpy(&retval->ctx, ctx, sizeof(MOJOSHADER_effectShaderContext)); + retval->ctx.m = m; + retval->ctx.f = f; - const uint32 passnameoffset = readui32(&ptr, &len); - const uint32 numannos = readui32(&ptr, &len); - const uint32 numstates = readui32(&ptr, &len); + if (len < 8) + goto parseEffect_unexpectedEOF; - if (passnameoffset >= _len) - goto parseEffect_unexpectedEOF; + /* Read in header magic, seek to initial offset */ + const uint8 *base = NULL; + uint16 magic; + uint8 version_major; + uint8 version_minor; + read_version_token(&ptr, &len, &magic, &version_major, &version_minor); + if ((magic == 0xBCF0) && (version_major == 0x0B) && (version_minor == 0xCF)) + { + /* The Effect compiler provided with XNA4 adds some extra mess at the + * beginning of the file. It's useless though, so just skip it. + * -flibit + */ + const uint32 skip = readui32(&ptr, &len) - 8; + ptr += skip; + len += skip; + read_version_token(&ptr, &len, &magic, &version_major, &version_minor); + } // if + if (!((magic == 0xFEFF) && (version_major == 0x09) && (version_minor == 0x01))) + { + MOJOSHADER_deleteEffect(retval); + return &MOJOSHADER_not_an_effect_effect; + } // if + else + { + const uint32 offset = readui32(&ptr, &len); + base = ptr; + if (offset > len) + goto parseEffect_unexpectedEOF; + ptr += offset; + len -= offset; + } // else - // !!! FIXME: verify this doesn't go past EOF looking for a null. - { - const char *namestr = ((char *) base) + passnameoffset; - uint32 len = *((const uint32 *) namestr); - char *strptr = (char *) m(len + 1, d); - memcpy(strptr, namestr + 4, len); - strptr[len] = '\0'; - pass->name = strptr; - } - - if (numannos > 0) - { - for (k = 0; k < numannos; k++) - { - if (len < 8) - goto parseEffect_unexpectedEOF; - // !!! FIXME: do something with this. - readui32(&ptr, &len); - readui32(&ptr, &len); - } // for - } // if + if (len < 16) + goto parseEffect_unexpectedEOF; - if (numstates > 0) - { - pass->state_count = numstates; + /* Parse structure counts */ + const uint32 numparams = readui32(&ptr, &len); + const uint32 numtechniques = readui32(&ptr, &len); + /*const uint32 FIXME =*/ readui32(&ptr, &len); + const uint32 numobjects = readui32(&ptr, &len); + + /* Alloc structures now, so object types can be stored */ + retval->object_count = numobjects; + const uint32 siz = sizeof (MOJOSHADER_effectObject) * numobjects; + retval->objects = (MOJOSHADER_effectObject *) m(siz, d); + if (retval->objects == NULL) + goto parseEffect_outOfMemory; + memset(retval->objects, '\0', siz); - siz = sizeof (MOJOSHADER_effectState) * numstates; - pass->states = (MOJOSHADER_effectState *) m(siz, d); - if (pass->states == NULL) - goto parseEffect_outOfMemory; - memset(pass->states, '\0', siz); + /* Parse effect parameters */ + retval->param_count = numparams; + readparameters(numparams, base, &ptr, &len, + &retval->params, retval->objects, + m, d); - for (k = 0; k < numstates; k++) - { - if (len < 16) - goto parseEffect_unexpectedEOF; - - MOJOSHADER_effectState *state = &pass->states[k]; - const uint32 type = readui32(&ptr, &len); - readui32(&ptr, &len); // !!! FIXME: don't know what this field does. - /*const uint32 offsetend = */ readui32(&ptr, &len); - /*const uint32 offsetstart = */ readui32(&ptr, &len); - state->type = type; - - if ((type == 0x92) || (type == 0x93)) - numshaders++; - } // for - } // if - } // for - } // if - } // for - } // if + /* Parse effect techniques */ + retval->technique_count = numtechniques; + readtechniques(numtechniques, base, &ptr, &len, + &retval->techniques, retval->objects, + m, d); - // textures... + /* Initial effect technique/pass */ + retval->current_technique = &retval->techniques[0]; + retval->current_pass = -1; if (len < 8) goto parseEffect_unexpectedEOF; - const int numtextures = readui32(&ptr, &len); - const int numobjects = readui32(&ptr, &len); // !!! FIXME: "objects" for lack of a better word. + /* Parse object counts */ + const int numsmallobjects = readui32(&ptr, &len); + const int numlargeobjects = readui32(&ptr, &len); + + errors = errorlist_create(m, f, d); + if (errors == NULL) + goto parseEffect_outOfMemory; - if (numtextures > 0) + /* Parse "small" object table */ + readsmallobjects(numsmallobjects, &ptr, &len, retval, + swiz, swizcount, smap, smapcount, errors); + if (errorlist_count(errors) == 0) { - siz = sizeof (MOJOSHADER_effectTexture) * numtextures; - retval->textures = (MOJOSHADER_effectTexture*)m(siz, d); - if (retval->textures == NULL) - goto parseEffect_outOfMemory; - memset(retval->textures, '\0', siz); + /* Parse "large" object table. */ + readlargeobjects(numlargeobjects, numsmallobjects, &ptr, &len, retval, + swiz, swizcount, smap, smapcount, errors); + } // if - for (i = 0; i < numtextures; i++) - { - if (len < 8) - goto parseEffect_unexpectedEOF; + retval->error_count = errorlist_count(errors); + retval->errors = errorlist_flatten(errors); + errorlist_destroy(errors); - MOJOSHADER_effectTexture *texture = &retval->textures[i]; - const uint32 texparam = readui32(&ptr, &len); - const uint32 texsize = readui32(&ptr, &len); - // apparently texsize will pad out to 32 bits. - const uint32 readsize = (((texsize + 3) / 4) * 4); - if (len < readsize) - goto parseEffect_unexpectedEOF; + return retval; - texture->param = texparam; - char *str = (char*)m(texsize + 1, d); - if (str == NULL) - goto parseEffect_outOfMemory; - memcpy(str, ptr, texsize); - str[texsize] = '\0'; - texture->name = str; +parseEffect_unexpectedEOF: + MOJOSHADER_deleteEffect(retval); + return &MOJOSHADER_unexpected_eof_effect; +parseEffect_outOfMemory: + MOJOSHADER_deleteEffect(retval); + return &MOJOSHADER_out_of_mem_effect; +} // MOJOSHADER_parseEffect - ptr += readsize; - len -= readsize; - } // for - } // if - // shaders... +void freetypeinfo(MOJOSHADER_symbolTypeInfo *typeinfo, + MOJOSHADER_free f, void *d) +{ + int i; + for (i = 0; i < typeinfo->member_count; i++) + { + f((void *) typeinfo->members[i].name, d); + freetypeinfo(&typeinfo->members[i].info, f, d); + } // for + f((void *) typeinfo->members, d); +} // freetypeinfo + + +void freevalue(MOJOSHADER_effectValue *value, MOJOSHADER_free f, void *d) +{ + int i; + f((void *) value->name, d); + f((void *) value->semantic, d); + freetypeinfo(&value->type, f, d); + if (value->type.parameter_type == MOJOSHADER_SYMTYPE_SAMPLER + || value->type.parameter_type == MOJOSHADER_SYMTYPE_SAMPLER1D + || value->type.parameter_type == MOJOSHADER_SYMTYPE_SAMPLER2D + || value->type.parameter_type == MOJOSHADER_SYMTYPE_SAMPLER3D + || value->type.parameter_type == MOJOSHADER_SYMTYPE_SAMPLERCUBE) + for (i = 0; i < value->value_count; i++) + freevalue(&value->valuesSS[i].value, f, d); + f(value->values, d); +} // freevalue + + +void MOJOSHADER_deleteEffect(const MOJOSHADER_effect *_effect) +{ + MOJOSHADER_effect *effect = (MOJOSHADER_effect *) _effect; + if ((effect == NULL) || (effect == &MOJOSHADER_out_of_mem_effect)) + return; // no-op. + + MOJOSHADER_free f = effect->ctx.f; + void *d = effect->ctx.malloc_data; + int i, j, k; + + /* Free errors */ + for (i = 0; i < effect->error_count; i++) + { + f((void *) effect->errors[i].error, d); + f((void *) effect->errors[i].filename, d); + } // for + f((void *) effect->errors, d); - if (numshaders > 0) + /* Free parameters, including annotations */ + for (i = 0; i < effect->param_count; i++) { - siz = sizeof (MOJOSHADER_effectShader) * numshaders; - retval->shaders = (MOJOSHADER_effectShader *) m(siz, d); - if (retval->shaders == NULL) - goto parseEffect_outOfMemory; - memset(retval->shaders, '\0', siz); + MOJOSHADER_effectParam *param = &effect->params[i]; + freevalue(¶m->value, f, d); + for (j = 0; j < param->annotation_count; j++) + { + freevalue(¶m->annotations[j], f, d); + } // for + f((void *) param->annotations, d); + } // for + f((void *) effect->params, d); - retval->shader_count = numshaders; + /* Free techniques, including passes and all annotations */ + for (i = 0; i < effect->technique_count; i++) + { + MOJOSHADER_effectTechnique *technique = &effect->techniques[i]; + f((void *) technique->name, d); + for (j = 0; j < technique->pass_count; j++) + { + MOJOSHADER_effectPass *pass = &technique->passes[j]; + f((void *) pass->name, d); + for (k = 0; k < pass->state_count; k++) + { + freevalue(&pass->states[k].value, f, d); + } // for + f((void *) pass->states, d); + for (k = 0; k < pass->annotation_count; k++) + { + freevalue(&pass->annotations[k], f, d); + } // for + f((void *) pass->annotations, d); + } // for + f((void *) technique->passes, d); + for (j = 0; j < technique->annotation_count; j++) + { + freevalue(&technique->annotations[j], f, d); + } // for + f((void *) technique->annotations, d); + } // for + f((void *) effect->techniques, d); - // !!! FIXME: I wonder if we should pull these from offsets and not - // !!! FIXME: count on them all being in a line like this. - for (i = 0; i < numshaders; i++) + /* Free object table */ + for (i = 0; i < effect->object_count; i++) + { + MOJOSHADER_effectObject *object = &effect->objects[i]; + if (object->type == MOJOSHADER_SYMTYPE_PIXELSHADER + || object->type == MOJOSHADER_SYMTYPE_VERTEXSHADER) { - if (len < 24) - goto parseEffect_unexpectedEOF; + if (object->shader.is_preshader) + MOJOSHADER_freePreshader(object->shader.preshader); + else + effect->ctx.deleteShader(effect->ctx.shaderContext, object->shader.shader); + f((void *) object->shader.params, d); + f((void *) object->shader.samplers, d); + f((void *) object->shader.preshader_params, d); + } // if + else if (object->type == MOJOSHADER_SYMTYPE_SAMPLER + || object->type == MOJOSHADER_SYMTYPE_SAMPLER1D + || object->type == MOJOSHADER_SYMTYPE_SAMPLER2D + || object->type == MOJOSHADER_SYMTYPE_SAMPLER3D + || object->type == MOJOSHADER_SYMTYPE_SAMPLERCUBE) + f((void *) object->mapping.name, d); + else if (object->type == MOJOSHADER_SYMTYPE_STRING) + f((void *) object->string.string, d); + } // for + f((void *) effect->objects, d); - MOJOSHADER_effectShader *shader = &retval->shaders[i]; - const uint32 technique = readui32(&ptr, &len); - const uint32 pass = readui32(&ptr, &len); - readui32(&ptr, &len); // !!! FIXME: don't know what this does. - readui32(&ptr, &len); // !!! FIXME: don't know what this does (vertex/pixel/geometry?) - readui32(&ptr, &len); // !!! FIXME: don't know what this does. - const uint32 shadersize = readui32(&ptr, &len); + /* Free base effect structure */ + f((void *) effect, d); +} // MOJOSHADER_freeEffect - if (len < shadersize) - goto parseEffect_unexpectedEOF; - shader->technique = technique; - shader->pass = pass; - shader->shader = MOJOSHADER_parse(profile, ptr, shadersize, - swiz, swizcount, smap, smapcount, - m, f, d); +// !!! FIXME: Out of memory check! +#define COPY_STRING(location) \ + if (src->location != NULL) \ + { \ + siz = strlen(src->location) + 1; \ + stringcopy = (char *) m(siz, d); \ + strcpy(stringcopy, src->location); \ + dst->location = stringcopy; \ + } // if - // !!! FIXME: check for errors. - ptr += shadersize; - len -= shadersize; +void copysymboltypeinfo(MOJOSHADER_symbolTypeInfo *dst, + MOJOSHADER_symbolTypeInfo *src, + MOJOSHADER_malloc m, + void *d) +{ + int i; + uint32 siz = 0; + char *stringcopy = NULL; + memcpy(dst, src, sizeof (MOJOSHADER_symbolTypeInfo)); + if (dst->member_count > 0) + { + siz = dst->member_count * sizeof (MOJOSHADER_symbolStructMember); + dst->members = (MOJOSHADER_symbolStructMember *) m(siz, d); + for (i = 0; i < dst->member_count; i++) + { + COPY_STRING(members[i].name) + copysymboltypeinfo(&dst->members[i].info, &src->members[i].info, m, d); } // for } // if +} // copysymboltypeinfo - // !!! FIXME: we parse this, but don't expose the data, yet. - // mappings ... - assert(numshaders <= numobjects); - const uint32 nummappings = numobjects - numshaders; - if (nummappings > 0) + +void copyvalue(MOJOSHADER_effectValue *dst, + MOJOSHADER_effectValue *src, + MOJOSHADER_malloc m, + void *d) +{ + int i; + uint32 siz = 0; + char *stringcopy = NULL; + + COPY_STRING(name) + COPY_STRING(semantic) + copysymboltypeinfo(&dst->type, &src->type, m, d); + dst->value_count = src->value_count; + + if (dst->type.parameter_class == MOJOSHADER_SYMCLASS_SCALAR + || dst->type.parameter_class == MOJOSHADER_SYMCLASS_VECTOR + || dst->type.parameter_class == MOJOSHADER_SYMCLASS_MATRIX_ROWS + || dst->type.parameter_class == MOJOSHADER_SYMCLASS_MATRIX_COLUMNS + || dst->type.parameter_class == MOJOSHADER_SYMCLASS_STRUCT) { - for (i = 0; i < nummappings; i++) + siz = dst->value_count * 4; + dst->values = m(siz, d); + // !!! FIXME: Out of memory check! + memcpy(dst->values, src->values, siz); + } // if + else if (dst->type.parameter_class == MOJOSHADER_SYMCLASS_OBJECT) + { + if (dst->type.parameter_type == MOJOSHADER_SYMTYPE_SAMPLER + || dst->type.parameter_type == MOJOSHADER_SYMTYPE_SAMPLER1D + || dst->type.parameter_type == MOJOSHADER_SYMTYPE_SAMPLER2D + || dst->type.parameter_type == MOJOSHADER_SYMTYPE_SAMPLER3D + || dst->type.parameter_type == MOJOSHADER_SYMTYPE_SAMPLERCUBE) { - if (len < 24) - goto parseEffect_unexpectedEOF; + siz = dst->value_count * sizeof (MOJOSHADER_effectSamplerState); + dst->values = m(siz, d); + // !!! FIXME: Out of memory check! + memset(dst->values, '\0', siz); + for (i = 0; i < dst->value_count; i++) + { + dst->valuesSS[i].type = src->valuesSS[i].type; + copyvalue(&dst->valuesSS[i].value, + &src->valuesSS[i].value, + m, d); + } // for + } // if + else + { + siz = dst->value_count * 4; + dst->values = m(siz, d); + // !!! FIXME: Out of memory check! + memcpy(dst->values, src->values, siz); + } // else + } // else if + +} // copyvalue - /*const uint32 magic = */ readui32(&ptr, &len); - /*const uint32 index = */ readui32(&ptr, &len); - readui32(&ptr, &len); // !!! FIXME: what is this field? - readui32(&ptr, &len); // !!! FIXME: what is this field? - /*const uint32 type = */ readui32(&ptr, &len); - const uint32 mapsize = readui32(&ptr, &len); - if (mapsize > 0) + +#undef COPY_STRING + + +void copysymbolinfo(MOJOSHADER_symbolTypeInfo *dst, + MOJOSHADER_symbolTypeInfo *src, + MOJOSHADER_malloc m, + void *d) +{ + int i; + uint32 siz; + char *stringcopy; + + dst->parameter_class = src->parameter_class; + dst->parameter_type = src->parameter_type; + dst->rows = src->rows; + dst->columns = src->columns; + dst->elements = src->elements; + dst->member_count = src->member_count; + + if (dst->member_count > 0) + { + siz = sizeof (MOJOSHADER_symbolStructMember) * dst->member_count; + dst->members = (MOJOSHADER_symbolStructMember *) m(siz, d); + // !!! FIXME: Out of memory check! + for (i = 0; i < dst->member_count; i++) + { + if (src->members[i].name != NULL) { - const uint32 readsize = (((mapsize + 3) / 4) * 4); - if (len < readsize) - goto parseEffect_unexpectedEOF; + siz = strlen(src->members[i].name) + 1; + stringcopy = (char *) m(siz, d); + strcpy(stringcopy, src->members[i].name); + dst->members[i].name = stringcopy; } // if + copysymbolinfo(&dst->members[i].info, &src->members[i].info, m, d); } // for } // if +} // copysymbolinfo - retval->profile = (char *) m(strlen(profile) + 1, d); - if (retval->profile == NULL) - goto parseEffect_outOfMemory; - strcpy((char *) retval->profile, profile); - return retval; +void copysymbol(MOJOSHADER_symbol *dst, + MOJOSHADER_symbol *src, + MOJOSHADER_malloc m, + void *d) +{ + uint32 siz = strlen(src->name) + 1; + char *stringcopy = (char *) m(siz, d); + // !!! FIXME: Out of memory check! + strcpy(stringcopy, src->name); + dst->name = stringcopy; + dst->register_set = src->register_set; + dst->register_index = src->register_index; + dst->register_count = src->register_count; + copysymbolinfo(&dst->info, &src->info, m, d); +} // copysymbol + + +MOJOSHADER_preshader *copypreshader(const MOJOSHADER_preshader *src, + MOJOSHADER_malloc m, + void *d) +{ + int i, j; + uint32 siz; + MOJOSHADER_preshader *retval; + + retval = (MOJOSHADER_preshader *) m(sizeof (MOJOSHADER_preshader), d); + // !!! FIXME: Out of memory check! + memset(retval, '\0', sizeof (MOJOSHADER_preshader)); + + siz = sizeof (double) * src->literal_count; + retval->literal_count = src->literal_count; + retval->literals = (double *) m(siz, d); + // !!! FIXME: Out of memory check! + memcpy(retval->literals, src->literals, siz); + + retval->temp_count = src->temp_count; + + siz = sizeof (MOJOSHADER_symbol) * src->symbol_count; + retval->symbol_count = src->symbol_count; + retval->symbols = (MOJOSHADER_symbol *) m(siz, d); + // !!! FIXME: Out of memory check! + memset(retval->symbols, '\0', siz); + + for (i = 0; i < retval->symbol_count; i++) + copysymbol(&retval->symbols[i], &src->symbols[i], m, d); + + siz = sizeof (MOJOSHADER_preshaderInstruction) * src->instruction_count; + retval->instruction_count = src->instruction_count; + retval->instructions = (MOJOSHADER_preshaderInstruction *) m(siz, d); + // !!! FIXME: Out of memory check! + memcpy(retval->instructions, src->instructions, siz); + for (i = 0; i < retval->instruction_count; i++) + for (j = 0; j < retval->instructions[i].operand_count; j++) + { + siz = sizeof (unsigned int) * retval->instructions[i].operands[j].array_register_count; + retval->instructions[i].operands[j].array_registers = (unsigned int *) m(siz, d); + // !!! FIXME: Out of memory check! + memcpy(retval->instructions[i].operands[j].array_registers, + src->instructions[i].operands[j].array_registers, + siz); + } // for + siz = sizeof (float) * 4 * src->register_count; + retval->register_count = src->register_count; + retval->registers = (float *) m(siz, d); + // !!! FIXME: Out of memory check! + memcpy(retval->registers, src->registers, siz); -// !!! FIXME: do something with this. -parseEffect_notAnEffectsFile: -parseEffect_unexpectedEOF: -parseEffect_outOfMemory: - MOJOSHADER_freeEffect(retval); - return &MOJOSHADER_out_of_mem_effect; -} // MOJOSHADER_parseEffect + return retval; +} // copypreshader -void MOJOSHADER_freeEffect(const MOJOSHADER_effect *_effect) +MOJOSHADER_effect *MOJOSHADER_cloneEffect(const MOJOSHADER_effect *effect) { - MOJOSHADER_effect *effect = (MOJOSHADER_effect *) _effect; + int i, j, k; + MOJOSHADER_parseData *pd; + MOJOSHADER_effect *clone; + MOJOSHADER_malloc m = effect->ctx.m; + void *d = effect->ctx.malloc_data; + uint32 siz = 0; + char *stringcopy = NULL; + uint32 curSampler; + if ((effect == NULL) || (effect == &MOJOSHADER_out_of_mem_effect)) - return; // no-op. + return NULL; // no-op. + + clone = (MOJOSHADER_effect *) m(sizeof (MOJOSHADER_effect), d); + if (clone == NULL) + return NULL; // Maybe out_of_mem_effect instead? + memset(clone, '\0', sizeof (MOJOSHADER_effect)); + + /* Copy ctx */ + memcpy(&clone->ctx, &effect->ctx, sizeof(MOJOSHADER_effectShaderContext)); + + #define COPY_STRING(location) \ + siz = strlen(effect->location) + 1; \ + stringcopy = (char *) m(siz, d); \ + if (stringcopy == NULL) \ + goto cloneEffect_outOfMemory; \ + strcpy(stringcopy, effect->location); \ + clone->location = stringcopy; \ + + /* Copy errors */ + siz = sizeof (MOJOSHADER_error) * effect->error_count; + clone->error_count = effect->error_count; + clone->errors = (MOJOSHADER_error *) m(siz, d); + if (clone->errors == NULL) + goto cloneEffect_outOfMemory; + memset(clone->errors, '\0', siz); + for (i = 0; i < clone->error_count; i++) + { + COPY_STRING(errors[i].error) + COPY_STRING(errors[i].filename) + clone->errors[i].error_position = effect->errors[i].error_position; + } // for - MOJOSHADER_free f = effect->free; - void *d = effect->malloc_data; - int i, j; + /* Copy parameters */ + siz = sizeof (MOJOSHADER_effectParam) * effect->param_count; + clone->param_count = effect->param_count; + clone->params = (MOJOSHADER_effectParam *) m(siz, d); + if (clone->params == NULL) + goto cloneEffect_outOfMemory; + memset(clone->params, '\0', siz); + for (i = 0; i < clone->param_count; i++) + { + copyvalue(&clone->params[i].value, &effect->params[i].value, m, d); + + /* Copy parameter annotations */ + siz = sizeof (MOJOSHADER_effectAnnotation) * effect->params[i].annotation_count; + clone->params[i].annotation_count = effect->params[i].annotation_count; + clone->params[i].annotations = (MOJOSHADER_effectAnnotation *) m(siz, d); + if (clone->params[i].annotations == NULL) + goto cloneEffect_outOfMemory; + memset(clone->params[i].annotations, '\0', siz); + for (j = 0; j < clone->params[i].annotation_count; j++) + copyvalue(&clone->params[i].annotations[j], + &effect->params[i].annotations[j], + m, d); + } // for - for (i = 0; i < effect->error_count; i++) + /* Copy techniques */ + siz = sizeof (MOJOSHADER_effectTechnique) * effect->technique_count; + clone->technique_count = effect->technique_count; + clone->techniques = (MOJOSHADER_effectTechnique *) m(siz, d); + if (clone->techniques == NULL) + goto cloneEffect_outOfMemory; + memset(clone->techniques, '\0', siz); + for (i = 0; i < clone->technique_count; i++) { - f((void *) effect->errors[i].error, d); - f((void *) effect->errors[i].filename, d); + COPY_STRING(techniques[i].name) + + /* Copy passes */ + siz = sizeof (MOJOSHADER_effectPass) * effect->techniques[i].pass_count; + clone->techniques[i].pass_count = effect->techniques[i].pass_count; + clone->techniques[i].passes = (MOJOSHADER_effectPass *) m(siz, d); + if (clone->techniques[i].passes == NULL) + goto cloneEffect_outOfMemory; + memset(clone->techniques[i].passes, '\0', siz); + for (j = 0; j < clone->techniques[i].pass_count; j++) + { + COPY_STRING(techniques[i].passes[j].name) + + /* Copy pass states */ + siz = sizeof (MOJOSHADER_effectState) * effect->techniques[i].passes[j].state_count; + clone->techniques[i].passes[j].state_count = effect->techniques[i].passes[j].state_count; + clone->techniques[i].passes[j].states = (MOJOSHADER_effectState *) m(siz, d); + if (clone->techniques[i].passes[j].states == NULL) + goto cloneEffect_outOfMemory; + memset(clone->techniques[i].passes[j].states, '\0', siz); + for (k = 0; k < clone->techniques[i].passes[j].state_count; k++) + { + clone->techniques[i].passes[j].states[k].type = effect->techniques[i].passes[j].states[k].type; + copyvalue(&clone->techniques[i].passes[j].states[k].value, + &effect->techniques[i].passes[j].states[k].value, + m, d); + } // for + + /* Copy pass annotations */ + siz = sizeof (MOJOSHADER_effectAnnotation) * effect->techniques[i].passes[j].annotation_count; + clone->techniques[i].passes[j].annotation_count = effect->techniques[i].passes[j].annotation_count; + clone->techniques[i].passes[j].annotations = (MOJOSHADER_effectAnnotation *) m(siz, d); + if (clone->techniques[i].passes[j].annotations == NULL) + goto cloneEffect_outOfMemory; + memset(clone->techniques[i].passes[j].annotations, '\0', siz); + for (k = 0; k < clone->techniques[i].passes[j].annotation_count; k++) + copyvalue(&clone->techniques[i].passes[j].annotations[k], + &effect->techniques[i].passes[j].annotations[k], + m, d); + } // for + + /* Copy technique annotations */ + siz = sizeof (MOJOSHADER_effectAnnotation) * effect->techniques[i].annotation_count; + clone->techniques[i].annotation_count = effect->techniques[i].annotation_count; + clone->techniques[i].annotations = (MOJOSHADER_effectAnnotation *) m(siz, d); + if (clone->techniques[i].annotations == NULL) + goto cloneEffect_outOfMemory; + memset(clone->techniques[i].annotations, '\0', siz); + for (j = 0; j < clone->techniques[i].annotation_count; j++) + copyvalue(&clone->techniques[i].annotations[j], + &effect->techniques[i].annotations[j], + m, d); } // for - f((void *) effect->errors, d); - f((void *) effect->profile, d); + /* Copy the current technique, but do NOT copy the pass, pass >= 0 just + * means that the effect we're cloning is currently active + */ + for (i = 0; i < effect->technique_count; i++) + if (&effect->techniques[i] == effect->current_technique) + { + clone->current_technique = &clone->techniques[i]; + break; + } // if + assert(clone->current_technique != NULL); + clone->current_pass = -1; + + /* Copy object table */ + siz = sizeof (MOJOSHADER_effectObject) * effect->object_count; + clone->object_count = effect->object_count; + clone->objects = (MOJOSHADER_effectObject *) m(siz, d); + if (clone->objects == NULL) + goto cloneEffect_outOfMemory; + memset(clone->objects, '\0', siz); + for (i = 0; i < clone->object_count; i++) + { + clone->objects[i].type = effect->objects[i].type; + if (clone->objects[i].type == MOJOSHADER_SYMTYPE_PIXELSHADER + || clone->objects[i].type == MOJOSHADER_SYMTYPE_VERTEXSHADER) + { + clone->objects[i].shader.technique = effect->objects[i].shader.technique; + clone->objects[i].shader.pass = effect->objects[i].shader.pass; + clone->objects[i].shader.is_preshader = effect->objects[i].shader.is_preshader; + siz = sizeof (uint32) * effect->objects[i].shader.preshader_param_count; + clone->objects[i].shader.preshader_param_count = effect->objects[i].shader.preshader_param_count; + clone->objects[i].shader.preshader_params = (uint32 *) m(siz, d); + memcpy(clone->objects[i].shader.preshader_params, + effect->objects[i].shader.preshader_params, + siz); + siz = sizeof (uint32) * effect->objects[i].shader.param_count; + clone->objects[i].shader.param_count = effect->objects[i].shader.param_count; + clone->objects[i].shader.params = (uint32 *) m(siz, d); + memcpy(clone->objects[i].shader.params, + effect->objects[i].shader.params, + siz); + + if (clone->objects[i].shader.is_preshader) + { + clone->objects[i].shader.preshader = copypreshader(effect->objects[i].shader.preshader, + m, d); + continue; + } // if + effect->ctx.shaderAddRef(effect->objects[i].shader.shader); + clone->objects[i].shader.shader = effect->objects[i].shader.shader; + pd = clone->ctx.getParseData(clone->objects[i].shader.shader); + + siz = sizeof (MOJOSHADER_samplerStateRegister) * effect->objects[i].shader.sampler_count; + clone->objects[i].shader.sampler_count = effect->objects[i].shader.sampler_count; + clone->objects[i].shader.samplers = (MOJOSHADER_samplerStateRegister *) m(siz, d); + if (clone->objects[i].shader.samplers == NULL) + goto cloneEffect_outOfMemory; + curSampler = 0; + for (j = 0; j < pd->symbol_count; j++) + if (pd->symbols[j].register_set == MOJOSHADER_SYMREGSET_SAMPLER) + { + clone->objects[i].shader.samplers[curSampler].sampler_name = clone->params[clone->objects[i].shader.params[j]].value.name; + clone->objects[i].shader.samplers[curSampler].sampler_register = pd->symbols[j].register_index; + clone->objects[i].shader.samplers[curSampler].sampler_state_count = clone->params[clone->objects[i].shader.params[j]].value.value_count; + clone->objects[i].shader.samplers[curSampler].sampler_states = clone->params[clone->objects[i].shader.params[j]].value.valuesSS; + curSampler++; + } // if + } // if + else if (clone->objects[i].type == MOJOSHADER_SYMTYPE_SAMPLER + || clone->objects[i].type == MOJOSHADER_SYMTYPE_SAMPLER1D + || clone->objects[i].type == MOJOSHADER_SYMTYPE_SAMPLER2D + || clone->objects[i].type == MOJOSHADER_SYMTYPE_SAMPLER3D + || clone->objects[i].type == MOJOSHADER_SYMTYPE_SAMPLERCUBE) + { + COPY_STRING(objects[i].mapping.name) + } // else if + else if (clone->objects[i].type == MOJOSHADER_SYMTYPE_STRING) + { + COPY_STRING(objects[i].string.string) + } // else if + } // for + + #undef COPY_STRING + + return clone; + +cloneEffect_outOfMemory: + MOJOSHADER_deleteEffect(clone); + return NULL; +} // MOJOSHADER_cloneEffect + + +void MOJOSHADER_effectSetRawValueHandle(const MOJOSHADER_effectParam *parameter, + const void *data, + const unsigned int offset, + const unsigned int len) +{ + // !!! FIXME: char* case is arbitary, for Win32 -flibit + memcpy((char *) parameter->value.values + offset, data, len); +} // MOJOSHADER_effectSetRawValueHandle + + +void MOJOSHADER_effectSetRawValueName(const MOJOSHADER_effect *effect, + const char *name, + const void *data, + const unsigned int offset, + const unsigned int len) +{ + int i; for (i = 0; i < effect->param_count; i++) { - f((void *) effect->params[i].name, d); - f((void *) effect->params[i].semantic, d); + if (strcmp(name, effect->params[i].value.name) == 0) + { + // !!! FIXME: char* case is arbitary, for Win32 -flibit + memcpy((char *) effect->params[i].value.values + offset, data, len); + return; + } // if } // for - f(effect->params, d); + assert(0 && "Effect parameter not found!"); +} // MOJOSHADER_effectSetRawValueName + +const MOJOSHADER_effectTechnique *MOJOSHADER_effectGetCurrentTechnique(const MOJOSHADER_effect *effect) +{ + return effect->current_technique; +} // MOJOSHADER_effectGetCurrentTechnique + + +void MOJOSHADER_effectSetTechnique(MOJOSHADER_effect *effect, + const MOJOSHADER_effectTechnique *technique) +{ + int i; for (i = 0; i < effect->technique_count; i++) { - MOJOSHADER_effectTechnique *technique = &effect->techniques[i]; - f((void *) technique->name, d); - for (j = 0; j < technique->pass_count; j++) + if (technique == &effect->techniques[i]) { - f((void *) technique->passes[j].name, d); - f(technique->passes[j].states, d); - } // for - f(technique->passes, d); + effect->current_technique = technique; + return; + } // if + } // for + assert(0 && "Technique is not part of this effect!"); +} // MOJOSHADER_effectSetTechnique + + +const MOJOSHADER_effectTechnique *MOJOSHADER_effectFindNextValidTechnique(const MOJOSHADER_effect *effect, + const MOJOSHADER_effectTechnique *technique +) +{ + int i; + if (technique == NULL) + return &effect->techniques[0]; + for (i = 0; i < effect->technique_count; i++) + { + if (technique == &effect->techniques[i]) + { + if (i == effect->technique_count - 1) + return NULL; /* We were passed the last technique! */ + return &effect->techniques[i + 1]; + } // if } // for + assert(0 && "Technique is not part of this effect!"); + return NULL; +} // MOJOSHADER_effectFindNextValidTechnique + - f(effect->techniques, d); +void MOJOSHADER_effectBegin(MOJOSHADER_effect *effect, + unsigned int *numPasses, + int saveShaderState, + MOJOSHADER_effectStateChanges *stateChanges) +{ + *numPasses = effect->current_technique->pass_count; + effect->restore_shader_state = saveShaderState; + effect->state_changes = stateChanges; - for (i = 0; i < effect->texture_count; i++) - f((void *) effect->textures[i].name, d); - f(effect->textures, d); + if (effect->restore_shader_state) + { + effect->ctx.getBoundShaders(effect->ctx.shaderContext, + &effect->prev_vertex_shader, + &effect->prev_pixel_shader); + } // if +} // MOJOSHADER_effectBegin - for (i = 0; i < effect->shader_count; i++) - MOJOSHADER_freeParseData(effect->shaders[i].shader); - f(effect->shaders, d); - f(effect, d); -} // MOJOSHADER_freeEffect +void MOJOSHADER_effectBeginPass(MOJOSHADER_effect *effect, + unsigned int pass) +{ + int i; + MOJOSHADER_effectPass *curPass; + MOJOSHADER_effectState *state; + MOJOSHADER_effectShader *rawVert = effect->current_vert_raw; + MOJOSHADER_effectShader *rawPixl = effect->current_pixl_raw; + int has_preshader = 0; + + effect->ctx.getBoundShaders(effect->ctx.shaderContext, + &effect->current_vert, + &effect->current_pixl); + + assert(effect->current_pass == -1); + effect->current_pass = pass; + curPass = &effect->current_technique->passes[pass]; + + // !!! FIXME: I bet this could be stored at parse/compile time. -flibit + for (i = 0; i < curPass->state_count; i++) + { + state = &curPass->states[i]; + if (state->type == MOJOSHADER_RS_VERTEXSHADER) + { + rawVert = &effect->objects[*state->value.valuesI].shader; + if (rawVert->is_preshader) + has_preshader = 1; + else + effect->current_vert = rawVert->shader; + } // if + else if (state->type == MOJOSHADER_RS_PIXELSHADER) + { + rawPixl = &effect->objects[*state->value.valuesI].shader; + if (rawPixl->is_preshader) + has_preshader = 1; + else + effect->current_pixl = rawPixl->shader; + } + } // for + + effect->state_changes->render_state_changes = curPass->states; + effect->state_changes->render_state_change_count = curPass->state_count; + + effect->current_vert_raw = rawVert; + effect->current_pixl_raw = rawPixl; + + /* If this effect pass has an array of shaders, we get to wait until + * CommitChanges to actually bind the final shaders. + * -flibit + */ + if (!has_preshader) + { + effect->ctx.bindShaders(effect->ctx.shaderContext, + effect->current_vert, + effect->current_pixl); + if (effect->current_vert_raw != NULL) + { + effect->state_changes->vertex_sampler_state_changes = rawVert->samplers; + effect->state_changes->vertex_sampler_state_change_count = rawVert->sampler_count; + } // if + if (effect->current_pixl_raw != NULL) + { + effect->state_changes->sampler_state_changes = rawPixl->samplers; + effect->state_changes->sampler_state_change_count = rawPixl->sampler_count; + } // if + } // if + + MOJOSHADER_effectCommitChanges(effect); +} // MOJOSHADER_effectBeginPass + + +static inline void copy_parameter_data(MOJOSHADER_effectParam *params, + unsigned int *param_loc, + MOJOSHADER_symbol *symbols, + unsigned int symbol_count, + float *regf, int *regi, uint8 *regb) +{ + int i, j, r, c; + + i = 0; + for (i = 0; i < symbol_count; i++) + { + const MOJOSHADER_symbol *sym = &symbols[i]; + const MOJOSHADER_effectValue *param = ¶ms[param_loc[i]].value; + + // float/int registers are vec4, so they have 4 elements each + const uint32 start = sym->register_index << 2; + + if (param->type.parameter_type == MOJOSHADER_SYMTYPE_FLOAT) + memcpy(regf + start, param->valuesF, sym->register_count << 4); + else if (sym->register_set == MOJOSHADER_SYMREGSET_FLOAT4) + { + // Structs are a whole different world... + if (param->type.parameter_class == MOJOSHADER_SYMCLASS_STRUCT) + memcpy(regf + start, param->valuesF, sym->register_count << 4); + else + { + // Sometimes int/bool parameters get thrown into float registers... + j = 0; + do + { + c = 0; + do + { + regf[start + (j << 2) + c] = (float) param->valuesI[(j << 2) + c]; + } while (++c < param->type.columns); + } while (++j < sym->register_count); + } // else + } // else if + else if (sym->register_set == MOJOSHADER_SYMREGSET_INT4) + memcpy(regi + start, param->valuesI, sym->register_count << 4); + else if (sym->register_set == MOJOSHADER_SYMREGSET_BOOL) + { + j = 0; + r = 0; + do + { + c = 0; + do + { + // regb is not a vec4, enjoy that 'start' bitshift! -flibit + regb[(start >> 2) + r + c] = param->valuesI[(j << 2) + c]; + c++; + } while (c < param->type.columns && ((r + c) < sym->register_count)); + r += c; + j++; + } while (r < sym->register_count); + } // else if + } // for +} // copy_parameter_data + + +void MOJOSHADER_effectCommitChanges(MOJOSHADER_effect *effect) +{ + MOJOSHADER_effectShader *rawVert = effect->current_vert_raw; + MOJOSHADER_effectShader *rawPixl = effect->current_pixl_raw; + + /* Used for shader selection from preshaders */ + int i, j; + MOJOSHADER_effectValue *param; + MOJOSHADER_parseData *pd; + float selector; + int shader_object; + int selector_ran = 0; + + float *vs_reg_file_f, *ps_reg_file_f; + int *vs_reg_file_i, *ps_reg_file_i; + uint8 *vs_reg_file_b, *ps_reg_file_b; + + /* For effect passes with arrays of shaders, we have to run a preshader + * that determines which shader to use, based on a parameter's value. + * -flibit + */ + // !!! FIXME: We're just running the preshaders every time. Blech. -flibit + #define SELECT_SHADER_FROM_PRESHADER(raw, gls) \ + if (raw != NULL && raw->is_preshader) \ + { \ + i = 0; \ + do \ + { \ + param = &effect->params[raw->preshader_params[i]].value; \ + for (j = 0; j < (param->value_count >> 2); j++) \ + memcpy(raw->preshader->registers + raw->preshader->symbols[i].register_index + j, \ + param->valuesI + (j << 2), \ + param->type.columns << 2); \ + } while (++i < raw->preshader->symbol_count); \ + run_preshader(raw->preshader, &selector); \ + shader_object = effect->params[raw->params[0]].value.valuesI[(int) selector]; \ + raw = &effect->objects[shader_object].shader; \ + gls = raw->shader; \ + selector_ran = 1; \ + } + SELECT_SHADER_FROM_PRESHADER(rawVert, effect->current_vert) + SELECT_SHADER_FROM_PRESHADER(rawPixl, effect->current_pixl) + #undef SELECT_SHADER_FROM_PRESHADER + if (selector_ran) + { + effect->ctx.bindShaders(effect->ctx.shaderContext, + effect->current_vert, + effect->current_pixl); + if (effect->current_vert_raw != NULL) + { + effect->state_changes->vertex_sampler_state_changes = rawVert->samplers; + effect->state_changes->vertex_sampler_state_change_count = rawVert->sampler_count; + } // if + if (effect->current_pixl_raw != NULL) + { + effect->state_changes->sampler_state_changes = rawPixl->samplers; + effect->state_changes->sampler_state_change_count = rawPixl->sampler_count; + } // if + } // if + + /* This is where parameters are copied into the constant buffers. + * If you're looking for where things slow down immensely, look at + * the copy_parameter_data() and run_preshader() functions. + * -flibit + */ + // !!! FIXME: We're just copying everything every time. Blech. -flibit + // !!! FIXME: We're just running the preshaders every time. Blech. -flibit + // !!! FIXME: Will the preshader ever want int/bool registers? -flibit + #define COPY_PARAMETER_DATA(raw, stage) \ + if (raw != NULL && raw->shader != NULL) \ + { \ + pd = effect->ctx.getParseData(raw->shader); \ + copy_parameter_data(effect->params, raw->params, \ + pd->symbols, \ + pd->symbol_count, \ + stage##_reg_file_f, \ + stage##_reg_file_i, \ + stage##_reg_file_b); \ + if (pd->preshader) \ + { \ + copy_parameter_data(effect->params, raw->preshader_params, \ + pd->preshader->symbols, \ + pd->preshader->symbol_count, \ + pd->preshader->registers, \ + NULL, \ + NULL); \ + run_preshader(pd->preshader, stage##_reg_file_f); \ + } \ + } + effect->ctx.mapUniformBufferMemory(effect->ctx.shaderContext, + &vs_reg_file_f, &vs_reg_file_i, &vs_reg_file_b, + &ps_reg_file_f, &ps_reg_file_i, &ps_reg_file_b); + COPY_PARAMETER_DATA(rawVert, vs) + COPY_PARAMETER_DATA(rawPixl, ps) + effect->ctx.unmapUniformBufferMemory(effect->ctx.shaderContext); + #undef COPY_PARAMETER_DATA +} // MOJOSHADER_effectCommitChanges + + +void MOJOSHADER_effectEndPass(MOJOSHADER_effect *effect) +{ + assert(effect->current_pass != -1); + effect->current_pass = -1; +} // MOJOSHADER_effectEndPass + + +void MOJOSHADER_effectEnd(MOJOSHADER_effect *effect) +{ + if (effect->restore_shader_state) + { + effect->restore_shader_state = 0; + effect->ctx.bindShaders(effect->ctx.shaderContext, + effect->prev_vertex_shader, + effect->prev_pixel_shader); + } // if + + effect->state_changes = NULL; +} // MOJOSHADER_effectEnd + +#endif // MOJOSHADER_EFFECT_SUPPORT // end of mojoshader_effects.c ... diff --git a/mojoshader/mojoshader_internal.h b/mojoshader/mojoshader_internal.h index fac2cbd..c60dbec 100644 --- a/mojoshader/mojoshader_internal.h +++ b/mojoshader/mojoshader_internal.h @@ -8,33 +8,148 @@ // Shader bytecode format is described at MSDN: // http://msdn.microsoft.com/en-us/library/ff569705.aspx +#ifdef MOJOSHADER_USE_SDL_STDLIB +#ifdef USE_SDL3 /* Private define, for now */ +#include +#include +#include +#include +#else +#include +#include +#include +#include +#endif +#include /* Needed for isinf/isnan :( */ + +/* FIXME: These includes are needed for alloca :( */ +#include +#if defined(__linux__) || defined(__sun) +#include +#endif +#ifdef _MSC_VER +#include +#endif + +/* stdint.h */ +typedef Uint8 uint8; +typedef Uint16 uint16; +typedef Uint32 uint32; +typedef Sint32 int32; +typedef Sint64 int64; +typedef Uint64 uint64; + +/* assert.h */ +#define assert SDL_assert + +/* stdlib.h */ +#define malloc SDL_malloc +#define free SDL_free + +/* stdio.h */ +#define sscanf SDL_sscanf +#ifdef snprintf +#undef snprintf +#endif +#define snprintf SDL_snprintf +#ifdef vsnprintf +#undef vsnprintf +#endif +#define vsnprintf SDL_vsnprintf + +/* math.h */ +#define acos SDL_acos +#define asin SDL_asin +#define atan SDL_atan +#define atan2 SDL_atan2 +#define cos SDL_cos +#define exp SDL_exp +#define floor SDL_floor +#define log SDL_log +#define sin SDL_sin +#define sqrt SDL_sqrt + +/* string.h */ +#ifdef memcmp +#undef memcmp +#endif +#define memcmp SDL_memcmp +#ifdef memcpy +#undef memcpy +#endif +#define memcpy SDL_memcpy +#ifdef memset +#undef memset +#endif +#define memset SDL_memset +#ifdef strchr +#undef strchr +#endif +#define strchr SDL_strchr +#ifdef strcmp +#undef strcmp +#endif +#define strcmp SDL_strcmp +#ifdef strlen +#undef strlen +#endif +#define strlen SDL_strlen +#ifdef strncmp +#undef strncmp +#endif +#define strncmp SDL_strncmp +#ifdef strstr +#undef strstr +#endif +#define strstr SDL_strstr +#ifdef strcat +#undef strcat +#endif +/* TODO: Move MojoShader away from strcat! This len is awful! */ +#define strcat(dst, src) SDL_strlcat(dst, src, SDL_strlen(src) + 1) +#ifdef strcpy +#undef strcpy +#endif +/* TODO: Move MojoShader away from strcpy! This len is awful! */ +#define strcpy(dst, src) SDL_strlcpy(dst, src, SDL_strlen(src) + 1) + +/* ctype.h */ +#ifdef isalnum +#undef isalnum +#endif +#define isalnum SDL_isalnum + +/* endian.h */ +#define MOJOSHADER_BIG_ENDIAN (SDL_BYTEORDER == SDL_BIG_ENDIAN) + +/* dlfcn.h */ +#define dlopen(a, b) SDL_LoadObject(a) +#define dlclose SDL_UnloadObject +#define dlsym SDL_LoadFunction +#else /* MOJOSHADER_USE_SDL_STDLIB */ #include #include #include #include #include -#ifndef DLLEXPORT -#ifdef _WIN32 -#define DLLEXPORT __declspec(dllexport) +#ifdef __BYTE_ORDER__ +#define MOJOSHADER_BIG_ENDIAN (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) +#elif defined(__linux__) +#include +#define MOJOSHADER_BIG_ENDIAN (__BYTE_ORDER == __BIG_ENDIAN) +#else +/* TODO: Detect little endian PowerPC? */ +#if defined(__POWERPC__) || defined(__powerpc__) +#define MOJOSHADER_BIG_ENDIAN 1 #else -#define DLLEXPORT +#define MOJOSHADER_BIG_ENDIAN 0 #endif #endif +#endif /* MOJOSHADER_USE_SDL_STDLIB */ #include "mojoshader.h" -#define DEBUG_LEXER 0 -#define DEBUG_PREPROCESSOR 0 -#define DEBUG_ASSEMBLER_PARSER 0 -#define DEBUG_COMPILER_PARSER 0 -#define DEBUG_TOKENIZER \ - (DEBUG_PREPROCESSOR || DEBUG_ASSEMBLER_PARSER || DEBUG_LEXER) - -#if (defined(__APPLE__) && defined(__MACH__)) -//#define PLATFORM_MACOSX 1 -#endif - // This is the highest shader version we currently support. #define MAX_SHADER_MAJOR 3 @@ -52,6 +167,10 @@ #define SUPPORT_PROFILE_BYTECODE 1 #endif +#ifndef SUPPORT_PROFILE_HLSL +#define SUPPORT_PROFILE_HLSL 1 +#endif + #ifndef SUPPORT_PROFILE_GLSL #define SUPPORT_PROFILE_GLSL 1 #endif @@ -60,6 +179,14 @@ #define SUPPORT_PROFILE_GLSL120 1 #endif +#ifndef SUPPORT_PROFILE_GLSLES +#define SUPPORT_PROFILE_GLSLES 1 +#endif + +#ifndef SUPPORT_PROFILE_GLSLES3 +#define SUPPORT_PROFILE_GLSLES3 1 +#endif + #ifndef SUPPORT_PROFILE_ARB1 #define SUPPORT_PROFILE_ARB1 1 #endif @@ -68,6 +195,18 @@ #define SUPPORT_PROFILE_ARB1_NV 1 #endif +#ifndef SUPPORT_PROFILE_METAL +#define SUPPORT_PROFILE_METAL 1 +#endif + +#ifndef SUPPORT_PROFILE_SPIRV +#define SUPPORT_PROFILE_SPIRV 1 +#endif + +#ifndef SUPPORT_PROFILE_GLSPIRV +#define SUPPORT_PROFILE_GLSPIRV 1 +#endif + #if SUPPORT_PROFILE_ARB1_NV && !SUPPORT_PROFILE_ARB1 #error nv profiles require arb1 profile. Fix your build. #endif @@ -76,11 +215,24 @@ #error glsl120 profile requires glsl profile. Fix your build. #endif +#if SUPPORT_PROFILE_GLSLES && !SUPPORT_PROFILE_GLSL +#error glsles profile requires glsl profile. Fix your build. +#endif + +#if SUPPORT_PROFILE_GLSLES3 && !SUPPORT_PROFILE_GLSLES +#error glsles3 profile requires glsles profile. Fix your build. +#endif + -// Other stuff you can disable... +#if SUPPORT_PROFILE_GLSPIRV && !SUPPORT_PROFILE_SPIRV +#error glspirv profile requires spirv profile. Fix your build. +#endif -// This removes the preshader parsing and execution code. You can save some -// bytes if you have normal shaders and not Effect files. +// Microsoft's preprocessor has some quirks. In some ways, it doesn't work +// like you'd expect a C preprocessor to function. +#ifndef MATCH_MICROSOFT_PREPROCESSOR +#define MATCH_MICROSOFT_PREPROCESSOR 1 +#endif // Get basic wankery out of the way here... @@ -93,9 +245,21 @@ typedef unsigned int uint; // this is a printf() helper. don't use for code. +// Locale-independent float printing replacement for snprintf +size_t MOJOSHADER_printFloat(char *text, size_t maxlen, float arg); + #ifdef _MSC_VER -#include +#include +#define isnan _isnan // !!! FIXME: not a safe replacement! +#if _MSC_VER < 1900 // pre MSVC 2015 +#define isinf(x) (!_finite(x)) // FIXME: not a safe replacement! +#endif #define va_copy(a, b) a = b +#endif + +#ifndef MOJOSHADER_USE_SDL_STDLIB +#ifdef _MSC_VER +#include #define snprintf _snprintf // !!! FIXME: not a safe replacement! #define vsnprintf _vsnprintf // !!! FIXME: not a safe replacement! #define strcasecmp stricmp @@ -125,10 +289,7 @@ typedef int32_t int32; typedef int64_t int64; typedef uint64_t uint64; #endif - -#ifdef sun -#include -#endif +#endif /* MOJOSHADER_USE_SDL_STDLIB */ #ifdef __GNUC__ #define ISPRINTF(x,y) __attribute__((format (printf, x, y))) @@ -141,7 +302,7 @@ typedef uint64_t uint64; // Byteswap magic... -#if ((defined __GNUC__) && (defined __POWERPC__)) +#if (defined(__GNUC__) && MOJOSHADER_BIG_ENDIAN && (defined(__POWERPC__) || defined(__powerpc__))) static inline uint32 SWAP32(uint32 x) { __asm__ __volatile__("lwbrx %0,0,%1" : "=r" (x) : "r" (&x)); @@ -152,7 +313,7 @@ typedef uint64_t uint64; __asm__ __volatile__("lhbrx %0,0,%1" : "=r" (x) : "r" (&x)); return x; } // SWAP16 -#elif defined(__POWERPC__) +#elif MOJOSHADER_BIG_ENDIAN static inline uint32 SWAP32(uint32 x) { return ( (((x) >> 24) & 0x000000FF) | (((x) >> 8) & 0x0000FF00) | @@ -180,16 +341,16 @@ static inline int Min(const int a, const int b) typedef struct HashTable HashTable; typedef uint32 (*HashTable_HashFn)(const void *key, void *data); typedef int (*HashTable_KeyMatchFn)(const void *a, const void *b, void *data); -typedef void (*HashTable_NukeFn)(const void *key, const void *value, void *data); +typedef void (*HashTable_NukeFn)(const void *ctx, const void *key, const void *value, void *data); HashTable *hash_create(void *data, const HashTable_HashFn hashfn, const HashTable_KeyMatchFn keymatchfn, const HashTable_NukeFn nukefn, const int stackable, MOJOSHADER_malloc m, MOJOSHADER_free f, void *d); -void hash_destroy(HashTable *table); +void hash_destroy(HashTable *table, const void *ctx); int hash_insert(HashTable *table, const void *key, const void *value); -int hash_remove(HashTable *table, const void *key); +int hash_remove(HashTable *table, const void *key, const void *ctx); int hash_find(const HashTable *table, const void *key, const void **_value); int hash_iter(const HashTable *table, const void *key, const void **_value, void **iter); int hash_iter_keys(const HashTable *table, const void **_key, void **iter); @@ -216,6 +377,7 @@ const char *stringcache(StringCache *cache, const char *str); const char *stringcache_len(StringCache *cache, const char *str, const unsigned int len); const char *stringcache_fmt(StringCache *cache, const char *fmt, ...); +int stringcache_iscached(StringCache *cache, const char *str); void stringcache_destroy(StringCache *cache); @@ -237,7 +399,22 @@ void errorlist_destroy(ErrorList *list); // Dynamic buffers... -typedef struct Buffer Buffer; +typedef struct BufferBlock +{ + uint8 *data; + size_t bytes; + struct BufferBlock *next; +} BufferBlock; +typedef struct Buffer +{ + size_t total_bytes; + BufferBlock *head; + BufferBlock *tail; + size_t block_size; + MOJOSHADER_malloc m; + MOJOSHADER_free f; + void *d; +} Buffer; Buffer *buffer_create(size_t blksz,MOJOSHADER_malloc m,MOJOSHADER_free f,void *d); char *buffer_reserve(Buffer *buffer, const size_t len); int buffer_append(Buffer *buffer, const void *_data, size_t len); @@ -248,8 +425,8 @@ void buffer_empty(Buffer *buffer); char *buffer_flatten(Buffer *buffer); char *buffer_merge(Buffer **buffers, const size_t n, size_t *_len); void buffer_destroy(Buffer *buffer); -ssize_t buffer_find(Buffer *buffer, const size_t start, - const void *data, const size_t len); +void buffer_patch(Buffer *buffer, const size_t start, + const void *data, const size_t len); @@ -267,6 +444,8 @@ ssize_t buffer_find(Buffer *buffer, const size_t start, #define FXLC_ID 0x434C5846 // 0x434C5846 == 'FXLC' // we need to reference these by explicit value occasionally... +#define OPCODE_RCP 6 +#define OPCODE_RSQ 7 #define OPCODE_RET 28 #define OPCODE_IF 40 #define OPCODE_IFC 41 @@ -286,23 +465,8 @@ ssize_t buffer_find(Buffer *buffer, const size_t start, #define MOJOSHADER_internal_malloc NULL #define MOJOSHADER_internal_free NULL #else -void *MOJOSHADER_internal_malloc(int bytes, void *d); -void MOJOSHADER_internal_free(void *ptr, void *d); -#endif - -#if MOJOSHADER_FORCE_INCLUDE_CALLBACKS -#define MOJOSHADER_internal_include_open NULL -#define MOJOSHADER_internal_include_close NULL -#else -int MOJOSHADER_internal_include_open(MOJOSHADER_includeType inctype, - const char *fname, const char *parent, - const char **outdata, - unsigned int *outbytes, - MOJOSHADER_malloc m, MOJOSHADER_free f, - void *d); - -void MOJOSHADER_internal_include_close(const char *data, MOJOSHADER_malloc m, - MOJOSHADER_free f, void *d); +void * MOJOSHADERCALL MOJOSHADER_internal_malloc(int bytes, void *d); +void MOJOSHADERCALL MOJOSHADER_internal_free(void *ptr, void *d); #endif @@ -436,142 +600,65 @@ extern MOJOSHADER_error MOJOSHADER_out_of_mem_error; extern MOJOSHADER_parseData MOJOSHADER_out_of_mem_data; -// preprocessor stuff. - -typedef enum -{ - TOKEN_UNKNOWN = 256, // start past ASCII character values. - - // These are all C-like constructs. Tokens < 256 may be single - // chars (like '+' or whatever). These are just multi-char sequences - // (like "+=" or whatever). - TOKEN_IDENTIFIER, - TOKEN_INT_LITERAL, - TOKEN_FLOAT_LITERAL, - TOKEN_STRING_LITERAL, - TOKEN_RSHIFTASSIGN, - TOKEN_LSHIFTASSIGN, - TOKEN_ADDASSIGN, - TOKEN_SUBASSIGN, - TOKEN_MULTASSIGN, - TOKEN_DIVASSIGN, - TOKEN_MODASSIGN, - TOKEN_XORASSIGN, - TOKEN_ANDASSIGN, - TOKEN_ORASSIGN, - TOKEN_INCREMENT, - TOKEN_DECREMENT, - TOKEN_RSHIFT, - TOKEN_LSHIFT, - TOKEN_ANDAND, - TOKEN_OROR, - TOKEN_LEQ, - TOKEN_GEQ, - TOKEN_EQL, - TOKEN_NEQ, - TOKEN_HASH, - TOKEN_HASHHASH, - - // This is returned at the end of input...no more to process. - TOKEN_EOI, - - // This is returned for char sequences we think are bogus. You'll have - // to judge for yourself. In most cases, you'll probably just fail with - // bogus syntax without explicitly checking for this token. - TOKEN_BAD_CHARS, - - // This is returned if there's an error condition (the error is returned - // as a NULL-terminated string from preprocessor_nexttoken(), instead - // of actual token data). You can continue getting tokens after this - // is reported. It happens for things like missing #includes, etc. - TOKEN_PREPROCESSING_ERROR, - - // These are all caught by the preprocessor. Caller won't ever see them, - // except TOKEN_PP_PRAGMA. - // They control the preprocessor (#includes new files, etc). - TOKEN_PP_INCLUDE, - TOKEN_PP_LINE, - TOKEN_PP_DEFINE, - TOKEN_PP_UNDEF, - TOKEN_PP_IF, - TOKEN_PP_IFDEF, - TOKEN_PP_IFNDEF, - TOKEN_PP_ELSE, - TOKEN_PP_ELIF, - TOKEN_PP_ENDIF, - TOKEN_PP_ERROR, // caught, becomes TOKEN_PREPROCESSING_ERROR - TOKEN_PP_PRAGMA, - TOKEN_INCOMPLETE_COMMENT, // caught, becomes TOKEN_PREPROCESSING_ERROR - TOKEN_PP_UNARY_MINUS, // used internally, never returned. - TOKEN_PP_UNARY_PLUS, // used internally, never returned. -} Token; - - -// This is opaque. -struct Preprocessor; -typedef struct Preprocessor Preprocessor; - -typedef struct Conditional -{ - Token type; - int linenum; - int skipping; - int chosen; - struct Conditional *next; -} Conditional; - -typedef struct Define +#if SUPPORT_PROFILE_SPIRV +// Patching SPIR-V binaries before linking is needed to ensure locations do not +// overlap between shader stages. Unfortunately, OpDecorate takes Literal, so we +// can't use Result from OpSpecConstant and leave this up to specialization +// mechanism. +// Patch table must be propagated from parsing to program linking, but since +// MOJOSHADER_parseData is public and I'd like to avoid changing ABI and exposing +// this, it is appended to MOJOSHADER_parseData::output using postflight buffer. +typedef struct SpirvPatchEntry { - const char *identifier; - const char *definition; - const char *original; - const char **parameters; - int paramcount; - struct Define *next; -} Define; - -typedef struct IncludeState + uint32 offset; + int32 location; +} SpirvPatchEntry; + +typedef struct SpirvPatchTable { - const char *filename; - const char *source_base; - const char *source; - const char *token; - unsigned int tokenlen; - Token tokenval; - int pushedback; - const unsigned char *lexer_marker; - int report_whitespace; - int asm_comments; - unsigned int orig_length; - unsigned int bytes_left; - unsigned int line; - Conditional *conditional_stack; - MOJOSHADER_includeClose close_callback; - struct IncludeState *next; -} IncludeState; - -Token preprocessor_lexer(IncludeState *s); - -// This will only fail if the allocator fails, so it doesn't return any -// error code...NULL on failure. -Preprocessor *preprocessor_start(const char *fname, const char *source, - unsigned int sourcelen, - MOJOSHADER_includeOpen open_callback, - MOJOSHADER_includeClose close_callback, - const MOJOSHADER_preprocessorDefine *defines, - unsigned int define_count, int asm_comments, - MOJOSHADER_malloc m, MOJOSHADER_free f, void *d); - -void preprocessor_end(Preprocessor *pp); -int preprocessor_outofmemory(Preprocessor *pp); -const char *preprocessor_nexttoken(Preprocessor *_ctx, - unsigned int *_len, Token *_token); -const char *preprocessor_sourcepos(Preprocessor *pp, unsigned int *pos); - - -void MOJOSHADER_print_debug_token(const char *subsystem, const char *token, - const unsigned int tokenlen, - const Token tokenval); + // Patches for uniforms + SpirvPatchEntry vpflip; + SpirvPatchEntry array_vec4; + SpirvPatchEntry array_ivec4; + SpirvPatchEntry array_bool; + SpirvPatchEntry samplers[16]; + int32 location_count; + + // TEXCOORD0 is patched to PointCoord if VS outputs PointSize. + // In `helpers`: [OpDecorate|id|Location|0xDEADBEEF] -> [OpDecorate|id|BuiltIn|PointCoord] + // Offset derived from attrib_offsets[TEXCOORD][0]. + uint32 pointcoord_var_offset; // in `mainline_intro`, [OpVariable|tid|id|StorageClass], patch tid to pvec2i + uint32 pointcoord_load_offset; // in `mainline_top`, [OpLoad|tid|id|src_id], patch tid to vec2 + uint32 tid_pvec2i; + uint32 tid_vec2; + uint32 tid_pvec4i; + + /// Patches for TEXCOORD0 and vertex attribute types + uint32 tid_vec4; + uint32 tid_ivec4; + uint32 tid_uvec4; + + // Patches for vertex attribute types + uint32 tid_vec4_p; + uint32 tid_ivec4_p; + uint32 tid_uvec4_p; + uint32 attrib_type_offsets[MOJOSHADER_USAGE_TOTAL][16]; + struct + { + uint32 num_loads; + uint32 *load_types; + uint32 *load_opcodes; + } attrib_type_load_offsets[MOJOSHADER_USAGE_TOTAL][16]; + + // Patches for linking vertex output/pixel input + uint32 attrib_offsets[MOJOSHADER_USAGE_TOTAL][16]; + uint32 output_offsets[16]; +} SpirvPatchTable; + +void MOJOSHADER_spirv_link_attributes(const MOJOSHADER_parseData *vertex, + const MOJOSHADER_parseData *pixel, + int is_glspirv); +#endif #endif // _INCLUDE_MOJOSHADER_INTERNAL_H_ @@ -587,103 +674,108 @@ void MOJOSHADER_print_debug_token(const char *subsystem, const char *token, // !!! FIXME: Some of these MOJOSHADER_TYPE_ANYs need to have their scope // !!! FIXME: reduced to just PIXEL or VERTEX. -INSTRUCTION(NOP, "NOP", 1, NULL, MOJOSHADER_TYPE_ANY) -INSTRUCTION(MOV, "MOV", 1, DS, MOJOSHADER_TYPE_ANY) -INSTRUCTION(ADD, "ADD", 1, DSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION(SUB, "SUB", 1, DSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION(MAD, "MAD", 1, DSSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION(MUL, "MUL", 1, DSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(RCP, "RCP", 1, DS, MOJOSHADER_TYPE_ANY) -INSTRUCTION(RSQ, "RSQ", 1, DS, MOJOSHADER_TYPE_ANY) -INSTRUCTION(DP3, "DP3", 1, DSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(DP4, "DP4", 1, DSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION(MIN, "MIN", 1, DSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION(MAX, "MAX", 1, DSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION(SLT, "SLT", 1, DSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION(SGE, "SGE", 1, DSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION(EXP, "EXP", 1, DS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(LOG, "LOG", 1, DS, MOJOSHADER_TYPE_ANY) -INSTRUCTION(LIT, "LIT", 3, DS, MOJOSHADER_TYPE_ANY) -INSTRUCTION(DST, "DST", 1, DSS, MOJOSHADER_TYPE_VERTEX) -INSTRUCTION(LRP, "LRP", 2, DSSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(FRC, "FRC", 1, DS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(M4X4, "M4X4", 4, DSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(M4X3, "M4X3", 3, DSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(M3X4, "M3X4", 4, DSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(M3X3, "M3X3", 3, DSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(M3X2, "M3X2", 2, DSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(CALL, "CALL", 2, S, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(CALLNZ, "CALLNZ", 3, SS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(LOOP, "LOOP", 3, SS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(RET, "RET", 1, NULL, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(ENDLOOP, "ENDLOOP", 2, NULL, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(LABEL, "LABEL", 0, S, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(DCL, "DCL", 0, DCL, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(POW, "POW", 3, DSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION(CRS, "CRS", 2, DSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION(SGN, "SGN", 3, DSSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION(ABS, "ABS", 1, DS, MOJOSHADER_TYPE_ANY) -INSTRUCTION(NRM, "NRM", 3, DS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(SINCOS, "SINCOS", 8, SINCOS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(REP, "REP", 3, S, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(ENDREP, "ENDREP", 2, NULL, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(IF, "IF", 3, S, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(IFC, "IF", 3, SS, MOJOSHADER_TYPE_ANY) -INSTRUCTION(ELSE, "ELSE", 1, NULL, MOJOSHADER_TYPE_ANY) // !!! FIXME: state! -INSTRUCTION(ENDIF, "ENDIF", 1, NULL, MOJOSHADER_TYPE_ANY) // !!! FIXME: state! -INSTRUCTION_STATE(BREAK, "BREAK", 1, NULL, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(BREAKC, "BREAK", 3, SS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(MOVA, "MOVA", 1, DS, MOJOSHADER_TYPE_VERTEX) -INSTRUCTION_STATE(DEFB, "DEFB", 0, DEFB, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(DEFI, "DEFI", 0, DEFI, MOJOSHADER_TYPE_ANY) -INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN) -INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN) -INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN) -INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN) -INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN) -INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN) -INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN) -INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN) -INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN) -INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN) -INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN) -INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN) -INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN) -INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN) -INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN) -INSTRUCTION_STATE(TEXCRD, "TEXCRD", 1, TEXCRD, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION_STATE(TEXKILL, "TEXKILL", 2, D, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION_STATE(TEXLD, "TEXLD", 1, TEXLD, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION_STATE(TEXBEM, "TEXBEM", 1, DS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION_STATE(TEXBEML, "TEXBEML", 2, DS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION(TEXREG2AR, "TEXREG2AR", 1, DS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION(TEXREG2GB, "TEXREG2GB", 1, DS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION_STATE(TEXM3X2PAD, "TEXM3X2PAD", 1, DS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION_STATE(TEXM3X2TEX, "TEXM3X2TEX", 1, DS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION_STATE(TEXM3X3PAD, "TEXM3X3PAD", 1, DS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION_STATE(TEXM3X3TEX, "TEXM3X3TEX", 1, DS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN) -INSTRUCTION_STATE(TEXM3X3SPEC, "TEXM3X3SPEC", 1, DSS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION_STATE(TEXM3X3VSPEC, "TEXM3X3VSPEC", 1, DS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION(EXPP, "EXPP", 1, DS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(LOGP, "LOGP", 1, DS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(CND, "CND", 1, DSSS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION_STATE(DEF, "DEF", 0, DEF, MOJOSHADER_TYPE_ANY) -INSTRUCTION(TEXREG2RGB, "TEXREG2RGB", 1, DS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION(TEXDP3TEX, "TEXDP3TEX", 1, DS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION(TEXM3X2DEPTH, "TEXM3X2DEPTH", 1, DS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION(TEXDP3, "TEXDP3", 1, DS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION_STATE(TEXM3X3, "TEXM3X3", 1, DS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION(TEXDEPTH, "TEXDEPTH", 1, D, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION_STATE(CMP, "CMP", 1, DSSS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION(BEM, "BEM", 2, DSS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION_STATE(DP2ADD, "DP2ADD", 2, DSSS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION(DSX, "DSX", 2, DS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION(DSY, "DSY", 2, DS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION(TEXLDD, "TEXLDD", 3, DSSSS, MOJOSHADER_TYPE_PIXEL) -INSTRUCTION_STATE(SETP, "SETP", 1, DSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(TEXLDL, "TEXLDL", 2, DSS, MOJOSHADER_TYPE_ANY) -INSTRUCTION_STATE(BREAKP, "BREAKP", 3, S, MOJOSHADER_TYPE_ANY) +INSTRUCTION(NOP, "NOP", 1, NULL, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(MOV, "MOV", 1, DS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(ADD, "ADD", 1, DSS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(SUB, "SUB", 1, DSS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(MAD, "MAD", 1, DSSS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(MUL, "MUL", 1, DSS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(RCP, "RCP", 1, DS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(RSQ, "RSQ", 1, DS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(DP3, "DP3", 1, DSS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(DP4, "DP4", 1, DSS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(MIN, "MIN", 1, DSS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(MAX, "MAX", 1, DSS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(SLT, "SLT", 1, DSS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(SGE, "SGE", 1, DSS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(EXP, "EXP", 1, DS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(LOG, "LOG", 1, DS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(LIT, "LIT", 3, DS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(DST, "DST", 1, DSS, MOJOSHADER_TYPE_VERTEX, 0xF) +INSTRUCTION(LRP, "LRP", 2, DSSS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(FRC, "FRC", 1, DS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(M4X4, "M4X4", 4, DSS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(M4X3, "M4X3", 3, DSS, MOJOSHADER_TYPE_ANY, 0x7) +INSTRUCTION_STATE(M3X4, "M3X4", 4, DSS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(M3X3, "M3X3", 3, DSS, MOJOSHADER_TYPE_ANY, 0x7) +INSTRUCTION_STATE(M3X2, "M3X2", 2, DSS, MOJOSHADER_TYPE_ANY, 0x3) +INSTRUCTION_STATE(CALL, "CALL", 2, S, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(CALLNZ, "CALLNZ", 3, SS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(LOOP, "LOOP", 3, SS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(RET, "RET", 1, NULL, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(ENDLOOP, "ENDLOOP", 2, NULL, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(LABEL, "LABEL", 0, S, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(DCL, "DCL", 0, DCL, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(POW, "POW", 3, DSS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(CRS, "CRS", 2, DSS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(SGN, "SGN", 3, DSSS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(ABS, "ABS", 1, DS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(NRM, "NRM", 3, DS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(SINCOS, "SINCOS", 8, SINCOS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(REP, "REP", 3, S, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(ENDREP, "ENDREP", 2, NULL, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(IF, "IF", 3, S, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(IFC, "IF", 3, SS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(ELSE, "ELSE", 1, NULL, MOJOSHADER_TYPE_ANY, 0xF) // !!! FIXME: state! +INSTRUCTION(ENDIF, "ENDIF", 1, NULL, MOJOSHADER_TYPE_ANY, 0xF) // !!! FIXME: state! +INSTRUCTION_STATE(BREAK, "BREAK", 1, NULL, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(BREAKC, "BREAK", 3, SS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(MOVA, "MOVA", 1, DS, MOJOSHADER_TYPE_VERTEX, 0xF) +INSTRUCTION_STATE(DEFB, "DEFB", 0, DEFB, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(DEFI, "DEFI", 0, DEFI, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN, 0xF) +INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN, 0xF) +INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN, 0xF) +INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN, 0xF) +INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN, 0xF) +INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN, 0xF) +INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN, 0xF) +INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN, 0xF) +INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN, 0xF) +INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN, 0xF) +INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN, 0xF) +INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN, 0xF) +INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN, 0xF) +INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN, 0xF) +INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN, 0xF) +INSTRUCTION_STATE(TEXCRD, "TEXCRD", 1, TEXCRD, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION_STATE(TEXKILL, "TEXKILL", 2, D, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION_STATE(TEXLD, "TEXLD", 1, TEXLD, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION_STATE(TEXBEM, "TEXBEM", 1, DS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION_STATE(TEXBEML, "TEXBEML", 2, DS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION(TEXREG2AR, "TEXREG2AR", 1, DS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION(TEXREG2GB, "TEXREG2GB", 1, DS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION_STATE(TEXM3X2PAD, "TEXM3X2PAD", 1, DS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION_STATE(TEXM3X2TEX, "TEXM3X2TEX", 1, DS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION_STATE(TEXM3X3PAD, "TEXM3X3PAD", 1, DS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION_STATE(TEXM3X3TEX, "TEXM3X3TEX", 1, DS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION(RESERVED, 0, 0, NULL, MOJOSHADER_TYPE_UNKNOWN, 0xF) +INSTRUCTION_STATE(TEXM3X3SPEC, "TEXM3X3SPEC", 1, DSS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION_STATE(TEXM3X3VSPEC, "TEXM3X3VSPEC", 1, DS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION(EXPP, "EXPP", 1, DS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(LOGP, "LOGP", 1, DS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(CND, "CND", 1, DSSS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION_STATE(DEF, "DEF", 0, DEF, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION(TEXREG2RGB, "TEXREG2RGB", 1, DS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION(TEXDP3TEX, "TEXDP3TEX", 1, DS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION(TEXM3X2DEPTH, "TEXM3X2DEPTH", 1, DS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION(TEXDP3, "TEXDP3", 1, DS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION_STATE(TEXM3X3, "TEXM3X3", 1, DS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION(TEXDEPTH, "TEXDEPTH", 1, D, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION_STATE(CMP, "CMP", 1, DSSS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION(BEM, "BEM", 2, DSS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION_STATE(DP2ADD, "DP2ADD", 2, DSSS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION(DSX, "DSX", 2, DS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION(DSY, "DSY", 2, DS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION(TEXLDD, "TEXLDD", 3, DSSSS, MOJOSHADER_TYPE_PIXEL, 0xF) +INSTRUCTION_STATE(SETP, "SETP", 1, DSS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(TEXLDL, "TEXLDL", 2, DSS, MOJOSHADER_TYPE_ANY, 0xF) +INSTRUCTION_STATE(BREAKP, "BREAKP", 3, S, MOJOSHADER_TYPE_ANY, 0xF) + +#undef MOJOSHADER_DO_INSTRUCTION_TABLE +#undef INSTRUCTION +#undef INSTRUCTION_STATE + #endif // end of mojoshader_internal.h ... diff --git a/mojoshader/mojoshader_lexer.c b/mojoshader/mojoshader_lexer.c deleted file mode 100644 index 5336178..0000000 --- a/mojoshader/mojoshader_lexer.c +++ /dev/null @@ -1,1504 +0,0 @@ -/* Generated by re2c 0.13.5 */ -/** - * MojoShader; generate shader programs from bytecode of compiled - * Direct3D shaders. - * - * Please see the file LICENSE.txt in the source's root directory. - * - * This file written by Ryan C. Gordon. - */ - -// This was originally based on examples/pp-c.re from re2c: http://re2c.org/ -// re2c is public domain code. -// -// You build mojoshader_lexer_preprocessor.c from the .re file with re2c... -// re2c -is -o mojoshader_lexer_preprocessor.c mojoshader_lexer_preprocessor.re -// -// Changes to the lexer are done to the .re file, not the C code! -// -// Please note that this isn't a perfect C lexer, since it is used for both -// HLSL and shader assembly language, and follows the quirks of Microsoft's -// tools. - -#define __MOJOSHADER_INTERNAL__ 1 -#include "mojoshader_internal.h" - -typedef unsigned char uchar; - -#define YYMAXFILL 8 -#define RET(t) return update_state(s, eoi, cursor, token, (Token) t) -#define YYCTYPE uchar -#define YYCURSOR cursor -#define YYLIMIT limit -#define YYMARKER s->lexer_marker -#define YYFILL(n) { if ((n) == 1) { cursor = sentinel; limit = cursor + YYMAXFILL; eoi = 1; } } - -static uchar sentinel[YYMAXFILL]; - -static Token update_state(IncludeState *s, int eoi, const uchar *cur, - const uchar *tok, const Token val) -{ - if (eoi) - { - s->bytes_left = 0; - s->source = (const char *) s->source_base + s->orig_length; - if ( (tok >= sentinel) && (tok < (sentinel+YYMAXFILL)) ) - s->token = s->source; - else - s->token = (const char *) tok; - } // if - else - { - s->bytes_left -= (unsigned int) (cur - ((const uchar *) s->source)); - s->source = (const char *) cur; - s->token = (const char *) tok; - } // else - s->tokenlen = (unsigned int) (s->source - s->token); - s->tokenval = val; - return val; -} // update_state - -Token preprocessor_lexer(IncludeState *s) -{ - const uchar *cursor = (const uchar *) s->source; - const uchar *token = cursor; - const uchar *matchptr; - const uchar *limit = cursor + s->bytes_left; - int eoi = 0; - int saw_newline = 0; - - - - // preprocessor directives are only valid at start of line. - if (s->tokenval == ((Token) '\n')) - goto ppdirective; // may jump back to scanner_loop. - -scanner_loop: - if (YYLIMIT == YYCURSOR) YYFILL(1); - token = cursor; - - -{ - YYCTYPE yych; - unsigned int yyaccept = 0; - - if ((YYLIMIT - YYCURSOR) < 5) YYFILL(5); - yych = *YYCURSOR; - switch (yych) { - case 0x00: goto yy61; - case '\t': - case '\v': - case '\f': - case ' ': goto yy63; - case '\n': goto yy65; - case '\r': goto yy67; - case '!': goto yy35; - case '"': goto yy14; - case '#': goto yy37; - case '%': goto yy25; - case '&': goto yy29; - case '\'': goto yy11; - case '(': goto yy39; - case ')': goto yy41; - case '*': goto yy23; - case '+': goto yy19; - case ',': goto yy47; - case '-': goto yy21; - case '.': goto yy12; - case '/': goto yy4; - case '0': goto yy8; - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': goto yy10; - case ':': goto yy51; - case ';': goto yy59; - case '<': goto yy17; - case '=': goto yy33; - case '>': goto yy15; - case '?': goto yy57; - 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 '_': - 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': goto yy6; - case '[': goto yy43; - case '\\': goto yy2; - case ']': goto yy45; - case '^': goto yy27; - case '{': goto yy53; - case '|': goto yy31; - case '}': goto yy55; - case '~': goto yy49; - default: goto yy68; - } -yy2: - yyaccept = 0; - yych = *(YYMARKER = ++YYCURSOR); - if (yych <= 0x08) goto yy3; - if (yych <= '\r') goto yy177; - if (yych == ' ') goto yy177; -yy3: - { goto bad_chars; } -yy4: - ++YYCURSOR; - if ((yych = *YYCURSOR) <= '.') { - if (yych == '*') goto yy174; - } else { - if (yych <= '/') goto yy172; - if (yych == '=') goto yy170; - } - { RET('/'); } -yy6: - ++YYCURSOR; - yych = *YYCURSOR; - goto yy169; -yy7: - { RET(TOKEN_IDENTIFIER); } -yy8: - yyaccept = 1; - yych = *(YYMARKER = ++YYCURSOR); - if (yych <= 'X') { - if (yych <= 'T') { - if (yych == 'L') goto yy144; - goto yy160; - } else { - if (yych <= 'U') goto yy144; - if (yych <= 'W') goto yy160; - goto yy161; - } - } else { - if (yych <= 't') { - if (yych == 'l') goto yy144; - goto yy160; - } else { - if (yych <= 'u') goto yy144; - if (yych == 'x') goto yy161; - goto yy160; - } - } -yy9: - { RET(TOKEN_INT_LITERAL); } -yy10: - yyaccept = 1; - yych = *(YYMARKER = ++YYCURSOR); - goto yy142; -yy11: - yyaccept = 0; - yych = *(YYMARKER = ++YYCURSOR); - if (yych == '\n') goto yy3; - if (yych == '\r') goto yy3; - goto yy132; -yy12: - ++YYCURSOR; - if ((yych = *YYCURSOR) <= '/') goto yy13; - if (yych <= '9') goto yy123; -yy13: - { RET('.'); } -yy14: - yyaccept = 0; - yych = *(YYMARKER = ++YYCURSOR); - if (yych == '\n') goto yy3; - if (yych == '\r') goto yy3; - goto yy113; -yy15: - ++YYCURSOR; - if ((yych = *YYCURSOR) <= '<') goto yy16; - if (yych <= '=') goto yy106; - if (yych <= '>') goto yy108; -yy16: - { RET('>'); } -yy17: - ++YYCURSOR; - if ((yych = *YYCURSOR) <= ';') goto yy18; - if (yych <= '<') goto yy102; - if (yych <= '=') goto yy100; -yy18: - { RET('<'); } -yy19: - ++YYCURSOR; - if ((yych = *YYCURSOR) == '+') goto yy96; - if (yych == '=') goto yy98; - { RET('+'); } -yy21: - ++YYCURSOR; - if ((yych = *YYCURSOR) == '-') goto yy92; - if (yych == '=') goto yy94; - { RET('-'); } -yy23: - ++YYCURSOR; - if ((yych = *YYCURSOR) == '=') goto yy90; - { RET('*'); } -yy25: - ++YYCURSOR; - if ((yych = *YYCURSOR) == '=') goto yy88; - { RET('%'); } -yy27: - ++YYCURSOR; - if ((yych = *YYCURSOR) == '=') goto yy86; - { RET('^'); } -yy29: - ++YYCURSOR; - if ((yych = *YYCURSOR) == '&') goto yy82; - if (yych == '=') goto yy84; - { RET('&'); } -yy31: - ++YYCURSOR; - if ((yych = *YYCURSOR) == '=') goto yy80; - if (yych == '|') goto yy78; - { RET('|'); } -yy33: - ++YYCURSOR; - if ((yych = *YYCURSOR) == '=') goto yy76; - { RET('='); } -yy35: - ++YYCURSOR; - if ((yych = *YYCURSOR) == '=') goto yy74; - { RET('!'); } -yy37: - ++YYCURSOR; - if ((yych = *YYCURSOR) == '#') goto yy72; - { RET(TOKEN_HASH); } -yy39: - ++YYCURSOR; - { RET('('); } -yy41: - ++YYCURSOR; - { RET(')'); } -yy43: - ++YYCURSOR; - { RET('['); } -yy45: - ++YYCURSOR; - { RET(']'); } -yy47: - ++YYCURSOR; - { RET(','); } -yy49: - ++YYCURSOR; - { RET('~'); } -yy51: - ++YYCURSOR; - { RET(':'); } -yy53: - ++YYCURSOR; - { RET('{'); } -yy55: - ++YYCURSOR; - { RET('}'); } -yy57: - ++YYCURSOR; - { RET('?'); } -yy59: - ++YYCURSOR; - { if (s->asm_comments) goto singlelinecomment; RET(';'); } -yy61: - ++YYCURSOR; - { if (eoi) { RET(TOKEN_EOI); } goto bad_chars; } -yy63: - ++YYCURSOR; - yych = *YYCURSOR; - goto yy71; -yy64: - { if (s->report_whitespace) RET(' '); goto scanner_loop; } -yy65: - ++YYCURSOR; -yy66: - { s->line++; RET('\n'); } -yy67: - yych = *++YYCURSOR; - if (yych == '\n') goto yy69; - goto yy66; -yy68: - yych = *++YYCURSOR; - goto yy3; -yy69: - yych = *++YYCURSOR; - goto yy66; -yy70: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; -yy71: - if (yych <= '\n') { - if (yych == '\t') goto yy70; - goto yy64; - } else { - if (yych <= '\f') goto yy70; - if (yych == ' ') goto yy70; - goto yy64; - } -yy72: - ++YYCURSOR; - { RET(TOKEN_HASHHASH); } -yy74: - ++YYCURSOR; - { RET(TOKEN_NEQ); } -yy76: - ++YYCURSOR; - { RET(TOKEN_EQL); } -yy78: - ++YYCURSOR; - { RET(TOKEN_OROR); } -yy80: - ++YYCURSOR; - { RET(TOKEN_ORASSIGN); } -yy82: - ++YYCURSOR; - { RET(TOKEN_ANDAND); } -yy84: - ++YYCURSOR; - { RET(TOKEN_ANDASSIGN); } -yy86: - ++YYCURSOR; - { RET(TOKEN_XORASSIGN); } -yy88: - ++YYCURSOR; - { RET(TOKEN_MODASSIGN); } -yy90: - ++YYCURSOR; - { RET(TOKEN_MULTASSIGN); } -yy92: - ++YYCURSOR; - { RET(TOKEN_DECREMENT); } -yy94: - ++YYCURSOR; - { RET(TOKEN_SUBASSIGN); } -yy96: - ++YYCURSOR; - { RET(TOKEN_INCREMENT); } -yy98: - ++YYCURSOR; - { RET(TOKEN_ADDASSIGN); } -yy100: - ++YYCURSOR; - { RET(TOKEN_LEQ); } -yy102: - ++YYCURSOR; - if ((yych = *YYCURSOR) == '=') goto yy104; - { RET(TOKEN_LSHIFT); } -yy104: - ++YYCURSOR; - { RET(TOKEN_LSHIFTASSIGN); } -yy106: - ++YYCURSOR; - { RET(TOKEN_GEQ); } -yy108: - ++YYCURSOR; - if ((yych = *YYCURSOR) == '=') goto yy110; - { RET(TOKEN_RSHIFT); } -yy110: - ++YYCURSOR; - { RET(TOKEN_RSHIFTASSIGN); } -yy112: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; -yy113: - if (yych <= '\r') { - if (yych == '\n') goto yy114; - if (yych <= '\f') goto yy112; - } else { - if (yych <= '"') { - if (yych <= '!') goto yy112; - goto yy116; - } else { - if (yych == '\\') goto yy115; - goto yy112; - } - } -yy114: - YYCURSOR = YYMARKER; - if (yyaccept <= 1) { - if (yyaccept <= 0) { - goto yy3; - } else { - goto yy9; - } - } else { - goto yy125; - } -yy115: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; - if (yych <= 'b') { - if (yych <= '7') { - if (yych <= '&') { - if (yych == '"') goto yy112; - goto yy114; - } else { - if (yych <= '\'') goto yy112; - if (yych <= '/') goto yy114; - goto yy119; - } - } else { - if (yych <= '[') { - if (yych == '?') goto yy112; - goto yy114; - } else { - if (yych <= '\\') goto yy112; - if (yych <= '`') goto yy114; - goto yy112; - } - } - } else { - if (yych <= 'r') { - if (yych <= 'm') { - if (yych == 'f') goto yy112; - goto yy114; - } else { - if (yych <= 'n') goto yy112; - if (yych <= 'q') goto yy114; - goto yy112; - } - } else { - if (yych <= 'u') { - if (yych == 't') goto yy112; - goto yy114; - } else { - if (yych <= 'v') goto yy112; - if (yych == 'x') goto yy118; - goto yy114; - } - } - } -yy116: - ++YYCURSOR; - { RET(TOKEN_STRING_LITERAL); } -yy118: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; - if (yych <= '@') { - if (yych <= '/') goto yy114; - if (yych <= '9') goto yy121; - goto yy114; - } else { - if (yych <= 'F') goto yy121; - if (yych <= '`') goto yy114; - if (yych <= 'f') goto yy121; - goto yy114; - } -yy119: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; - if (yych <= '!') { - if (yych <= '\n') { - if (yych <= '\t') goto yy112; - goto yy114; - } else { - if (yych == '\r') goto yy114; - goto yy112; - } - } else { - if (yych <= '7') { - if (yych <= '"') goto yy116; - if (yych <= '/') goto yy112; - goto yy119; - } else { - if (yych == '\\') goto yy115; - goto yy112; - } - } -yy121: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; - if (yych <= '/') { - if (yych <= '\f') { - if (yych == '\n') goto yy114; - goto yy112; - } else { - if (yych <= '\r') goto yy114; - if (yych == '"') goto yy116; - goto yy112; - } - } else { - if (yych <= '[') { - if (yych <= '9') goto yy121; - if (yych <= '@') goto yy112; - if (yych <= 'F') goto yy121; - goto yy112; - } else { - if (yych <= '\\') goto yy115; - if (yych <= '`') goto yy112; - if (yych <= 'f') goto yy121; - goto yy112; - } - } -yy123: - yyaccept = 2; - YYMARKER = ++YYCURSOR; - if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3); - yych = *YYCURSOR; - if (yych <= 'G') { - if (yych <= 'D') { - if (yych <= '/') goto yy125; - if (yych <= '9') goto yy123; - } else { - if (yych <= 'E') goto yy126; - if (yych <= 'F') goto yy127; - } - } else { - if (yych <= 'e') { - if (yych <= 'H') goto yy127; - if (yych >= 'e') goto yy126; - } else { - if (yych == 'g') goto yy125; - if (yych <= 'h') goto yy127; - } - } -yy125: - { RET(TOKEN_FLOAT_LITERAL); } -yy126: - yych = *++YYCURSOR; - if (yych <= ',') { - if (yych == '+') goto yy128; - goto yy114; - } else { - if (yych <= '-') goto yy128; - if (yych <= '/') goto yy114; - if (yych <= '9') goto yy129; - goto yy114; - } -yy127: - yych = *++YYCURSOR; - goto yy125; -yy128: - yych = *++YYCURSOR; - if (yych <= '/') goto yy114; - if (yych >= ':') goto yy114; -yy129: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; - if (yych <= 'G') { - if (yych <= '9') { - if (yych <= '/') goto yy125; - goto yy129; - } else { - if (yych == 'F') goto yy127; - goto yy125; - } - } else { - if (yych <= 'f') { - if (yych <= 'H') goto yy127; - if (yych <= 'e') goto yy125; - goto yy127; - } else { - if (yych == 'h') goto yy127; - goto yy125; - } - } -yy131: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; -yy132: - if (yych <= '\r') { - if (yych == '\n') goto yy114; - if (yych <= '\f') goto yy131; - goto yy114; - } else { - if (yych <= '\'') { - if (yych <= '&') goto yy131; - goto yy134; - } else { - if (yych != '\\') goto yy131; - } - } -yy133: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; - if (yych <= 'b') { - if (yych <= '7') { - if (yych <= '&') { - if (yych == '"') goto yy131; - goto yy114; - } else { - if (yych <= '\'') goto yy131; - if (yych <= '/') goto yy114; - goto yy136; - } - } else { - if (yych <= '[') { - if (yych == '?') goto yy131; - goto yy114; - } else { - if (yych <= '\\') goto yy131; - if (yych <= '`') goto yy114; - goto yy131; - } - } - } else { - if (yych <= 'r') { - if (yych <= 'm') { - if (yych == 'f') goto yy131; - goto yy114; - } else { - if (yych <= 'n') goto yy131; - if (yych <= 'q') goto yy114; - goto yy131; - } - } else { - if (yych <= 'u') { - if (yych == 't') goto yy131; - goto yy114; - } else { - if (yych <= 'v') goto yy131; - if (yych == 'x') goto yy135; - goto yy114; - } - } - } -yy134: - yych = *++YYCURSOR; - goto yy9; -yy135: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; - if (yych <= '@') { - if (yych <= '/') goto yy114; - if (yych <= '9') goto yy138; - goto yy114; - } else { - if (yych <= 'F') goto yy138; - if (yych <= '`') goto yy114; - if (yych <= 'f') goto yy138; - goto yy114; - } -yy136: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; - if (yych <= '&') { - if (yych <= '\n') { - if (yych <= '\t') goto yy131; - goto yy114; - } else { - if (yych == '\r') goto yy114; - goto yy131; - } - } else { - if (yych <= '7') { - if (yych <= '\'') goto yy134; - if (yych <= '/') goto yy131; - goto yy136; - } else { - if (yych == '\\') goto yy133; - goto yy131; - } - } -yy138: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; - if (yych <= '/') { - if (yych <= '\f') { - if (yych == '\n') goto yy114; - goto yy131; - } else { - if (yych <= '\r') goto yy114; - if (yych == '\'') goto yy134; - goto yy131; - } - } else { - if (yych <= '[') { - if (yych <= '9') goto yy138; - if (yych <= '@') goto yy131; - if (yych <= 'F') goto yy138; - goto yy131; - } else { - if (yych <= '\\') goto yy133; - if (yych <= '`') goto yy131; - if (yych <= 'f') goto yy138; - goto yy131; - } - } -yy140: - yyaccept = 2; - yych = *(YYMARKER = ++YYCURSOR); - if (yych == 'E') goto yy151; - if (yych == 'e') goto yy151; - goto yy150; -yy141: - yyaccept = 1; - YYMARKER = ++YYCURSOR; - if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4); - yych = *YYCURSOR; -yy142: - if (yych <= 'L') { - if (yych <= '9') { - if (yych == '.') goto yy140; - if (yych <= '/') goto yy9; - goto yy141; - } else { - if (yych == 'E') goto yy143; - if (yych <= 'K') goto yy9; - goto yy144; - } - } else { - if (yych <= 'e') { - if (yych == 'U') goto yy144; - if (yych <= 'd') goto yy9; - } else { - if (yych <= 'l') { - if (yych <= 'k') goto yy9; - goto yy144; - } else { - if (yych == 'u') goto yy144; - goto yy9; - } - } - } -yy143: - yych = *++YYCURSOR; - if (yych <= ',') { - if (yych == '+') goto yy146; - goto yy114; - } else { - if (yych <= '-') goto yy146; - if (yych <= '/') goto yy114; - if (yych <= '9') goto yy147; - goto yy114; - } -yy144: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; - if (yych <= 'U') { - if (yych == 'L') goto yy144; - if (yych <= 'T') goto yy9; - goto yy144; - } else { - if (yych <= 'l') { - if (yych <= 'k') goto yy9; - goto yy144; - } else { - if (yych == 'u') goto yy144; - goto yy9; - } - } -yy146: - yych = *++YYCURSOR; - if (yych <= '/') goto yy114; - if (yych >= ':') goto yy114; -yy147: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; - if (yych <= 'G') { - if (yych <= '9') { - if (yych <= '/') goto yy125; - goto yy147; - } else { - if (yych == 'F') goto yy127; - goto yy125; - } - } else { - if (yych <= 'f') { - if (yych <= 'H') goto yy127; - if (yych <= 'e') goto yy125; - goto yy127; - } else { - if (yych == 'h') goto yy127; - goto yy125; - } - } -yy149: - yyaccept = 2; - YYMARKER = ++YYCURSOR; - if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3); - yych = *YYCURSOR; -yy150: - if (yych <= 'G') { - if (yych <= 'D') { - if (yych <= '/') goto yy125; - if (yych <= '9') goto yy149; - goto yy125; - } else { - if (yych <= 'E') goto yy155; - if (yych <= 'F') goto yy127; - goto yy125; - } - } else { - if (yych <= 'e') { - if (yych <= 'H') goto yy127; - if (yych <= 'd') goto yy125; - goto yy155; - } else { - if (yych == 'g') goto yy125; - if (yych <= 'h') goto yy127; - goto yy125; - } - } -yy151: - yych = *++YYCURSOR; - if (yych <= ',') { - if (yych != '+') goto yy114; - } else { - if (yych <= '-') goto yy152; - if (yych <= '/') goto yy114; - if (yych <= '9') goto yy153; - goto yy114; - } -yy152: - yych = *++YYCURSOR; - if (yych <= '/') goto yy114; - if (yych >= ':') goto yy114; -yy153: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; - if (yych <= 'G') { - if (yych <= '9') { - if (yych <= '/') goto yy125; - goto yy153; - } else { - if (yych == 'F') goto yy127; - goto yy125; - } - } else { - if (yych <= 'f') { - if (yych <= 'H') goto yy127; - if (yych <= 'e') goto yy125; - goto yy127; - } else { - if (yych == 'h') goto yy127; - goto yy125; - } - } -yy155: - yych = *++YYCURSOR; - if (yych <= ',') { - if (yych != '+') goto yy114; - } else { - if (yych <= '-') goto yy156; - if (yych <= '/') goto yy114; - if (yych <= '9') goto yy157; - goto yy114; - } -yy156: - yych = *++YYCURSOR; - if (yych <= '/') goto yy114; - if (yych >= ':') goto yy114; -yy157: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; - if (yych <= 'G') { - if (yych <= '9') { - if (yych <= '/') goto yy125; - goto yy157; - } else { - if (yych == 'F') goto yy127; - goto yy125; - } - } else { - if (yych <= 'f') { - if (yych <= 'H') goto yy127; - if (yych <= 'e') goto yy125; - goto yy127; - } else { - if (yych == 'h') goto yy127; - goto yy125; - } - } -yy159: - yyaccept = 1; - YYMARKER = ++YYCURSOR; - if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4); - yych = *YYCURSOR; -yy160: - if (yych <= 'L') { - if (yych <= '9') { - if (yych == '.') goto yy140; - if (yych <= '/') goto yy9; - goto yy159; - } else { - if (yych == 'E') goto yy143; - if (yych <= 'K') goto yy9; - goto yy166; - } - } else { - if (yych <= 'e') { - if (yych == 'U') goto yy166; - if (yych <= 'd') goto yy9; - goto yy143; - } else { - if (yych <= 'l') { - if (yych <= 'k') goto yy9; - goto yy166; - } else { - if (yych == 'u') goto yy166; - goto yy9; - } - } - } -yy161: - yych = *++YYCURSOR; - if (yych <= '@') { - if (yych <= '/') goto yy114; - if (yych >= ':') goto yy114; - } else { - if (yych <= 'F') goto yy162; - if (yych <= '`') goto yy114; - if (yych >= 'g') goto yy114; - } -yy162: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; - if (yych <= 'T') { - if (yych <= '@') { - if (yych <= '/') goto yy9; - if (yych <= '9') goto yy162; - goto yy9; - } else { - if (yych <= 'F') goto yy162; - if (yych != 'L') goto yy9; - } - } else { - if (yych <= 'k') { - if (yych <= 'U') goto yy164; - if (yych <= '`') goto yy9; - if (yych <= 'f') goto yy162; - goto yy9; - } else { - if (yych <= 'l') goto yy164; - if (yych != 'u') goto yy9; - } - } -yy164: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; - if (yych <= 'U') { - if (yych == 'L') goto yy164; - if (yych <= 'T') goto yy9; - goto yy164; - } else { - if (yych <= 'l') { - if (yych <= 'k') goto yy9; - goto yy164; - } else { - if (yych == 'u') goto yy164; - goto yy9; - } - } -yy166: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; - if (yych <= 'U') { - if (yych == 'L') goto yy166; - if (yych <= 'T') goto yy9; - goto yy166; - } else { - if (yych <= 'l') { - if (yych <= 'k') goto yy9; - goto yy166; - } else { - if (yych == 'u') goto yy166; - goto yy9; - } - } -yy168: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; -yy169: - if (yych <= 'Z') { - if (yych <= '/') goto yy7; - if (yych <= '9') goto yy168; - if (yych <= '@') goto yy7; - goto yy168; - } else { - if (yych <= '_') { - if (yych <= '^') goto yy7; - goto yy168; - } else { - if (yych <= '`') goto yy7; - if (yych <= 'z') goto yy168; - goto yy7; - } - } -yy170: - ++YYCURSOR; - { RET(TOKEN_DIVASSIGN); } -yy172: - ++YYCURSOR; - { goto singlelinecomment; } -yy174: - ++YYCURSOR; - { goto multilinecomment; } -yy176: - ++YYCURSOR; - if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); - yych = *YYCURSOR; -yy177: - if (yych <= '\f') { - if (yych <= 0x08) goto yy114; - if (yych != '\n') goto yy176; - } else { - if (yych <= '\r') goto yy180; - if (yych == ' ') goto yy176; - goto yy114; - } -yy178: - ++YYCURSOR; -yy179: - { s->line++; goto scanner_loop; } -yy180: - ++YYCURSOR; - if ((yych = *YYCURSOR) == '\n') goto yy178; - goto yy179; -} - - -multilinecomment: - if (YYLIMIT == YYCURSOR) YYFILL(1); - matchptr = cursor; -// The "*\/" is just to avoid screwing up text editor syntax highlighting. - -{ - YYCTYPE yych; - if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); - yych = *YYCURSOR; - if (yych <= '\f') { - if (yych <= 0x00) goto yy188; - if (yych == '\n') goto yy185; - goto yy190; - } else { - if (yych <= '\r') goto yy187; - if (yych != '*') goto yy190; - } - ++YYCURSOR; - if ((yych = *YYCURSOR) == '/') goto yy192; -yy184: - { goto multilinecomment; } -yy185: - ++YYCURSOR; -yy186: - { - s->line++; - token = matchptr; - saw_newline = 1; - goto multilinecomment; - } -yy187: - yych = *++YYCURSOR; - if (yych == '\n') goto yy191; - goto yy186; -yy188: - ++YYCURSOR; - { - if (eoi) - RET(TOKEN_INCOMPLETE_COMMENT); - goto multilinecomment; - } -yy190: - yych = *++YYCURSOR; - goto yy184; -yy191: - yych = *++YYCURSOR; - goto yy186; -yy192: - ++YYCURSOR; - { - if (saw_newline) - RET('\n'); - else if (s->report_whitespace) - RET(' '); - goto scanner_loop; - } -} - - -singlelinecomment: - if (YYLIMIT == YYCURSOR) YYFILL(1); - matchptr = cursor; - -{ - YYCTYPE yych; - if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); - yych = *YYCURSOR; - if (yych <= '\n') { - if (yych <= 0x00) goto yy199; - if (yych <= '\t') goto yy201; - } else { - if (yych == '\r') goto yy198; - goto yy201; - } - ++YYCURSOR; -yy197: - { s->line++; token = matchptr; RET('\n'); } -yy198: - yych = *++YYCURSOR; - if (yych == '\n') goto yy203; - goto yy197; -yy199: - ++YYCURSOR; - { if (eoi) { RET(TOKEN_EOI); } goto singlelinecomment; } -yy201: - ++YYCURSOR; - { goto singlelinecomment; } -yy203: - ++YYCURSOR; - yych = *YYCURSOR; - goto yy197; -} - - -ppdirective: - if (YYLIMIT == YYCURSOR) YYFILL(1); - -{ - YYCTYPE yych; - unsigned int yyaccept = 0; - if ((YYLIMIT - YYCURSOR) < 8) YYFILL(8); - yych = *YYCURSOR; - if (yych <= '\f') { - if (yych == '\t') goto yy208; - if (yych <= '\n') goto yy210; - goto yy208; - } else { - if (yych <= ' ') { - if (yych <= 0x1F) goto yy210; - goto yy208; - } else { - if (yych != '#') goto yy210; - } - } - yyaccept = 0; - yych = *(YYMARKER = ++YYCURSOR); - if (yych <= 'h') { - if (yych <= 0x1F) { - if (yych == '\t') goto yy214; - } else { - if (yych <= ' ') goto yy214; - if (yych <= 'c') goto yy207; - if (yych <= 'e') goto yy214; - } - } else { - if (yych <= 'o') { - if (yych <= 'i') goto yy214; - if (yych == 'l') goto yy214; - } else { - if (yych <= 'p') goto yy214; - if (yych == 'u') goto yy214; - } - } -yy207: - { - token = cursor = (const uchar *) s->source; - limit = cursor + s->bytes_left; - goto scanner_loop; - } -yy208: - ++YYCURSOR; - yych = *YYCURSOR; - goto yy212; -yy209: - { goto ppdirective; } -yy210: - yych = *++YYCURSOR; - goto yy207; -yy211: - ++YYCURSOR; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; -yy212: - if (yych <= '\n') { - if (yych == '\t') goto yy211; - goto yy209; - } else { - if (yych <= '\f') goto yy211; - if (yych == ' ') goto yy211; - goto yy209; - } -yy213: - ++YYCURSOR; - if ((YYLIMIT - YYCURSOR) < 7) YYFILL(7); - yych = *YYCURSOR; -yy214: - if (yych <= 'h') { - if (yych <= ' ') { - if (yych == '\t') goto yy213; - if (yych >= ' ') goto yy213; - } else { - if (yych <= 'c') goto yy215; - if (yych <= 'd') goto yy220; - if (yych <= 'e') goto yy217; - } - } else { - if (yych <= 'o') { - if (yych <= 'i') goto yy218; - if (yych == 'l') goto yy221; - } else { - if (yych <= 'p') goto yy216; - if (yych == 'u') goto yy219; - } - } -yy215: - YYCURSOR = YYMARKER; - if (yyaccept <= 0) { - goto yy207; - } else { - goto yy239; - } -yy216: - yych = *++YYCURSOR; - if (yych == 'r') goto yy272; - goto yy215; -yy217: - yych = *++YYCURSOR; - if (yych <= 'm') { - if (yych == 'l') goto yy255; - goto yy215; - } else { - if (yych <= 'n') goto yy256; - if (yych == 'r') goto yy257; - goto yy215; - } -yy218: - yych = *++YYCURSOR; - if (yych == 'f') goto yy238; - if (yych == 'n') goto yy237; - goto yy215; -yy219: - yych = *++YYCURSOR; - if (yych == 'n') goto yy232; - goto yy215; -yy220: - yych = *++YYCURSOR; - if (yych == 'e') goto yy226; - goto yy215; -yy221: - yych = *++YYCURSOR; - if (yych != 'i') goto yy215; - yych = *++YYCURSOR; - if (yych != 'n') goto yy215; - yych = *++YYCURSOR; - if (yych != 'e') goto yy215; - ++YYCURSOR; - { RET(TOKEN_PP_LINE); } -yy226: - yych = *++YYCURSOR; - if (yych != 'f') goto yy215; - yych = *++YYCURSOR; - if (yych != 'i') goto yy215; - yych = *++YYCURSOR; - if (yych != 'n') goto yy215; - yych = *++YYCURSOR; - if (yych != 'e') goto yy215; - ++YYCURSOR; - { RET(TOKEN_PP_DEFINE); } -yy232: - yych = *++YYCURSOR; - if (yych != 'd') goto yy215; - yych = *++YYCURSOR; - if (yych != 'e') goto yy215; - yych = *++YYCURSOR; - if (yych != 'f') goto yy215; - ++YYCURSOR; - { RET(TOKEN_PP_UNDEF); } -yy237: - yych = *++YYCURSOR; - if (yych == 'c') goto yy249; - goto yy215; -yy238: - yyaccept = 1; - yych = *(YYMARKER = ++YYCURSOR); - if (yych == 'd') goto yy241; - if (yych == 'n') goto yy240; -yy239: - { RET(TOKEN_PP_IF); } -yy240: - yych = *++YYCURSOR; - if (yych == 'd') goto yy245; - goto yy215; -yy241: - yych = *++YYCURSOR; - if (yych != 'e') goto yy215; - yych = *++YYCURSOR; - if (yych != 'f') goto yy215; - ++YYCURSOR; - { RET(TOKEN_PP_IFDEF); } -yy245: - yych = *++YYCURSOR; - if (yych != 'e') goto yy215; - yych = *++YYCURSOR; - if (yych != 'f') goto yy215; - ++YYCURSOR; - { RET(TOKEN_PP_IFNDEF); } -yy249: - yych = *++YYCURSOR; - if (yych != 'l') goto yy215; - yych = *++YYCURSOR; - if (yych != 'u') goto yy215; - yych = *++YYCURSOR; - if (yych != 'd') goto yy215; - yych = *++YYCURSOR; - if (yych != 'e') goto yy215; - ++YYCURSOR; - { RET(TOKEN_PP_INCLUDE); } -yy255: - yych = *++YYCURSOR; - if (yych == 'i') goto yy266; - if (yych == 's') goto yy267; - goto yy215; -yy256: - yych = *++YYCURSOR; - if (yych == 'd') goto yy262; - goto yy215; -yy257: - yych = *++YYCURSOR; - if (yych != 'r') goto yy215; - yych = *++YYCURSOR; - if (yych != 'o') goto yy215; - yych = *++YYCURSOR; - if (yych != 'r') goto yy215; - ++YYCURSOR; - { RET(TOKEN_PP_ERROR); } -yy262: - yych = *++YYCURSOR; - if (yych != 'i') goto yy215; - yych = *++YYCURSOR; - if (yych != 'f') goto yy215; - ++YYCURSOR; - { RET(TOKEN_PP_ENDIF); } -yy266: - yych = *++YYCURSOR; - if (yych == 'f') goto yy270; - goto yy215; -yy267: - yych = *++YYCURSOR; - if (yych != 'e') goto yy215; - ++YYCURSOR; - { RET(TOKEN_PP_ELSE); } -yy270: - ++YYCURSOR; - { RET(TOKEN_PP_ELIF); } -yy272: - yych = *++YYCURSOR; - if (yych != 'a') goto yy215; - yych = *++YYCURSOR; - if (yych != 'g') goto yy215; - yych = *++YYCURSOR; - if (yych != 'm') goto yy215; - yych = *++YYCURSOR; - if (yych != 'a') goto yy215; - ++YYCURSOR; - { RET(TOKEN_PP_PRAGMA); } -} - - -bad_chars: - if (YYLIMIT == YYCURSOR) YYFILL(1); - -{ - YYCTYPE yych; - if (YYLIMIT <= YYCURSOR) YYFILL(1); - yych = *YYCURSOR; - if (yych <= '#') { - if (yych <= '\r') { - if (yych <= 0x00) goto yy282; - if (yych <= 0x08) goto yy284; - } else { - if (yych <= 0x1F) goto yy284; - if (yych == '"') goto yy284; - } - } else { - if (yych <= '@') { - if (yych <= '$') goto yy284; - if (yych >= '@') goto yy284; - } else { - if (yych == '`') goto yy284; - if (yych >= 0x7F) goto yy284; - } - } - ++YYCURSOR; - { cursor--; RET(TOKEN_BAD_CHARS); } -yy282: - ++YYCURSOR; - { - if (eoi) - { - assert( !((token >= sentinel) && - (token < sentinel+YYMAXFILL)) ); - eoi = 0; - cursor = (uchar *) s->source_base + s->orig_length; - RET(TOKEN_BAD_CHARS); // next call will be EOI. - } - goto bad_chars; - } -yy284: - ++YYCURSOR; - { goto bad_chars; } -} - - - assert(0 && "Shouldn't hit this code"); - RET(TOKEN_UNKNOWN); -} // preprocessor_lexer - -// end of mojoshader_lexer_preprocessor.re (or .c) ... - diff --git a/mojoshader/mojoshader_lexer.re b/mojoshader/mojoshader_lexer.re deleted file mode 100644 index 0ac656a..0000000 --- a/mojoshader/mojoshader_lexer.re +++ /dev/null @@ -1,249 +0,0 @@ -/** - * MojoShader; generate shader programs from bytecode of compiled - * Direct3D shaders. - * - * Please see the file LICENSE.txt in the source's root directory. - * - * This file written by Ryan C. Gordon. - */ - -// This was originally based on examples/pp-c.re from re2c: http://re2c.org/ -// re2c is public domain code. -// -// You build mojoshader_lexer_preprocessor.c from the .re file with re2c... -// re2c -is -o mojoshader_lexer_preprocessor.c mojoshader_lexer_preprocessor.re -// -// Changes to the lexer are done to the .re file, not the C code! -// -// Please note that this isn't a perfect C lexer, since it is used for both -// HLSL and shader assembly language, and follows the quirks of Microsoft's -// tools. - -#define __MOJOSHADER_INTERNAL__ 1 -#include "mojoshader_internal.h" - -typedef unsigned char uchar; - -/*!max:re2c */ -#define RET(t) return update_state(s, eoi, cursor, token, (Token) t) -#define YYCTYPE uchar -#define YYCURSOR cursor -#define YYLIMIT limit -#define YYMARKER s->lexer_marker -#define YYFILL(n) { if ((n) == 1) { cursor = sentinel; limit = cursor + YYMAXFILL; eoi = 1; } } - -static uchar sentinel[YYMAXFILL]; - -static Token update_state(IncludeState *s, int eoi, const uchar *cur, - const uchar *tok, const Token val) -{ - if (eoi) - { - s->bytes_left = 0; - s->source = (const char *) s->source_base + s->orig_length; - if ( (tok >= sentinel) && (tok < (sentinel+YYMAXFILL)) ) - s->token = s->source; - else - s->token = (const char *) tok; - } // if - else - { - s->bytes_left -= (unsigned int) (cur - ((const uchar *) s->source)); - s->source = (const char *) cur; - s->token = (const char *) tok; - } // else - s->tokenlen = (unsigned int) (s->source - s->token); - s->tokenval = val; - return val; -} // update_state - -Token preprocessor_lexer(IncludeState *s) -{ - const uchar *cursor = (const uchar *) s->source; - const uchar *token = cursor; - const uchar *matchptr; - const uchar *limit = cursor + s->bytes_left; - int eoi = 0; - int saw_newline = 0; - -/*!re2c - ANY = [\000-\377]; - ANYLEGAL = [a-zA-Z0-9_/'*=+%^&|!#<>()[{}.,~^:;? \t\v\f\r\n\-\]\\]; - O = [0-7]; - D = [0-9]; - L = [a-zA-Z_]; - H = [a-fA-F0-9]; - E = [Ee] [+-]? D+; - FS = [fFhH]; - IS = [uUlL]*; - ESC = [\\] ([abfnrtv?'"\\] | "x" H+ | O+); - PP = "#" [ \t]*; - NEWLINE = ("\r\n" | "\r" | "\n"); - WHITESPACE = [ \t\v\f]+; -*/ - - // preprocessor directives are only valid at start of line. - if (s->tokenval == ((Token) '\n')) - goto ppdirective; // may jump back to scanner_loop. - -scanner_loop: - if (YYLIMIT == YYCURSOR) YYFILL(1); - token = cursor; - -/*!re2c - "\\" [ \t\v\f]* NEWLINE { s->line++; goto scanner_loop; } - - "/*" { goto multilinecomment; } - "//" { goto singlelinecomment; } - - L (L|D)* { RET(TOKEN_IDENTIFIER); } - - ("0" [xX] H+ IS?) | ("0" D+ IS?) | (D+ IS?) | - (['] (ESC|ANY\[\r\n\\'])* [']) - { RET(TOKEN_INT_LITERAL); } - - (D+ E FS?) | (D* "." D+ E? FS?) | (D+ "." D* E? FS?) - { RET(TOKEN_FLOAT_LITERAL); } - - (["] (ESC|ANY\[\r\n\\"])* ["]) - { RET(TOKEN_STRING_LITERAL); } - - ">>=" { RET(TOKEN_RSHIFTASSIGN); } - "<<=" { RET(TOKEN_LSHIFTASSIGN); } - "+=" { RET(TOKEN_ADDASSIGN); } - "-=" { RET(TOKEN_SUBASSIGN); } - "*=" { RET(TOKEN_MULTASSIGN); } - "/=" { RET(TOKEN_DIVASSIGN); } - "%=" { RET(TOKEN_MODASSIGN); } - "^=" { RET(TOKEN_XORASSIGN); } - "&=" { RET(TOKEN_ANDASSIGN); } - "|=" { RET(TOKEN_ORASSIGN); } - "++" { RET(TOKEN_INCREMENT); } - "--" { RET(TOKEN_DECREMENT); } - ">>" { RET(TOKEN_RSHIFT); } - "<<" { RET(TOKEN_LSHIFT); } - "&&" { RET(TOKEN_ANDAND); } - "||" { RET(TOKEN_OROR); } - "<=" { RET(TOKEN_LEQ); } - ">=" { RET(TOKEN_GEQ); } - "==" { RET(TOKEN_EQL); } - "!=" { RET(TOKEN_NEQ); } - "#" { RET(TOKEN_HASH); } - "##" { RET(TOKEN_HASHHASH); } - "(" { RET('('); } - ")" { RET(')'); } - "[" { RET('['); } - "]" { RET(']'); } - "." { RET('.'); } - "," { RET(','); } - "&" { RET('&'); } - "!" { RET('!'); } - "~" { RET('~'); } - "-" { RET('-'); } - "+" { RET('+'); } - "*" { RET('*'); } - "/" { RET('/'); } - "%" { RET('%'); } - "<" { RET('<'); } - ">" { RET('>'); } - "^" { RET('^'); } - "|" { RET('|'); } - ":" { RET(':'); } - "{" { RET('{'); } - "}" { RET('}'); } - "=" { RET('='); } - "?" { RET('?'); } - - ";" { if (s->asm_comments) goto singlelinecomment; RET(';'); } - - "\000" { if (eoi) { RET(TOKEN_EOI); } goto bad_chars; } - - WHITESPACE { if (s->report_whitespace) RET(' '); goto scanner_loop; } - NEWLINE { s->line++; RET('\n'); } - ANY { goto bad_chars; } -*/ - -multilinecomment: - if (YYLIMIT == YYCURSOR) YYFILL(1); - matchptr = cursor; -// The "*\/" is just to avoid screwing up text editor syntax highlighting. -/*!re2c - "*\/" { - if (saw_newline) - RET('\n'); - else if (s->report_whitespace) - RET(' '); - goto scanner_loop; - } - NEWLINE { - s->line++; - token = matchptr; - saw_newline = 1; - goto multilinecomment; - } - "\000" { - if (eoi) - RET(TOKEN_INCOMPLETE_COMMENT); - goto multilinecomment; - } - ANY { goto multilinecomment; } -*/ - -singlelinecomment: - if (YYLIMIT == YYCURSOR) YYFILL(1); - matchptr = cursor; -/*!re2c - NEWLINE { s->line++; token = matchptr; RET('\n'); } - "\000" { if (eoi) { RET(TOKEN_EOI); } goto singlelinecomment; } - ANY { goto singlelinecomment; } -*/ - -ppdirective: - if (YYLIMIT == YYCURSOR) YYFILL(1); -/*!re2c - PP "include" { RET(TOKEN_PP_INCLUDE); } - PP "line" { RET(TOKEN_PP_LINE); } - PP "define" { RET(TOKEN_PP_DEFINE); } - PP "undef" { RET(TOKEN_PP_UNDEF); } - PP "if" { RET(TOKEN_PP_IF); } - PP "ifdef" { RET(TOKEN_PP_IFDEF); } - PP "ifndef" { RET(TOKEN_PP_IFNDEF); } - PP "else" { RET(TOKEN_PP_ELSE); } - PP "elif" { RET(TOKEN_PP_ELIF); } - PP "endif" { RET(TOKEN_PP_ENDIF); } - PP "error" { RET(TOKEN_PP_ERROR); } - PP "pragma" { RET(TOKEN_PP_PRAGMA); } - WHITESPACE { goto ppdirective; } - - ANY { - token = cursor = (const uchar *) s->source; - limit = cursor + s->bytes_left; - goto scanner_loop; - } -*/ - -bad_chars: - if (YYLIMIT == YYCURSOR) YYFILL(1); -/*!re2c - ANYLEGAL { cursor--; RET(TOKEN_BAD_CHARS); } - "\000" { - if (eoi) - { - assert( !((token >= sentinel) && - (token < sentinel+YYMAXFILL)) ); - eoi = 0; - cursor = (uchar *) s->source_base + s->orig_length; - RET(TOKEN_BAD_CHARS); // next call will be EOI. - } - goto bad_chars; - } - - ANY { goto bad_chars; } -*/ - - assert(0 && "Shouldn't hit this code"); - RET(TOKEN_UNKNOWN); -} // preprocessor_lexer - -// end of mojoshader_lexer_preprocessor.re (or .c) ... - diff --git a/mojoshader/mojoshader_opengl.c b/mojoshader/mojoshader_opengl.c index 260abf2..d4ac441 100644 --- a/mojoshader/mojoshader_opengl.c +++ b/mojoshader/mojoshader_opengl.c @@ -7,24 +7,17 @@ * This file written by Ryan C. Gordon. */ -// !!! FIXME: preshaders shouldn't be handled in here at all. This should -// !!! FIXME: be in the Effects API, once that's actually written. - -#include -#include -#include -#include -#include - -// !!! FIXME: most of these _MSC_VER should probably be _WINDOWS? -#ifdef _MSC_VER +#ifdef _WIN32 #define WIN32_LEAN_AND_MEAN 1 #include // GL headers need this for WINGDIAPI definition. #endif #if (defined(__APPLE__) && defined(__MACH__)) -//#define PLATFORM_MACOSX 1 -#endif +#include "TargetConditionals.h" +#if !TARGET_OS_IPHONE && !TARGET_OS_TV +#define PLATFORM_MACOSX 1 +#endif /* !TARGET_OS_IPHONE && !TARGET_OS_TV */ +#endif /* (defined(__APPLE__) && defined(__MACH__)) */ #if PLATFORM_MACOSX #include @@ -37,6 +30,10 @@ #include "GL/gl.h" #include "GL/glext.h" +#if SUPPORT_PROFILE_GLSPIRV +#include "spirv/spirv.h" +#endif + #ifndef GL_HALF_FLOAT_NV #define GL_HALF_FLOAT_NV 0x140B #endif @@ -54,6 +51,19 @@ #define GL_PROGRAM_POINT_SIZE 0x8642 #endif +// FIXME: ARB_gl_spirv in glext.h? -flibit +#ifndef GL_ARB_gl_spirv +#define GL_ARB_gl_spirv 1 +#define GL_SHADER_BINARY_FORMAT_SPIR_V_ARB 0x9551 +typedef void (APIENTRYP PFNGLSPECIALIZESHADERARBPROC) ( + GLuint shader, + const GLchar* pEntryPoint, + GLuint numSpecializationConstants, + const GLuint* pConstantIndex, + const GLuint* pConstantValue +); +#endif + struct MOJOSHADER_glShader { const MOJOSHADER_parseData *parseData; @@ -98,15 +108,19 @@ struct MOJOSHADER_glProgram size_t ps_uniforms_bool_count; GLint *ps_uniforms_bool; - size_t vs_preshader_reg_count; - GLfloat *vs_preshader_regs; - size_t ps_preshader_reg_count; - GLfloat *ps_preshader_regs; - uint32 refcount; int uses_pointsize; + // According to MSDN... + // + // n is an optional integer between 0 and the number of resources supported. + // For example, POSITION0, TEXCOOR1, etc. + // + // The input registers consist of 16 four-component floating-point vectors, + // designated as v0 through v15. + GLint vertex_attrib_loc[MOJOSHADER_USAGE_TOTAL][16]; + // GLSL uses these...location of uniform arrays. GLint vs_float4_loc; GLint vs_int4_loc; @@ -114,6 +128,14 @@ struct MOJOSHADER_glProgram GLint ps_float4_loc; GLint ps_int4_loc; GLint ps_bool_loc; + + // Numerous fixes for coordinate system mismatches + GLint ps_vpos_flip_loc; + int current_vpos_flip[2]; +#ifdef MOJOSHADER_FLIP_RENDERTARGET + GLint vs_flip_loc; + int current_flip; +#endif }; #ifndef WINGDIAPI @@ -163,6 +185,9 @@ struct MOJOSHADER_glContext uint8 want_attr[32]; uint8 have_attr[32]; + // This shadows vertex attribute and divisor states. + GLuint attr_divisor[32]; + // rarely used, so we don't touch when we don't have to. int pointsize_enabled; @@ -174,9 +199,17 @@ struct MOJOSHADER_glContext MOJOSHADER_glProgram *bound_program; char profile[16]; +#ifdef MOJOSHADER_XNA4_VERTEX_TEXTURES + // Vertex texture sampler offset... + int vertex_sampler_offset; +#endif + // Extensions... int have_core_opengl; int have_opengl_2; // different entry points than ARB extensions. + int have_opengl_3; // different extension query. + int have_opengl_es; // different extension requirements + int have_opengl_es3; // different shader synxtax and attributes int have_GL_ARB_vertex_program; int have_GL_ARB_fragment_program; int have_GL_NV_vertex_program2_option; @@ -190,9 +223,13 @@ struct MOJOSHADER_glContext int have_GL_NV_half_float; int have_GL_ARB_half_float_vertex; int have_GL_OES_vertex_half_float; + int have_GL_ARB_instanced_arrays; + int have_GL_ARB_ES2_compatibility; + int have_GL_ARB_gl_spirv; // Entry points... PFNGLGETSTRINGPROC glGetString; + PFNGLGETSTRINGIPROC glGetStringi; PFNGLGETERRORPROC glGetError; PFNGLGETINTEGERVPROC glGetIntegerv; PFNGLENABLEPROC glEnable; @@ -207,6 +244,7 @@ struct MOJOSHADER_glContext PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray; PFNGLGETATTRIBLOCATIONPROC glGetAttribLocation; PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog; + PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog; PFNGLGETSHADERIVPROC glGetShaderiv; PFNGLGETPROGRAMIVPROC glGetProgramiv; PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation; @@ -214,6 +252,10 @@ struct MOJOSHADER_glContext PFNGLSHADERSOURCEPROC glShaderSource; PFNGLUNIFORM1IPROC glUniform1i; PFNGLUNIFORM1IVPROC glUniform1iv; + PFNGLUNIFORM2FPROC glUniform2f; +#ifdef MOJOSHADER_FLIP_RENDERTARGET + PFNGLUNIFORM1FPROC glUniform1f; +#endif PFNGLUNIFORM4FVPROC glUniform4fv; PFNGLUNIFORM4IVPROC glUniform4iv; PFNGLUSEPROGRAMPROC glUseProgram; @@ -244,6 +286,9 @@ struct MOJOSHADER_glContext PFNGLGENPROGRAMSARBPROC glGenProgramsARB; PFNGLBINDPROGRAMARBPROC glBindProgramARB; PFNGLPROGRAMSTRINGARBPROC glProgramStringARB; + PFNGLVERTEXATTRIBDIVISORARBPROC glVertexAttribDivisorARB; + PFNGLSHADERBINARYPROC glShaderBinary; + PFNGLSPECIALIZESHADERARBPROC glSpecializeShaderARB; // interface for profile-specific things. int (*profileMaxUniforms)(MOJOSHADER_shaderType shader_type); @@ -261,10 +306,20 @@ struct MOJOSHADER_glContext void (*profilePushSampler)(GLint loc, GLuint sampler); int (*profileMustPushConstantArrays)(void); int (*profileMustPushSamplers)(void); + void (*profileToggleProgramPointSize)(int enable); }; +#ifdef MOJOSHADER_NO_THREAD_LOCAL +#define MOJOSHADER_THREADLOCAL +#elif defined(_WIN32) +#define MOJOSHADER_THREADLOCAL __declspec(thread) +#elif defined(__GNUC__) || defined(__clang__) +#define MOJOSHADER_THREADLOCAL __thread +#else +#error Please define your platform. +#endif -static MOJOSHADER_glContext *ctx = NULL; +static MOJOSHADER_THREADLOCAL MOJOSHADER_glContext *ctx = NULL; // Error state... static char error_buffer[1024] = { '\0' }; @@ -277,18 +332,29 @@ static void set_error(const char *str) #if PLATFORM_MACOSX static inline int macosx_version_atleast(int x, int y, int z) { +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1050 + return 1; +#else static int checked = 0; static int combined = 0; if (!checked) { - SInt32 ver, major, minor, patch; + SInt32 ver = 0; + SInt32 major = 0; + SInt32 minor = 0; + SInt32 patch = 0; int convert = 0; if (Gestalt(gestaltSystemVersion, &ver) != noErr) + { ver = 0x1000; // oh well. + convert = 1; // split (ver) into (major),(minor),(patch). + } else if (ver < 0x1030) + { convert = 1; // split (ver) into (major),(minor),(patch). + } else { // presumably this won't fail. But if it does, we'll just use the @@ -315,6 +381,7 @@ static inline int macosx_version_atleast(int x, int y, int z) } // if return (combined >= ((x << 16) | (y << 8) | z)); +#endif } // macosx_version_atleast #endif @@ -349,7 +416,7 @@ static inline void toggle_gl_state(GLenum state, int val) // profile-specific implementations... -#if SUPPORT_PROFILE_GLSL +#if SUPPORT_PROFILE_GLSL || SUPPORT_PROFILE_GLSPIRV static inline GLenum glsl_shader_type(const MOJOSHADER_shaderType t) { // these enums match between core 2.0 and the ARB extensions. @@ -359,6 +426,7 @@ static inline GLenum glsl_shader_type(const MOJOSHADER_shaderType t) return GL_FRAGMENT_SHADER; // !!! FIXME: geometry shaders? + assert(0 && "Unknown GLSL shader type!"); return GL_NONE; } // glsl_shader_type @@ -382,7 +450,222 @@ static int impl_GLSL_MaxUniforms(MOJOSHADER_shaderType shader_type) return (int) val; } // impl_GLSL_MaxUniforms +#if SUPPORT_PROFILE_GLSPIRV +static const SpirvPatchTable* spv_getPatchTable(MOJOSHADER_glShader *shader) +{ + const MOJOSHADER_parseData *pd = shader->parseData; + size_t table_offset = pd->output_len - sizeof(SpirvPatchTable); + return (const SpirvPatchTable *) (pd->output + table_offset); +} // spv_getPatchTable + +static int spv_CompileShader(const MOJOSHADER_parseData *pd, int32 base_location, GLuint *s) +{ + GLint ok = 0; + + GLsizei data_len = pd->output_len - sizeof(SpirvPatchTable); + const GLvoid* data = pd->output; + uint32 *patched_data = NULL; + if (base_location) + { + size_t i, max; + + patched_data = (uint32 *) Malloc(data_len); + memcpy(patched_data, data, data_len); + const SpirvPatchTable *table = (const SpirvPatchTable *) &pd->output[data_len]; + if (table->vpflip.offset) patched_data[table->vpflip.offset] += base_location; + if (table->array_vec4.offset) patched_data[table->array_vec4.offset] += base_location; + if (table->array_ivec4.offset) patched_data[table->array_ivec4.offset] += base_location; + if (table->array_bool.offset) patched_data[table->array_bool.offset] += base_location; + + for (i = 0, max = STATICARRAYLEN(table->samplers); i < max; i++) + { + SpirvPatchEntry entry = table->samplers[i]; + if (entry.offset) + patched_data[entry.offset] += base_location; + } // for + + data = patched_data; + } // if + + const GLuint shader = ctx->glCreateShader(glsl_shader_type(pd->shader_type)); + ctx->glShaderBinary(1, &shader, GL_SHADER_BINARY_FORMAT_SPIR_V_ARB, data, data_len); + ctx->glSpecializeShaderARB(shader, pd->mainfn, 0, NULL, NULL); // FIXME: Spec Constants? -flibit + ctx->glGetShaderiv(shader, GL_COMPILE_STATUS, &ok); + + if (patched_data) + Free(patched_data); + + if (!ok) + { + GLsizei len = 0; + ctx->glGetShaderInfoLog(shader, sizeof(error_buffer), &len, + (GLchar *) error_buffer); + ctx->glDeleteShader(shader); + *s = 0; + return 0; + } // if + + *s = shader; + + return 1; +} // spv_CompileShader + +static int impl_SPIRV_CompileShader(const MOJOSHADER_parseData *pd, GLuint *s) +{ + // Compilation postponed until linking, but generate dummy shader id so hash table lookups work. + *s = ctx->glCreateShader(glsl_shader_type(pd->shader_type)); + return 1; +} // impl_SPIRV_CompileShader + +static GLuint impl_SPIRV_LinkProgram(MOJOSHADER_glShader *vshader, + MOJOSHADER_glShader *pshader) +{ + GLint ok = 0; + GLuint vs_handle = 0; + int32 base_location = 0; + + // Shader compilation postponed until linking due to locations being global + // in program. To avoid overlap between VS and PS, we need to know about + // other shader stages to assign final uniform/attrib locations before + // compilation. + + MOJOSHADER_spirv_link_attributes(vshader->parseData, pshader->parseData, 1); + + if (vshader) + { + if (!spv_CompileShader(vshader->parseData, base_location, &vs_handle)) + return 0; + + const SpirvPatchTable* patch_table = spv_getPatchTable(vshader); + base_location += patch_table->location_count; + } // if + + GLuint ps_handle = 0; + if (pshader) + { + if (!spv_CompileShader(pshader->parseData, base_location, &ps_handle)) + return 0; + } // if + + if (ctx->have_opengl_2) + { + const GLuint program = ctx->glCreateProgram(); + if (vs_handle) + { + ctx->glAttachShader(program, vs_handle); + ctx->glDeleteShader(vs_handle); + } // if + if (ps_handle) + { + ctx->glAttachShader(program, ps_handle); + ctx->glDeleteShader(ps_handle); + } // if + ctx->glLinkProgram(program); + ctx->glGetProgramiv(program, GL_LINK_STATUS, &ok); + if (!ok) + { + GLsizei len = 0; + ctx->glGetProgramInfoLog(program, sizeof (error_buffer), + &len, (GLchar *) error_buffer); + ctx->glDeleteProgram(program); + return 0; + } // if + + return program; + } // if + else + { + const GLhandleARB program = ctx->glCreateProgramObjectARB(); + assert(sizeof(program) == sizeof(GLuint)); // not always true on OS X! + if (vs_handle) + { + ctx->glAttachObjectARB(program, (GLhandleARB) vs_handle); + ctx->glDeleteObjectARB((GLhandleARB) vs_handle); + } // if + if (ps_handle) + { + ctx->glAttachObjectARB(program, (GLhandleARB) ps_handle); + ctx->glDeleteObjectARB((GLhandleARB) ps_handle); + } // if + ctx->glLinkProgramARB(program); + ctx->glGetObjectParameterivARB(program, GL_OBJECT_LINK_STATUS_ARB, &ok); + if (!ok) + { + GLsizei len = 0; + ctx->glGetInfoLogARB(program, sizeof (error_buffer), + &len, (GLcharARB *) error_buffer); + ctx->glDeleteObjectARB(program); + return 0; + } // if + + return (GLuint) program; + } // else +} // impl_SPIRV_LinkProgram + +static void impl_SPIRV_DeleteShader(const GLuint shader) +{ + ctx->glDeleteShader(shader); +} // impl_SPIRV_DeleteShader +static void impl_SPIRV_DeleteProgram(const GLuint program) +{ + if (ctx->have_opengl_2) + ctx->glDeleteProgram(program); + else + ctx->glDeleteObjectARB((GLhandleARB) program); +} // impl_SPIRV_DeleteProgram + +static GLint impl_SPIRV_GetAttribLocation(MOJOSHADER_glProgram *program, int idx) +{ + return idx; +} // impl_SPIRV_GetAttribLocation + +static GLint impl_SPIRV_GetUniformLocation(MOJOSHADER_glProgram *program, MOJOSHADER_glShader *shader, int idx) +{ + return 0; // no-op, we push this as one big-ass array now. +} // impl_SPIRV_GetUniformLocation + +static GLint impl_SPIRV_GetSamplerLocation(MOJOSHADER_glProgram *program, MOJOSHADER_glShader *shader, int idx) +{ + const SpirvPatchTable *table = spv_getPatchTable(shader); + GLint location = table->samplers[idx].location; + if (location == -1) + return location; + + assert(location >= 0); + if (shader->parseData->shader_type == MOJOSHADER_TYPE_PIXEL) + location += spv_getPatchTable(program->vertex)->location_count; + + return location; +} // impl_SPIRV_GetSamplerLocation + +static void impl_SPIRV_FinalInitProgram(MOJOSHADER_glProgram *program) +{ + const SpirvPatchTable *vs_table = spv_getPatchTable(program->vertex); + const SpirvPatchTable *ps_table = spv_getPatchTable(program->fragment); + program->vs_float4_loc = vs_table->array_vec4.location; + program->vs_int4_loc = vs_table->array_ivec4.location; + program->vs_bool_loc = vs_table->array_bool.location; + program->ps_float4_loc = ps_table->array_vec4.location; + program->ps_int4_loc = ps_table->array_ivec4.location; + program->ps_bool_loc = ps_table->array_bool.location; + program->ps_vpos_flip_loc = ps_table->vpflip.location; +#ifdef MOJOSHADER_FLIP_RENDERTARGET + program->vs_flip_loc = vs_table->vpflip.location; +#endif + + int32 ps_base_location = vs_table->location_count; + if (ps_base_location) + { + if (program->ps_float4_loc != -1) program->ps_float4_loc += ps_base_location; + if (program->ps_int4_loc != -1) program->ps_int4_loc += ps_base_location; + if (program->ps_bool_loc != -1) program->ps_bool_loc += ps_base_location; + if (program->ps_vpos_flip_loc != -1) program->ps_vpos_flip_loc += ps_base_location; + } // if +} // impl_SPIRV_FinalInitProgram +#endif // SUPPORT_PROFILE_GLSPIRV + +#if SUPPORT_PROFILE_GLSL static int impl_GLSL_CompileShader(const MOJOSHADER_parseData *pd, GLuint *s) { GLint ok = 0; @@ -398,8 +681,9 @@ static int impl_GLSL_CompileShader(const MOJOSHADER_parseData *pd, GLuint *s) if (!ok) { GLsizei len = 0; - ctx->glGetInfoLogARB(shader, sizeof (error_buffer), &len, + ctx->glGetShaderInfoLog(shader, sizeof (error_buffer), &len, (GLchar *) error_buffer); + ctx->glDeleteShader(shader); *s = 0; return 0; } // if @@ -419,6 +703,7 @@ static int impl_GLSL_CompileShader(const MOJOSHADER_parseData *pd, GLuint *s) GLsizei len = 0; ctx->glGetInfoLogARB(shader, sizeof (error_buffer), &len, (GLcharARB *) error_buffer); + ctx->glDeleteObjectARB(shader); *s = 0; return 0; } // if @@ -428,6 +713,7 @@ static int impl_GLSL_CompileShader(const MOJOSHADER_parseData *pd, GLuint *s) return 1; } // impl_GLSL_CompileShader +#endif // SUPPORT_PROFILE_GLSL static void impl_GLSL_DeleteShader(const GLuint shader) @@ -542,13 +828,16 @@ static GLuint impl_GLSL_LinkProgram(MOJOSHADER_glShader *vshader, static void impl_GLSL_FinalInitProgram(MOJOSHADER_glProgram *program) { - program->vs_float4_loc = glsl_uniform_loc(program, "vs_uniforms_vec4"); program->vs_int4_loc = glsl_uniform_loc(program, "vs_uniforms_ivec4"); program->vs_bool_loc = glsl_uniform_loc(program, "vs_uniforms_bool"); program->ps_float4_loc = glsl_uniform_loc(program, "ps_uniforms_vec4"); program->ps_int4_loc = glsl_uniform_loc(program, "ps_uniforms_ivec4"); program->ps_bool_loc = glsl_uniform_loc(program, "ps_uniforms_bool"); + program->ps_vpos_flip_loc = glsl_uniform_loc(program, "vposFlip"); +#ifdef MOJOSHADER_FLIP_RENDERTARGET + program->vs_flip_loc = glsl_uniform_loc(program, "vpFlip"); +#endif } // impl_GLSL_FinalInitProgram @@ -626,7 +915,7 @@ static void impl_GLSL_PushSampler(GLint loc, GLuint sampler) ctx->glUniform1i(loc, sampler); } // impl_GLSL_PushSampler -#endif // SUPPORT_PROFILE_GLSL +#endif // SUPPORT_PROFILE_GLSL || SUPPORT_PROFILE_GLSPIRV #if SUPPORT_PROFILE_ARB1 @@ -669,7 +958,7 @@ static int impl_ARB1_CompileShader(const MOJOSHADER_parseData *pd, GLuint *s) shaderlen, pd->output); if (ctx->glGetError() == GL_INVALID_OPERATION) - { + { GLint pos = 0; ctx->glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos); const GLubyte *errstr = ctx->glGetString(GL_PROGRAM_ERROR_STRING_ARB); @@ -697,7 +986,7 @@ static void impl_ARB1_DeleteShader(const GLuint _shader) static void impl_ARB1_DeleteProgram(const GLuint program) { // no-op. ARB1 doesn't have real linked programs. -} // impl_GLSL_DeleteProgram +} // impl_ARB1_DeleteProgram static GLint impl_ARB1_GetUniformLocation(MOJOSHADER_glProgram *program, MOJOSHADER_glShader *shader, int idx) @@ -888,6 +1177,20 @@ static void impl_ARB1_PushSampler(GLint loc, GLuint sampler) #endif // SUPPORT_PROFILE_ARB1 +#if SUPPORT_PROFILE_GLSL || SUPPORT_PROFILE_ARB1 + +static void impl_REAL_ToggleProgramPointSize(int enable) +{ + toggle_gl_state(GL_PROGRAM_POINT_SIZE, enable); +} // impl_REAL_ToggleProgramPointSize + +static void impl_NOOP_ToggleProgramPointSize(int enable) +{ + // No-op, this profile's GL context forces this to always be on +} // impl_NOOP_ToggleProgramPointSize + +#endif // SUPPORT_PROFILE_GLSL || SUPPORT_PROFILE_ARB1 + const char *MOJOSHADER_glGetError(void) { @@ -919,6 +1222,7 @@ static void lookup_entry_points(MOJOSHADER_glGetProcAddress lookup, void *d) DO_LOOKUP(core_opengl, PFNGLGETINTEGERVPROC, glGetIntegerv); DO_LOOKUP(core_opengl, PFNGLENABLEPROC, glEnable); DO_LOOKUP(core_opengl, PFNGLDISABLEPROC, glDisable); + DO_LOOKUP(opengl_3, PFNGLGETSTRINGIPROC, glGetStringi); DO_LOOKUP(opengl_2, PFNGLDELETESHADERPROC, glDeleteShader); DO_LOOKUP(opengl_2, PFNGLDELETEPROGRAMPROC, glDeleteProgram); DO_LOOKUP(opengl_2, PFNGLATTACHSHADERPROC, glAttachShader); @@ -929,6 +1233,7 @@ static void lookup_entry_points(MOJOSHADER_glGetProcAddress lookup, void *d) DO_LOOKUP(opengl_2, PFNGLENABLEVERTEXATTRIBARRAYPROC, glEnableVertexAttribArray); DO_LOOKUP(opengl_2, PFNGLGETATTRIBLOCATIONPROC, glGetAttribLocation); DO_LOOKUP(opengl_2, PFNGLGETPROGRAMINFOLOGPROC, glGetProgramInfoLog); + DO_LOOKUP(opengl_2, PFNGLGETSHADERINFOLOGPROC, glGetShaderInfoLog); DO_LOOKUP(opengl_2, PFNGLGETSHADERIVPROC, glGetShaderiv); DO_LOOKUP(opengl_2, PFNGLGETPROGRAMIVPROC, glGetProgramiv); DO_LOOKUP(opengl_2, PFNGLGETUNIFORMLOCATIONPROC, glGetUniformLocation); @@ -936,6 +1241,10 @@ static void lookup_entry_points(MOJOSHADER_glGetProcAddress lookup, void *d) DO_LOOKUP(opengl_2, PFNGLSHADERSOURCEPROC, glShaderSource); DO_LOOKUP(opengl_2, PFNGLUNIFORM1IPROC, glUniform1i); DO_LOOKUP(opengl_2, PFNGLUNIFORM1IVPROC, glUniform1iv); + DO_LOOKUP(opengl_2, PFNGLUNIFORM2FPROC, glUniform2f); +#ifdef MOJOSHADER_FLIP_RENDERTARGET + DO_LOOKUP(opengl_2, PFNGLUNIFORM1FPROC, glUniform1f); +#endif DO_LOOKUP(opengl_2, PFNGLUNIFORM4FVPROC, glUniform4fv); DO_LOOKUP(opengl_2, PFNGLUNIFORM4IVPROC, glUniform4iv); DO_LOOKUP(opengl_2, PFNGLUSEPROGRAMPROC, glUseProgram); @@ -967,6 +1276,9 @@ static void lookup_entry_points(MOJOSHADER_glGetProcAddress lookup, void *d) DO_LOOKUP(GL_ARB_vertex_program, PFNGLBINDPROGRAMARBPROC, glBindProgramARB); DO_LOOKUP(GL_ARB_vertex_program, PFNGLPROGRAMSTRINGARBPROC, glProgramStringARB); DO_LOOKUP(GL_NV_gpu_program4, PFNGLPROGRAMLOCALPARAMETERI4IVNVPROC, glProgramLocalParameterI4ivNV); + DO_LOOKUP(GL_ARB_instanced_arrays, PFNGLVERTEXATTRIBDIVISORARBPROC, glVertexAttribDivisorARB); + DO_LOOKUP(GL_ARB_ES2_compatibility, PFNGLSHADERBINARYPROC, glShaderBinary); + DO_LOOKUP(GL_ARB_gl_spirv, PFNGLSPECIALIZESHADERARBPROC, glSpecializeShaderARB); #undef DO_LOOKUP } // lookup_entry_points @@ -977,7 +1289,7 @@ static inline int opengl_version_atleast(const int major, const int minor) ((major << 16) | (minor & 0xFFFF)) ); } // opengl_version_atleast -static int verify_extension(const char *ext, int have, const char *extlist, +static int verify_extension(const char *ext, int have, StringCache *exts, int major, int minor) { if (have == 0) @@ -991,15 +1303,7 @@ static int verify_extension(const char *ext, int have, const char *extlist, return 1; // Not available in the GL version, check the extension list. - const char *ptr = strstr(extlist, ext); - if (ptr == NULL) - return 0; - - const char endchar = ptr[strlen(ext)]; - if ((endchar == '\0') || (endchar == ' ')) - return 1; // extension is in the list. - - return 0; // just not supported, fail. + return stringcache_iscached(exts, ext); } // verify_extension @@ -1047,18 +1351,38 @@ static void detect_glsl_version(void) const char *str = (const char *) ctx->glGetString(enumval); if (ctx->glGetError() == GL_INVALID_ENUM) str = NULL; + if (strstr(str, "OpenGL ES GLSL ")) + str += 15; + if (strstr(str, "ES ")) + str += 3; parse_opengl_version_str(str, &ctx->glsl_major, &ctx->glsl_minor); } // if #endif } // detect_glsl_version +static int iswhitespace(const char ch) +{ + switch (ch) + { + case ' ': case '\t': case '\r': case '\n': return 1; + default: return 0; + } // switch +} // iswhitespace + + static void load_extensions(MOJOSHADER_glGetProcAddress lookup, void *d) { - const char *extlist = NULL; + StringCache *exts = stringcache_create(ctx->malloc_fn, ctx->free_fn, ctx->malloc_data); + if (!exts) + { + out_of_memory(); + return; + } // if ctx->have_core_opengl = 1; ctx->have_opengl_2 = 1; + ctx->have_opengl_3 = 1; ctx->have_GL_ARB_vertex_program = 1; ctx->have_GL_ARB_fragment_program = 1; ctx->have_GL_NV_vertex_program2_option = 1; @@ -1072,6 +1396,9 @@ static void load_extensions(MOJOSHADER_glGetProcAddress lookup, void *d) ctx->have_GL_NV_half_float = 1; ctx->have_GL_ARB_half_float_vertex = 1; ctx->have_GL_OES_vertex_half_float = 1; + ctx->have_GL_ARB_instanced_arrays = 1; + ctx->have_GL_ARB_ES2_compatibility = 1; + ctx->have_GL_ARB_gl_spirv = 1; lookup_entry_points(lookup, d); @@ -1080,12 +1407,67 @@ static void load_extensions(MOJOSHADER_glGetProcAddress lookup, void *d) else { const char *str = (const char *) ctx->glGetString(GL_VERSION); + if (strstr(str, "OpenGL ES ")) + { + ctx->have_opengl_es = 1; + str += 10; + } parse_opengl_version_str(str, &ctx->opengl_major, &ctx->opengl_minor); - extlist = (const char *) ctx->glGetString(GL_EXTENSIONS); - } // else - if (extlist == NULL) - extlist = ""; // just in case. + if (opengl_version_atleast(3, 0) && ctx->have_opengl_es) + { + ctx->have_opengl_es3 = 1; + } + + if ((ctx->have_opengl_3) && (opengl_version_atleast(3, 0))) + { + GLint i; + GLint num_exts = 0; + ctx->glGetIntegerv(GL_NUM_EXTENSIONS, &num_exts); + for (i = 0; i < num_exts; i++) + { + if (!stringcache(exts, (const char *) ctx->glGetStringi(GL_EXTENSIONS, i))) + out_of_memory(); + } // for + } // if + else + { + const char *str = (const char *) ctx->glGetString(GL_EXTENSIONS); + const char *ext; + ctx->have_opengl_3 = 0; + + while (*str && iswhitespace(*str)) + str++; + ext = str; + + while (1) + { + const char ch = *str; + if (ch && (!iswhitespace(ch))) + { + str++; + continue; + } // else if + + if (str != ext) + { + if (!stringcache_len(exts, ext, (unsigned int) (str - ext))) + { + out_of_memory(); + break; + } // if + } // if + + if (ch == '\0') + break; + + str++; + while (*str && iswhitespace(*str)) + str++; + ext = str; + } // while + } // else + } // else if ((ctx->have_opengl_2) && (!opengl_version_atleast(2, 0))) { @@ -1105,7 +1487,7 @@ static void load_extensions(MOJOSHADER_glGetProcAddress lookup, void *d) } // if #define VERIFY_EXT(ext, major, minor) \ - ctx->have_##ext = verify_extension(#ext, ctx->have_##ext, extlist, major, minor) + ctx->have_##ext = verify_extension(#ext, ctx->have_##ext, exts, major, minor) VERIFY_EXT(GL_ARB_vertex_program, -1, -1); VERIFY_EXT(GL_ARB_fragment_program, -1, -1); @@ -1119,9 +1501,14 @@ static void load_extensions(MOJOSHADER_glGetProcAddress lookup, void *d) VERIFY_EXT(GL_NV_half_float, -1, -1); VERIFY_EXT(GL_ARB_half_float_vertex, 3, 0); VERIFY_EXT(GL_OES_vertex_half_float, -1, -1); + VERIFY_EXT(GL_ARB_instanced_arrays, 3, 3); + VERIFY_EXT(GL_ARB_ES2_compatibility, 4, 1); + VERIFY_EXT(GL_ARB_gl_spirv, -1, -1); #undef VERIFY_EXT + stringcache_destroy(exts); + detect_glsl_version(); } // load_extensions @@ -1177,6 +1564,28 @@ static int valid_profile(const char *profile) } // else if #endif + #if SUPPORT_PROFILE_GLSPIRV + else if (strcmp(profile, MOJOSHADER_PROFILE_GLSPIRV) == 0) + { + MUST_HAVE(MOJOSHADER_PROFILE_GLSPIRV, GL_ARB_ES2_compatibility); + MUST_HAVE(MOJOSHADER_PROFILE_GLSPIRV, GL_ARB_gl_spirv); + } // else if + #endif + + #if SUPPORT_PROFILE_GLSLES + else if (strcmp(profile, MOJOSHADER_PROFILE_GLSLES3) == 0) + { + MUST_HAVE_GLSL(MOJOSHADER_PROFILE_GLSLES3, 3, 00); + } // else if + #endif + + #if SUPPORT_PROFILE_GLSLES + else if (strcmp(profile, MOJOSHADER_PROFILE_GLSLES) == 0) + { + MUST_HAVE_GLSL(MOJOSHADER_PROFILE_GLSLES, 1, 00); + } // else if + #endif + #if SUPPORT_PROFILE_GLSL120 else if (strcmp(profile, MOJOSHADER_PROFILE_GLSL120) == 0) { @@ -1204,6 +1613,9 @@ static int valid_profile(const char *profile) static const char *profile_priorities[] = { +#if SUPPORT_PROFILE_GLSPIRV + MOJOSHADER_PROFILE_GLSPIRV, +#endif #if SUPPORT_PROFILE_GLSL120 MOJOSHADER_PROFILE_GLSL120, #endif @@ -1220,16 +1632,42 @@ static const char *profile_priorities[] = { #endif }; -int MOJOSHADER_glAvailableProfiles(MOJOSHADER_glGetProcAddress lookup, void *d, - const char **profs, const int size) +int MOJOSHADER_glAvailableProfiles(MOJOSHADER_glGetProcAddress lookup, + void *lookup_d, + const char **profs, const int size, + MOJOSHADER_malloc m, MOJOSHADER_free f, + void *malloc_d) { int retval = 0; MOJOSHADER_glContext _ctx; MOJOSHADER_glContext *current_ctx = ctx; + if (m == NULL) m = MOJOSHADER_internal_malloc; + if (f == NULL) f = MOJOSHADER_internal_free; + ctx = &_ctx; memset(ctx, '\0', sizeof (MOJOSHADER_glContext)); - load_extensions(lookup, d); + ctx->malloc_fn = m; + ctx->free_fn = f; + ctx->malloc_data = malloc_d; + + load_extensions(lookup, lookup_d); + +#if SUPPORT_PROFILE_GLSLES3 + if (ctx->have_opengl_es3) + { + profs[0] = MOJOSHADER_PROFILE_GLSLES3; + return 1; + } // if +#endif + +#if SUPPORT_PROFILE_GLSLES + if (ctx->have_opengl_es) + { + profs[0] = MOJOSHADER_PROFILE_GLSLES; + return 1; + } // if +#endif if (ctx->have_core_opengl) { @@ -1251,10 +1689,16 @@ int MOJOSHADER_glAvailableProfiles(MOJOSHADER_glGetProcAddress lookup, void *d, } // MOJOSHADER_glAvailableProfiles -const char *MOJOSHADER_glBestProfile(MOJOSHADER_glGetProcAddress gpa, void *d) +const char *MOJOSHADER_glBestProfile(MOJOSHADER_glGetProcAddress gpa, + void *lookup_d, + MOJOSHADER_malloc m, MOJOSHADER_free f, + void *malloc_d) { const char *prof[STATICARRAYLEN(profile_priorities)]; - if (MOJOSHADER_glAvailableProfiles(gpa, d, prof, STATICARRAYLEN(prof)) <= 0) + const int avail = MOJOSHADER_glAvailableProfiles(gpa, lookup_d, prof, + STATICARRAYLEN(prof), + m, f, malloc_d); + if (avail <= 0) { set_error("no profiles available"); return NULL; @@ -1295,15 +1739,53 @@ MOJOSHADER_glContext *MOJOSHADER_glCreateContext(const char *profile, if (!valid_profile(profile)) goto init_fail; +#ifdef MOJOSHADER_XNA4_VERTEX_TEXTURES + GLint maxTextures; + GLint maxVertexTextures; + ctx->glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxTextures); + if (maxTextures > 20) + maxTextures = 20; + if (maxTextures > 16) + maxVertexTextures = maxTextures - 16; + else + maxVertexTextures = 0; + ctx->vertex_sampler_offset = maxTextures - maxVertexTextures; +#endif + MOJOSHADER_glBindProgram(NULL); // !!! FIXME: generalize this part. if (profile == NULL) {} - // We don't check SUPPORT_PROFILE_GLSL120 here, since valid_profile() does. + // We don't check SUPPORT_PROFILE_GLSPIRV here, since valid_profile() does. +#if SUPPORT_PROFILE_GLSPIRV + else if (strcmp(profile, MOJOSHADER_PROFILE_GLSPIRV) == 0) + { + ctx->profileMaxUniforms = impl_GLSL_MaxUniforms; + ctx->profileCompileShader = impl_SPIRV_CompileShader; + ctx->profileDeleteShader = impl_SPIRV_DeleteShader; + ctx->profileDeleteProgram = impl_SPIRV_DeleteProgram; + ctx->profileGetAttribLocation = impl_SPIRV_GetAttribLocation; + ctx->profileGetUniformLocation = impl_SPIRV_GetUniformLocation; + ctx->profileGetSamplerLocation = impl_SPIRV_GetSamplerLocation; + ctx->profileLinkProgram = impl_SPIRV_LinkProgram; + ctx->profileFinalInitProgram = impl_SPIRV_FinalInitProgram; + ctx->profileUseProgram = impl_GLSL_UseProgram; + ctx->profilePushConstantArray = impl_GLSL_PushConstantArray; + ctx->profilePushUniforms = impl_GLSL_PushUniforms; + ctx->profilePushSampler = impl_GLSL_PushSampler; + ctx->profileMustPushConstantArrays = impl_GLSL_MustPushConstantArrays; + ctx->profileMustPushSamplers = impl_GLSL_MustPushSamplers; + ctx->profileToggleProgramPointSize = impl_REAL_ToggleProgramPointSize; + } // if +#endif + + // We don't check SUPPORT_PROFILE_GLSL120/ES here, since valid_profile() does. #if SUPPORT_PROFILE_GLSL else if ( (strcmp(profile, MOJOSHADER_PROFILE_GLSL) == 0) || - (strcmp(profile, MOJOSHADER_PROFILE_GLSL120) == 0) ) + (strcmp(profile, MOJOSHADER_PROFILE_GLSL120) == 0) || + (strcmp(profile, MOJOSHADER_PROFILE_GLSLES) == 0) || + (strcmp(profile, MOJOSHADER_PROFILE_GLSLES3) == 0) ) { ctx->profileMaxUniforms = impl_GLSL_MaxUniforms; ctx->profileCompileShader = impl_GLSL_CompileShader; @@ -1320,6 +1802,10 @@ MOJOSHADER_glContext *MOJOSHADER_glCreateContext(const char *profile, ctx->profilePushSampler = impl_GLSL_PushSampler; ctx->profileMustPushConstantArrays = impl_GLSL_MustPushConstantArrays; ctx->profileMustPushSamplers = impl_GLSL_MustPushSamplers; + if (strcmp(profile, MOJOSHADER_PROFILE_GLSLES) == 0 || strcmp(profile, MOJOSHADER_PROFILE_GLSLES3) == 0) + ctx->profileToggleProgramPointSize = impl_NOOP_ToggleProgramPointSize; + else + ctx->profileToggleProgramPointSize = impl_REAL_ToggleProgramPointSize; } // if #endif @@ -1345,6 +1831,7 @@ MOJOSHADER_glContext *MOJOSHADER_glCreateContext(const char *profile, ctx->profilePushSampler = impl_ARB1_PushSampler; ctx->profileMustPushConstantArrays = impl_ARB1_MustPushConstantArrays; ctx->profileMustPushSamplers = impl_ARB1_MustPushSamplers; + ctx->profileToggleProgramPointSize = impl_REAL_ToggleProgramPointSize; } // if #endif @@ -1364,6 +1851,7 @@ MOJOSHADER_glContext *MOJOSHADER_glCreateContext(const char *profile, assert(ctx->profilePushSampler != NULL); assert(ctx->profileMustPushConstantArrays != NULL); assert(ctx->profileMustPushSamplers != NULL); + assert(ctx->profileToggleProgramPointSize != NULL); retval = ctx; ctx = current_ctx; @@ -1398,8 +1886,11 @@ MOJOSHADER_glShader *MOJOSHADER_glCompileShader(const unsigned char *tokenbuf, { MOJOSHADER_glShader *retval = NULL; GLuint shader = 0; - const MOJOSHADER_parseData *pd = MOJOSHADER_parse(ctx->profile, tokenbuf, - bufsize, swiz, swizcount, + + // This doesn't need a mainfn, since there's no GL lang that does. + const MOJOSHADER_parseData *pd = MOJOSHADER_parse(ctx->profile, NULL, + tokenbuf, bufsize, + swiz, swizcount, smap, smapcount, ctx->malloc_fn, ctx->free_fn, @@ -1433,6 +1924,13 @@ MOJOSHADER_glShader *MOJOSHADER_glCompileShader(const unsigned char *tokenbuf, } // MOJOSHADER_glCompileShader +void MOJOSHADER_glShaderAddRef(MOJOSHADER_glShader *shader) +{ + if (shader != NULL) + shader->refcount++; +} // MOJOSHADER_glShaderAddRef + + const MOJOSHADER_parseData *MOJOSHADER_glGetShaderParseData( MOJOSHADER_glShader *shader) { @@ -1469,8 +1967,6 @@ static void program_unref(MOJOSHADER_glProgram *program) ctx->profileDeleteProgram(program->handle); shader_unref(program->vertex); shader_unref(program->fragment); - Free(program->vs_preshader_regs); - Free(program->ps_preshader_regs); Free(program->vs_uniforms_float4); Free(program->vs_uniforms_int4); Free(program->vs_uniforms_bool); @@ -1599,38 +2095,6 @@ static int lookup_uniforms(MOJOSHADER_glProgram *program, #undef MAKE_ARRAY - if (pd->preshader) - { - unsigned int largest = 0; - const MOJOSHADER_symbol *sym = pd->preshader->symbols; - for (i = 0; i < pd->preshader->symbol_count; i++, sym++) - { - const unsigned int val = sym->register_index + sym->register_count; - if (val > largest) - largest = val; - } // for - - if (largest > 0) - { - const size_t len = largest * sizeof (GLfloat) * 4; - GLfloat *buf = (GLfloat *) Malloc(len); - if (buf == NULL) - return 0; - memset(buf, '\0', len); - - if (shader_type == MOJOSHADER_TYPE_VERTEX) - { - program->vs_preshader_reg_count = largest; - program->vs_preshader_regs = buf; - } // if - else if (shader_type == MOJOSHADER_TYPE_PIXEL) - { - program->ps_preshader_reg_count = largest; - program->ps_preshader_regs = buf; - } // else if - } // if - } // if - return 1; } // lookup_uniforms @@ -1658,7 +2122,14 @@ static void lookup_samplers(MOJOSHADER_glProgram *program, { const GLint loc = ctx->profileGetSamplerLocation(program, shader, i); if (loc >= 0) // maybe the Sampler was optimized out? - ctx->profilePushSampler(loc, s[i].index); + { +#ifdef MOJOSHADER_XNA4_VERTEX_TEXTURES + if (pd->shader_type == MOJOSHADER_TYPE_VERTEX) + ctx->profilePushSampler(loc, s[i].index + ctx->vertex_sampler_offset); + else +#endif + ctx->profilePushSampler(loc, s[i].index); + } // if } // for } // lookup_samplers @@ -1698,6 +2169,7 @@ static int lookup_attributes(MOJOSHADER_glProgram *program) AttributeMap *map = &program->attributes[program->attribute_count]; map->attribute = &a[i]; map->location = loc; + program->vertex_attrib_loc[map->attribute->usage][map->attribute->index] = loc; program->attribute_count++; if (((size_t)loc) > STATICARRAYLEN(ctx->want_attr)) @@ -1758,6 +2230,7 @@ MOJOSHADER_glProgram *MOJOSHADER_glLinkProgram(MOJOSHADER_glShader *vshader, if (retval == NULL) goto link_program_fail; memset(retval, '\0', sizeof (MOJOSHADER_glProgram)); + memset(retval->vertex_attrib_loc, 0xFF, sizeof(retval->vertex_attrib_loc)); numregs = 0; if (vshader != NULL) numregs += vshader->parseData->uniform_count; @@ -1795,7 +2268,7 @@ MOJOSHADER_glProgram *MOJOSHADER_glLinkProgram(MOJOSHADER_glShader *vshader, if (!lookup_uniforms(retval, vshader, &bound)) goto link_program_fail; lookup_samplers(retval, vshader, &bound); - lookup_outputs(retval, pshader); + lookup_outputs(retval, vshader); vshader->refcount++; } // if @@ -1927,8 +2400,9 @@ static int match_shaders(const void *_a, const void *_b, void *data) return 1; } // match_shaders -static void nuke_shaders(const void *key, const void *value, void *data) +static void nuke_shaders(const void *_ctx, const void *key, const void *value, void *data) { + (void) _ctx; (void) data; Free((void *) key); // this was a BoundShaders struct. MOJOSHADER_glDeleteProgram((MOJOSHADER_glProgram *) value); @@ -1992,6 +2466,26 @@ void MOJOSHADER_glBindShaders(MOJOSHADER_glShader *v, MOJOSHADER_glShader *p) } // MOJOSHADER_glBindShaders +void MOJOSHADER_glGetBoundShaders(MOJOSHADER_glShader **v, + MOJOSHADER_glShader **p) +{ + if (v != NULL) + { + if (ctx->bound_program != NULL) + *v = ctx->bound_program->vertex; + else + *v = NULL; + } // if + if (p != NULL) + { + if (ctx->bound_program != NULL) + *p = ctx->bound_program->fragment; + else + *p = NULL; + } // if +} // MOJOSHADER_glGetBoundShaders + + static inline uint minuint(const uint a, const uint b) { return ((a < b) ? a : b); @@ -2055,7 +2549,7 @@ void MOJOSHADER_glGetVertexShaderUniformI(unsigned int idx, int *data, void MOJOSHADER_glSetVertexShaderUniformB(unsigned int idx, const int *data, unsigned int bcount) { - const uint maxregs = STATICARRAYLEN(ctx->vs_reg_file_f) / 4; + const uint maxregs = STATICARRAYLEN(ctx->vs_reg_file_b) / 4; if (idx < maxregs) { uint8 *wptr = ctx->vs_reg_file_b + idx; @@ -2070,7 +2564,7 @@ void MOJOSHADER_glSetVertexShaderUniformB(unsigned int idx, const int *data, void MOJOSHADER_glGetVertexShaderUniformB(unsigned int idx, int *data, unsigned int bcount) { - const uint maxregs = STATICARRAYLEN(ctx->vs_reg_file_f) / 4; + const uint maxregs = STATICARRAYLEN(ctx->vs_reg_file_b) / 4; if (idx < maxregs) { uint8 *rptr = ctx->vs_reg_file_b + idx; @@ -2138,7 +2632,7 @@ void MOJOSHADER_glGetPixelShaderUniformI(unsigned int idx, int *data, void MOJOSHADER_glSetPixelShaderUniformB(unsigned int idx, const int *data, unsigned int bcount) { - const uint maxregs = STATICARRAYLEN(ctx->ps_reg_file_f) / 4; + const uint maxregs = STATICARRAYLEN(ctx->ps_reg_file_b) / 4; if (idx < maxregs) { uint8 *wptr = ctx->ps_reg_file_b + idx; @@ -2153,7 +2647,7 @@ void MOJOSHADER_glSetPixelShaderUniformB(unsigned int idx, const int *data, void MOJOSHADER_glGetPixelShaderUniformB(unsigned int idx, int *data, unsigned int bcount) { - const uint maxregs = STATICARRAYLEN(ctx->ps_reg_file_f) / 4; + const uint maxregs = STATICARRAYLEN(ctx->ps_reg_file_b) / 4; if (idx < maxregs) { uint8 *rptr = ctx->ps_reg_file_b + idx; @@ -2164,6 +2658,24 @@ void MOJOSHADER_glGetPixelShaderUniformB(unsigned int idx, int *data, } // MOJOSHADER_glGetPixelShaderUniformB +void MOJOSHADER_glMapUniformBufferMemory(float **vsf, int **vsi, unsigned char **vsb, + float **psf, int **psi, unsigned char **psb) +{ + *vsf = ctx->vs_reg_file_f; + *vsi = ctx->vs_reg_file_i; + *vsb = ctx->vs_reg_file_b; + *psf = ctx->ps_reg_file_f; + *psi = ctx->ps_reg_file_i; + *psb = ctx->ps_reg_file_b; +} // MOJOSHADER_glMapUniformBufferMemory + + +void MOJOSHADER_glUnmapUniformBufferMemory() +{ + ctx->generation++; +} // MOJOSHADER_glUnmapUniformBufferMemory + + static inline GLenum opengl_attr_type(const MOJOSHADER_attributeType type) { switch (type) @@ -2192,6 +2704,15 @@ static inline GLenum opengl_attr_type(const MOJOSHADER_attributeType type) } // opengl_attr_type +int MOJOSHADER_glGetVertexAttribLocation(MOJOSHADER_usage usage, int index) +{ + if ((ctx->bound_program == NULL) || (ctx->bound_program->vertex == NULL)) + return -1; + + return ctx->bound_program->vertex_attrib_loc[usage][index]; +} // MOJOSHADER_glGetVertexAttribLocation + + // !!! FIXME: shouldn't (index) be unsigned? void MOJOSHADER_glSetVertexAttribute(MOJOSHADER_usage usage, int index, unsigned int size, @@ -2204,27 +2725,10 @@ void MOJOSHADER_glSetVertexAttribute(MOJOSHADER_usage usage, const GLenum gl_type = opengl_attr_type(type); const GLboolean norm = (normalized) ? GL_TRUE : GL_FALSE; - const int count = ctx->bound_program->attribute_count; - GLint gl_index = 0; - int i; - - for (i = 0; i < count; i++) - { - const AttributeMap *map = &ctx->bound_program->attributes[i]; - const MOJOSHADER_attribute *a = map->attribute; - - // !!! FIXME: is this array guaranteed to be sorted by usage? - // !!! FIXME: if so, we can break if a->usage > usage. - - if ((a->usage == usage) && (a->index == index)) - { - gl_index = map->location; - break; - } // if - } // for + const GLint gl_index = ctx->bound_program->vertex_attrib_loc[usage][index]; - if (i == count) - return; // nothing to do, this shader doesn't use this stream. + if (gl_index == -1) + return; // Nothing to do, this shader doesn't use this stream. // this happens to work in both ARB1 and GLSL, but if something alien // shows up, we'll have to split these into profile*() functions. @@ -2237,76 +2741,26 @@ void MOJOSHADER_glSetVertexAttribute(MOJOSHADER_usage usage, } // MOJOSHADER_glSetVertexAttribute -void MOJOSHADER_glSetVertexPreshaderUniformF(unsigned int idx, - const float *data, - unsigned int vec4n) -{ - MOJOSHADER_glProgram *program = ctx->bound_program; - if (program == NULL) - return; // nothing to do. - - const uint maxregs = program->vs_preshader_reg_count; - if (idx < maxregs) - { - assert(sizeof (GLfloat) == sizeof (float)); - const uint cpy = (minuint(maxregs - idx, vec4n) * sizeof (*data)) * 4; - memcpy(program->vs_preshader_regs + (idx * 4), data, cpy); - program->generation = ctx->generation-1; - } // if -} // MOJOSHADER_glSetVertexPreshaderUniformF - - -void MOJOSHADER_glGetVertexPreshaderUniformF(unsigned int idx, float *data, - unsigned int vec4n) -{ - MOJOSHADER_glProgram *program = ctx->bound_program; - if (program == NULL) - return; // nothing to do. - - const uint maxregs = program->vs_preshader_reg_count; - if (idx < maxregs) - { - assert(sizeof (GLfloat) == sizeof (float)); - const uint cpy = (minuint(maxregs - idx, vec4n) * sizeof (*data)) * 4; - memcpy(data, program->vs_preshader_regs + (idx * 4), cpy); - } // if -} // MOJOSHADER_glGetVertexPreshaderUniformF - - -void MOJOSHADER_glSetPixelPreshaderUniformF(unsigned int idx, - const float *data, - unsigned int vec4n) +// !!! FIXME: shouldn't (index) be unsigned? +void MOJOSHADER_glSetVertexAttribDivisor(MOJOSHADER_usage usage, + int index, unsigned int divisor) { - MOJOSHADER_glProgram *program = ctx->bound_program; - if (program == NULL) - return; // nothing to do. + assert(ctx->have_GL_ARB_instanced_arrays); - const uint maxregs = program->ps_preshader_reg_count; - if (idx < maxregs) - { - assert(sizeof (GLfloat) == sizeof (float)); - const uint cpy = (minuint(maxregs - idx, vec4n) * sizeof (*data)) * 4; - memcpy(program->ps_preshader_regs + (idx * 4), data, cpy); - program->generation = ctx->generation-1; - } // if -} // MOJOSHADER_glSetPixelPreshaderUniformF + if ((ctx->bound_program == NULL) || (ctx->bound_program->vertex == NULL)) + return; + const GLint gl_index = ctx->bound_program->vertex_attrib_loc[usage][index]; -void MOJOSHADER_glGetPixelPreshaderUniformF(unsigned int idx, float *data, - unsigned int vec4n) -{ - MOJOSHADER_glProgram *program = ctx->bound_program; - if (program == NULL) - return; // nothing to do. + if (gl_index == -1) + return; // Nothing to do, this shader doesn't use this stream. - const uint maxregs = program->ps_preshader_reg_count; - if (idx < maxregs) + if (divisor != ctx->attr_divisor[gl_index]) { - assert(sizeof (GLfloat) == sizeof (float)); - const uint cpy = (minuint(maxregs - idx, vec4n) * sizeof (*data)) * 4; - memcpy(data, program->ps_preshader_regs + (idx * 4), cpy); + ctx->glVertexAttribDivisorARB(gl_index, divisor); + ctx->attr_divisor[gl_index] = divisor; } // if -} // MOJOSHADER_glGetPixelPreshaderUniformF +} // MOJOSHADER_glSetVertexAttribDivisor void MOJOSHADER_glSetLegacyBumpMapEnv(unsigned int sampler, float mat00, @@ -2339,10 +2793,7 @@ void MOJOSHADER_glProgramReady(void) if (program->uses_pointsize != ctx->pointsize_enabled) { - if (program->uses_pointsize) - ctx->glEnable(GL_PROGRAM_POINT_SIZE); - else - ctx->glDisable(GL_PROGRAM_POINT_SIZE); + ctx->profileToggleProgramPointSize(program->uses_pointsize); ctx->pointsize_enabled = program->uses_pointsize; } // if @@ -2359,36 +2810,9 @@ void MOJOSHADER_glProgramReady(void) GLfloat *dstf = program->vs_uniforms_float4; GLint *dsti = program->vs_uniforms_int4; GLint *dstb = program->vs_uniforms_bool; - const MOJOSHADER_preshader *preshader = NULL; + uint8 uniforms_changed = 0; uint32 i; - // !!! FIXME: shouldn't this run even if the generation hasn't changed? - int ran_preshader = 0; - if (program->vertex) - { - preshader = program->vertex->parseData->preshader; - if (preshader) - { - MOJOSHADER_runPreshader(preshader, program->vs_preshader_regs, - ctx->vs_reg_file_f); - ran_preshader = 1; - } // if - } // if - - if (program->fragment) - { - preshader = program->fragment->parseData->preshader; - if (preshader) - { - MOJOSHADER_runPreshader(preshader, program->ps_preshader_regs, - ctx->ps_reg_file_f); - ran_preshader = 1; - } // if - } // if - - if (ran_preshader) - ctx->generation++; - for (i = 0; i < count; i++) { UniformMap *map = &program->uniforms[i]; @@ -2428,14 +2852,22 @@ void MOJOSHADER_glProgramReady(void) { const size_t count = 4 * size; const GLfloat *f = &srcf[index * 4]; - memcpy(dstf, f, sizeof (GLfloat) * count); + if (memcmp(dstf, f, sizeof (GLfloat) * count) != 0) + { + memcpy(dstf, f, sizeof (GLfloat) * count); + uniforms_changed = 1; + } dstf += count; } // if else if (type == MOJOSHADER_UNIFORM_INT) { const size_t count = 4 * size; const GLint *i = &srci[index * 4]; - memcpy(dsti, i, sizeof (GLint) * count); + if (memcmp(dsti, i, sizeof (GLint) * count) != 0) + { + memcpy(dsti, i, sizeof (GLint) * count); + uniforms_changed = 1; + } // if dsti += count; } // else if else if (type == MOJOSHADER_UNIFORM_BOOL) @@ -2444,7 +2876,11 @@ void MOJOSHADER_glProgramReady(void) const uint8 *b = &srcb[index]; size_t i; for (i = 0; i < count; i++) - dstb[i] = (GLint) b[i]; + if (dstb[i] != b[i]) + { + dstb[i] = (GLint) b[i]; + uniforms_changed = 1; + } // if dstb += count; } // else if @@ -2484,11 +2920,63 @@ void MOJOSHADER_glProgramReady(void) program->generation = ctx->generation; - ctx->profilePushUniforms(); + if (uniforms_changed) + ctx->profilePushUniforms(); } // if } // MOJOSHADER_glProgramReady +void MOJOSHADER_glProgramViewportInfo(int viewportW, int viewportH, + int backbufferW, int backbufferH, + int renderTargetBound) +{ + int vposFlip[2]; + + /* The uniform is only going to exist if VPOS is used! */ + if (ctx->bound_program->ps_vpos_flip_loc != -1) + { + if (renderTargetBound) + { + vposFlip[0] = 1; + vposFlip[1] = 0; + } // if + else + { + vposFlip[0] = -1; + vposFlip[1] = backbufferH; + } // else + if ( (ctx->bound_program->current_vpos_flip[0] != vposFlip[0]) || + (ctx->bound_program->current_vpos_flip[1] != vposFlip[1]) ) + { + ctx->glUniform2f( + ctx->bound_program->ps_vpos_flip_loc, + (float) vposFlip[0], + (float) vposFlip[1] + ); + ctx->bound_program->current_vpos_flip[0] = vposFlip[0]; + ctx->bound_program->current_vpos_flip[1] = vposFlip[1]; + } // if + } // if + +#ifdef MOJOSHADER_FLIP_RENDERTARGET + if (ctx->bound_program->vs_flip_loc != -1) + { + /* Some compilers require that vpFlip be a float value, rather than int. + * However, there's no real reason for it to be a float in the API, so we + * do a cast in here. That's not so bad, right...? + * -flibit + */ + const int flip = renderTargetBound ? -1 : 1; + if (flip != ctx->bound_program->current_flip) + { + ctx->glUniform1f(ctx->bound_program->vs_flip_loc, (float) flip); + ctx->bound_program->current_flip = flip; + } // if + } // if +#endif +} // MOJOSHADER_glViewportInfo + + void MOJOSHADER_glDeleteProgram(MOJOSHADER_glProgram *program) { program_unref(program); @@ -2511,7 +2999,7 @@ void MOJOSHADER_glDeleteShader(MOJOSHADER_glShader *shader) if ((shaders->vertex == shader) || (shaders->fragment == shader)) { // Deletes the linked program, which will unref the shader. - hash_remove(ctx->linker_cache, shaders); + hash_remove(ctx->linker_cache, shaders, ctx); } // if } // while } // if @@ -2526,7 +3014,7 @@ void MOJOSHADER_glDestroyContext(MOJOSHADER_glContext *_ctx) ctx = _ctx; MOJOSHADER_glBindProgram(NULL); if (ctx->linker_cache) - hash_destroy(ctx->linker_cache); + hash_destroy(ctx->linker_cache, ctx); lookup_entry_points(NULL, NULL); // !!! FIXME: is there a value to this? Free(ctx); ctx = ((current_ctx == _ctx) ? NULL : current_ctx); diff --git a/mojoshader/mojoshader_parser_hlsl.lemon b/mojoshader/mojoshader_parser_hlsl.lemon deleted file mode 100644 index 5870c6f..0000000 --- a/mojoshader/mojoshader_parser_hlsl.lemon +++ /dev/null @@ -1,593 +0,0 @@ -/** - * MojoShader; generate shader programs from bytecode of compiled - * Direct3D shaders. - * - * Please see the file LICENSE.txt in the source's root directory. - * - * This file written by Ryan C. Gordon. - */ - -// This is a Lemon Parser grammar for HLSL. It is based on an ANSI C YACC -// grammar by Jeff Lee: http://www.lysator.liu.se/c/ANSI-C-grammar-y.html - -// Lemon is here: http://www.hwaci.com/sw/lemon/ ... the source is included -// with MojoShader, and built with the library, so you don't have to track -// down the dependency. - -// HLSL syntax is described, informally, here: -// http://msdn.microsoft.com/en-us/library/bb509615(VS.85).aspx - -%name ParseHLSL - -// Some shift-reduce conflicts are basically unavoidable, but if the final -// conflict count matches this value, we consider it known and acceptable. -%expect 2 - -%start_symbol shader -%token_prefix TOKEN_HLSL_ -%token_type { TokenData } -%extra_argument { Context *ctx } - -%include { -#ifndef __MOJOSHADER_HLSL_COMPILER__ -#error Do not compile this file directly. -#endif -} - -%syntax_error { - // !!! FIXME: make this a proper fail() function. - fail(ctx, "Syntax error"); -} - -%parse_failure { - // !!! FIXME: make this a proper fail() function. - fail(ctx, "Giving up. Parser is hopelessly lost..."); -} - -%stack_overflow { - // !!! FIXME: make this a proper fail() function. - fail(ctx, "Giving up. Parser stack overflow"); -} - -// operator precedence (matches C spec)... - -%left COMMA. -%right ASSIGN ADDASSIGN SUBASSIGN MULASSIGN DIVASSIGN MODASSIGN LSHIFTASSIGN - RSHIFTASSIGN ANDASSIGN ORASSIGN XORASSIGN. -%right QUESTION. -%left OROR. -%left ANDAND. -%left OR. -%left XOR. -%left AND. -%left EQL NEQ. -%left LT LEQ GT GEQ. -%left LSHIFT RSHIFT. -%left PLUS MINUS. -%left STAR SLASH PERCENT. -%right TYPECAST EXCLAMATION COMPLEMENT MINUSMINUS PLUSPLUS. -%left DOT LBRACKET RBRACKET LPAREN RPAREN. - -// bump up the precedence of ELSE, to avoid shift/reduce conflict on the -// usual "dangling else ambiguity" ... -%right ELSE. - - -// The rules... - -shader ::= compilation_units(B). { assert(ctx->ast == NULL); REVERSE_LINKED_LIST(MOJOSHADER_astCompilationUnit, B); ctx->ast = (MOJOSHADER_astNode *) B; } - -%type compilation_units { MOJOSHADER_astCompilationUnit * } -%destructor compilation_units { delete_compilation_unit(ctx, $$); } -compilation_units(A) ::= compilation_unit(B). { A = B; } -compilation_units(A) ::= compilation_units(B) compilation_unit(C). { if (C) { C->next = B; A = C; } } - -%type compilation_unit { MOJOSHADER_astCompilationUnit * } -%destructor compilation_unit { delete_compilation_unit(ctx, $$); } -//compilation_unit(A) ::= PRAGMA . { A = NULL; } // !!! FIXME: deal with pragmas. -compilation_unit(A) ::= variable_declaration(B). { A = new_global_variable(ctx, B); } -compilation_unit(A) ::= function_signature(B) SEMICOLON. { A = new_function(ctx, B, NULL); } -compilation_unit(A) ::= function_signature(B) statement_block(C). { A = new_function(ctx, B, C); } -compilation_unit(A) ::= typedef(B). { A = new_global_typedef(ctx, B); } -compilation_unit(A) ::= struct_declaration(B) SEMICOLON. { A = new_global_struct(ctx, B); } -//compilation_unit(A) ::= error SEMICOLON. { A = NULL; } // !!! FIXME: research using the error nonterminal - -%type typedef { MOJOSHADER_astTypedef * } -%destructor typedef { delete_typedef(ctx, $$); } -// !!! FIXME: should CONST be here, or in datatype? -typedef(A) ::= TYPEDEF CONST datatype(B) scalar_or_array(C). { A = new_typedef(ctx, 1, B, C); push_usertype(ctx, C->identifier, A->datatype); } -typedef(A) ::= TYPEDEF datatype(B) scalar_or_array(C). { A = new_typedef(ctx, 0, B, C); push_usertype(ctx, C->identifier, A->datatype); } - -%type function_signature { MOJOSHADER_astFunctionSignature * } -%destructor function_signature { delete_function_signature(ctx, $$); } -function_signature(A) ::= function_storageclass(B) function_details(C) semantic(D). { A = C; A->storage_class = B; A->semantic = D; } -function_signature(A) ::= function_storageclass(B) function_details(C). { A = C; A->storage_class = B; } -function_signature(A) ::= function_details(B) semantic(C). { A = B; A->semantic = C; } -function_signature(A) ::= function_details(B). { A = B; } - -%type function_details { MOJOSHADER_astFunctionSignature * } -%destructor function_details { delete_function_signature(ctx, $$); } -function_details(A) ::= datatype(B) IDENTIFIER(C) LPAREN function_parameters(D) RPAREN. { A = new_function_signature(ctx, B, C.string, D); } -function_details(A) ::= VOID IDENTIFIER(B) LPAREN function_parameters(C) RPAREN. { A = new_function_signature(ctx, NULL, B.string, C); } - -// !!! FIXME: there is a "target" storage class that is the name of the -// !!! FIXME: platform that this function is meant for...but I don't know -// !!! FIXME: what tokens are valid here. - -// !!! FIXME: Also, the docs say "one of" inline or target, but I bet you can -// !!! FIXME: specify both. -%type function_storageclass { MOJOSHADER_astFunctionStorageClass } -//function_storageclass(A) ::= target(B). { A = B; } -function_storageclass(A) ::= INLINE. { A = MOJOSHADER_AST_FNSTORECLS_INLINE; } - -%type function_parameters { MOJOSHADER_astFunctionParameters * } -%destructor function_parameters { delete_function_params(ctx, $$); } -function_parameters(A) ::= VOID. { A = NULL; } -function_parameters(A) ::= function_parameter_list(B). { REVERSE_LINKED_LIST(MOJOSHADER_astFunctionParameters, B); A = B; } -function_parameters(A) ::= . { A = NULL; } - -%type function_parameter_list { MOJOSHADER_astFunctionParameters * } -%destructor function_parameter_list { delete_function_params(ctx, $$); } -function_parameter_list(A) ::= function_parameter(B). { A = B; } -function_parameter_list(A) ::= function_parameter_list(B) COMMA function_parameter(C). { C->next = B; A = C; } - -// !!! FIXME: this is pretty unreadable. -// !!! FIXME: CONST? -%type function_parameter { MOJOSHADER_astFunctionParameters * } -%destructor function_parameter { delete_function_params(ctx, $$); } -function_parameter(A) ::= input_modifier(B) datatype(C) IDENTIFIER(D) semantic(E) interpolation_mod(F) initializer(G). { A = new_function_param(ctx, B, C, D.string, E, F, G); } -function_parameter(A) ::= input_modifier(B) datatype(C) IDENTIFIER(D) semantic(E) interpolation_mod(F). { A = new_function_param(ctx, B, C, D.string, E, F, NULL); } -function_parameter(A) ::= input_modifier(B) datatype(C) IDENTIFIER(D) semantic(E) initializer(F). { A = new_function_param(ctx, B, C, D.string, E, MOJOSHADER_AST_INTERPMOD_NONE, F); } -function_parameter(A) ::= input_modifier(B) datatype(C) IDENTIFIER(D) semantic(E). { A = new_function_param(ctx, B, C, D.string, E, MOJOSHADER_AST_INTERPMOD_NONE, NULL); } -function_parameter(A) ::= input_modifier(B) datatype(C) IDENTIFIER(D) interpolation_mod(E) initializer(F). { A = new_function_param(ctx, B, C, D.string, NULL, E, F); } -function_parameter(A) ::= input_modifier(B) datatype(C) IDENTIFIER(D) interpolation_mod(E). { A = new_function_param(ctx, B, C, D.string, NULL, E, NULL); } -function_parameter(A) ::= input_modifier(B) datatype(C) IDENTIFIER(D) initializer(E). { A = new_function_param(ctx, B, C, D.string, NULL, MOJOSHADER_AST_INTERPMOD_NONE, E); } -function_parameter(A) ::= input_modifier(B) datatype(C) IDENTIFIER(D). { A = new_function_param(ctx, B, C, D.string, NULL, MOJOSHADER_AST_INTERPMOD_NONE, NULL); } -function_parameter(A) ::= datatype(B) IDENTIFIER(C) semantic(D) interpolation_mod(E) initializer(F). { A = new_function_param(ctx, MOJOSHADER_AST_INPUTMOD_NONE, B, C.string, D, E, F); } -function_parameter(A) ::= datatype(B) IDENTIFIER(C) semantic(D) interpolation_mod(E). { A = new_function_param(ctx, MOJOSHADER_AST_INPUTMOD_NONE, B, C.string, D, E, NULL); } -function_parameter(A) ::= datatype(B) IDENTIFIER(C) semantic(D) initializer(E). { A = new_function_param(ctx, MOJOSHADER_AST_INPUTMOD_NONE, B, C.string, D, MOJOSHADER_AST_INTERPMOD_NONE, E); } -function_parameter(A) ::= datatype(B) IDENTIFIER(C) semantic(D). { A = new_function_param(ctx, MOJOSHADER_AST_INPUTMOD_NONE, B, C.string, D, MOJOSHADER_AST_INTERPMOD_NONE, NULL); } -function_parameter(A) ::= datatype(B) IDENTIFIER(C) interpolation_mod(D) initializer(E). { A = new_function_param(ctx, MOJOSHADER_AST_INPUTMOD_NONE, B, C.string, NULL, D, E); } -function_parameter(A) ::= datatype(B) IDENTIFIER(C) interpolation_mod(D). { A = new_function_param(ctx, MOJOSHADER_AST_INPUTMOD_NONE, B, C.string, NULL, D, NULL); } -function_parameter(A) ::= datatype(B) IDENTIFIER(C) initializer(D). { A = new_function_param(ctx, MOJOSHADER_AST_INPUTMOD_NONE, B, C.string, NULL, MOJOSHADER_AST_INTERPMOD_NONE, D); } -function_parameter(A) ::= datatype(B) IDENTIFIER(C). { A = new_function_param(ctx, MOJOSHADER_AST_INPUTMOD_NONE, B, C.string, NULL, MOJOSHADER_AST_INTERPMOD_NONE, NULL); } - -%type input_modifier { MOJOSHADER_astInputModifier } -input_modifier(A) ::= IN. { A = MOJOSHADER_AST_INPUTMOD_IN; } -input_modifier(A) ::= INOUT. { A = MOJOSHADER_AST_INPUTMOD_INOUT; } -input_modifier(A) ::= OUT. { A = MOJOSHADER_AST_INPUTMOD_OUT; } -input_modifier(A) ::= IN OUT. { A = MOJOSHADER_AST_INPUTMOD_INOUT; } -input_modifier(A) ::= OUT IN. { A = MOJOSHADER_AST_INPUTMOD_INOUT; } -input_modifier(A) ::= UNIFORM. { A = MOJOSHADER_AST_INPUTMOD_UNIFORM; } - -%type semantic { const char * } -semantic(A) ::= COLON IDENTIFIER(B). { A = B.string; } - -// DX10 only? -%type interpolation_mod { MOJOSHADER_astInterpolationModifier } -interpolation_mod(A) ::= LINEAR. { A = MOJOSHADER_AST_INTERPMOD_LINEAR; } -interpolation_mod(A) ::= CENTROID. { A = MOJOSHADER_AST_INTERPMOD_CENTROID; } -interpolation_mod(A) ::= NOINTERPOLATION. { A = MOJOSHADER_AST_INTERPMOD_NOINTERPOLATION; } -interpolation_mod(A) ::= NOPERSPECTIVE. { A = MOJOSHADER_AST_INTERPMOD_NOPERSPECTIVE; } -interpolation_mod(A) ::= SAMPLE. { A = MOJOSHADER_AST_INTERPMOD_SAMPLE; } - -%type variable_declaration { MOJOSHADER_astVariableDeclaration * } -%destructor variable_declaration { delete_variable_declaration(ctx, $$); } -variable_declaration(A) ::= variable_attribute_list(B) datatype(C) variable_declaration_details_list(D) SEMICOLON. { REVERSE_LINKED_LIST(MOJOSHADER_astVariableDeclaration, D); A = D; A->attributes = B; A->datatype = C; } -variable_declaration(A) ::= datatype(B) variable_declaration_details_list(C) SEMICOLON. { REVERSE_LINKED_LIST(MOJOSHADER_astVariableDeclaration, C); A = C; A->datatype = B; } -// !!! FIXME: this expects "struct Identifier {} varname" ... that "Identifier" is wrong. -variable_declaration(A) ::= struct_declaration(B) variable_declaration_details_list(C) SEMICOLON. { REVERSE_LINKED_LIST(MOJOSHADER_astVariableDeclaration, C); A = C; A->anonymous_datatype = B; } - -%type variable_attribute_list { int } -variable_attribute_list(A) ::= variable_attribute(B). { A = B; } -variable_attribute_list(A) ::= variable_attribute_list(B) variable_attribute(C). { A = B | C; } - -%type variable_attribute { int } -variable_attribute(A) ::= EXTERN. { A = MOJOSHADER_AST_VARATTR_EXTERN; } -variable_attribute(A) ::= NOINTERPOLATION. { A = MOJOSHADER_AST_VARATTR_NOINTERPOLATION; } -variable_attribute(A) ::= SHARED. { A = MOJOSHADER_AST_VARATTR_SHARED; } -variable_attribute(A) ::= STATIC. { A = MOJOSHADER_AST_VARATTR_STATIC; } -variable_attribute(A) ::= UNIFORM. { A = MOJOSHADER_AST_VARATTR_UNIFORM; } -variable_attribute(A) ::= VOLATILE. { A = MOJOSHADER_AST_VARATTR_VOLATILE; } -variable_attribute(A) ::= CONST. { A = MOJOSHADER_AST_VARATTR_CONST; } -variable_attribute(A) ::= ROWMAJOR. { A = MOJOSHADER_AST_VARATTR_ROWMAJOR; } -variable_attribute(A) ::= COLUMNMAJOR. { A = MOJOSHADER_AST_VARATTR_COLUMNMAJOR; } - -%type variable_declaration_details_list { MOJOSHADER_astVariableDeclaration * } -%destructor variable_declaration_details_list { delete_variable_declaration(ctx, $$); } -variable_declaration_details_list(A) ::= variable_declaration_details(B). { A = B; } -variable_declaration_details_list(A) ::= variable_declaration_details_list(B) COMMA variable_declaration_details(C). { A = C; A->next = B; } - -%type variable_declaration_details { MOJOSHADER_astVariableDeclaration * } -%destructor variable_declaration_details { delete_variable_declaration(ctx, $$); } -variable_declaration_details(A) ::= scalar_or_array(B) semantic(C) annotations(D) initializer(E) variable_lowlevel(F). { A = new_variable_declaration(ctx, B, C, D, E, F); } -variable_declaration_details(A) ::= scalar_or_array(B) semantic(C) annotations(D) initializer(E). { A = new_variable_declaration(ctx, B, C, D, E, NULL); } -variable_declaration_details(A) ::= scalar_or_array(B) semantic(C) annotations(D) variable_lowlevel(E). { A = new_variable_declaration(ctx, B, C, D, NULL, E); } -variable_declaration_details(A) ::= scalar_or_array(B) semantic(C) annotations(D). { A = new_variable_declaration(ctx, B, C, D, NULL, NULL); } -variable_declaration_details(A) ::= scalar_or_array(B) semantic(C) initializer(D) variable_lowlevel(E). { A = new_variable_declaration(ctx, B, C, NULL, D, E); } -variable_declaration_details(A) ::= scalar_or_array(B) semantic(C) initializer(D). { A = new_variable_declaration(ctx, B, C, NULL, D, NULL); } -variable_declaration_details(A) ::= scalar_or_array(B) semantic(C) variable_lowlevel(D). { A = new_variable_declaration(ctx, B, C, NULL, NULL, D); } -variable_declaration_details(A) ::= scalar_or_array(B) semantic(C). { A = new_variable_declaration(ctx, B, C, NULL, NULL, NULL); } -variable_declaration_details(A) ::= scalar_or_array(B) annotations(C) initializer(D) variable_lowlevel(E). { A = new_variable_declaration(ctx, B, NULL, C, D, E); } -variable_declaration_details(A) ::= scalar_or_array(B) annotations(C) initializer(D). { A = new_variable_declaration(ctx, B, NULL, C, D, NULL); } -variable_declaration_details(A) ::= scalar_or_array(B) annotations(C) variable_lowlevel(D). { A = new_variable_declaration(ctx, B, NULL, C, NULL, D); } -variable_declaration_details(A) ::= scalar_or_array(B) annotations(C). { A = new_variable_declaration(ctx, B, NULL, C, NULL, NULL); } -variable_declaration_details(A) ::= scalar_or_array(B) initializer(C) variable_lowlevel(D). { A = new_variable_declaration(ctx, B, NULL, NULL, C, D); } -variable_declaration_details(A) ::= scalar_or_array(B) initializer(C). { A = new_variable_declaration(ctx, B, NULL, NULL, C, NULL); } -variable_declaration_details(A) ::= scalar_or_array(B) variable_lowlevel(C). { A = new_variable_declaration(ctx, B, NULL, NULL, NULL, C); } -variable_declaration_details(A) ::= scalar_or_array(B). { A = new_variable_declaration(ctx, B, NULL, NULL, NULL, NULL); } - -// !!! FIXME: we don't handle full sampler declarations at the moment. - - -%type struct_declaration { MOJOSHADER_astStructDeclaration * } -%destructor struct_declaration { delete_struct_declaration(ctx, $$); } -struct_declaration(A) ::= struct_intro(B) LBRACE struct_member_list(C) RBRACE. { REVERSE_LINKED_LIST(MOJOSHADER_astStructMembers, C); A = new_struct_declaration(ctx, B, C); } - -// This has to be separate from struct_declaration so that the struct is in the usertypemap when parsing its members. -%type struct_intro { const char * } -struct_intro(A) ::= STRUCT IDENTIFIER(B). { A = B.string; push_usertype(ctx, A, &ctx->dt_none); } // datatype is bogus until semantic analysis. - -%type struct_member_list { MOJOSHADER_astStructMembers * } -%destructor struct_member_list { delete_struct_member(ctx, $$); } -struct_member_list(A) ::= struct_member(B). { A = B; } -struct_member_list(A) ::= struct_member_list(B) struct_member(C). { A = C; MOJOSHADER_astStructMembers *i = A; while (i->next) { i = i->next; } i->next = B; } - -%type struct_member { MOJOSHADER_astStructMembers * } -%destructor struct_member { delete_struct_member(ctx, $$); } -struct_member(A) ::= interpolation_mod(B) struct_member_details(C). { MOJOSHADER_astStructMembers *i = C; A = C; while (i) { i->interpolation_mod = B; i = i->next; } } -struct_member(A) ::= struct_member_details(B). { A = B; } - -%type struct_member_details { MOJOSHADER_astStructMembers * } -%destructor struct_member_details { delete_struct_member(ctx, $$); } -struct_member_details(A) ::= datatype(B) struct_member_item_list(C) SEMICOLON. { MOJOSHADER_astStructMembers *i = C; A = C; while (i) { i->datatype = B; i = i->next; } } - -%type struct_member_item_list { MOJOSHADER_astStructMembers * } -%destructor struct_member_item_list { delete_struct_member(ctx, $$); } -struct_member_item_list(A) ::= scalar_or_array(B). { A = new_struct_member(ctx, B, NULL); } -struct_member_item_list(A) ::= scalar_or_array(B) semantic(C). { A = new_struct_member(ctx, B, C); } -struct_member_item_list(A) ::= struct_member_item_list(B) COMMA IDENTIFIER(C). { A = new_struct_member(ctx, new_scalar_or_array(ctx, C.string, 0, NULL), NULL); A->next = B; A->semantic = B->semantic; } - -%type variable_lowlevel { MOJOSHADER_astVariableLowLevel * } -%destructor variable_lowlevel { delete_variable_lowlevel(ctx, $$); } -variable_lowlevel(A) ::= packoffset(B) register(C). { A = new_variable_lowlevel(ctx, B, C); } -variable_lowlevel(A) ::= register(B) packoffset(C). { A = new_variable_lowlevel(ctx, C, B); } -variable_lowlevel(A) ::= packoffset(B). { A = new_variable_lowlevel(ctx, B, NULL); } -variable_lowlevel(A) ::= register(B). { A = new_variable_lowlevel(ctx, NULL, B); } - -// !!! FIXME: I sort of hate this type name. -%type scalar_or_array { MOJOSHADER_astScalarOrArray * } -%destructor scalar_or_array { delete_scalar_or_array(ctx, $$); } -scalar_or_array(A) ::= IDENTIFIER(B) LBRACKET RBRACKET. { A = new_scalar_or_array(ctx, B.string, 1, NULL); } -scalar_or_array(A) ::= IDENTIFIER(B) LBRACKET expression(C) RBRACKET. { A = new_scalar_or_array(ctx, B.string, 1, C); } -scalar_or_array(A) ::= IDENTIFIER(B). { A = new_scalar_or_array(ctx, B.string, 0, NULL); } - -%type packoffset { MOJOSHADER_astPackOffset * } -%destructor packoffset { delete_pack_offset(ctx, $$); } -packoffset(A) ::= COLON PACKOFFSET LPAREN IDENTIFIER(B) DOT IDENTIFIER(C) RPAREN. { A = new_pack_offset(ctx, B.string, C.string); } -packoffset(A) ::= COLON PACKOFFSET LPAREN IDENTIFIER(B) RPAREN. { A = new_pack_offset(ctx, B.string, NULL); } - -// !!! FIXME: can take a profile, like ": register(ps_5_0, s)" -// !!! FIXME: IDENTIFIER is wrong: "s[2]" works, apparently. Use scalar_or_array instead? -// !!! FIXME: (these might be SM4 features) -%type register { const char * } -register(A) ::= COLON REGISTER LPAREN IDENTIFIER(B) RPAREN. { A = B.string; } - -%type annotations { MOJOSHADER_astAnnotations * } -%destructor annotations { delete_annotation(ctx, $$); } -annotations(A) ::= LT annotation_list(B) GT. { REVERSE_LINKED_LIST(MOJOSHADER_astAnnotations, B); A = B; } - -%type annotation_list { MOJOSHADER_astAnnotations * } -%destructor annotation_list { delete_annotation(ctx, $$); } -annotation_list(A) ::= annotation(B). { A = B; } -annotation_list(A) ::= annotation_list(B) annotation(C). { A = C; A->next = B; } - -// !!! FIXME: can this take a USERTYPE if we typedef'd a scalar type? -%type annotation { MOJOSHADER_astAnnotations * } -%destructor annotation { delete_annotation(ctx, $$); } -annotation(A) ::= datatype_scalar(B) initializer(C) SEMICOLON. { A = new_annotation(ctx, B, C); } - -%type initializer_block_list { MOJOSHADER_astExpression * } -%destructor initializer_block_list { delete_expr(ctx, $$); } -initializer_block_list(A) ::= expression(B). { A = B; } -initializer_block_list(A) ::= LBRACE initializer_block_list(B) RBRACE. { A = B; } -initializer_block_list(A) ::= initializer_block_list(B) COMMA initializer_block_list(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_COMMA, B, C); } - -%type initializer_block { MOJOSHADER_astExpression * } -%destructor initializer_block { delete_expr(ctx, $$); } -initializer_block(A) ::= LBRACE initializer_block_list(B) RBRACE. { A = B; } - -%type initializer { MOJOSHADER_astExpression * } -%destructor initializer { delete_expr(ctx, $$); } -initializer(A) ::= ASSIGN initializer_block(B). { A = B; } -initializer(A) ::= ASSIGN expression(B). { A = B; } - -%type intrinsic_datatype { const MOJOSHADER_astDataType * } -intrinsic_datatype(A) ::= datatype_vector(B). { A = B; } -intrinsic_datatype(A) ::= datatype_matrix(B). { A = B; } -intrinsic_datatype(A) ::= datatype_scalar(B). { A = B; } -intrinsic_datatype(A) ::= datatype_sampler(B). { A = B; } -intrinsic_datatype(A) ::= datatype_buffer(B). { A = B; } - -%type datatype { const MOJOSHADER_astDataType * } -datatype(A) ::= intrinsic_datatype(B). { A = B; } -datatype(A) ::= USERTYPE(B). { A = B.datatype; } - -%type datatype_sampler { const MOJOSHADER_astDataType * } -datatype_sampler(A) ::= SAMPLER. { A = &ctx->dt_sampler2d; } -datatype_sampler(A) ::= SAMPLER1D. { A = &ctx->dt_sampler1d; } -datatype_sampler(A) ::= SAMPLER2D. { A = &ctx->dt_sampler2d; } -datatype_sampler(A) ::= SAMPLER3D. { A = &ctx->dt_sampler3d; } -datatype_sampler(A) ::= SAMPLERCUBE. { A = &ctx->dt_samplercube; } -datatype_sampler(A) ::= SAMPLER_STATE. { A = &ctx->dt_samplerstate; } -datatype_sampler(A) ::= SAMPLERSTATE. { A = &ctx->dt_samplerstate; } -datatype_sampler(A) ::= SAMPLERCOMPARISONSTATE. { A = &ctx->dt_samplercompstate; } - -%type datatype_scalar { const MOJOSHADER_astDataType * } -datatype_scalar(A) ::= BOOL. { A = &ctx->dt_bool; } -datatype_scalar(A) ::= INT. { A = &ctx->dt_int; } -datatype_scalar(A) ::= UINT. { A = &ctx->dt_uint; } -datatype_scalar(A) ::= HALF. { A = &ctx->dt_half; } -datatype_scalar(A) ::= FLOAT. { A = &ctx->dt_float; } -datatype_scalar(A) ::= DOUBLE. { A = &ctx->dt_double; } -datatype_scalar(A) ::= STRING. { A = &ctx->dt_string; } // this is for the effects framework, not HLSL. -datatype_scalar(A) ::= SNORM FLOAT. { A = &ctx->dt_float_snorm; } -datatype_scalar(A) ::= UNORM FLOAT. { A = &ctx->dt_float_unorm; } - -%type datatype_buffer { const MOJOSHADER_astDataType * } -datatype_buffer(A) ::= BUFFER LT BOOL GT. { A = &ctx->dt_buf_bool; } -datatype_buffer(A) ::= BUFFER LT INT GT. { A = &ctx->dt_buf_int; } -datatype_buffer(A) ::= BUFFER LT UINT GT. { A = &ctx->dt_buf_uint; } -datatype_buffer(A) ::= BUFFER LT HALF GT. { A = &ctx->dt_buf_half; } -datatype_buffer(A) ::= BUFFER LT FLOAT GT. { A = &ctx->dt_buf_float; } -datatype_buffer(A) ::= BUFFER LT DOUBLE GT. { A = &ctx->dt_buf_double; } -datatype_buffer(A) ::= BUFFER LT SNORM FLOAT GT. { A = &ctx->dt_buf_float_snorm; } -datatype_buffer(A) ::= BUFFER LT UNORM FLOAT GT. { A = &ctx->dt_buf_float_unorm; } - -%type datatype_vector { const MOJOSHADER_astDataType * } -datatype_vector(A) ::= VECTOR LT datatype_scalar(B) COMMA INT_CONSTANT(C) GT. { A = new_datatype_vector(ctx, B, (int) C.i64); } - -%type datatype_matrix { const MOJOSHADER_astDataType * } -datatype_matrix(A) ::= MATRIX LT datatype_scalar(B) COMMA INT_CONSTANT(C) COMMA INT_CONSTANT(D) GT. { A = new_datatype_matrix(ctx, B, (int) C.i64, (int) D.i64); } - -%type statement_block { MOJOSHADER_astStatement * } -%destructor statement_block { delete_statement(ctx, $$); } -statement_block(A) ::= LBRACE RBRACE. { A = new_block_statement(ctx, NULL); } -statement_block(A) ::= LBRACE statement_list(B) RBRACE. { REVERSE_LINKED_LIST(MOJOSHADER_astStatement, B); A = new_block_statement(ctx, B); } - -%type statement_list { MOJOSHADER_astStatement * } -%destructor statement_list { delete_statement(ctx, $$); } -statement_list(A) ::= statement(B). { A = B; } -statement_list(A) ::= statement_list(B) statement(C). { A = C; A->next = B; } - -// These are for Shader Model 4 and Xbox 360 only, apparently. -// !!! FIXME: ...so we ignore them for now. -// !!! FIXME: can these stack? "[isolate][unused]{}" or something? -%type statement_attribute { int } -statement_attribute(A) ::= ISOLATE. { A = 0; } // !!! FIXME -statement_attribute(A) ::= MAXINSTRUCTIONCOUNT LPAREN INT_CONSTANT RPAREN. { A = 0; } // !!! FIXME -statement_attribute(A) ::= NOEXPRESSIONOPTIMIZATIONS. { A = 0; } // !!! FIXME -statement_attribute(A) ::= REMOVEUNUSEDINPUTS. { A = 0; } // !!! FIXME -statement_attribute(A) ::= UNUSED. { A = 0; } // !!! FIXME -statement_attribute(A) ::= XPS. { A = 0; } // !!! FIXME - -%type statement { MOJOSHADER_astStatement * } -%destructor statement { delete_statement(ctx, $$); } -statement(A) ::= BREAK SEMICOLON. { A = new_break_statement(ctx); } -statement(A) ::= CONTINUE SEMICOLON. { A = new_continue_statement(ctx); } -statement(A) ::= DISCARD SEMICOLON. { A = new_discard_statement(ctx); } -statement(A) ::= LBRACKET statement_attribute(B) RBRACKET statement_block(C). { A = C; /* !!! FIXME: A->attributes = B;*/ B = 0; } -statement(A) ::= variable_declaration(B). { A = new_vardecl_statement(ctx, B); } -statement(A) ::= struct_declaration(B) SEMICOLON. { A = new_struct_statement(ctx, B); } -statement(A) ::= do_intro(B) DO statement(C) WHILE LPAREN expression(D) RPAREN SEMICOLON. { A = new_do_statement(ctx, B, C, D); } -statement(A) ::= while_intro(B) LPAREN expression(C) RPAREN statement(D). { A = new_while_statement(ctx, B, C, D); } -statement(A) ::= if_intro(B) LPAREN expression(C) RPAREN statement(D). { A = new_if_statement(ctx, B, C, D, NULL); } -statement(A) ::= if_intro(B) LPAREN expression(C) RPAREN statement(D) ELSE statement(E). { A = new_if_statement(ctx, B, C, D, E); } -statement(A) ::= switch_intro(B) LPAREN expression(C) RPAREN LBRACE switch_case_list(D) RBRACE. { REVERSE_LINKED_LIST(MOJOSHADER_astSwitchCases, D); A = new_switch_statement(ctx, B, C, D); } -statement(A) ::= typedef(B). { A = new_typedef_statement(ctx, B); } -statement(A) ::= SEMICOLON. { A = new_empty_statement(ctx); } -statement(A) ::= expression(B) SEMICOLON. { A = new_expr_statement(ctx, B); } -statement(A) ::= RETURN SEMICOLON. { A = new_return_statement(ctx, NULL); } -statement(A) ::= RETURN expression(B) SEMICOLON. { A = new_return_statement(ctx, B); } -statement(A) ::= statement_block(B). { A = B; } -statement(A) ::= for_statement(B). { A = B; } -//statement(A) ::= error SEMICOLON. { A = NULL; } // !!! FIXME: research using the error nonterminal - -%type while_intro { int } -while_intro(A) ::= LBRACKET UNROLL LPAREN INT_CONSTANT(B) RPAREN RBRACKET WHILE. { A = (B.i64 < 0) ? 0 : B.i64; } -while_intro(A) ::= LBRACKET UNROLL RBRACKET WHILE. { A = -1; } -while_intro(A) ::= LBRACKET LOOP RBRACKET WHILE. { A = 0; } -while_intro(A) ::= WHILE. { A = -2; } - -%type for_statement { MOJOSHADER_astStatement * } -%destructor for_statement { delete_statement(ctx, $$); } -for_statement(A) ::= for_intro(B) for_details(C). { A = C; ((MOJOSHADER_astForStatement *) A)->unroll = B; } - -%type for_intro { int } -for_intro(A) ::= LBRACKET UNROLL LPAREN INT_CONSTANT(B) RPAREN RBRACKET FOR. { A = (B.i64 < 0) ? 0 : B.i64; } -for_intro(A) ::= LBRACKET UNROLL RBRACKET FOR. { A = -1; } -for_intro(A) ::= LBRACKET LOOP RBRACKET FOR. { A = 0; } -for_intro(A) ::= FOR. { A = -2; } - -%type for_details { MOJOSHADER_astStatement * } -%destructor for_details { delete_statement(ctx, $$); } -for_details(A) ::= LPAREN expression(B) SEMICOLON expression(C) SEMICOLON expression(D) RPAREN statement(E). { A = new_for_statement(ctx, NULL, B, C, D, E); } -for_details(A) ::= LPAREN SEMICOLON SEMICOLON RPAREN statement(B). { A = new_for_statement(ctx, NULL, NULL, NULL, NULL, B); } -for_details(A) ::= LPAREN SEMICOLON SEMICOLON expression(B) RPAREN statement(C). { A = new_for_statement(ctx, NULL, NULL, NULL, B, C); } -for_details(A) ::= LPAREN SEMICOLON expression(B) SEMICOLON RPAREN statement(C). { A = new_for_statement(ctx, NULL, NULL, B, NULL, C); } -for_details(A) ::= LPAREN SEMICOLON expression(B) SEMICOLON expression(C) RPAREN statement(D). { A = new_for_statement(ctx, NULL, NULL, B, C, D); } -for_details(A) ::= LPAREN expression(B) SEMICOLON SEMICOLON RPAREN statement(C). { A = new_for_statement(ctx, NULL, B, NULL, NULL, C); } -for_details(A) ::= LPAREN expression(B) SEMICOLON SEMICOLON expression(C) RPAREN statement(D). { A = new_for_statement(ctx, NULL, B, NULL, C, D); } -for_details(A) ::= LPAREN expression(B) SEMICOLON expression(C) SEMICOLON RPAREN statement(D). { A = new_for_statement(ctx, NULL, B, C, NULL, D); } -for_details(A) ::= LPAREN variable_declaration(B) expression(C) SEMICOLON expression(D) RPAREN statement(E). { A = new_for_statement(ctx, B, NULL, C, D, E); } -for_details(A) ::= LPAREN variable_declaration(B) SEMICOLON RPAREN statement(C). { A = new_for_statement(ctx, B, NULL, NULL, NULL, C); } -for_details(A) ::= LPAREN variable_declaration(B) SEMICOLON expression(C) RPAREN statement(D). { A = new_for_statement(ctx, B, NULL, C, NULL, D); } -for_details(A) ::= LPAREN variable_declaration(B) expression(C) SEMICOLON RPAREN statement(D). { A = new_for_statement(ctx, B, NULL, C, NULL, D); } - -%type do_intro { int } -do_intro(A) ::= LBRACKET UNROLL LPAREN INT_CONSTANT(B) RPAREN RBRACKET DO. { A = (B.i64 < 0) ? 0 : (int) B.i64; } -do_intro(A) ::= LBRACKET UNROLL RBRACKET DO. { A = -1; } -do_intro(A) ::= LBRACKET LOOP RBRACKET DO. { A = 0; } -do_intro(A) ::= DO. { A = -2; } - -%type if_intro { int } -if_intro(A) ::= LBRACKET BRANCH RBRACKET IF. { A = MOJOSHADER_AST_IFATTR_BRANCH; } -if_intro(A) ::= LBRACKET FLATTEN RBRACKET IF. { A = MOJOSHADER_AST_IFATTR_FLATTEN; } -if_intro(A) ::= LBRACKET IFALL RBRACKET IF. { A = MOJOSHADER_AST_IFATTR_IFALL; } -if_intro(A) ::= LBRACKET IFANY RBRACKET IF. { A = MOJOSHADER_AST_IFATTR_IFANY; } -if_intro(A) ::= LBRACKET PREDICATE RBRACKET IF. { A = MOJOSHADER_AST_IFATTR_PREDICATE; } -if_intro(A) ::= LBRACKET PREDICATEBLOCK RBRACKET IF. { A = MOJOSHADER_AST_IFATTR_PREDICATEBLOCK; } -if_intro(A) ::= IF. { A = MOJOSHADER_AST_IFATTR_NONE; } - -%type switch_intro { int } -switch_intro(A) ::= LBRACKET FLATTEN RBRACKET SWITCH. { A = MOJOSHADER_AST_SWITCHATTR_FLATTEN; } -switch_intro(A) ::= LBRACKET BRANCH RBRACKET SWITCH. { A = MOJOSHADER_AST_SWITCHATTR_BRANCH; } -switch_intro(A) ::= LBRACKET FORCECASE RBRACKET SWITCH. { A = MOJOSHADER_AST_SWITCHATTR_FORCECASE; } -switch_intro(A) ::= LBRACKET CALL RBRACKET SWITCH. { A = MOJOSHADER_AST_SWITCHATTR_CALL; } -switch_intro(A) ::= SWITCH. { A = MOJOSHADER_AST_SWITCHATTR_NONE; } - -%type switch_case_list { MOJOSHADER_astSwitchCases * } -%destructor switch_case_list { delete_switch_case(ctx, $$); } -switch_case_list(A) ::= switch_case(B). { A = B; } -switch_case_list(A) ::= switch_case_list(B) switch_case(C). { A = C; A->next = B; } - -// You can do math here, apparently, as long as it produces an int constant. -// ...so "case 3+2:" works. -%type switch_case { MOJOSHADER_astSwitchCases * } -%destructor switch_case { delete_switch_case(ctx, $$); } -switch_case(A) ::= CASE expression(B) COLON statement_list(C). { REVERSE_LINKED_LIST(MOJOSHADER_astStatement, C); A = new_switch_case(ctx, B, C); } -switch_case(A) ::= CASE expression(B) COLON. { A = new_switch_case(ctx, B, NULL); } -switch_case(A) ::= DEFAULT COLON statement_list(B). { REVERSE_LINKED_LIST(MOJOSHADER_astStatement, B); A = new_switch_case(ctx, NULL, B); } -switch_case(A) ::= DEFAULT COLON. { A = new_switch_case(ctx, NULL, NULL); } - -// the expression stuff is based on Jeff Lee's ANSI C grammar. -%type primary_expr { MOJOSHADER_astExpression * } -%destructor primary_expr { delete_expr(ctx, $$); } -primary_expr(A) ::= IDENTIFIER(B). { A = new_identifier_expr(ctx, B.string); } -primary_expr(A) ::= INT_CONSTANT(B). { A = new_literal_int_expr(ctx, B.i64); } -primary_expr(A) ::= FLOAT_CONSTANT(B). { A = new_literal_float_expr(ctx, B.dbl); } -primary_expr(A) ::= STRING_LITERAL(B). { A = new_literal_string_expr(ctx, B.string); } -primary_expr(A) ::= TRUE. { A = new_literal_boolean_expr(ctx, 1); } -primary_expr(A) ::= FALSE. { A = new_literal_boolean_expr(ctx, 0); } -primary_expr(A) ::= LPAREN expression(B) RPAREN. { A = B; } - -%type postfix_expr { MOJOSHADER_astExpression * } -%destructor postfix_expr { delete_expr(ctx, $$); } -postfix_expr(A) ::= primary_expr(B). { A = B; } -postfix_expr(A) ::= postfix_expr(B) LBRACKET expression(C) RBRACKET. { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_DEREF_ARRAY, B, C); } -postfix_expr(A) ::= IDENTIFIER(B) arguments(C). { A = new_callfunc_expr(ctx, B.string, C); } -postfix_expr(A) ::= datatype(B) arguments(C). { A = new_constructor_expr(ctx, B, C); } // HLSL constructor -postfix_expr(A) ::= postfix_expr(B) DOT IDENTIFIER(C). { A = new_deref_struct_expr(ctx, B, C.string); } -postfix_expr(A) ::= postfix_expr(B) PLUSPLUS. { A = new_unary_expr(ctx, MOJOSHADER_AST_OP_POSTINCREMENT, B); } -postfix_expr(A) ::= postfix_expr(B) MINUSMINUS. { A = new_unary_expr(ctx, MOJOSHADER_AST_OP_POSTDECREMENT, B); } - -%type arguments { MOJOSHADER_astArguments * } -%destructor arguments { delete_arguments(ctx, $$); } -arguments(A) ::= LPAREN RPAREN. { A = NULL; } -arguments(A) ::= LPAREN argument_list(B) RPAREN. { REVERSE_LINKED_LIST(MOJOSHADER_astArguments, B); A = B; } - -%type argument_list { MOJOSHADER_astArguments * } -%destructor argument_list { delete_arguments(ctx, $$); } -argument_list(A) ::= assignment_expr(B). { A = new_argument(ctx, B); } -argument_list(A) ::= argument_list(B) COMMA assignment_expr(C). { A = new_argument(ctx, C); A->next = B; } - -%type unary_expr { MOJOSHADER_astExpression * } -%destructor unary_expr { delete_expr(ctx, $$); } -unary_expr(A) ::= postfix_expr(B). { A = B; } -unary_expr(A) ::= PLUSPLUS unary_expr(B). { A = new_unary_expr(ctx, MOJOSHADER_AST_OP_PREINCREMENT, B); } -unary_expr(A) ::= MINUSMINUS unary_expr(B). { A = new_unary_expr(ctx, MOJOSHADER_AST_OP_PREDECREMENT, B); } -unary_expr(A) ::= PLUS cast_expr(B). { A = B; } // unary "+x" is always a no-op, so throw it away here. -unary_expr(A) ::= MINUS cast_expr(B). { A = new_unary_expr(ctx, MOJOSHADER_AST_OP_NEGATE, B); } -unary_expr(A) ::= COMPLEMENT cast_expr(B). { A = new_unary_expr(ctx, MOJOSHADER_AST_OP_COMPLEMENT, B); } -unary_expr(A) ::= EXCLAMATION cast_expr(B). { A = new_unary_expr(ctx, MOJOSHADER_AST_OP_NOT, B); } - -%type cast_expr { MOJOSHADER_astExpression * } -%destructor cast_expr { delete_expr(ctx, $$); } -cast_expr(A) ::= unary_expr(B). { A = B; } -cast_expr(A) ::= LPAREN datatype(B) RPAREN cast_expr(C). { A = new_cast_expr(ctx, B, C); } - -%type multiplicative_expr { MOJOSHADER_astExpression * } -%destructor multiplicative_expr { delete_expr(ctx, $$); } -multiplicative_expr(A) ::= cast_expr(B). { A = B; } -multiplicative_expr(A) ::= multiplicative_expr(B) STAR cast_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_MULTIPLY, B, C); } -multiplicative_expr(A) ::= multiplicative_expr(B) SLASH cast_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_DIVIDE, B, C); } -multiplicative_expr(A) ::= multiplicative_expr(B) PERCENT cast_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_MODULO, B, C); } - -%type additive_expr { MOJOSHADER_astExpression * } -%destructor additive_expr { delete_expr(ctx, $$); } -additive_expr(A) ::= multiplicative_expr(B). { A = B; } -additive_expr(A) ::= additive_expr(B) PLUS multiplicative_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_ADD, B, C); } -additive_expr(A) ::= additive_expr(B) MINUS multiplicative_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_SUBTRACT, B, C); } - -%type shift_expr { MOJOSHADER_astExpression * } -%destructor shift_expr { delete_expr(ctx, $$); } -shift_expr(A) ::= additive_expr(B). { A = B; } -shift_expr(A) ::= shift_expr(B) LSHIFT additive_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_LSHIFT, B, C); } -shift_expr(A) ::= shift_expr(B) RSHIFT additive_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_RSHIFT, B, C); } - -%type relational_expr { MOJOSHADER_astExpression * } -%destructor relational_expr { delete_expr(ctx, $$); } -relational_expr(A) ::= shift_expr(B). { A = B; } -relational_expr(A) ::= relational_expr(B) LT shift_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_LESSTHAN, B, C); } -relational_expr(A) ::= relational_expr(B) GT shift_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_GREATERTHAN, B, C); } -relational_expr(A) ::= relational_expr(B) LEQ shift_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_LESSTHANOREQUAL, B, C); } -relational_expr(A) ::= relational_expr(B) GEQ shift_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_GREATERTHANOREQUAL, B, C); } - -%type equality_expr { MOJOSHADER_astExpression * } -%destructor equality_expr { delete_expr(ctx, $$); } -equality_expr(A) ::= relational_expr(B). { A = B; } -equality_expr(A) ::= equality_expr(B) EQL relational_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_EQUAL, B, C); } -equality_expr(A) ::= equality_expr(B) NEQ relational_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_NOTEQUAL, B, C); } - -%type and_expr { MOJOSHADER_astExpression * } -%destructor and_expr { delete_expr(ctx, $$); } -and_expr(A) ::= equality_expr(B). { A = B; } -and_expr(A) ::= and_expr(B) AND equality_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_BINARYAND, B, C); } - -%type exclusive_or_expr { MOJOSHADER_astExpression * } -%destructor exclusive_or_expr { delete_expr(ctx, $$); } -exclusive_or_expr(A) ::= and_expr(B). { A = B; } -exclusive_or_expr(A) ::= exclusive_or_expr(B) XOR and_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_BINARYXOR, B, C); } - -%type inclusive_or_expr { MOJOSHADER_astExpression * } -%destructor inclusive_or_expr { delete_expr(ctx, $$); } -inclusive_or_expr(A) ::= exclusive_or_expr(B). { A = B; } -inclusive_or_expr(A) ::= inclusive_or_expr(B) OR exclusive_or_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_BINARYOR, B, C); } - -%type logical_and_expr { MOJOSHADER_astExpression * } -%destructor logical_and_expr { delete_expr(ctx, $$); } -logical_and_expr(A) ::= inclusive_or_expr(B). { A = B; } -logical_and_expr(A) ::= logical_and_expr(B) ANDAND inclusive_or_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_LOGICALAND, B, C); } - -%type logical_or_expr { MOJOSHADER_astExpression * } -%destructor logical_or_expr { delete_expr(ctx, $$); } -logical_or_expr(A) ::= logical_and_expr(B). { A = B; } -logical_or_expr(A) ::= logical_or_expr(B) OROR logical_and_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_LOGICALOR, B, C); } - -%type conditional_expr { MOJOSHADER_astExpression * } -%destructor conditional_expr { delete_expr(ctx, $$); } -conditional_expr(A) ::= logical_or_expr(B). { A = B; } -conditional_expr(A) ::= logical_or_expr(B) QUESTION logical_or_expr(C) COLON conditional_expr(D). { A = new_ternary_expr(ctx, MOJOSHADER_AST_OP_CONDITIONAL, B, C, D); } - -%type assignment_expr { MOJOSHADER_astExpression * } -%destructor assignment_expr { delete_expr(ctx, $$); } -assignment_expr(A) ::= conditional_expr(B). { A = B; } -assignment_expr(A) ::= unary_expr(B) ASSIGN assignment_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_ASSIGN, B, C); } -assignment_expr(A) ::= unary_expr(B) MULASSIGN assignment_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_MULASSIGN, B, C); } -assignment_expr(A) ::= unary_expr(B) DIVASSIGN assignment_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_DIVASSIGN, B, C); } -assignment_expr(A) ::= unary_expr(B) MODASSIGN assignment_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_MODASSIGN, B, C); } -assignment_expr(A) ::= unary_expr(B) ADDASSIGN assignment_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_ADDASSIGN, B, C); } -assignment_expr(A) ::= unary_expr(B) SUBASSIGN assignment_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_SUBASSIGN, B, C); } -assignment_expr(A) ::= unary_expr(B) LSHIFTASSIGN assignment_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_LSHIFTASSIGN, B, C); } -assignment_expr(A) ::= unary_expr(B) RSHIFTASSIGN assignment_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_RSHIFTASSIGN, B, C); } -assignment_expr(A) ::= unary_expr(B) ANDASSIGN assignment_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_ANDASSIGN, B, C); } -assignment_expr(A) ::= unary_expr(B) XORASSIGN assignment_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_XORASSIGN, B, C); } -assignment_expr(A) ::= unary_expr(B) ORASSIGN assignment_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_ORASSIGN, B, C); } - -%type expression { MOJOSHADER_astExpression * } -%destructor expression { delete_expr(ctx, $$); } -expression(A) ::= assignment_expr(B). { A = B; } -expression(A) ::= expression(B) COMMA assignment_expr(C). { A = new_binary_expr(ctx, MOJOSHADER_AST_OP_COMMA, B, C); } - -// end of mojoshader_parser_hlsl.lemon ... - diff --git a/mojoshader/mojoshader_preprocessor.c b/mojoshader/mojoshader_preprocessor.c deleted file mode 100644 index 233566a..0000000 --- a/mojoshader/mojoshader_preprocessor.c +++ /dev/null @@ -1,2362 +0,0 @@ -/** - * MojoShader; generate shader programs from bytecode of compiled - * Direct3D shaders. - * - * Please see the file LICENSE.txt in the source's root directory. - * - * This file written by Ryan C. Gordon. - */ - -#define __MOJOSHADER_INTERNAL__ 1 -#include "mojoshader_internal.h" - -#if DEBUG_PREPROCESSOR - #define print_debug_token(token, len, val) \ - MOJOSHADER_print_debug_token("PREPROCESSOR", token, len, val) -#else - #define print_debug_token(token, len, val) -#endif - -#if DEBUG_LEXER -static Token debug_preprocessor_lexer(IncludeState *s) -{ - const Token retval = preprocessor_lexer(s); - MOJOSHADER_print_debug_token("LEXER", s->token, s->tokenlen, retval); - return retval; -} // debug_preprocessor_lexer -#define preprocessor_lexer(s) debug_preprocessor_lexer(s) -#endif - -#if DEBUG_TOKENIZER -static void print_debug_lexing_position(IncludeState *s) -{ - if (s != NULL) - printf("NOW LEXING %s:%d ...\n", s->filename, s->line); -} // print_debug_lexing_position -#else -#define print_debug_lexing_position(s) -#endif - -typedef struct Context -{ - int isfail; - int out_of_memory; - char failstr[256]; - int recursion_count; - int asm_comments; - int parsing_pragma; - Conditional *conditional_pool; - IncludeState *include_stack; - IncludeState *include_pool; - Define *define_hashtable[256]; - Define *define_pool; - Define *file_macro; - Define *line_macro; - StringCache *filename_cache; - MOJOSHADER_includeOpen open_callback; - MOJOSHADER_includeClose close_callback; - MOJOSHADER_malloc malloc; - MOJOSHADER_free free; - void *malloc_data; -} Context; - - -// Convenience functions for allocators... - -static inline void out_of_memory(Context *ctx) -{ - ctx->out_of_memory = 1; -} // out_of_memory - -static inline void *Malloc(Context *ctx, const size_t len) -{ - void *retval = ctx->malloc((int) len, ctx->malloc_data); - if (retval == NULL) - out_of_memory(ctx); - return retval; -} // Malloc - -static inline void Free(Context *ctx, void *ptr) -{ - ctx->free(ptr, ctx->malloc_data); -} // Free - -static void *MallocBridge(int bytes, void *data) -{ - return Malloc((Context *) data, (size_t) bytes); -} // MallocBridge - -static void FreeBridge(void *ptr, void *data) -{ - Free((Context *) data, ptr); -} // FreeBridge - -static inline char *StrDup(Context *ctx, const char *str) -{ - char *retval = (char *) Malloc(ctx, strlen(str) + 1); - if (retval != NULL) - strcpy(retval, str); - return retval; -} // StrDup - -static void failf(Context *ctx, const char *fmt, ...) ISPRINTF(2,3); -static void failf(Context *ctx, const char *fmt, ...) -{ - ctx->isfail = 1; - va_list ap; - va_start(ap, fmt); - vsnprintf(ctx->failstr, sizeof (ctx->failstr), fmt, ap); - va_end(ap); -} // failf - -static inline void fail(Context *ctx, const char *reason) -{ - failf(ctx, "%s", reason); -} // fail - - -#if DEBUG_TOKENIZER -void MOJOSHADER_print_debug_token(const char *subsystem, const char *token, - const unsigned int tokenlen, - const Token tokenval) -{ - printf("%s TOKEN: \"", subsystem); - unsigned int i; - for (i = 0; i < tokenlen; i++) - { - if (token[i] == '\n') - printf("\\n"); - else if (token[i] == '\\') - printf("\\\\"); - else - printf("%c", token[i]); - } // for - printf("\" ("); - switch (tokenval) - { - #define TOKENCASE(x) case x: printf("%s", #x); break - TOKENCASE(TOKEN_UNKNOWN); - TOKENCASE(TOKEN_IDENTIFIER); - TOKENCASE(TOKEN_INT_LITERAL); - TOKENCASE(TOKEN_FLOAT_LITERAL); - TOKENCASE(TOKEN_STRING_LITERAL); - TOKENCASE(TOKEN_ADDASSIGN); - TOKENCASE(TOKEN_SUBASSIGN); - TOKENCASE(TOKEN_MULTASSIGN); - TOKENCASE(TOKEN_DIVASSIGN); - TOKENCASE(TOKEN_MODASSIGN); - TOKENCASE(TOKEN_XORASSIGN); - TOKENCASE(TOKEN_ANDASSIGN); - TOKENCASE(TOKEN_ORASSIGN); - TOKENCASE(TOKEN_INCREMENT); - TOKENCASE(TOKEN_DECREMENT); - TOKENCASE(TOKEN_RSHIFT); - TOKENCASE(TOKEN_LSHIFT); - TOKENCASE(TOKEN_ANDAND); - TOKENCASE(TOKEN_OROR); - TOKENCASE(TOKEN_LEQ); - TOKENCASE(TOKEN_GEQ); - TOKENCASE(TOKEN_EQL); - TOKENCASE(TOKEN_NEQ); - TOKENCASE(TOKEN_HASH); - TOKENCASE(TOKEN_HASHHASH); - TOKENCASE(TOKEN_PP_INCLUDE); - TOKENCASE(TOKEN_PP_LINE); - TOKENCASE(TOKEN_PP_DEFINE); - TOKENCASE(TOKEN_PP_UNDEF); - TOKENCASE(TOKEN_PP_IF); - TOKENCASE(TOKEN_PP_IFDEF); - TOKENCASE(TOKEN_PP_IFNDEF); - TOKENCASE(TOKEN_PP_ELSE); - TOKENCASE(TOKEN_PP_ELIF); - TOKENCASE(TOKEN_PP_ENDIF); - TOKENCASE(TOKEN_PP_ERROR); - TOKENCASE(TOKEN_PP_PRAGMA); - TOKENCASE(TOKEN_INCOMPLETE_COMMENT); - TOKENCASE(TOKEN_BAD_CHARS); - TOKENCASE(TOKEN_EOI); - TOKENCASE(TOKEN_PREPROCESSING_ERROR); - #undef TOKENCASE - - case ((Token) '\n'): - printf("'\\n'"); - break; - - case ((Token) '\\'): - printf("'\\\\'"); - break; - - default: - assert(((int)tokenval) < 256); - printf("'%c'", (char) tokenval); - break; - } // switch - printf(")\n"); -} // MOJOSHADER_print_debug_token -#endif - - - -#if !MOJOSHADER_FORCE_INCLUDE_CALLBACKS - -// !!! FIXME: most of these _MSC_VER should probably be _WINDOWS? -#ifdef _MSC_VER -#define WIN32_LEAN_AND_MEAN 1 -#include // GL headers need this for WINGDIAPI definition. -#else -#include -#include -#include -#endif - -int MOJOSHADER_internal_include_open(MOJOSHADER_includeType inctype, - const char *fname, const char *parent, - const char **outdata, - unsigned int *outbytes, - MOJOSHADER_malloc m, MOJOSHADER_free f, - void *d) -{ -#ifdef _MSC_VER - WCHAR wpath[MAX_PATH]; - if (!MultiByteToWideChar(CP_UTF8, 0, fname, -1, wpath, MAX_PATH)) - return 0; - - const DWORD share = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; - const HANDLE handle = CreateFileW(wpath, FILE_GENERIC_READ, share, - NULL, OPEN_EXISTING, NULL, NULL); - if (handle == INVALID_HANDLE_VALUE) - return 0; - - const DWORD fileSize = GetFileSize(handle, NULL); - if (fileSize == INVALID_FILE_SIZE) - { - CloseHandle(handle); - return 0; - } // if - - char *data = (char *) m(fileSize, d); - if (data == NULL) - { - CloseHandle(handle); - return 0; - } // if - - DWORD readLength = 0; - if (!ReadFile(handle, data, fileSize, &readLength, NULL)) - { - CloseHandle(handle); - f(data, d); - return 0; - } // if - - CloseHandle(handle); - - if (readLength != fileSize) - { - f(data, d); - return 0; - } // if - *outdata = data; - *outbytes = fileSize; - return 1; -#else - struct stat statbuf; - if (stat(fname, &statbuf) == -1) - return 0; - char *data = (char *) m(statbuf.st_size, d); - if (data == NULL) - return 0; - const int fd = open(fname, O_RDONLY); - if (fd == -1) - { - f(data, d); - return 0; - } // if - if (read(fd, data, statbuf.st_size) != statbuf.st_size) - { - f(data, d); - close(fd); - return 0; - } // if - close(fd); - *outdata = data; - *outbytes = (unsigned int) statbuf.st_size; - return 1; -#endif -} // MOJOSHADER_internal_include_open - - -void MOJOSHADER_internal_include_close(const char *data, MOJOSHADER_malloc m, - MOJOSHADER_free f, void *d) -{ - f((void *) data, d); -} // MOJOSHADER_internal_include_close -#endif // !MOJOSHADER_FORCE_INCLUDE_CALLBACKS - - -// !!! FIXME: maybe use these pool magic elsewhere? -// !!! FIXME: maybe just get rid of this? (maybe the fragmentation isn't a big deal?) - -// Pool stuff... -// ugh, I hate this macro salsa. -#define FREE_POOL(type, poolname) \ - static void free_##poolname##_pool(Context *ctx) { \ - type *item = ctx->poolname##_pool; \ - while (item != NULL) { \ - type *next = item->next; \ - Free(ctx, item); \ - item = next; \ - } \ - } - -#define GET_POOL(type, poolname) \ - static type *get_##poolname(Context *ctx) { \ - type *retval = ctx->poolname##_pool; \ - if (retval != NULL) \ - ctx->poolname##_pool = retval->next; \ - else \ - retval = (type *) Malloc(ctx, sizeof (type)); \ - if (retval != NULL) \ - memset(retval, '\0', sizeof (type)); \ - return retval; \ - } - -#define PUT_POOL(type, poolname) \ - static void put_##poolname(Context *ctx, type *item) { \ - item->next = ctx->poolname##_pool; \ - ctx->poolname##_pool = item; \ - } - -#define IMPLEMENT_POOL(type, poolname) \ - FREE_POOL(type, poolname) \ - GET_POOL(type, poolname) \ - PUT_POOL(type, poolname) - -IMPLEMENT_POOL(Conditional, conditional) -IMPLEMENT_POOL(IncludeState, include) -IMPLEMENT_POOL(Define, define) - - -// Preprocessor define hashtable stuff... - -// !!! FIXME: why isn't this using mojoshader_common.c's code? - -// this is djb's xor hashing function. -static inline uint32 hash_string_djbxor(const char *sym) -{ - register uint32 hash = 5381; - while (*sym) - hash = ((hash << 5) + hash) ^ *(sym++); - return hash; -} // hash_string_djbxor - -static inline uint8 hash_define(const char *sym) -{ - return (uint8) hash_string_djbxor(sym); -} // hash_define - - -static int add_define(Context *ctx, const char *sym, const char *val, - char **parameters, int paramcount) -{ - const uint8 hash = hash_define(sym); - Define *bucket = ctx->define_hashtable[hash]; - while (bucket) - { - if (strcmp(bucket->identifier, sym) == 0) - { - failf(ctx, "'%s' already defined", sym); // !!! FIXME: warning? - // !!! FIXME: gcc reports the location of previous #define here. - return 0; - } // if - bucket = bucket->next; - } // while - - bucket = get_define(ctx); - if (bucket == NULL) - return 0; - - bucket->definition = val; - bucket->original = NULL; - bucket->identifier = sym; - bucket->parameters = (const char **) parameters; - bucket->paramcount = paramcount; - bucket->next = ctx->define_hashtable[hash]; - ctx->define_hashtable[hash] = bucket; - return 1; -} // add_define - - -static void free_define(Context *ctx, Define *def) -{ - if (def != NULL) - { - int i; - for (i = 0; i < def->paramcount; i++) - Free(ctx, (void *) def->parameters[i]); - Free(ctx, (void *) def->parameters); - Free(ctx, (void *) def->identifier); - Free(ctx, (void *) def->definition); - Free(ctx, (void *) def->original); - put_define(ctx, def); - } // if -} // free_define - - -static int remove_define(Context *ctx, const char *sym) -{ - const uint8 hash = hash_define(sym); - Define *bucket = ctx->define_hashtable[hash]; - Define *prev = NULL; - while (bucket) - { - if (strcmp(bucket->identifier, sym) == 0) - { - if (prev == NULL) - ctx->define_hashtable[hash] = bucket->next; - else - prev->next = bucket->next; - free_define(ctx, bucket); - return 1; - } // if - prev = bucket; - bucket = bucket->next; - } // while - - return 0; -} // remove_define - - -static const Define *find_define(Context *ctx, const char *sym) -{ - if ( (ctx->file_macro) && (strcmp(sym, "__FILE__") == 0) ) - { - Free(ctx, (char *) ctx->file_macro->definition); - const IncludeState *state = ctx->include_stack; - const char *fname = state ? state->filename : ""; - const size_t len = strlen(fname) + 2; - char *str = (char *) Malloc(ctx, len); - if (!str) - return NULL; - str[0] = '\"'; - memcpy(str + 1, fname, len - 2); - str[len - 1] = '\"'; - ctx->file_macro->definition = str; - return ctx->file_macro; - } // if - - else if ( (ctx->line_macro) && (strcmp(sym, "__LINE__") == 0) ) - { - Free(ctx, (char *) ctx->line_macro->definition); - const IncludeState *state = ctx->include_stack; - const size_t bufsize = 32; - char *str = (char *) Malloc(ctx, bufsize); - if (!str) - return 0; - - const size_t len = snprintf(str, bufsize, "%u", state->line); - assert(len < bufsize); - ctx->line_macro->definition = str; - return ctx->line_macro; - } // else - - const uint8 hash = hash_define(sym); - Define *bucket = ctx->define_hashtable[hash]; - while (bucket) - { - if (strcmp(bucket->identifier, sym) == 0) - return bucket; - bucket = bucket->next; - } // while - return NULL; -} // find_define - - -static const Define *find_define_by_token(Context *ctx) -{ - IncludeState *state = ctx->include_stack; - assert(state->tokenval == TOKEN_IDENTIFIER); - char *sym = (char *) alloca(state->tokenlen+1); - memcpy(sym, state->token, state->tokenlen); - sym[state->tokenlen] = '\0'; - return find_define(ctx, sym); -} // find_define_by_token - - -static const Define *find_macro_arg(const IncludeState *state, - const Define *defines) -{ - const Define *def = NULL; - char *sym = (char *) alloca(state->tokenlen + 1); - memcpy(sym, state->token, state->tokenlen); - sym[state->tokenlen] = '\0'; - - for (def = defines; def != NULL; def = def->next) - { - assert(def->parameters == NULL); // args can't have args! - assert(def->paramcount == 0); // args can't have args! - if (strcmp(def->identifier, sym) == 0) - break; - } // while - - return def; -} // find_macro_arg - - -static void put_all_defines(Context *ctx) -{ - size_t i; - for (i = 0; i < STATICARRAYLEN(ctx->define_hashtable); i++) - { - Define *bucket = ctx->define_hashtable[i]; - ctx->define_hashtable[i] = NULL; - while (bucket) - { - Define *next = bucket->next; - free_define(ctx, bucket); - bucket = next; - } // while - } // for -} // put_all_defines - - -static int push_source(Context *ctx, const char *fname, const char *source, - unsigned int srclen, unsigned int linenum, - MOJOSHADER_includeClose close_callback) -{ - IncludeState *state = get_include(ctx); - if (state == NULL) - return 0; - - if (fname != NULL) - { - state->filename = stringcache(ctx->filename_cache, fname); - if (state->filename == NULL) - { - put_include(ctx, state); - return 0; - } // if - } // if - - state->close_callback = close_callback; - state->source_base = source; - state->source = source; - state->token = source; - state->tokenval = ((Token) '\n'); - state->orig_length = srclen; - state->bytes_left = srclen; - state->line = linenum; - state->next = ctx->include_stack; - state->asm_comments = ctx->asm_comments; - - print_debug_lexing_position(state); - - ctx->include_stack = state; - - return 1; -} // push_source - - -static void pop_source(Context *ctx) -{ - IncludeState *state = ctx->include_stack; - assert(state != NULL); // more pops than pushes! - if (state == NULL) - return; - - if (state->close_callback) - { - state->close_callback(state->source_base, ctx->malloc, - ctx->free, ctx->malloc_data); - } // if - - // state->filename is a pointer to the filename cache; don't free it here! - - Conditional *cond = state->conditional_stack; - while (cond) - { - Conditional *next = cond->next; - put_conditional(ctx, cond); - cond = next; - } // while - - ctx->include_stack = state->next; - - print_debug_lexing_position(ctx->include_stack); - - put_include(ctx, state); -} // pop_source - - -static void close_define_include(const char *data, MOJOSHADER_malloc m, - MOJOSHADER_free f, void *d) -{ - f((void *) data, d); -} // close_define_include - - -Preprocessor *preprocessor_start(const char *fname, const char *source, - unsigned int sourcelen, - MOJOSHADER_includeOpen open_callback, - MOJOSHADER_includeClose close_callback, - const MOJOSHADER_preprocessorDefine *defines, - unsigned int define_count, int asm_comments, - MOJOSHADER_malloc m, MOJOSHADER_free f, void *d) -{ - int okay = 1; - unsigned int i = 0; - - // the preprocessor is internal-only, so we verify all these are != NULL. - assert(m != NULL); - assert(f != NULL); - - Context *ctx = (Context *) m(sizeof (Context), d); - if (ctx == NULL) - return NULL; - - memset(ctx, '\0', sizeof (Context)); - ctx->malloc = m; - ctx->free = f; - ctx->malloc_data = d; - ctx->open_callback = open_callback; - ctx->close_callback = close_callback; - ctx->asm_comments = asm_comments; - - ctx->filename_cache = stringcache_create(MallocBridge, FreeBridge, ctx); - okay = ((okay) && (ctx->filename_cache != NULL)); - - ctx->file_macro = get_define(ctx); - okay = ((okay) && (ctx->file_macro != NULL)); - if ((okay) && (ctx->file_macro)) - okay = ((ctx->file_macro->identifier = StrDup(ctx, "__FILE__")) != 0); - - ctx->line_macro = get_define(ctx); - okay = ((okay) && (ctx->line_macro != NULL)); - if ((okay) && (ctx->line_macro)) - okay = ((ctx->line_macro->identifier = StrDup(ctx, "__LINE__")) != 0); - - // let the usual preprocessor parser sort these out. - char *define_include = NULL; - unsigned int define_include_len = 0; - if ((okay) && (define_count > 0)) - { - Buffer *predefbuf = buffer_create(256, MallocBridge, FreeBridge, ctx); - okay = okay && (predefbuf != NULL); - for (i = 0; okay && (i < define_count); i++) - { - okay = okay && buffer_append_fmt(predefbuf, "#define %s %s\n", - defines[i].identifier, defines[i].definition); - } // for - - define_include_len = buffer_size(predefbuf); - if (define_include_len > 0) - { - define_include = buffer_flatten(predefbuf); - okay = okay && (define_include != NULL); - } // if - buffer_destroy(predefbuf); - } // if - - if ((okay) && (!push_source(ctx,fname,source,sourcelen,1,NULL))) - okay = 0; - - if ((okay) && (define_include_len > 0)) - { - assert(define_include != NULL); - okay = push_source(ctx, "", define_include, - define_include_len, 1, close_define_include); - } // if - - if (!okay) - { - preprocessor_end((Preprocessor *) ctx); - return NULL; - } // if - - return (Preprocessor *) ctx; -} // preprocessor_start - - -void preprocessor_end(Preprocessor *_ctx) -{ - Context *ctx = (Context *) _ctx; - if (ctx == NULL) - return; - - while (ctx->include_stack != NULL) - pop_source(ctx); - - put_all_defines(ctx); - - if (ctx->filename_cache != NULL) - stringcache_destroy(ctx->filename_cache); - - free_define(ctx, ctx->file_macro); - free_define(ctx, ctx->line_macro); - free_define_pool(ctx); - free_conditional_pool(ctx); - free_include_pool(ctx); - - Free(ctx, ctx); -} // preprocessor_end - - -int preprocessor_outofmemory(Preprocessor *_ctx) -{ - Context *ctx = (Context *) _ctx; - return ctx->out_of_memory; -} // preprocessor_outofmemory - - -static inline void pushback(IncludeState *state) -{ - #if DEBUG_PREPROCESSOR - printf("PREPROCESSOR PUSHBACK\n"); - #endif - assert(!state->pushedback); - state->pushedback = 1; -} // pushback - - -static Token lexer(IncludeState *state) -{ - if (!state->pushedback) - return preprocessor_lexer(state); - state->pushedback = 0; - return state->tokenval; -} // lexer - - -// !!! FIXME: parsing fails on preprocessor directives should skip rest of line. -static int require_newline(IncludeState *state) -{ - const Token token = lexer(state); - pushback(state); // rewind no matter what. - return ( (token == TOKEN_INCOMPLETE_COMMENT) || // call it an eol. - (token == ((Token) '\n')) || (token == TOKEN_EOI) ); -} // require_newline - -// !!! FIXME: didn't we implement this by hand elsewhere? -static int token_to_int(IncludeState *state) -{ - assert(state->tokenval == TOKEN_INT_LITERAL); - char *buf = (char *) alloca(state->tokenlen+1); - memcpy(buf, state->token, state->tokenlen); - buf[state->tokenlen] = '\0'; - return atoi(buf); -} // token_to_int - - -static void handle_pp_include(Context *ctx) -{ - IncludeState *state = ctx->include_stack; - Token token = lexer(state); - MOJOSHADER_includeType incltype; - char *filename = NULL; - int bogus = 0; - - if (token == TOKEN_STRING_LITERAL) - incltype = MOJOSHADER_INCLUDETYPE_LOCAL; - else if (token == ((Token) '<')) - { - incltype = MOJOSHADER_INCLUDETYPE_SYSTEM; - // can't use lexer, since every byte between the < > pair is - // considered part of the filename. :/ - while (!bogus) - { - if ( !(bogus = (state->bytes_left == 0)) ) - { - const char ch = *state->source; - if ( !(bogus = ((ch == '\r') || (ch == '\n'))) ) - { - state->source++; - state->bytes_left--; - - if (ch == '>') - break; - } // if - } // if - } // while - } // else if - else - { - bogus = 1; - } // else - - if (!bogus) - { - state->token++; // skip '<' or '\"'... - const unsigned int len = ((unsigned int) (state->source-state->token)); - filename = (char *) alloca(len); - memcpy(filename, state->token, len-1); - filename[len-1] = '\0'; - bogus = !require_newline(state); - } // if - - if (bogus) - { - fail(ctx, "Invalid #include directive"); - return; - } // else - - const char *newdata = NULL; - unsigned int newbytes = 0; - if ((ctx->open_callback == NULL) || (ctx->close_callback == NULL)) - { - fail(ctx, "Saw #include, but no include callbacks defined"); - return; - } // if - - if (!ctx->open_callback(incltype, filename, state->source_base, - &newdata, &newbytes, ctx->malloc, - ctx->free, ctx->malloc_data)) - { - fail(ctx, "Include callback failed"); // !!! FIXME: better error - return; - } // if - - MOJOSHADER_includeClose callback = ctx->close_callback; - if (!push_source(ctx, filename, newdata, newbytes, 1, callback)) - { - assert(ctx->out_of_memory); - ctx->close_callback(newdata, ctx->malloc, ctx->free, ctx->malloc_data); - } // if -} // handle_pp_include - - -static void handle_pp_line(Context *ctx) -{ - IncludeState *state = ctx->include_stack; - char *filename = NULL; - int linenum = 0; - int bogus = 0; - - if (lexer(state) != TOKEN_INT_LITERAL) - bogus = 1; - else - linenum = token_to_int(state); - - if (!bogus) - { - Token t = lexer(state); - if (t == ((Token) '\n')) - { - state->line = linenum; - return; - } - bogus = (t != TOKEN_STRING_LITERAL); - } - - if (!bogus) - { - state->token++; // skip '\"'... - filename = (char *) alloca(state->tokenlen); - memcpy(filename, state->token, state->tokenlen-1); - filename[state->tokenlen-1] = '\0'; - bogus = !require_newline(state); - } // if - - if (bogus) - { - fail(ctx, "Invalid #line directive"); - return; - } // if - - const char *cached = stringcache(ctx->filename_cache, filename); - state->filename = cached; // may be NULL if stringcache() failed. - state->line = linenum; -} // handle_pp_line - - -static void handle_pp_error(Context *ctx) -{ - IncludeState *state = ctx->include_stack; - char *ptr = ctx->failstr; - int avail = sizeof (ctx->failstr) - 1; - int cpy = 0; - int done = 0; - - const char *prefix = "#error"; - const size_t prefixlen = strlen(prefix); - strcpy(ctx->failstr, prefix); - avail -= prefixlen; - ptr += prefixlen; - - state->report_whitespace = 1; - while (!done) - { - const Token token = lexer(state); - switch (token) - { - case ((Token) '\n'): - state->line--; // make sure error is on the right line. - // fall through! - case TOKEN_INCOMPLETE_COMMENT: - case TOKEN_EOI: - pushback(state); // move back so we catch this later. - done = 1; - break; - - case ((Token) ' '): - if (!avail) - break; - *(ptr++) = ' '; - avail--; - break; - - default: - cpy = Min(avail, (int) state->tokenlen); - if (cpy) - memcpy(ptr, state->token, cpy); - ptr += cpy; - avail -= cpy; - break; - } // switch - } // while - - *ptr = '\0'; - state->report_whitespace = 0; - ctx->isfail = 1; -} // handle_pp_error - - -static void handle_pp_define(Context *ctx) -{ - IncludeState *state = ctx->include_stack; - int done = 0; - - if (lexer(state) != TOKEN_IDENTIFIER) - { - fail(ctx, "Macro names must be identifiers"); - return; - } // if - - char *definition = NULL; - char *sym = (char *) Malloc(ctx, state->tokenlen+1); - if (sym == NULL) - return; - memcpy(sym, state->token, state->tokenlen); - sym[state->tokenlen] = '\0'; - - if (strcmp(sym, "defined") == 0) - { - Free(ctx, sym); - fail(ctx, "'defined' cannot be used as a macro name"); - return; - } // if - - // Don't treat these symbols as special anymore if they get (re)#defined. - if (strcmp(sym, "__FILE__") == 0) - { - if (ctx->file_macro) - { - failf(ctx, "'%s' already defined", sym); // !!! FIXME: warning? - free_define(ctx, ctx->file_macro); - ctx->file_macro = NULL; - } // if - } // if - else if (strcmp(sym, "__LINE__") == 0) - { - if (ctx->line_macro) - { - failf(ctx, "'%s' already defined", sym); // !!! FIXME: warning? - free_define(ctx, ctx->line_macro); - ctx->line_macro = NULL; - } // if - } // else if - - // #define a(b) is different than #define a (b) :( - state->report_whitespace = 1; - lexer(state); - state->report_whitespace = 0; - - int params = 0; - char **idents = NULL; - static const char space = ' '; - - if (state->tokenval == ((Token) ' ')) - lexer(state); // skip it. - else if (state->tokenval == ((Token) '(')) - { - IncludeState saved; - memcpy(&saved, state, sizeof (IncludeState)); - while (1) - { - if (lexer(state) != TOKEN_IDENTIFIER) - break; - params++; - if (lexer(state) != ((Token) ',')) - break; - } // while - - if (state->tokenval != ((Token) ')')) - { - fail(ctx, "syntax error in macro parameter list"); - goto handle_pp_define_failed; - } // if - - if (params == 0) // special case for void args: "#define a() b" - params = -1; - else - { - idents = (char **) Malloc(ctx, sizeof (char *) * params); - if (idents == NULL) - goto handle_pp_define_failed; - - // roll all the way back, do it again. - memcpy(state, &saved, sizeof (IncludeState)); - memset(idents, '\0', sizeof (char *) * params); - - int i; - for (i = 0; i < params; i++) - { - lexer(state); - assert(state->tokenval == TOKEN_IDENTIFIER); - - char *dst = (char *) Malloc(ctx, state->tokenlen+1); - if (dst == NULL) - break; - - memcpy(dst, state->token, state->tokenlen); - dst[state->tokenlen] = '\0'; - idents[i] = dst; - - if (i < (params-1)) - { - lexer(state); - assert(state->tokenval == ((Token) ',')); - } // if - } // for - - if (i != params) - { - assert(ctx->out_of_memory); - goto handle_pp_define_failed; - } // if - - lexer(state); - assert(state->tokenval == ((Token) ')')); - } // else - - lexer(state); - } // else if - - pushback(state); - - Buffer *buffer = buffer_create(128, MallocBridge, FreeBridge, ctx); - - state->report_whitespace = 1; - while ((!done) && (!ctx->out_of_memory)) - { - const Token token = lexer(state); - switch (token) - { - case TOKEN_INCOMPLETE_COMMENT: - case TOKEN_EOI: - pushback(state); // move back so we catch this later. - done = 1; - break; - - case ((Token) '\n'): - done = 1; - break; - - case ((Token) ' '): // may not actually point to ' '. - assert(buffer_size(buffer) > 0); - buffer_append(buffer, &space, 1); - break; - - default: - buffer_append(buffer, state->token, state->tokenlen); - break; - } // switch - } // while - state->report_whitespace = 0; - - size_t buflen = buffer_size(buffer) + 1; - if (!ctx->out_of_memory) - definition = buffer_flatten(buffer); - - buffer_destroy(buffer); - - if (ctx->out_of_memory) - goto handle_pp_define_failed; - - int hashhash_error = 0; - if ((buflen > 2) && (definition[0] == '#') && (definition[1] == '#')) - { - hashhash_error = 1; - buflen -= 2; - memmove(definition, definition + 2, buflen); - } // if - - if (buflen > 2) - { - char *ptr = (definition + buflen) - 2; - if (*ptr == ' ') - { - ptr--; - buflen--; - } // if - if ((buflen > 2) && (ptr[0] == '#') && (ptr[-1] == '#')) - { - hashhash_error = 1; - buflen -= 2; - ptr[-1] = '\0'; - } // if - } // if - - if (hashhash_error) - fail(ctx, "'##' cannot appear at either end of a macro expansion"); - - assert(done); - - if (!add_define(ctx, sym, definition, idents, params)) - goto handle_pp_define_failed; - - return; - -handle_pp_define_failed: - Free(ctx, sym); - Free(ctx, definition); - if (idents != NULL) - { - while (params--) - Free(ctx, idents[params]); - } // if - Free(ctx, idents); -} // handle_pp_define - - -static void handle_pp_undef(Context *ctx) -{ - IncludeState *state = ctx->include_stack; - - if (lexer(state) != TOKEN_IDENTIFIER) - { - fail(ctx, "Macro names must be indentifiers"); - return; - } // if - - char *sym = (char *) alloca(state->tokenlen+1); - memcpy(sym, state->token, state->tokenlen); - sym[state->tokenlen] = '\0'; - - if (!require_newline(state)) - { - fail(ctx, "Invalid #undef directive"); - return; - } // if - - if (strcmp(sym, "__FILE__") == 0) - { - if (ctx->file_macro) - { - failf(ctx, "undefining \"%s\"", sym); // !!! FIXME: should be warning. - free_define(ctx, ctx->file_macro); - ctx->file_macro = NULL; - } // if - } // if - else if (strcmp(sym, "__LINE__") == 0) - { - if (ctx->line_macro) - { - failf(ctx, "undefining \"%s\"", sym); // !!! FIXME: should be warning. - free_define(ctx, ctx->line_macro); - ctx->line_macro = NULL; - } // if - } // if - - remove_define(ctx, sym); -} // handle_pp_undef - - -static Conditional *_handle_pp_ifdef(Context *ctx, const Token type) -{ - IncludeState *state = ctx->include_stack; - - assert((type == TOKEN_PP_IFDEF) || (type == TOKEN_PP_IFNDEF)); - - if (lexer(state) != TOKEN_IDENTIFIER) - { - fail(ctx, "Macro names must be indentifiers"); - return NULL; - } // if - - char *sym = (char *) alloca(state->tokenlen+1); - memcpy(sym, state->token, state->tokenlen); - sym[state->tokenlen] = '\0'; - - if (!require_newline(state)) - { - if (type == TOKEN_PP_IFDEF) - fail(ctx, "Invalid #ifdef directive"); - else - fail(ctx, "Invalid #ifndef directive"); - return NULL; - } // if - - Conditional *conditional = get_conditional(ctx); - assert((conditional != NULL) || (ctx->out_of_memory)); - if (conditional == NULL) - return NULL; - - Conditional *parent = state->conditional_stack; - const int found = (find_define(ctx, sym) != NULL); - const int chosen = (type == TOKEN_PP_IFDEF) ? found : !found; - const int skipping = ( (((parent) && (parent->skipping))) || (!chosen) ); - - conditional->type = type; - conditional->linenum = state->line - 1; - conditional->skipping = skipping; - conditional->chosen = chosen; - conditional->next = parent; - state->conditional_stack = conditional; - return conditional; -} // _handle_pp_ifdef - - -static inline void handle_pp_ifdef(Context *ctx) -{ - _handle_pp_ifdef(ctx, TOKEN_PP_IFDEF); -} // handle_pp_ifdef - - -static inline void handle_pp_ifndef(Context *ctx) -{ - _handle_pp_ifdef(ctx, TOKEN_PP_IFNDEF); -} // handle_pp_ifndef - - -static int replace_and_push_macro(Context *ctx, const Define *def, - const Define *params) -{ - char *final = NULL; - - // We push the #define and lex it, building a buffer with argument - // replacement, stringification, and concatenation. - Buffer *buffer = buffer_create(128, MallocBridge, FreeBridge, ctx); - if (buffer == NULL) - return 0; - - IncludeState *state = ctx->include_stack; - if (!push_source(ctx, state->filename, def->definition, - strlen(def->definition), state->line, NULL)) - { - buffer_destroy(buffer); - return 0; - } // if - - state = ctx->include_stack; - while (lexer(state) != TOKEN_EOI) - { - int wantorig = 0; - const Define *arg = NULL; - - // put a space between tokens if we're not concatenating. - if (state->tokenval == TOKEN_HASHHASH) // concatenate? - { - wantorig = 1; - lexer(state); - assert(state->tokenval != TOKEN_EOI); - } // if - else - { - if (buffer_size(buffer) > 0) - { - if (!buffer_append(buffer, " ", 1)) - goto replace_and_push_macro_failed; - } // if - } // else - - const char *data = state->token; - unsigned int len = state->tokenlen; - - if (state->tokenval == TOKEN_HASH) // stringify? - { - lexer(state); - assert(state->tokenval != TOKEN_EOI); // we checked for this. - - if (!buffer_append(buffer, "\"", 1)) - goto replace_and_push_macro_failed; - - if (state->tokenval == TOKEN_IDENTIFIER) - { - arg = find_macro_arg(state, params); - if (arg != NULL) - { - data = arg->original; - len = strlen(data); - } // if - } // if - - if (!buffer_append(buffer, data, len)) - goto replace_and_push_macro_failed; - - if (!buffer_append(buffer, "\"", 1)) - goto replace_and_push_macro_failed; - - continue; - } // if - - if (state->tokenval == TOKEN_IDENTIFIER) - { - arg = find_macro_arg(state, params); - if (arg != NULL) - { - if (!wantorig) - { - wantorig = (lexer(state) == TOKEN_HASHHASH); - pushback(state); - } // if - data = wantorig ? arg->original : arg->definition; - len = strlen(data); - } // if - } // if - - if (!buffer_append(buffer, data, len)) - goto replace_and_push_macro_failed; - } // while - - final = buffer_flatten(buffer); - if (!final) - goto replace_and_push_macro_failed; - - buffer_destroy(buffer); - pop_source(ctx); // ditch the macro. - state = ctx->include_stack; - if (!push_source(ctx, state->filename, final, strlen(final), state->line, - close_define_include)) - { - Free(ctx, final); - return 0; - } // if - - return 1; - -replace_and_push_macro_failed: - pop_source(ctx); - buffer_destroy(buffer); - return 0; -} // replace_and_push_macro - - -static int handle_macro_args(Context *ctx, const char *sym, const Define *def) -{ - int retval = 0; - IncludeState *state = ctx->include_stack; - Define *params = NULL; - const int expected = (def->paramcount < 0) ? 0 : def->paramcount; - int saw_params = 0; - IncludeState saved; // can't pushback, we need the original token. - memcpy(&saved, state, sizeof (IncludeState)); - if (lexer(state) != ((Token) '(')) - { - memcpy(state, &saved, sizeof (IncludeState)); - goto handle_macro_args_failed; // gcc abandons replacement, too. - } // if - - state->report_whitespace = 1; - - int void_call = 0; - int paren = 1; - while (paren > 0) - { - Buffer *buffer = buffer_create(128, MallocBridge, FreeBridge, ctx); - Buffer *origbuffer = buffer_create(128, MallocBridge, FreeBridge, ctx); - - Token t = lexer(state); - - assert(!void_call); - - while (1) - { - const char *origexpr = state->token; - unsigned int origexprlen = state->tokenlen; - const char *expr = state->token; - unsigned int exprlen = state->tokenlen; - - if (t == ((Token) '(')) - paren++; - - else if (t == ((Token) ')')) - { - paren--; - if (paren < 1) // end of macro? - break; - } // else if - - else if (t == ((Token) ',')) - { - if (paren == 1) // new macro arg? - break; - } // else if - - else if (t == ((Token) ' ')) - { - // don't add whitespace to the start, so we recognize - // void calls correctly. - origexpr = expr = " "; - origexprlen = (buffer_size(origbuffer) == 0) ? 0 : 1; - exprlen = (buffer_size(buffer) == 0) ? 0 : 1; - } // else if - - else if (t == TOKEN_IDENTIFIER) - { - const Define *def = find_define_by_token(ctx); - // don't replace macros with arguments so they replace correctly, later. - if ((def) && (def->paramcount == 0)) - { - expr = def->definition; - exprlen = strlen(def->definition); - } // if - } // else if - - else if ((t == TOKEN_INCOMPLETE_COMMENT) || (t == TOKEN_EOI)) - { - pushback(state); - fail(ctx, "Unterminated macro list"); - goto handle_macro_args_failed; - } // else if - - assert(expr != NULL); - - if (!buffer_append(buffer, expr, exprlen)) - goto handle_macro_args_failed; - - if (!buffer_append(origbuffer, origexpr, origexprlen)) - goto handle_macro_args_failed; - - t = lexer(state); - } // while - - if (buffer_size(buffer) == 0) - void_call = ((saw_params == 0) && (paren == 0)); - - if (saw_params < expected) - { - const int origdeflen = (int) buffer_size(origbuffer); - char *origdefinition = buffer_flatten(origbuffer); - const int deflen = (int) buffer_size(buffer); - char *definition = buffer_flatten(buffer); - Define *p = get_define(ctx); - if ((!origdefinition) || (!definition) || (!p)) - { - Free(ctx, origdefinition); - Free(ctx, definition); - buffer_destroy(origbuffer); - buffer_destroy(buffer); - free_define(ctx, p); - goto handle_macro_args_failed; - } // if - - // trim any whitespace from the end of the string... - int i; - for (i = deflen - 1; i >= 0; i--) - { - if (definition[i] == ' ') - definition[i] = '\0'; - else - break; - } // for - - for (i = origdeflen - 1; i >= 0; i--) - { - if (origdefinition[i] == ' ') - origdefinition[i] = '\0'; - else - break; - } // for - - p->identifier = def->parameters[saw_params]; - p->definition = definition; - p->original = origdefinition; - p->next = params; - params = p; - } // if - - buffer_destroy(buffer); - buffer_destroy(origbuffer); - saw_params++; - } // while - - assert(paren == 0); - - // "a()" should match "#define a()" ... - if ((expected == 0) && (saw_params == 1) && (void_call)) - { - assert(params == NULL); - saw_params = 0; - } // if - - if (saw_params != expected) - { - failf(ctx, "macro '%s' passed %d arguments, but requires %d", - sym, saw_params, expected); - goto handle_macro_args_failed; - } // if - - // this handles arg replacement and the '##' and '#' operators. - retval = replace_and_push_macro(ctx, def, params); - -handle_macro_args_failed: - while (params) - { - Define *next = params->next; - params->identifier = NULL; - free_define(ctx, params); - params = next; - } // while - - state->report_whitespace = 0; - return retval; -} // handle_macro_args - - -static int handle_pp_identifier(Context *ctx) -{ - if (ctx->recursion_count++ >= 256) // !!! FIXME: gcc can figure this out. - { - fail(ctx, "Recursing macros"); - return 0; - } // if - - IncludeState *state = ctx->include_stack; - const char *fname = state->filename; - const unsigned int line = state->line; - char *sym = (char *) alloca(state->tokenlen+1); - memcpy(sym, state->token, state->tokenlen); - sym[state->tokenlen] = '\0'; - - // Is this identifier #defined? - const Define *def = find_define(ctx, sym); - if (def == NULL) - return 0; // just send the token through unchanged. - else if (def->paramcount != 0) - return handle_macro_args(ctx, sym, def); - - const size_t deflen = strlen(def->definition); - return push_source(ctx, fname, def->definition, deflen, line, NULL); -} // handle_pp_identifier - - -static int find_precedence(const Token token) -{ - // operator precedence, left and right associative... - typedef struct { int precedence; Token token; } Precedence; - static const Precedence ops[] = { - { 0, TOKEN_OROR }, { 1, TOKEN_ANDAND }, { 2, ((Token) '|') }, - { 3, ((Token) '^') }, { 4, ((Token) '&') }, { 5, TOKEN_NEQ }, - { 6, TOKEN_EQL }, { 7, ((Token) '<') }, { 7, ((Token) '>') }, - { 7, TOKEN_LEQ }, { 7, TOKEN_GEQ }, { 8, TOKEN_LSHIFT }, - { 8, TOKEN_RSHIFT }, { 9, ((Token) '-') }, { 9, ((Token) '+') }, - { 10, ((Token) '%') }, { 10, ((Token) '/') }, { 10, ((Token) '*') }, - { 11, TOKEN_PP_UNARY_PLUS }, { 11, TOKEN_PP_UNARY_MINUS }, - { 11, ((Token) '!') }, { 11, ((Token) '~') }, - }; - - size_t i; - for (i = 0; i < STATICARRAYLEN(ops); i++) - { - if (ops[i].token == token) - return ops[i].precedence; - } // for - - return -1; -} // find_precedence - -// !!! FIXME: we're using way too much stack space here... -typedef struct RpnTokens -{ - int isoperator; - int value; -} RpnTokens; - -static long interpret_rpn(const RpnTokens *tokens, int tokencount, int *error) -{ - long stack[128]; - size_t stacksize = 0; - - *error = 1; - - #define NEED_X_TOKENS(x) do { if (stacksize < x) return 0; } while (0) - - #define BINARY_OPERATION(op) do { \ - NEED_X_TOKENS(2); \ - stack[stacksize-2] = stack[stacksize-2] op stack[stacksize-1]; \ - stacksize--; \ - } while (0) - - #define UNARY_OPERATION(op) do { \ - NEED_X_TOKENS(1); \ - stack[stacksize-1] = op stack[stacksize-1]; \ - } while (0) - - while (tokencount-- > 0) - { - if (!tokens->isoperator) - { - assert(stacksize < STATICARRAYLEN(stack)); - stack[stacksize++] = (long) tokens->value; - tokens++; - continue; - } // if - - // operators. - switch (tokens->value) - { - case '!': UNARY_OPERATION(!); break; - case '~': UNARY_OPERATION(~); break; - case TOKEN_PP_UNARY_MINUS: UNARY_OPERATION(-); break; - case TOKEN_PP_UNARY_PLUS: UNARY_OPERATION(+); break; - case TOKEN_OROR: BINARY_OPERATION(||); break; - case TOKEN_ANDAND: BINARY_OPERATION(&&); break; - case '|': BINARY_OPERATION(|); break; - case '^': BINARY_OPERATION(^); break; - case '&': BINARY_OPERATION(&); break; - case TOKEN_NEQ: BINARY_OPERATION(!=); break; - case TOKEN_EQL: BINARY_OPERATION(==); break; - case '<': BINARY_OPERATION(<); break; - case '>': BINARY_OPERATION(>); break; - case TOKEN_LEQ: BINARY_OPERATION(<=); break; - case TOKEN_GEQ: BINARY_OPERATION(>=); break; - case TOKEN_LSHIFT: BINARY_OPERATION(<<); break; - case TOKEN_RSHIFT: BINARY_OPERATION(>>); break; - case '-': BINARY_OPERATION(-); break; - case '+': BINARY_OPERATION(+); break; - case '%': BINARY_OPERATION(%); break; - case '/': BINARY_OPERATION(/); break; - case '*': BINARY_OPERATION(*); break; - default: return 0; - } // switch - - tokens++; - } // while - - #undef NEED_X_TOKENS - #undef BINARY_OPERATION - #undef UNARY_OPERATION - - if (stacksize != 1) - return 0; - - *error = 0; - return stack[0]; -} // interpret_rpn - -// http://en.wikipedia.org/wiki/Shunting_yard_algorithm -// Convert from infix to postfix, then use this for constant folding. -// Everything that parses should fold down to a constant value: any -// identifiers that aren't resolved as macros become zero. Anything we -// don't explicitly expect becomes a parsing error. -// returns 1 (true), 0 (false), or -1 (error) -static int reduce_pp_expression(Context *ctx) -{ - IncludeState *orig_state = ctx->include_stack; - RpnTokens output[128]; - Token stack[64]; - Token previous_token = TOKEN_UNKNOWN; - size_t outputsize = 0; - size_t stacksize = 0; - int matched = 0; - int done = 0; - - #define ADD_TO_OUTPUT(op, val) \ - assert(outputsize < STATICARRAYLEN(output)); \ - output[outputsize].isoperator = op; \ - output[outputsize].value = val; \ - outputsize++; - - #define PUSH_TO_STACK(t) \ - assert(stacksize < STATICARRAYLEN(stack)); \ - stack[stacksize] = t; \ - stacksize++; - - while (!done) - { - IncludeState *state = ctx->include_stack; - Token token = lexer(state); - int isleft = 1; - int precedence = -1; - - if ( (token == ((Token) '!')) || (token == ((Token) '~')) ) - isleft = 0; - else if (token == ((Token) '-')) - { - if ((isleft = (previous_token == TOKEN_INT_LITERAL)) == 0) - token = TOKEN_PP_UNARY_MINUS; - } // else if - else if (token == ((Token) '+')) - { - if ((isleft = (previous_token == TOKEN_INT_LITERAL)) == 0) - token = TOKEN_PP_UNARY_PLUS; - } // else if - - if (token != TOKEN_IDENTIFIER) - ctx->recursion_count = 0; - - switch (token) - { - case TOKEN_EOI: - if (state != orig_state) // end of a substate, or the expr? - { - pop_source(ctx); - continue; // substate, go again with the parent state. - } // if - done = 1; // the expression itself is done. - break; - - case ((Token) '\n'): - done = 1; - break; // we're done! - - case TOKEN_IDENTIFIER: - if (handle_pp_identifier(ctx)) - continue; // go again with new IncludeState. - - if ( (state->tokenlen == 7) && - (memcmp(state->token, "defined", 7) == 0) ) - { - token = lexer(state); - const int paren = (token == ((Token) '(')); - if (paren) // gcc doesn't let us nest parens here, either. - token = lexer(state); - if (token != TOKEN_IDENTIFIER) - { - fail(ctx, "operator 'defined' requires an identifier"); - return -1; - } // if - const int found = (find_define_by_token(ctx) != NULL); - - if (paren) - { - if (lexer(state) != ((Token) ')')) - { - fail(ctx, "Unmatched ')'"); - return -1; - } // if - } // if - - ADD_TO_OUTPUT(0, found); - continue; - } // if - - // can't replace identifier with a number? It becomes zero. - token = TOKEN_INT_LITERAL; - ADD_TO_OUTPUT(0, 0); - break; - - case TOKEN_INT_LITERAL: - ADD_TO_OUTPUT(0, token_to_int(state)); - break; - - case ((Token) '('): - PUSH_TO_STACK((Token) '('); - break; - - case ((Token) ')'): - matched = 0; - while (stacksize > 0) - { - const Token t = stack[--stacksize]; - if (t == ((Token) '(')) - { - matched = 1; - break; - } // if - ADD_TO_OUTPUT(1, t); - } // while - - if (!matched) - { - fail(ctx, "Unmatched ')'"); - return -1; - } // if - break; - - default: - precedence = find_precedence(token); - // bogus token, or two operators together. - if (precedence < 0) - { - pushback(state); - fail(ctx, "Invalid expression"); - return -1; - } // if - - else // it's an operator. - { - while (stacksize > 0) - { - const Token t = stack[stacksize-1]; - const int p = find_precedence(t); - if ( (p >= 0) && - ( ((isleft) && (precedence <= p)) || - ((!isleft) && (precedence < p)) ) ) - { - stacksize--; - ADD_TO_OUTPUT(1, t); - } // if - else - { - break; - } // else - } // while - PUSH_TO_STACK(token); - } // else - break; - } // switch - previous_token = token; - } // while - - while (stacksize > 0) - { - const Token t = stack[--stacksize]; - if (t == ((Token) '(')) - { - fail(ctx, "Unmatched ')'"); - return -1; - } // if - ADD_TO_OUTPUT(1, t); - } // while - - #undef ADD_TO_OUTPUT - #undef PUSH_TO_STACK - - // okay, you now have some validated data in reverse polish notation. - #if DEBUG_PREPROCESSOR - printf("PREPROCESSOR EXPRESSION RPN:"); - int i = 0; - for (i = 0; i < outputsize; i++) - { - if (!output[i].isoperator) - printf(" %d", output[i].value); - else - { - switch (output[i].value) - { - case TOKEN_OROR: printf(" ||"); break; - case TOKEN_ANDAND: printf(" &&"); break; - case TOKEN_NEQ: printf(" !="); break; - case TOKEN_EQL: printf(" =="); break; - case TOKEN_LEQ: printf(" <="); break; - case TOKEN_GEQ: printf(" >="); break; - case TOKEN_LSHIFT: printf(" <<"); break; - case TOKEN_RSHIFT: printf(" >>"); break; - case TOKEN_PP_UNARY_PLUS: printf(" +"); break; - case TOKEN_PP_UNARY_MINUS: printf(" -"); break; - default: printf(" %c", output[i].value); break; - } // switch - } // else - } // for - printf("\n"); - #endif - - int error = 0; - const long val = interpret_rpn(output, outputsize, &error); - - #if DEBUG_PREPROCESSOR - printf("PREPROCESSOR RPN RESULT: %ld%s\n", val, error ? " (ERROR)" : ""); - #endif - - if (error) - { - fail(ctx, "Invalid expression"); - return -1; - } // if - - return ((val) ? 1 : 0); -} // reduce_pp_expression - - -static Conditional *handle_pp_if(Context *ctx) -{ - IncludeState *state = ctx->include_stack; - const int result = reduce_pp_expression(ctx); - if (result == -1) - return NULL; - - Conditional *conditional = get_conditional(ctx); - assert((conditional != NULL) || (ctx->out_of_memory)); - if (conditional == NULL) - return NULL; - - Conditional *parent = state->conditional_stack; - const int chosen = result; - const int skipping = ( (((parent) && (parent->skipping))) || (!chosen) ); - - conditional->type = TOKEN_PP_IF; - conditional->linenum = state->line - 1; - conditional->skipping = skipping; - conditional->chosen = chosen; - conditional->next = parent; - state->conditional_stack = conditional; - return conditional; -} // handle_pp_if - - -static void handle_pp_elif(Context *ctx) -{ - const int rc = reduce_pp_expression(ctx); - if (rc == -1) - return; - - IncludeState *state = ctx->include_stack; - Conditional *cond = state->conditional_stack; - if (cond == NULL) - fail(ctx, "#elif without #if"); - else if (cond->type == TOKEN_PP_ELSE) - fail(ctx, "#elif after #else"); - else - { - const Conditional *parent = cond->next; - cond->type = TOKEN_PP_ELIF; - cond->skipping = (parent && parent->skipping) || cond->chosen || !rc; - if (!cond->chosen) - cond->chosen = rc; - } // else -} // handle_pp_elif - - -static void handle_pp_else(Context *ctx) -{ - IncludeState *state = ctx->include_stack; - Conditional *cond = state->conditional_stack; - - if (!require_newline(state)) - fail(ctx, "Invalid #else directive"); - else if (cond == NULL) - fail(ctx, "#else without #if"); - else if (cond->type == TOKEN_PP_ELSE) - fail(ctx, "#else after #else"); - else - { - const Conditional *parent = cond->next; - cond->type = TOKEN_PP_ELSE; - cond->skipping = (parent && parent->skipping) || cond->chosen; - if (!cond->chosen) - cond->chosen = 1; - } // else -} // handle_pp_else - - -static void handle_pp_endif(Context *ctx) -{ - IncludeState *state = ctx->include_stack; - Conditional *cond = state->conditional_stack; - - if (!require_newline(state)) - fail(ctx, "Invalid #endif directive"); - else if (cond == NULL) - fail(ctx, "Unmatched #endif"); - else - { - state->conditional_stack = cond->next; // pop it. - put_conditional(ctx, cond); - } // else -} // handle_pp_endif - - -static void unterminated_pp_condition(Context *ctx) -{ - IncludeState *state = ctx->include_stack; - Conditional *cond = state->conditional_stack; - - // !!! FIXME: report the line number where the #if is, not the EOI. - switch (cond->type) - { - case TOKEN_PP_IF: fail(ctx, "Unterminated #if"); break; - case TOKEN_PP_IFDEF: fail(ctx, "Unterminated #ifdef"); break; - case TOKEN_PP_IFNDEF: fail(ctx, "Unterminated #ifndef"); break; - case TOKEN_PP_ELSE: fail(ctx, "Unterminated #else"); break; - case TOKEN_PP_ELIF: fail(ctx, "Unterminated #elif"); break; - default: assert(0 && "Shouldn't hit this case"); break; - } // switch - - // pop this conditional, we'll report the next error next time... - - state->conditional_stack = cond->next; // pop it. - put_conditional(ctx, cond); -} // unterminated_pp_condition - - -static inline const char *_preprocessor_nexttoken(Preprocessor *_ctx, - unsigned int *_len, Token *_token) -{ - Context *ctx = (Context *) _ctx; - - while (1) - { - if (ctx->isfail) - { - ctx->isfail = 0; - *_token = TOKEN_PREPROCESSING_ERROR; - *_len = strlen(ctx->failstr); - return ctx->failstr; - } // if - - IncludeState *state = ctx->include_stack; - if (state == NULL) - { - *_token = TOKEN_EOI; - *_len = 0; - return NULL; // we're done! - } // if - - const Conditional *cond = state->conditional_stack; - const int skipping = ((cond != NULL) && (cond->skipping)); - - const Token token = lexer(state); - - if (token != TOKEN_IDENTIFIER) - ctx->recursion_count = 0; - - if (token == TOKEN_EOI) - { - assert(state->bytes_left == 0); - if (state->conditional_stack != NULL) - { - unterminated_pp_condition(ctx); - continue; // returns an error. - } // if - - pop_source(ctx); - continue; // pick up again after parent's #include line. - } // if - - else if (token == TOKEN_INCOMPLETE_COMMENT) - { - fail(ctx, "Incomplete multiline comment"); - continue; // will return at top of loop. - } // else if - - else if (token == TOKEN_PP_IFDEF) - { - handle_pp_ifdef(ctx); - continue; // get the next thing. - } // else if - - else if (token == TOKEN_PP_IFNDEF) - { - handle_pp_ifndef(ctx); - continue; // get the next thing. - } // else if - - else if (token == TOKEN_PP_IF) - { - handle_pp_if(ctx); - continue; // get the next thing. - } // else if - - else if (token == TOKEN_PP_ELIF) - { - handle_pp_elif(ctx); - continue; // get the next thing. - } // else if - - else if (token == TOKEN_PP_ENDIF) - { - handle_pp_endif(ctx); - continue; // get the next thing. - } // else if - - else if (token == TOKEN_PP_ELSE) - { - handle_pp_else(ctx); - continue; // get the next thing. - } // else if - - // NOTE: Conditionals must be above (skipping) test. - else if (skipping) - continue; // just keep dumping tokens until we get end of block. - - else if (token == TOKEN_PP_INCLUDE) - { - handle_pp_include(ctx); - continue; // will return error or use new top of include_stack. - } // else if - - else if (token == TOKEN_PP_LINE) - { - handle_pp_line(ctx); - continue; // get the next thing. - } // else if - - else if (token == TOKEN_PP_ERROR) - { - handle_pp_error(ctx); - continue; // will return at top of loop. - } // else if - - else if (token == TOKEN_PP_DEFINE) - { - handle_pp_define(ctx); - continue; // will return at top of loop. - } // else if - - else if (token == TOKEN_PP_UNDEF) - { - handle_pp_undef(ctx); - continue; // will return at top of loop. - } // else if - - else if (token == TOKEN_PP_PRAGMA) - { - ctx->parsing_pragma = 1; - } // else if - - if (token == TOKEN_IDENTIFIER) - { - if (handle_pp_identifier(ctx)) - continue; // pushed the include_stack. - } // else if - - else if (token == ((Token) '\n')) - { - print_debug_lexing_position(state); - if (ctx->parsing_pragma) // let this one through. - ctx->parsing_pragma = 0; - else - { - // preprocessor is line-oriented, nothing else gets newlines. - continue; // get the next thing. - } // else - } // else if - - assert(!skipping); - *_token = token; - *_len = state->tokenlen; - return state->token; - } // while - - assert(0 && "shouldn't hit this code"); - *_token = TOKEN_UNKNOWN; - *_len = 0; - return NULL; -} // _preprocessor_nexttoken - - -const char *preprocessor_nexttoken(Preprocessor *ctx, unsigned int *len, - Token *token) -{ - const char *retval = _preprocessor_nexttoken(ctx, len, token); - print_debug_token(retval, *len, *token); - return retval; -} // preprocessor_nexttoken - - -const char *preprocessor_sourcepos(Preprocessor *_ctx, unsigned int *pos) -{ - Context *ctx = (Context *) _ctx; - if (ctx->include_stack == NULL) - { - *pos = 0; - return NULL; - } // if - - *pos = ctx->include_stack->line; - return ctx->include_stack->filename; -} // preprocessor_sourcepos - - -static void indent_buffer(Buffer *buffer, int n, const int newline) -{ - static char spaces[4] = { ' ', ' ', ' ', ' ' }; - if (newline) - { - while (n--) - { - if (!buffer_append(buffer, spaces, sizeof (spaces))) - return; - } // while - } // if - else - { - if (!buffer_append(buffer, spaces, 1)) - return; - } // else -} // indent_buffer - - -static const MOJOSHADER_preprocessData out_of_mem_data_preprocessor = { - 1, &MOJOSHADER_out_of_mem_error, 0, 0, 0, 0, 0 -}; - - -// public API... - -const MOJOSHADER_preprocessData *MOJOSHADER_preprocess(const char *filename, - const char *source, unsigned int sourcelen, - const MOJOSHADER_preprocessorDefine *defines, - unsigned int define_count, - MOJOSHADER_includeOpen include_open, - MOJOSHADER_includeClose include_close, - MOJOSHADER_malloc m, MOJOSHADER_free f, void *d) -{ - MOJOSHADER_preprocessData *retval = NULL; - Preprocessor *pp = NULL; - ErrorList *errors = NULL; - Buffer *buffer = NULL; - Token token = TOKEN_UNKNOWN; - const char *tokstr = NULL; - int nl = 1; - int indent = 0; - unsigned int len = 0; - char *output = NULL; - int errcount = 0; - size_t total_bytes = 0; - - // !!! FIXME: what's wrong with ENDLINE_STR? - #ifdef _WINDOWS - static const char endline[] = { '\r', '\n' }; - #else - static const char endline[] = { '\n' }; - #endif - - if (!m) m = MOJOSHADER_internal_malloc; - if (!f) f = MOJOSHADER_internal_free; - if (!include_open) include_open = MOJOSHADER_internal_include_open; - if (!include_close) include_close = MOJOSHADER_internal_include_close; - - pp = preprocessor_start(filename, source, sourcelen, - include_open, include_close, - defines, define_count, 0, m, f, d); - if (pp == NULL) - goto preprocess_out_of_mem; - - errors = errorlist_create(MallocBridge, FreeBridge, pp); - if (errors == NULL) - goto preprocess_out_of_mem; - - buffer = buffer_create(4096, MallocBridge, FreeBridge, pp); - if (buffer == NULL) - goto preprocess_out_of_mem; - - while ((tokstr = preprocessor_nexttoken(pp, &len, &token)) != NULL) - { - int isnewline = 0; - - assert(token != TOKEN_EOI); - - if (preprocessor_outofmemory(pp)) - goto preprocess_out_of_mem; - - // Microsoft's preprocessor is weird. - // It ignores newlines, and then inserts its own around certain - // tokens. For example, after a semicolon. This allows HLSL code to - // be mostly readable, instead of a stream of tokens. - if ( (token == ((Token) '}')) || (token == ((Token) ';')) ) - { - if ( (token == ((Token) '}')) && (indent > 0) ) - indent--; - - indent_buffer(buffer, indent, nl); - buffer_append(buffer, tokstr, len); - buffer_append(buffer, endline, sizeof (endline)); - - isnewline = 1; - } // if - - else if (token == ((Token) '\n')) - { - buffer_append(buffer, endline, sizeof (endline)); - isnewline = 1; - } // else if - - else if (token == ((Token) '{')) - { - buffer_append(buffer, endline, sizeof (endline)); - indent_buffer(buffer, indent, 1); - buffer_append(buffer, "{", 1); - buffer_append(buffer, endline, sizeof (endline)); - indent++; - isnewline = 1; - } // else if - - else if (token == TOKEN_PREPROCESSING_ERROR) - { - unsigned int pos = 0; - const char *fname = preprocessor_sourcepos(pp, &pos); - errorlist_add(errors, fname, (int) pos, tokstr); - } // else if - - else - { - indent_buffer(buffer, indent, nl); - buffer_append(buffer, tokstr, len); - } // else - - nl = isnewline; - } // while - - assert(token == TOKEN_EOI); - - total_bytes = buffer_size(buffer); - output = buffer_flatten(buffer); - buffer_destroy(buffer); - buffer = NULL; // don't free this pointer again. - - if (output == NULL) - goto preprocess_out_of_mem; - - retval = (MOJOSHADER_preprocessData *) m(sizeof (*retval), d); - if (retval == NULL) - goto preprocess_out_of_mem; - - memset(retval, '\0', sizeof (*retval)); - errcount = errorlist_count(errors); - if (errcount > 0) - { - retval->error_count = errcount; - retval->errors = errorlist_flatten(errors); - if (retval->errors == NULL) - goto preprocess_out_of_mem; - } // if - - retval->output = output; - retval->output_len = total_bytes; - retval->malloc = m; - retval->free = f; - retval->malloc_data = d; - - errorlist_destroy(errors); - preprocessor_end(pp); - return retval; - -preprocess_out_of_mem: - if (retval != NULL) - f(retval->errors, d); - f(retval, d); - f(output, d); - buffer_destroy(buffer); - errorlist_destroy(errors); - preprocessor_end(pp); - return &out_of_mem_data_preprocessor; -} // MOJOSHADER_preprocess - - -void MOJOSHADER_freePreprocessData(const MOJOSHADER_preprocessData *_data) -{ - MOJOSHADER_preprocessData *data = (MOJOSHADER_preprocessData *) _data; - if ((data == NULL) || (data == &out_of_mem_data_preprocessor)) - return; - - MOJOSHADER_free f = (data->free == NULL) ? MOJOSHADER_internal_free : data->free; - void *d = data->malloc_data; - int i; - - f((void *) data->output, d); - - for (i = 0; i < data->error_count; i++) - { - f((void *) data->errors[i].error, d); - f((void *) data->errors[i].filename, d); - } // for - f(data->errors, d); - - f(data, d); -} // MOJOSHADER_freePreprocessData - - -// end of mojoshader_preprocessor.c ... - diff --git a/mojoshader/mojoshader_sdlgpu.c b/mojoshader/mojoshader_sdlgpu.c new file mode 100644 index 0000000..b7d824c --- /dev/null +++ b/mojoshader/mojoshader_sdlgpu.c @@ -0,0 +1,892 @@ +/** + * MojoShader; generate shader programs from bytecode of compiled + * Direct3D shaders. + * + * Please see the file LICENSE.txt in the source's root directory. + * + * This file written by Ryan C. Gordon. + */ + +#define __MOJOSHADER_INTERNAL__ 1 +#include "mojoshader_internal.h" + +#ifdef USE_SDL3 /* Private define, for now */ + +#include + +/* SDL_shadercross API */ + +typedef enum SDL_ShaderCross_ShaderStage +{ + SDL_SHADERCROSS_SHADERSTAGE_VERTEX, + SDL_SHADERCROSS_SHADERSTAGE_FRAGMENT, + SDL_SHADERCROSS_SHADERSTAGE_COMPUTE +} SDL_ShaderCross_ShaderStage; + +typedef struct SDL_ShaderCross_SPIRV_Info +{ + const Uint8 *bytecode; /**< The SPIRV bytecode. */ + size_t bytecode_size; /**< The length of the SPIRV bytecode. */ + const char *entrypoint; /**< The entry point function name for the shader in UTF-8. */ + SDL_ShaderCross_ShaderStage shader_stage; /**< The shader stage to transpile the shader with. */ + + SDL_PropertiesID props; /**< A properties ID for extensions. Should be 0 if no extensions are needed. */ +} SDL_ShaderCross_SPIRV_Info; + +typedef struct SDL_ShaderCross_GraphicsShaderMetadata SDL_ShaderCross_GraphicsShaderMetadata; + +typedef SDL_GPUShaderFormat (SDLCALL *PFN_SDL_ShaderCross_GetSPIRVShaderFormats)(void); +typedef SDL_ShaderCross_GraphicsShaderMetadata *(SDLCALL *PFN_SDL_ShaderCross_ReflectGraphicsSPIRV)( + const Uint8 *bytecode, + size_t bytecode_size, + SDL_PropertiesID props); +typedef SDL_GPUShader *(SDLCALL *PFN_SDL_ShaderCross_CompileGraphicsShaderFromSPIRV)( + SDL_GPUDevice *device, + const SDL_ShaderCross_SPIRV_Info *info, + const SDL_ShaderCross_GraphicsShaderMetadata *metadata, + SDL_PropertiesID props); + +static SDL_SharedObject *SDL_shadercross_lib = NULL; +static PFN_SDL_ShaderCross_GetSPIRVShaderFormats SDL_ShaderCross_GetSPIRVShaderFormats = NULL; +static PFN_SDL_ShaderCross_ReflectGraphicsSPIRV SDL_ShaderCross_ReflectGraphicsSPIRV = NULL; +static PFN_SDL_ShaderCross_CompileGraphicsShaderFromSPIRV SDL_ShaderCross_CompileGraphicsShaderFromSPIRV = NULL; + +#ifdef _WIN32 +#define SDL_SHADERCROSS_LIB_NAME "SDL3_shadercross.dll" +#elif defined(__APPLE__) +#define SDL_SHADERCROSS_LIB_NAME "libSDL3_shadercross.0.dylib" +#else +#define SDL_SHADERCROSS_LIB_NAME "libSDL3_shadercross.so.0" +#endif + +/* Max entries for each register file type */ +#define MAX_REG_FILE_F 8192 +#define MAX_REG_FILE_I 2047 +#define MAX_REG_FILE_B 2047 + +/* The destination shader format to use */ +static SDL_GPUShaderFormat shader_format = +#ifdef __APPLE__ + SDL_GPU_SHADERFORMAT_MSL; +#else + SDL_GPU_SHADERFORMAT_SPIRV; +#endif + +typedef struct ShaderEntry +{ + uint64_t hash; + uint32_t offset; + uint32_t size; +} ShaderEntry; + +typedef struct ShaderBlob +{ + uint64_t hash; + void* binary; +} ShaderBlob; + +struct MOJOSHADER_sdlContext +{ + SDL_GPUDevice *device; + const char *profile; + + MOJOSHADER_malloc malloc_fn; + MOJOSHADER_free free_fn; + void *malloc_data; + + /* The constant register files... + * !!! FIXME: Man, it kills me how much memory this takes... + * !!! FIXME: ... make this dynamically allocated on demand. + */ + float vs_reg_file_f[MAX_REG_FILE_F * 4]; + int32_t vs_reg_file_i[MAX_REG_FILE_I * 4]; + uint8_t vs_reg_file_b[MAX_REG_FILE_B * 4]; + float ps_reg_file_f[MAX_REG_FILE_F * 4]; + int32_t ps_reg_file_i[MAX_REG_FILE_I * 4]; + uint8_t ps_reg_file_b[MAX_REG_FILE_B * 4]; + + uint8_t *uniform_staging; + uint32_t uniform_staging_length; + + MOJOSHADER_sdlShaderData *bound_vshader_data; + MOJOSHADER_sdlShaderData *bound_pshader_data; + MOJOSHADER_sdlProgram *bound_program; + HashTable *linker_cache; +}; + +struct MOJOSHADER_sdlShaderData +{ + const MOJOSHADER_parseData *parseData; + uint16_t tag; + uint32_t refcount; + uint32_t samplerSlots; + int32_t uniformBufferSize; +}; + +struct MOJOSHADER_sdlProgram +{ + SDL_GPUShader *vertexShader; + SDL_GPUShader *pixelShader; + MOJOSHADER_sdlShaderData *vertexShaderData; + MOJOSHADER_sdlShaderData *pixelShaderData; +}; + +/* Error state... */ + +static char error_buffer[1024] = { '\0' }; + +static void set_error(const char *str) +{ + snprintf(error_buffer, sizeof (error_buffer), "%s", str); +} // set_error + +static inline void out_of_memory(void) +{ + set_error("out of memory"); +} // out_of_memory + +/* Internals */ + +typedef struct LinkedShaderData +{ + MOJOSHADER_sdlShaderData *vertex; + MOJOSHADER_sdlShaderData *fragment; + MOJOSHADER_vertexAttribute vertexAttributes[16]; + uint32_t vertexAttributeCount; +} LinkedShaderData; + +static uint32_t hash_shaders(const void *sym, void *data) +{ + (void) data; + const LinkedShaderData *s = (const LinkedShaderData *) sym; + const uint32_t HASH_FACTOR = 31; + uint32_t hash = s->vertexAttributeCount; + for (uint32_t i = 0; i < s->vertexAttributeCount; i += 1) + { + hash = hash * HASH_FACTOR + s->vertexAttributes[i].usage; + hash = hash * HASH_FACTOR + s->vertexAttributes[i].usageIndex; + hash = hash * HASH_FACTOR + s->vertexAttributes[i].vertexElementFormat; + } + hash = hash * HASH_FACTOR + s->vertex->tag; + hash = hash * HASH_FACTOR + s->fragment->tag; + return hash; +} // hash_shaders + +static int match_shaders(const void *_a, const void *_b, void *data) +{ + (void) data; + const LinkedShaderData *a = (const LinkedShaderData *) _a; + const LinkedShaderData *b = (const LinkedShaderData *) _b; + + const uint16_t av = (a->vertex) ? a->vertex->tag : 0; + const uint16_t bv = (b->vertex) ? b->vertex->tag : 0; + if (av != bv) + return 0; + + const uint16_t af = (a->fragment) ? a->fragment->tag : 0; + const uint16_t bf = (b->fragment) ? b->fragment->tag : 0; + if (af != bf) + return 0; + + if (a->vertexAttributeCount != b->vertexAttributeCount) + return 0; + + for (uint32_t i = 0; i < a->vertexAttributeCount; i += 1) + { + if (a->vertexAttributes[i].usage != b->vertexAttributes[i].usage) + { + return 0; + } + if (a->vertexAttributes[i].usageIndex != b->vertexAttributes[i].usageIndex) + { + return 0; + } + if (a->vertexAttributes[i].vertexElementFormat != b->vertexAttributes[i].vertexElementFormat) + { + return 0; + } + } + + return 1; +} // match_shaders + +static void nuke_shaders( + const void *_ctx, + const void *key, + const void *value, + void *data +) { + MOJOSHADER_sdlContext *ctx = (MOJOSHADER_sdlContext *) _ctx; + (void) data; + ctx->free_fn((void *) key, ctx->malloc_data); // this was a LinkedShaderData struct. + MOJOSHADER_sdlDeleteProgram(ctx, (MOJOSHADER_sdlProgram *) value); +} // nuke_shaders + +static uint8_t update_uniform_buffer( + MOJOSHADER_sdlContext *ctx, + SDL_GPUCommandBuffer *cb, + MOJOSHADER_sdlShaderData *shader, + float *regF, + int *regI, + uint8_t *regB +) { + int32_t i, j; + int32_t offset; + uint32_t *contentsI; + + if (shader->uniformBufferSize > ctx->uniform_staging_length) + { + ctx->free_fn(ctx->uniform_staging, ctx->malloc_data); + ctx->uniform_staging = (uint8_t*) ctx->malloc_fn(shader->uniformBufferSize, ctx->malloc_data); + ctx->uniform_staging_length = shader->uniformBufferSize; + } // if + + offset = 0; + for (i = 0; i < shader->parseData->uniform_count; i++) + { + const int32_t index = shader->parseData->uniforms[i].index; + const int32_t arrayCount = shader->parseData->uniforms[i].array_count; + const int32_t size = arrayCount ? arrayCount : 1; + + switch (shader->parseData->uniforms[i].type) + { + case MOJOSHADER_UNIFORM_FLOAT: + memcpy( + ctx->uniform_staging + offset, + ®F[4 * index], + size * 16 + ); + break; + + case MOJOSHADER_UNIFORM_INT: + memcpy( + ctx->uniform_staging + offset, + ®I[4 * index], + size * 16 + ); + break; + + case MOJOSHADER_UNIFORM_BOOL: + contentsI = (uint32_t *) (ctx->uniform_staging + offset); + for (j = 0; j < size; j++) + contentsI[j * 4] = regB[index + j]; + break; + + default: + set_error( + "SOMETHING VERY WRONG HAPPENED WHEN UPDATING UNIFORMS" + ); + assert(0); + break; + } // switch + + offset += size * 16; + } // for + + return 1; // FIXME: Return 0 when uniform data is unchanged +} // update_uniform_buffer + +/* Public API */ + +unsigned int MOJOSHADER_sdlGetShaderFormats(void) +{ + int ret = shader_format; + if (SDL_ShaderCross_GetSPIRVShaderFormats != NULL) + ret |= SDL_ShaderCross_GetSPIRVShaderFormats(); + else + { + // We only care about this on Windows, hardcode the DLL name :shrug: + SDL_shadercross_lib = SDL_LoadObject(SDL_SHADERCROSS_LIB_NAME); + if (SDL_shadercross_lib != NULL) + { + SDL_ShaderCross_GetSPIRVShaderFormats = (PFN_SDL_ShaderCross_GetSPIRVShaderFormats) SDL_LoadFunction( + SDL_shadercross_lib, + "SDL_ShaderCross_GetSPIRVShaderFormats" + ); + ret |= SDL_ShaderCross_GetSPIRVShaderFormats(); + SDL_ShaderCross_GetSPIRVShaderFormats = NULL; + SDL_UnloadObject(SDL_shadercross_lib); + SDL_shadercross_lib = NULL; + } // if + } // else + return ret; +} // MOJOSHADER_sdlGetShaderFormats + +MOJOSHADER_sdlContext *MOJOSHADER_sdlCreateContext( + SDL_GPUDevice *device, + MOJOSHADER_malloc m, + MOJOSHADER_free f, + void *malloc_d +) { + MOJOSHADER_sdlContext* resultCtx; + + if (m == NULL) m = MOJOSHADER_internal_malloc; + if (f == NULL) f = MOJOSHADER_internal_free; + + resultCtx = (MOJOSHADER_sdlContext*) m(sizeof(MOJOSHADER_sdlContext), malloc_d); + if (resultCtx == NULL) + { + out_of_memory(); + goto init_fail; + } // if + + SDL_memset(resultCtx, '\0', sizeof(MOJOSHADER_sdlContext)); + resultCtx->device = device; + resultCtx->malloc_fn = m; + resultCtx->free_fn = f; + resultCtx->malloc_data = malloc_d; + + resultCtx->profile = (shader_format == SDL_GPU_SHADERFORMAT_SPIRV) ? "spirv" : "metal"; + + // We only care about ShaderCross if the device doesn't natively support the profile + if (!(SDL_GetGPUShaderFormats(device) & shader_format)) + { + SDL_shadercross_lib = SDL_LoadObject(SDL_SHADERCROSS_LIB_NAME); + if (SDL_shadercross_lib != NULL) + { + SDL_ShaderCross_GetSPIRVShaderFormats = (PFN_SDL_ShaderCross_GetSPIRVShaderFormats) SDL_LoadFunction( + SDL_shadercross_lib, + "SDL_ShaderCross_GetSPIRVShaderFormats" + ); + SDL_ShaderCross_ReflectGraphicsSPIRV = (PFN_SDL_ShaderCross_ReflectGraphicsSPIRV) SDL_LoadFunction( + SDL_shadercross_lib, + "SDL_ShaderCross_ReflectGraphicsSPIRV" + ); + SDL_ShaderCross_CompileGraphicsShaderFromSPIRV = (PFN_SDL_ShaderCross_CompileGraphicsShaderFromSPIRV) SDL_LoadFunction( + SDL_shadercross_lib, + "SDL_ShaderCross_CompileGraphicsShaderFromSPIRV" + ); + } // if + } // if + + return resultCtx; + +init_fail: + if (resultCtx != NULL) + f(resultCtx, malloc_d); + return NULL; +} // MOJOSHADER_sdlCreateContext + +const char *MOJOSHADER_sdlGetError( + MOJOSHADER_sdlContext *ctx +) { + return error_buffer; +} // MOJOSHADER_sdlGetError + +void MOJOSHADER_sdlDestroyContext( + MOJOSHADER_sdlContext *ctx +) { + uint32_t i; + + if (SDL_shadercross_lib != NULL) + { + SDL_ShaderCross_GetSPIRVShaderFormats = NULL; + SDL_ShaderCross_ReflectGraphicsSPIRV = NULL; + SDL_ShaderCross_CompileGraphicsShaderFromSPIRV = NULL; + SDL_UnloadObject(SDL_shadercross_lib); + SDL_shadercross_lib = NULL; + } // if + + if (ctx->linker_cache) + hash_destroy(ctx->linker_cache, ctx); + + ctx->free_fn(ctx->uniform_staging, ctx->malloc_data); + + ctx->free_fn(ctx, ctx->malloc_data); +} // MOJOSHADER_sdlDestroyContext + +static uint16_t shaderTagCounter = 1; + +MOJOSHADER_sdlShaderData *MOJOSHADER_sdlCompileShader( + MOJOSHADER_sdlContext *ctx, + const char *mainfn, + const unsigned char *tokenbuf, + const unsigned int bufsize, + const MOJOSHADER_swizzle *swiz, + const unsigned int swizcount, + const MOJOSHADER_samplerMap *smap, + const unsigned int smapcount +) { + MOJOSHADER_sdlShaderData *shader = NULL;; + int maxSamplerIndex = 0; + int i; + + const MOJOSHADER_parseData *pd = MOJOSHADER_parse( + ctx->profile, mainfn, + tokenbuf, bufsize, + swiz, swizcount, + smap, smapcount, + ctx->malloc_fn, + ctx->free_fn, + ctx->malloc_data + ); + + if (pd->error_count > 0) + { + set_error(pd->errors[0].error); + goto parse_shader_fail; + } // if + + shader = (MOJOSHADER_sdlShaderData*) ctx->malloc_fn(sizeof(MOJOSHADER_sdlShaderData), ctx->malloc_data); + if (shader == NULL) + { + out_of_memory(); + goto parse_shader_fail; + } // if + + shader->parseData = pd; + shader->refcount = 1; + shader->tag = shaderTagCounter++; + + /* XNA allows empty shader slots in the middle, so we have to find the actual max binding index */ + for (i = 0; i < pd->sampler_count; i += 1) + { + if (pd->samplers[i].index > maxSamplerIndex) + { + maxSamplerIndex = pd->samplers[i].index; + } + } + + shader->samplerSlots = (uint32_t) maxSamplerIndex + 1; + + shader->uniformBufferSize = 0; + for (i = 0; i < pd->uniform_count; i++) + { + shader->uniformBufferSize += SDL_max(pd->uniforms[i].array_count, 1); + } // for + shader->uniformBufferSize *= 16; // Yes, even the bool registers are this size + + return shader; + +parse_shader_fail: + MOJOSHADER_freeParseData(pd); + if (shader != NULL) + ctx->free_fn(shader, ctx->malloc_data); + return NULL; +} // MOJOSHADER_sdlCompileShader + +static MOJOSHADER_sdlProgram *compile_program( + MOJOSHADER_sdlContext *ctx, + MOJOSHADER_sdlShaderData *vshader, + MOJOSHADER_sdlShaderData *pshader) +{ + SDL_GPUShaderCreateInfo createInfo; + SDL_ShaderCross_SPIRV_Info crossCreateInfo; + SDL_ShaderCross_GraphicsShaderMetadata *whoCares; + MOJOSHADER_sdlProgram *program = (MOJOSHADER_sdlProgram*) ctx->malloc_fn(sizeof(MOJOSHADER_sdlProgram), + ctx->malloc_data); + if (program == NULL) + { + out_of_memory(); + return NULL; + } // if + + char *vshaderSource = (char*) vshader->parseData->output; + char *pshaderSource = (char*) pshader->parseData->output; + size_t vshaderCodeSize = vshader->parseData->output_len; + size_t pshaderCodeSize = pshader->parseData->output_len; + + // Last-minute fixups before we actually invoke the compiler + if (shader_format == SDL_GPU_SHADERFORMAT_SPIRV) + { + vshaderCodeSize -= sizeof(SpirvPatchTable); + pshaderCodeSize -= sizeof(SpirvPatchTable); + } // if + else if (shader_format == SDL_GPU_SHADERFORMAT_MSL) + { + // Handle texcoord0 -> point_coord conversion + if (strstr((char*) vshader->parseData->output, "[[point_size]]")) + { + pshaderSource = (char *) ctx->malloc_fn(strlen(pshader->parseData->output) + 1, ctx->malloc_data); + if (!pshaderSource) + { + out_of_memory(); + return NULL; + } + strcpy(pshaderSource, pshader->parseData->output); + + // !!! FIXME: This assumes all texcoord0 attributes in the effect are + // !!! FIXME: actually point coords! It ain't necessarily so! -caleb + const char *repl = "[[ point_coord ]]"; + char *ptr; + while ((ptr = strstr(pshaderSource, "[[user(texcoord0)]]"))) + { + memcpy(ptr, repl, strlen(repl)); + + // "float4" -> "float2" + int spaces = 0; + while (spaces < 2) + if (*(ptr--) == ' ') + spaces++; + *ptr = '2'; + } // while + } // if + } // else if + + if (SDL_ShaderCross_CompileGraphicsShaderFromSPIRV != NULL) + { + crossCreateInfo.bytecode = (const Uint8*) vshaderSource; + crossCreateInfo.bytecode_size = vshaderCodeSize; + crossCreateInfo.entrypoint = vshader->parseData->mainfn; + crossCreateInfo.shader_stage = SDL_SHADERCROSS_SHADERSTAGE_VERTEX; + crossCreateInfo.props = 0; + + whoCares = SDL_ShaderCross_ReflectGraphicsSPIRV( + crossCreateInfo.bytecode, + crossCreateInfo.bytecode_size, + 0 + ); + + program->vertexShader = SDL_ShaderCross_CompileGraphicsShaderFromSPIRV( + ctx->device, + &crossCreateInfo, + whoCares, + 0 + ); + + SDL_free(whoCares); + } // if + else + { + SDL_zero(createInfo); + createInfo.code = (const Uint8*) vshaderSource; + createInfo.code_size = vshaderCodeSize; + createInfo.entrypoint = vshader->parseData->mainfn; + createInfo.format = shader_format; + createInfo.stage = SDL_GPU_SHADERSTAGE_VERTEX; + createInfo.num_samplers = vshader->samplerSlots; + createInfo.num_uniform_buffers = 1; + + program->vertexShader = SDL_CreateGPUShader( + ctx->device, + &createInfo + ); + } // else + + if (program->vertexShader == NULL) + { + set_error(SDL_GetError()); + ctx->free_fn(program, ctx->malloc_data); + return NULL; + } // if + + if (SDL_ShaderCross_CompileGraphicsShaderFromSPIRV != NULL) + { + crossCreateInfo.bytecode = (const Uint8*) pshaderSource; + crossCreateInfo.bytecode_size = pshaderCodeSize; + crossCreateInfo.entrypoint = pshader->parseData->mainfn; + crossCreateInfo.shader_stage = SDL_SHADERCROSS_SHADERSTAGE_FRAGMENT; + crossCreateInfo.props = 0; + + whoCares = SDL_ShaderCross_ReflectGraphicsSPIRV( + crossCreateInfo.bytecode, + crossCreateInfo.bytecode_size, + 0 + ); + + program->pixelShader = SDL_ShaderCross_CompileGraphicsShaderFromSPIRV( + ctx->device, + &crossCreateInfo, + whoCares, + 0 + ); + + SDL_free(whoCares); + } // if + else + { + createInfo.code = (const Uint8*) pshaderSource; + createInfo.code_size = pshaderCodeSize; + createInfo.entrypoint = pshader->parseData->mainfn; + createInfo.format = shader_format; + createInfo.stage = SDL_GPU_SHADERSTAGE_FRAGMENT; + createInfo.num_samplers = pshader->samplerSlots; + + program->pixelShader = SDL_CreateGPUShader( + ctx->device, + &createInfo + ); + } // else + + if (program->pixelShader == NULL) + { + set_error(SDL_GetError()); + SDL_ReleaseGPUShader(ctx->device, program->vertexShader); + ctx->free_fn(program, ctx->malloc_data); + return NULL; + } // if + + if (pshaderSource != pshader->parseData->output) + ctx->free_fn(pshaderSource, ctx->malloc_data); + + return program; +} // compile_program + +MOJOSHADER_sdlProgram *MOJOSHADER_sdlLinkProgram( + MOJOSHADER_sdlContext *ctx, + MOJOSHADER_vertexAttribute *vertexAttributes, + int vertexAttributeCount +) { + MOJOSHADER_sdlProgram *program = NULL; + + MOJOSHADER_sdlShaderData *vshader = ctx->bound_vshader_data; + MOJOSHADER_sdlShaderData *pshader = ctx->bound_pshader_data; + + if ((vshader == NULL) || (pshader == NULL)) /* Both shaders MUST exist! */ + return NULL; + + if (ctx->linker_cache == NULL) + { + ctx->linker_cache = hash_create(NULL, hash_shaders, match_shaders, + nuke_shaders, 0, ctx->malloc_fn, + ctx->free_fn, ctx->malloc_data); + + if (ctx->linker_cache == NULL) + { + out_of_memory(); + return NULL; + } // if + } // if + + LinkedShaderData shaders; + shaders.vertex = vshader; + shaders.fragment = pshader; + memset(shaders.vertexAttributes, 0, sizeof(MOJOSHADER_vertexAttribute) * 16); + shaders.vertexAttributeCount = vertexAttributeCount; + for (int i = 0; i < vertexAttributeCount; i += 1) + { + shaders.vertexAttributes[i] = vertexAttributes[i]; + } + + const void *val = NULL; + + if (hash_find(ctx->linker_cache, &shaders, &val)) + { + ctx->bound_program = (MOJOSHADER_sdlProgram *) val; + return ctx->bound_program; + } + + if (shader_format == SDL_GPU_SHADERFORMAT_SPIRV) + MOJOSHADER_linkSPIRVShaders(vshader->parseData, pshader->parseData, + vertexAttributes, vertexAttributeCount); + program = compile_program(ctx, vshader, pshader); + + if (program == NULL) + return NULL; + + program->vertexShaderData = vshader; + program->pixelShaderData = pshader; + + LinkedShaderData *item = (LinkedShaderData *) ctx->malloc_fn(sizeof (LinkedShaderData), + ctx->malloc_data); + + if (item == NULL) + { + MOJOSHADER_sdlDeleteProgram(ctx, program); + } + + memcpy(item, &shaders, sizeof(LinkedShaderData)); + if (hash_insert(ctx->linker_cache, item, program) != 1) + { + ctx->free_fn(item, ctx->malloc_data); + MOJOSHADER_sdlDeleteProgram(ctx, program); + out_of_memory(); + return NULL; + } + + ctx->bound_program = program; + return program; +} // MOJOSHADER_sdlLinkProgram + +void MOJOSHADER_sdlShaderAddRef(MOJOSHADER_sdlShaderData *shader) +{ + if (shader != NULL) + shader->refcount++; +} // MOJOSHADER_sdlShaderAddRef + +void MOJOSHADER_sdlDeleteShader( + MOJOSHADER_sdlContext *ctx, + MOJOSHADER_sdlShaderData *shader +) { + if (shader != NULL) + { + if (shader->refcount > 1) + shader->refcount--; + else + { + // See if this was bound as an unlinked program anywhere... + if (ctx->linker_cache) + { + const void *key = NULL; + void *iter = NULL; + int morekeys = hash_iter_keys(ctx->linker_cache, &key, &iter); + while (morekeys) + { + const LinkedShaderData *shaders = (const LinkedShaderData *) key; + // Do this here so we don't confuse the iteration by removing... + morekeys = hash_iter_keys(ctx->linker_cache, &key, &iter); + if ((shaders->vertex == shader) || (shaders->fragment == shader)) + { + // Deletes the linked program + hash_remove(ctx->linker_cache, shaders, ctx); + } // if + } // while + } // if + + MOJOSHADER_freeParseData(shader->parseData); + ctx->free_fn(shader, ctx->malloc_data); + } // else + } // if +} // MOJOSHADER_sdlDeleteShader + +const MOJOSHADER_parseData *MOJOSHADER_sdlGetShaderParseData( + MOJOSHADER_sdlShaderData *shader +) { + return (shader != NULL) ? shader->parseData : NULL; +} // MOJOSHADER_sdlGetShaderParseData + +void MOJOSHADER_sdlDeleteProgram( + MOJOSHADER_sdlContext *ctx, + MOJOSHADER_sdlProgram *p +) { + if (ctx->bound_program == p) + ctx->bound_program = NULL; + if (p->vertexShader != NULL) + SDL_ReleaseGPUShader(ctx->device, p->vertexShader); + if (p->pixelShader != NULL) + SDL_ReleaseGPUShader(ctx->device, p->pixelShader); + ctx->free_fn(p, ctx->malloc_data); +} // MOJOSHADER_sdlDeleteProgram + +void MOJOSHADER_sdlBindProgram( + MOJOSHADER_sdlContext *ctx, + MOJOSHADER_sdlProgram *p +) { + ctx->bound_program = p; +} // MOJOSHADER_sdlBindProgram + +void MOJOSHADER_sdlBindShaders( + MOJOSHADER_sdlContext *ctx, + MOJOSHADER_sdlShaderData *vshader, + MOJOSHADER_sdlShaderData *pshader +) { + MOJOSHADER_sdlProgram *program = NULL; + ctx->bound_vshader_data = vshader; + ctx->bound_pshader_data = pshader; +} // MOJOSHADER_sdlBindShaders + +void MOJOSHADER_sdlGetBoundShaderData( + MOJOSHADER_sdlContext *ctx, + MOJOSHADER_sdlShaderData **vshaderdata, + MOJOSHADER_sdlShaderData **pshaderdata +) { + if (vshaderdata != NULL) + { + *vshaderdata = ctx->bound_vshader_data; + } // if + if (pshaderdata != NULL) + { + *pshaderdata = ctx->bound_pshader_data; + } // if +} // MOJOSHADER_sdlGetBoundShaderData + +void MOJOSHADER_sdlMapUniformBufferMemory( + MOJOSHADER_sdlContext *ctx, + float **vsf, int **vsi, unsigned char **vsb, + float **psf, int **psi, unsigned char **psb +) { + *vsf = ctx->vs_reg_file_f; + *vsi = ctx->vs_reg_file_i; + *vsb = ctx->vs_reg_file_b; + *psf = ctx->ps_reg_file_f; + *psi = ctx->ps_reg_file_i; + *psb = ctx->ps_reg_file_b; +} // MOJOSHADER_sdlMapUniformBufferMemory + +void MOJOSHADER_sdlUnmapUniformBufferMemory(MOJOSHADER_sdlContext *ctx) +{ + /* no-op! real work done in sdlUpdateUniformBuffers */ +} // MOJOSHADER_sdlUnmapUniformBufferMemory + +int MOJOSHADER_sdlGetUniformBufferSize(MOJOSHADER_sdlShaderData *shader) +{ + if (shader == NULL) + return 0; + return shader->uniformBufferSize; +} // MOJOSHADER_sdlGetUniformBufferSize + +void MOJOSHADER_sdlUpdateUniformBuffers(MOJOSHADER_sdlContext *ctx, + SDL_GPUCommandBuffer *cb) +{ + if (MOJOSHADER_sdlGetUniformBufferSize(ctx->bound_program->vertexShaderData) > 0) + { + if (update_uniform_buffer(ctx, cb, ctx->bound_program->vertexShaderData, + ctx->vs_reg_file_f, + ctx->vs_reg_file_i, + ctx->vs_reg_file_b)) + { + SDL_PushGPUVertexUniformData( + cb, + 0, + ctx->uniform_staging, + ctx->bound_program->vertexShaderData->uniformBufferSize + ); + } // if + } // if + if (MOJOSHADER_sdlGetUniformBufferSize(ctx->bound_program->pixelShaderData) > 0) + { + if (update_uniform_buffer(ctx, cb, ctx->bound_program->pixelShaderData, + ctx->ps_reg_file_f, + ctx->ps_reg_file_i, + ctx->ps_reg_file_b)) + { + SDL_PushGPUFragmentUniformData( + cb, + 0, + ctx->uniform_staging, + ctx->bound_program->pixelShaderData->uniformBufferSize + ); + } // if + } // if +} // MOJOSHADER_sdlUpdateUniformBuffers + +int MOJOSHADER_sdlGetVertexAttribLocation( + MOJOSHADER_sdlShaderData *vert, + MOJOSHADER_usage usage, int index +) { + int32_t i; + if (vert == NULL) + return -1; + + for (i = 0; i < vert->parseData->attribute_count; i++) + { + if (vert->parseData->attributes[i].usage == usage && + vert->parseData->attributes[i].index == index) + { + return i; + } // if + } // for + + // failure + return -1; +} // MOJOSHADER_sdlGetVertexAttribLocation + +void MOJOSHADER_sdlGetShaders( + MOJOSHADER_sdlContext *ctx, + SDL_GPUShader **vshader, + SDL_GPUShader **pshader +) { + assert(ctx->bound_program != NULL); + if (vshader != NULL) + *vshader = ctx->bound_program->vertexShader; + if (pshader != NULL) + *pshader = ctx->bound_program->pixelShader; +} // MOJOSHADER_sdlGetShaders + +unsigned int MOJOSHADER_sdlGetSamplerSlots(MOJOSHADER_sdlShaderData *shader) +{ + assert(shader != NULL); + return shader->samplerSlots; +} // MOJOSHADER_sdlGetSamplerSlots + +#endif // USE_SDL3 diff --git a/mojoshader/mojoshader_version.h b/mojoshader/mojoshader_version.h new file mode 100644 index 0000000..8681813 --- /dev/null +++ b/mojoshader/mojoshader_version.h @@ -0,0 +1,7 @@ +/* This file was autogenerated. Do not edit! */ +#ifndef _INCL_MOJOSHADER_VERSION_H_ +#define _INCL_MOJOSHADER_VERSION_H_ +#define MOJOSHADER_VERSION -1 +#define MOJOSHADER_CHANGESET "git-fe0be727cadd7b2976c56206af6dad0c8f4df859" +#endif + diff --git a/mojoshader/profiles/mojoshader_profile.h b/mojoshader/profiles/mojoshader_profile.h new file mode 100644 index 0000000..acf6c88 --- /dev/null +++ b/mojoshader/profiles/mojoshader_profile.h @@ -0,0 +1,397 @@ +/** + * MojoShader; generate shader programs from bytecode of compiled + * Direct3D shaders. + * + * Please see the file LICENSE.txt in the source's root directory. + * + * This file written by Ryan C. Gordon. + */ + +#ifndef MOJOSHADER_PROFILE_H +#define MOJOSHADER_PROFILE_H + +#include "../mojoshader_internal.h" + +#if SUPPORT_PROFILE_SPIRV +#include "mojoshader_profile_spirv.h" +#endif + +typedef struct ConstantsList +{ + MOJOSHADER_constant constant; + struct ConstantsList *next; +} ConstantsList; + +typedef struct VariableList +{ + MOJOSHADER_uniformType type; + int index; + int count; + ConstantsList *constant; + int used; + int emit_position; // used in some profiles. + struct VariableList *next; +} VariableList; + +typedef struct RegisterList +{ + RegisterType regtype; + int regnum; + MOJOSHADER_usage usage; + unsigned int index; + int writemask; + int misc; + int written; +#if SUPPORT_PROFILE_SPIRV + struct { + uint32 iddecl; + int is_ssa; // FIXME(krolli): Is there an existing way to tell constants and uniforms apart? + } spirv; +#endif + const VariableList *array; + struct RegisterList *next; +} RegisterList; + +typedef struct +{ + const uint32 *token; // this is the unmolested token in the stream. + int regnum; + int swizzle; // xyzw (all four, not split out). + int swizzle_x; + int swizzle_y; + int swizzle_z; + int swizzle_w; + SourceMod src_mod; + RegisterType regtype; + int relative; + RegisterType relative_regtype; + int relative_regnum; + int relative_component; + const VariableList *relative_array; +} SourceArgInfo; + +struct Profile; // predeclare. + +typedef struct CtabData +{ + int have_ctab; + int symbol_count; + MOJOSHADER_symbol *symbols; +} CtabData; + +// Context...this is state that changes as we parse through a shader... +typedef struct Context +{ + int isfail; + int out_of_memory; + MOJOSHADER_malloc malloc; + MOJOSHADER_free free; + void *malloc_data; + int current_position; + const uint32 *orig_tokens; + const uint32 *tokens; + uint32 tokencount; + int know_shader_size; + const MOJOSHADER_swizzle *swizzles; + unsigned int swizzles_count; + const MOJOSHADER_samplerMap *samplermap; + unsigned int samplermap_count; + Buffer *output; + Buffer *preflight; + Buffer *globals; + Buffer *inputs; + Buffer *outputs; + Buffer *helpers; + Buffer *subroutines; + Buffer *mainline_intro; + Buffer *mainline_arguments; + Buffer *mainline_top; + Buffer *mainline; + Buffer *postflight; + Buffer *ignore; + Buffer *output_stack[3]; + int indent_stack[3]; + int output_stack_len; + int indent; + const char *shader_type_str; + const char *endline; + const char *mainfn; + int endline_len; + int profileid; + const struct Profile *profile; + MOJOSHADER_shaderType shader_type; + uint8 major_ver; + uint8 minor_ver; + DestArgInfo dest_arg; + SourceArgInfo source_args[5]; + SourceArgInfo predicate_arg; // for predicated instructions. + uint32 dwords[4]; + uint32 version_token; + int instruction_count; + uint32 instruction_controls; + uint32 previous_opcode; + int coissue; + int loops; + int reps; + int max_reps; + int cmps; + int scratch_registers; + int max_scratch_registers; + int branch_labels_stack_index; + int branch_labels_stack[32]; + int assigned_branch_labels; + int assigned_vertex_attributes; + int last_address_reg_component; + RegisterList used_registers; + RegisterList defined_registers; + ErrorList *errors; + int constant_count; + ConstantsList *constants; + int uniform_count; + int uniform_float4_count; + int uniform_int4_count; + int uniform_bool_count; + RegisterList uniforms; + int attribute_count; + RegisterList attributes; + int sampler_count; + RegisterList samplers; + VariableList *variables; // variables to register mapping. + int centroid_allowed; + CtabData ctab; + int have_relative_input_registers; + int have_multi_color_outputs; + int determined_constants_arrays; + int predicated; + int uses_pointsize; + int uses_fog; + int need_max_float; + + // !!! FIXME: move these into SUPPORT_PROFILE sections. + int glsl_generated_lit_helper; + int glsl_generated_texlod_setup; + int glsl_generated_texm3x3spec_helper; + int arb1_wrote_position; + // !!! FIXME: move these into SUPPORT_PROFILE sections. + + int have_preshader; + int ignores_ctab; + int reset_texmpad; + int texm3x2pad_dst0; + int texm3x2pad_src0; + int texm3x3pad_dst0; + int texm3x3pad_src0; + int texm3x3pad_dst1; + int texm3x3pad_src1; + MOJOSHADER_preshader *preshader; + +#if SUPPORT_PROFILE_ARB1_NV + int profile_supports_nv2; + int profile_supports_nv3; + int profile_supports_nv4; +#endif +#if SUPPORT_PROFILE_GLSL120 + int profile_supports_glsl120; +#endif +#if SUPPORT_PROFILE_GLSLES + int profile_supports_glsles; +#endif +#if SUPPORT_PROFILE_GLSLES3 + int profile_supports_glsles3; +#endif + +#if SUPPORT_PROFILE_METAL + int metal_need_header_common; + int metal_need_header_math; + int metal_need_header_relational; + int metal_need_header_geometric; + int metal_need_header_graphics; + int metal_need_header_texture; +#endif + +#if SUPPORT_PROFILE_SPIRV + int branch_labels_patch_stack[32]; + SpirvContext spirv; +#endif +#if SUPPORT_PROFILE_GLSPIRV + int profile_supports_glspirv; +#endif + +#if SUPPORT_PROFILE_HLSL + char hlsl_outpos_name[16]; +#endif +} Context; + +// Use these macros so we can remove all bits of these profiles from the build. +#if SUPPORT_PROFILE_ARB1_NV +#define support_nv2(ctx) ((ctx)->profile_supports_nv2) +#define support_nv3(ctx) ((ctx)->profile_supports_nv3) +#define support_nv4(ctx) ((ctx)->profile_supports_nv4) +#else +#define support_nv2(ctx) (0) +#define support_nv3(ctx) (0) +#define support_nv4(ctx) (0) +#endif + +#if SUPPORT_PROFILE_GLSL120 +#define support_glsl120(ctx) ((ctx)->profile_supports_glsl120) +#else +#define support_glsl120(ctx) (0) +#endif + +#if SUPPORT_PROFILE_GLSLES3 +#define support_glsles3(ctx) ((ctx)->profile_supports_glsles3) +#else +#define support_glsles3(ctx) (0) +#endif + +#if SUPPORT_PROFILE_GLSLES +#define support_glsles(ctx) ((ctx)->profile_supports_glsles || support_glsles3(ctx)) +#else +#define support_glsles(ctx) (0) +#endif + +// Profile entry points... + +// one emit function for each opcode in each profile. +typedef void (*emit_function)(Context *ctx); + +// one emit function for starting output in each profile. +typedef void (*emit_start)(Context *ctx, const char *profilestr); + +// one emit function for ending output in each profile. +typedef void (*emit_end)(Context *ctx); + +// one emit function for phase opcode output in each profile. +typedef void (*emit_phase)(Context *ctx); + +// one emit function for finalizing output in each profile. +typedef void (*emit_finalize)(Context *ctx); + +// one emit function for global definitions in each profile. +typedef void (*emit_global)(Context *ctx, RegisterType regtype, int regnum); + +// one emit function for relative uniform arrays in each profile. +typedef void (*emit_array)(Context *ctx, VariableList *var); + +// one emit function for relative constants arrays in each profile. +typedef void (*emit_const_array)(Context *ctx, + const struct ConstantsList *constslist, + int base, int size); + +// one emit function for uniforms in each profile. +typedef void (*emit_uniform)(Context *ctx, RegisterType regtype, int regnum, + const VariableList *var); + +// one emit function for samplers in each profile. +typedef void (*emit_sampler)(Context *ctx, int stage, TextureType ttype, + int texbem); + +// one emit function for attributes in each profile. +typedef void (*emit_attribute)(Context *ctx, RegisterType regtype, int regnum, + MOJOSHADER_usage usage, int index, int wmask, + int flags); + +// one args function for each possible sequence of opcode arguments. +typedef int (*args_function)(Context *ctx); + +// one state function for each opcode where we have state machine updates. +typedef void (*state_function)(Context *ctx); + +// one function for varnames in each profile. +typedef const char *(*varname_function)(Context *c, RegisterType t, int num); + +// one function for const var array in each profile. +typedef const char *(*const_array_varname_function)(Context *c, int base, int size); + +typedef struct Profile +{ + const char *name; + emit_start start_emitter; + emit_end end_emitter; + emit_phase phase_emitter; + emit_global global_emitter; + emit_array array_emitter; + emit_const_array const_array_emitter; + emit_uniform uniform_emitter; + emit_sampler sampler_emitter; + emit_attribute attribute_emitter; + emit_finalize finalize_emitter; + varname_function get_varname; + const_array_varname_function get_const_array_varname; +} Profile; + +// Common utilities... + +void out_of_memory(Context *ctx); +void *Malloc(Context *ctx, const size_t len); +char *StrDup(Context *ctx, const char *str); +void Free(Context *ctx, void *ptr); +void * MOJOSHADERCALL MallocBridge(int bytes, void *data); +void MOJOSHADERCALL FreeBridge(void *ptr, void *data); + +int set_output(Context *ctx, Buffer **section); +void push_output(Context *ctx, Buffer **section); +void pop_output(Context *ctx); + +uint32 ver_ui32(const uint8 major, const uint8 minor); +int shader_version_supported(const uint8 maj, const uint8 min); +int shader_version_atleast(const Context *ctx, const uint8 maj, + const uint8 min); +int shader_version_exactly(const Context *ctx, const uint8 maj, + const uint8 min); +int shader_is_pixel(const Context *ctx); +int shader_is_vertex(const Context *ctx); + +int isfail(const Context *ctx); +void failf(Context *ctx, const char *fmt, ...); +void fail(Context *ctx, const char *reason); + +void output_line(Context *ctx, const char *fmt, ...); +void output_blank_line(Context *ctx); + +void floatstr(Context *ctx, char *buf, size_t bufsize, float f, + int leavedecimal); + +RegisterList *reglist_insert(Context *ctx, RegisterList *prev, + const RegisterType regtype, + const int regnum); +RegisterList *reglist_find(const RegisterList *prev, + const RegisterType rtype, + const int regnum); +RegisterList *set_used_register(Context *ctx, + const RegisterType regtype, + const int regnum, + const int written); +void set_defined_register(Context *ctx, const RegisterType rtype, + const int regnum); + +int writemask_xyzw(const int writemask); +int writemask_xyz(const int writemask); +int writemask_xy(const int writemask); +int writemask_x(const int writemask); +int writemask_y(const int writemask); +int replicate_swizzle(const int swizzle); +int no_swizzle(const int swizzle); +int vecsize_from_writemask(const int m); +void set_dstarg_writemask(DestArgInfo *dst, const int mask); + +int isscalar(Context *ctx, const MOJOSHADER_shaderType shader_type, + const RegisterType rtype, const int rnum); + +static const char swizzle_channels[] = { 'x', 'y', 'z', 'w' }; + +const char *get_D3D_register_string(Context *ctx, + RegisterType regtype, + int regnum, char *regnum_str, + size_t regnum_size); + +// !!! FIXME: These should stay in the mojoshader_profile_d3d file +// !!! FIXME: but ARB1 relies on them, so we have to move them here. +// !!! FIXME: If/when we kill off ARB1, we can move these back. +const char *get_D3D_varname_in_buf(Context *ctx, RegisterType rt, + int regnum, char *buf, + const size_t len); +const char *get_D3D_varname(Context *ctx, RegisterType rt, int regnum); + +#endif diff --git a/mojoshader/profiles/mojoshader_profile_arb1.c b/mojoshader/profiles/mojoshader_profile_arb1.c new file mode 100644 index 0000000..2f374e5 --- /dev/null +++ b/mojoshader/profiles/mojoshader_profile_arb1.c @@ -0,0 +1,2252 @@ +/** + * MojoShader; generate shader programs from bytecode of compiled + * Direct3D shaders. + * + * Please see the file LICENSE.txt in the source's root directory. + * + * This file written by Ryan C. Gordon. + */ + +#define __MOJOSHADER_INTERNAL__ 1 +#include "mojoshader_profile.h" + +#pragma GCC visibility push(hidden) + +#if SUPPORT_PROFILE_ARB1 + +static inline const char *get_ARB1_register_string(Context *ctx, + const RegisterType regtype, const int regnum, + char *regnum_str, const size_t regnum_size) +{ + // turns out these are identical at the moment. + return get_D3D_register_string(ctx,regtype,regnum,regnum_str,regnum_size); +} // get_ARB1_register_string + +int allocate_scratch_register(Context *ctx) +{ + const int retval = ctx->scratch_registers++; + if (retval >= ctx->max_scratch_registers) + ctx->max_scratch_registers = retval + 1; + return retval; +} // allocate_scratch_register + +int allocate_branch_label(Context *ctx) +{ + return ctx->assigned_branch_labels++; +} // allocate_branch_label + +const char *allocate_ARB1_scratch_reg_name(Context *ctx, char *buf, + const size_t buflen) +{ + const int scratch = allocate_scratch_register(ctx); + snprintf(buf, buflen, "scratch%d", scratch); + return buf; +} // allocate_ARB1_scratch_reg_name + +static inline const char *get_ARB1_branch_label_name(Context *ctx, const int id, + char *buf, const size_t buflen) +{ + snprintf(buf, buflen, "branch_label%d", id); + return buf; +} // get_ARB1_branch_label_name + +const char *get_ARB1_varname_in_buf(Context *ctx, const RegisterType rt, + const int regnum, char *buf, + const size_t buflen) +{ + // turns out these are identical at the moment. + return get_D3D_varname_in_buf(ctx, rt, regnum, buf, buflen); +} // get_ARB1_varname_in_buf + +const char *get_ARB1_varname(Context *ctx, const RegisterType rt, + const int regnum) +{ + // turns out these are identical at the moment. + return get_D3D_varname(ctx, rt, regnum); +} // get_ARB1_varname + + +static inline const char *get_ARB1_const_array_varname_in_buf(Context *ctx, + const int base, const int size, + char *buf, const size_t buflen) +{ + snprintf(buf, buflen, "c_array_%d_%d", base, size); + return buf; +} // get_ARB1_const_array_varname_in_buf + + +const char *get_ARB1_const_array_varname(Context *ctx, int base, int size) +{ + char buf[64]; + get_ARB1_const_array_varname_in_buf(ctx, base, size, buf, sizeof (buf)); + return StrDup(ctx, buf); +} // get_ARB1_const_array_varname + + +const char *make_ARB1_srcarg_string_in_buf(Context *ctx, + const SourceArgInfo *arg, + char *buf, size_t buflen) +{ + // !!! FIXME: this can hit pathological cases where we look like this... + // + // dp3 r1.xyz, t0_bx2, t0_bx2 + // mad r1.xyz, t0_bias, 1-r1, t0_bx2 + // + // ...which do a lot of duplicate work in arb1... + // + // SUB scratch0, t0, { 0.5, 0.5, 0.5, 0.5 }; + // MUL scratch0, scratch0, { 2.0, 2.0, 2.0, 2.0 }; + // SUB scratch1, t0, { 0.5, 0.5, 0.5, 0.5 }; + // MUL scratch1, scratch1, { 2.0, 2.0, 2.0, 2.0 }; + // DP3 r1.xyz, scratch0, scratch1; + // SUB scratch0, t0, { 0.5, 0.5, 0.5, 0.5 }; + // SUB scratch1, { 1.0, 1.0, 1.0, 1.0 }, r1; + // SUB scratch2, t0, { 0.5, 0.5, 0.5, 0.5 }; + // MUL scratch2, scratch2, { 2.0, 2.0, 2.0, 2.0 }; + // MAD r1.xyz, scratch0, scratch1, scratch2; + // + // ...notice that the dp3 calculates the same value into two scratch + // registers. This case is easier to handle; just see if multiple + // source args are identical, build it up once, and use the same + // scratch register for multiple arguments in that opcode. + // Even better still, only calculate things once across instructions, + // and be smart about letting it linger in a scratch register until we + // definitely don't need the calculation anymore. That's harder to + // write, though. + + char regnum_str[16] = { '\0' }; + + // !!! FIXME: use get_ARB1_varname_in_buf() instead? + const char *regtype_str = NULL; + if (!arg->relative) + { + regtype_str = get_ARB1_register_string(ctx, arg->regtype, + arg->regnum, regnum_str, + sizeof (regnum_str)); + } // if + + const char *rel_lbracket = ""; + char rel_offset[32] = { '\0' }; + const char *rel_rbracket = ""; + char rel_swizzle[4] = { '\0' }; + const char *rel_regtype_str = ""; + if (arg->relative) + { + rel_regtype_str = get_ARB1_varname_in_buf(ctx, arg->relative_regtype, + arg->relative_regnum, + (char *) alloca(64), 64); + + rel_swizzle[0] = '.'; + rel_swizzle[1] = swizzle_channels[arg->relative_component]; + rel_swizzle[2] = '\0'; + + if (!support_nv2(ctx)) + { + // The address register in ARB1 only allows the '.x' component, so + // we need to load the component we need from a temp vector + // register into .x as needed. + assert(arg->relative_regtype == REG_TYPE_ADDRESS); + assert(arg->relative_regnum == 0); + if (ctx->last_address_reg_component != arg->relative_component) + { + output_line(ctx, "ARL %s.x, addr%d.%c;", rel_regtype_str, + arg->relative_regnum, + swizzle_channels[arg->relative_component]); + ctx->last_address_reg_component = arg->relative_component; + } // if + + rel_swizzle[1] = 'x'; + } // if + + if (arg->regtype == REG_TYPE_INPUT) + regtype_str = "vertex.attrib"; + else + { + assert(arg->regtype == REG_TYPE_CONST); + const int arrayidx = arg->relative_array->index; + const int arraysize = arg->relative_array->count; + const int offset = arg->regnum - arrayidx; + assert(offset >= 0); + regtype_str = get_ARB1_const_array_varname_in_buf(ctx, arrayidx, + arraysize, (char *) alloca(64), 64); + if (offset != 0) + snprintf(rel_offset, sizeof (rel_offset), " + %d", offset); + } // else + + rel_lbracket = "["; + rel_rbracket = "]"; + } // if + + // This is the source register with everything but swizzle and source mods. + snprintf(buf, buflen, "%s%s%s%s%s%s%s", regtype_str, regnum_str, + rel_lbracket, rel_regtype_str, rel_swizzle, rel_offset, + rel_rbracket); + + // Some of the source mods need to generate instructions to a temp + // register, in which case we'll replace the register name. + const SourceMod mod = arg->src_mod; + const int inplace = ( (mod == SRCMOD_NONE) || (mod == SRCMOD_NEGATE) || + ((mod == SRCMOD_ABS) && support_nv2(ctx)) ); + + if (!inplace) + { + const size_t len = 64; + char *stackbuf = (char *) alloca(len); + regtype_str = allocate_ARB1_scratch_reg_name(ctx, stackbuf, len); + regnum_str[0] = '\0'; // move value to scratch register. + rel_lbracket = ""; // scratch register won't use array. + rel_rbracket = ""; + rel_offset[0] = '\0'; + rel_swizzle[0] = '\0'; + rel_regtype_str = ""; + } // if + + const char *premod_str = ""; + const char *postmod_str = ""; + switch (mod) + { + case SRCMOD_NEGATE: + premod_str = "-"; + break; + + case SRCMOD_BIASNEGATE: + premod_str = "-"; + // fall through. + case SRCMOD_BIAS: + output_line(ctx, "SUB %s, %s, { 0.5, 0.5, 0.5, 0.5 };", + regtype_str, buf); + break; + + case SRCMOD_SIGNNEGATE: + premod_str = "-"; + // fall through. + case SRCMOD_SIGN: + output_line(ctx, + "MAD %s, %s, { 2.0, 2.0, 2.0, 2.0 }, { -1.0, -1.0, -1.0, -1.0 };", + regtype_str, buf); + break; + + case SRCMOD_COMPLEMENT: + output_line(ctx, "SUB %s, { 1.0, 1.0, 1.0, 1.0 }, %s;", + regtype_str, buf); + break; + + case SRCMOD_X2NEGATE: + premod_str = "-"; + // fall through. + case SRCMOD_X2: + output_line(ctx, "MUL %s, %s, { 2.0, 2.0, 2.0, 2.0 };", + regtype_str, buf); + break; + + case SRCMOD_DZ: + fail(ctx, "SRCMOD_DZ currently unsupported in arb1"); + postmod_str = "_dz"; + break; + + case SRCMOD_DW: + fail(ctx, "SRCMOD_DW currently unsupported in arb1"); + postmod_str = "_dw"; + break; + + case SRCMOD_ABSNEGATE: + premod_str = "-"; + // fall through. + case SRCMOD_ABS: + if (!support_nv2(ctx)) // GL_NV_vertex_program2_option adds this. + output_line(ctx, "ABS %s, %s;", regtype_str, buf); + else + { + premod_str = (mod == SRCMOD_ABSNEGATE) ? "-|" : "|"; + postmod_str = "|"; + } // else + break; + + case SRCMOD_NOT: + fail(ctx, "SRCMOD_NOT currently unsupported in arb1"); + premod_str = "!"; + break; + + case SRCMOD_NONE: + case SRCMOD_TOTAL: + break; // stop compiler whining. + } // switch + + char swizzle_str[6]; + size_t i = 0; + + if (support_nv4(ctx)) // vFace must be output as "vFace.x" in nv4. + { + if (arg->regtype == REG_TYPE_MISCTYPE) + { + if ( ((const MiscTypeType) arg->regnum) == MISCTYPE_TYPE_FACE ) + { + swizzle_str[i++] = '.'; + swizzle_str[i++] = 'x'; + } // if + } // if + } // if + + const int scalar = isscalar(ctx, ctx->shader_type, arg->regtype, arg->regnum); + if (!scalar && !no_swizzle(arg->swizzle)) + { + swizzle_str[i++] = '.'; + + // .xxxx is the same as .x, but .xx is illegal...scalar or full! + if (replicate_swizzle(arg->swizzle)) + swizzle_str[i++] = swizzle_channels[arg->swizzle_x]; + else + { + swizzle_str[i++] = swizzle_channels[arg->swizzle_x]; + swizzle_str[i++] = swizzle_channels[arg->swizzle_y]; + swizzle_str[i++] = swizzle_channels[arg->swizzle_z]; + swizzle_str[i++] = swizzle_channels[arg->swizzle_w]; + } // else + } // if + swizzle_str[i] = '\0'; + assert(i < sizeof (swizzle_str)); + + snprintf(buf, buflen, "%s%s%s%s%s%s%s%s%s%s", premod_str, + regtype_str, regnum_str, rel_lbracket, + rel_regtype_str, rel_swizzle, rel_offset, rel_rbracket, + swizzle_str, postmod_str); + // !!! FIXME: make sure the scratch buffer was large enough. + return buf; +} // make_ARB1_srcarg_string_in_buf + +const char *get_ARB1_destarg_varname(Context *ctx, char *buf, + const size_t buflen) +{ + const DestArgInfo *arg = &ctx->dest_arg; + return get_ARB1_varname_in_buf(ctx, arg->regtype, arg->regnum, buf, buflen); +} // get_ARB1_destarg_varname + +const char *get_ARB1_srcarg_varname(Context *ctx, const size_t idx, + char *buf, const size_t buflen) +{ + if (idx >= STATICARRAYLEN(ctx->source_args)) + { + fail(ctx, "Too many source args"); + *buf = '\0'; + return buf; + } // if + + const SourceArgInfo *arg = &ctx->source_args[idx]; + return get_ARB1_varname_in_buf(ctx, arg->regtype, arg->regnum, buf, buflen); +} // get_ARB1_srcarg_varname + + +const char *make_ARB1_destarg_string(Context *ctx, char *buf, + const size_t buflen) +{ + const DestArgInfo *arg = &ctx->dest_arg; + + *buf = '\0'; + + const char *sat_str = ""; + if (arg->result_mod & MOD_SATURATE) + { + // nv4 can use ".SAT" in all program types. + // For less than nv4, the "_SAT" modifier is only available in + // fragment shaders. Every thing else will fake it later in + // emit_ARB1_dest_modifiers() ... + if (support_nv4(ctx)) + sat_str = ".SAT"; + else if (shader_is_pixel(ctx)) + sat_str = "_SAT"; + } // if + + const char *pp_str = ""; + if (arg->result_mod & MOD_PP) + { + // Most ARB1 profiles can't do partial precision (MOD_PP), but that's + // okay. The spec says lots of Direct3D implementations ignore the + // flag anyhow. + if (support_nv4(ctx)) + pp_str = "H"; + } // if + + // CENTROID only allowed in DCL opcodes, which shouldn't come through here. + assert((arg->result_mod & MOD_CENTROID) == 0); + + char regnum_str[16]; + const char *regtype_str = get_ARB1_register_string(ctx, arg->regtype, + arg->regnum, regnum_str, + sizeof (regnum_str)); + if (regtype_str == NULL) + { + fail(ctx, "Unknown destination register type."); + return buf; + } // if + + char writemask_str[6]; + size_t i = 0; + const int scalar = isscalar(ctx, ctx->shader_type, arg->regtype, arg->regnum); + if (!scalar && !writemask_xyzw(arg->writemask)) + { + writemask_str[i++] = '.'; + if (arg->writemask0) writemask_str[i++] = 'x'; + if (arg->writemask1) writemask_str[i++] = 'y'; + if (arg->writemask2) writemask_str[i++] = 'z'; + if (arg->writemask3) writemask_str[i++] = 'w'; + } // if + writemask_str[i] = '\0'; + assert(i < sizeof (writemask_str)); + + //const char *pred_left = ""; + //const char *pred_right = ""; + char pred[32] = { '\0' }; + if (ctx->predicated) + { + fail(ctx, "dest register predication currently unsupported in arb1"); + return buf; + //pred_left = "("; + //pred_right = ") "; + make_ARB1_srcarg_string_in_buf(ctx, &ctx->predicate_arg, + pred, sizeof (pred)); + } // if + + snprintf(buf, buflen, "%s%s %s%s%s", pp_str, sat_str, + regtype_str, regnum_str, writemask_str); + // !!! FIXME: make sure the scratch buffer was large enough. + return buf; +} // make_ARB1_destarg_string + + +void emit_ARB1_dest_modifiers(Context *ctx) +{ + const DestArgInfo *arg = &ctx->dest_arg; + + if (arg->result_shift != 0x0) + { + char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); + const char *multiplier = NULL; + + switch (arg->result_shift) + { + case 0x1: multiplier = "2.0"; break; + case 0x2: multiplier = "4.0"; break; + case 0x3: multiplier = "8.0"; break; + case 0xD: multiplier = "0.125"; break; + case 0xE: multiplier = "0.25"; break; + case 0xF: multiplier = "0.5"; break; + } // switch + + if (multiplier != NULL) + { + char var[64]; get_ARB1_destarg_varname(ctx, var, sizeof (var)); + output_line(ctx, "MUL%s, %s, %s;", dst, var, multiplier); + } // if + } // if + + if (arg->result_mod & MOD_SATURATE) + { + // nv4 and/or pixel shaders just used the "SAT" modifier, instead. + if ( (!support_nv4(ctx)) && (!shader_is_pixel(ctx)) ) + { + char var[64]; get_ARB1_destarg_varname(ctx, var, sizeof (var)); + char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); + output_line(ctx, "MIN%s, %s, 1.0;", dst, var); + output_line(ctx, "MAX%s, %s, 0.0;", dst, var); + } // if + } // if +} // emit_ARB1_dest_modifiers + + +const char *make_ARB1_srcarg_string(Context *ctx, const size_t idx, + char *buf, const size_t buflen) +{ + if (idx >= STATICARRAYLEN(ctx->source_args)) + { + fail(ctx, "Too many source args"); + *buf = '\0'; + return buf; + } // if + + const SourceArgInfo *arg = &ctx->source_args[idx]; + return make_ARB1_srcarg_string_in_buf(ctx, arg, buf, buflen); +} // make_ARB1_srcarg_string + +void emit_ARB1_opcode_ds(Context *ctx, const char *opcode) +{ + char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); + char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); + output_line(ctx, "%s%s, %s;", opcode, dst, src0); + emit_ARB1_dest_modifiers(ctx); +} // emit_ARB1_opcode_ds + +void emit_ARB1_opcode_dss(Context *ctx, const char *opcode) +{ + char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); + char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_ARB1_srcarg_string(ctx, 1, src1, sizeof (src1)); + output_line(ctx, "%s%s, %s, %s;", opcode, dst, src0, src1); + emit_ARB1_dest_modifiers(ctx); +} // emit_ARB1_opcode_dss + +void emit_ARB1_opcode_dsss(Context *ctx, const char *opcode) +{ + char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); + char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_ARB1_srcarg_string(ctx, 1, src1, sizeof (src1)); + char src2[64]; make_ARB1_srcarg_string(ctx, 2, src2, sizeof (src2)); + output_line(ctx, "%s%s, %s, %s, %s;", opcode, dst, src0, src1, src2); + emit_ARB1_dest_modifiers(ctx); +} // emit_ARB1_opcode_dsss + + +#define EMIT_ARB1_OPCODE_FUNC(op) \ + void emit_ARB1_##op(Context *ctx) { \ + emit_ARB1_opcode(ctx, #op); \ + } +#define EMIT_ARB1_OPCODE_D_FUNC(op) \ + void emit_ARB1_##op(Context *ctx) { \ + emit_ARB1_opcode_d(ctx, #op); \ + } +#define EMIT_ARB1_OPCODE_S_FUNC(op) \ + void emit_ARB1_##op(Context *ctx) { \ + emit_ARB1_opcode_s(ctx, #op); \ + } +#define EMIT_ARB1_OPCODE_SS_FUNC(op) \ + void emit_ARB1_##op(Context *ctx) { \ + emit_ARB1_opcode_ss(ctx, #op); \ + } +#define EMIT_ARB1_OPCODE_DS_FUNC(op) \ + void emit_ARB1_##op(Context *ctx) { \ + emit_ARB1_opcode_ds(ctx, #op); \ + } +#define EMIT_ARB1_OPCODE_DSS_FUNC(op) \ + void emit_ARB1_##op(Context *ctx) { \ + emit_ARB1_opcode_dss(ctx, #op); \ + } +#define EMIT_ARB1_OPCODE_DSSS_FUNC(op) \ + void emit_ARB1_##op(Context *ctx) { \ + emit_ARB1_opcode_dsss(ctx, #op); \ + } +#define EMIT_ARB1_OPCODE_DSSSS_FUNC(op) \ + void emit_ARB1_##op(Context *ctx) { \ + emit_ARB1_opcode_dssss(ctx, #op); \ + } +#define EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(op) \ + void emit_ARB1_##op(Context *ctx) { \ + failf(ctx, #op " unimplemented in %s profile", ctx->profile->name); \ + } + + +void emit_ARB1_start(Context *ctx, const char *profilestr) +{ + const char *shader_str = NULL; + const char *shader_full_str = NULL; + if (shader_is_vertex(ctx)) + { + shader_str = "vp"; + shader_full_str = "vertex"; + } // if + else if (shader_is_pixel(ctx)) + { + shader_str = "fp"; + shader_full_str = "fragment"; + } // else if + else + { + failf(ctx, "Shader type %u unsupported in this profile.", + (uint) ctx->shader_type); + return; + } // if + + set_output(ctx, &ctx->preflight); + + if (strcmp(profilestr, MOJOSHADER_PROFILE_ARB1) == 0) + output_line(ctx, "!!ARB%s1.0", shader_str); + + #if SUPPORT_PROFILE_ARB1_NV + else if (strcmp(profilestr, MOJOSHADER_PROFILE_NV2) == 0) + { + ctx->profile_supports_nv2 = 1; + output_line(ctx, "!!ARB%s1.0", shader_str); + output_line(ctx, "OPTION NV_%s_program2;", shader_full_str); + } // else if + + else if (strcmp(profilestr, MOJOSHADER_PROFILE_NV3) == 0) + { + // there's no NV_fragment_program3, so just use 2. + const int ver = shader_is_pixel(ctx) ? 2 : 3; + ctx->profile_supports_nv2 = 1; + ctx->profile_supports_nv3 = 1; + output_line(ctx, "!!ARB%s1.0", shader_str); + output_line(ctx, "OPTION NV_%s_program%d;", shader_full_str, ver); + } // else if + + else if (strcmp(profilestr, MOJOSHADER_PROFILE_NV4) == 0) + { + ctx->profile_supports_nv2 = 1; + ctx->profile_supports_nv3 = 1; + ctx->profile_supports_nv4 = 1; + output_line(ctx, "!!NV%s4.0", shader_str); + } // else if + #endif + + else + { + failf(ctx, "Profile '%s' unsupported or unknown.", profilestr); + } // else + + set_output(ctx, &ctx->mainline); +} // emit_ARB1_start + +void emit_ARB1_end(Context *ctx) +{ + // ps_1_* writes color to r0 instead oC0. We move it to the right place. + // We don't have to worry about a RET opcode messing this up, since + // RET isn't available before ps_2_0. + if (shader_is_pixel(ctx) && !shader_version_atleast(ctx, 2, 0)) + { + set_used_register(ctx, REG_TYPE_COLOROUT, 0, 1); + output_line(ctx, "MOV oC0, r0;"); + } // if + + output_line(ctx, "END"); +} // emit_ARB1_end + +void emit_ARB1_phase(Context *ctx) +{ + // no-op in arb1. +} // emit_ARB1_phase + +static inline const char *arb1_float_temp(const Context *ctx) +{ + // nv4 lets you specify data type. + return (support_nv4(ctx)) ? "FLOAT TEMP" : "TEMP"; +} // arb1_float_temp + +void emit_ARB1_finalize(Context *ctx) +{ + push_output(ctx, &ctx->preflight); + + if (shader_is_vertex(ctx) && !ctx->arb1_wrote_position) + output_line(ctx, "OPTION ARB_position_invariant;"); + + if (shader_is_pixel(ctx) && ctx->have_multi_color_outputs) + output_line(ctx, "OPTION ARB_draw_buffers;"); + + pop_output(ctx); + + const char *tmpstr = arb1_float_temp(ctx); + int i; + push_output(ctx, &ctx->globals); + for (i = 0; i < ctx->max_scratch_registers; i++) + { + char buf[64]; + allocate_ARB1_scratch_reg_name(ctx, buf, sizeof (buf)); + output_line(ctx, "%s %s;", tmpstr, buf); + } // for + + // nv2 fragment programs (and anything nv4) have a real REP/ENDREP. + if ( (support_nv2(ctx)) && (!shader_is_pixel(ctx)) && (!support_nv4(ctx)) ) + { + // set up temps for nv2 REP/ENDREP emulation through branching. + for (i = 0; i < ctx->max_reps; i++) + output_line(ctx, "TEMP rep%d;", i); + } // if + + pop_output(ctx); + assert(ctx->scratch_registers == ctx->max_scratch_registers); +} // emit_ARB1_finalize + +void emit_ARB1_global(Context *ctx, RegisterType regtype, int regnum) +{ + // !!! FIXME: dependency on ARB1 profile. // !!! FIXME about FIXME: huh? + char varname[64]; + get_ARB1_varname_in_buf(ctx, regtype, regnum, varname, sizeof (varname)); + + push_output(ctx, &ctx->globals); + switch (regtype) + { + case REG_TYPE_ADDRESS: + if (shader_is_pixel(ctx)) // actually REG_TYPE_TEXTURE. + { + // We have to map texture registers to temps for ps_1_1, since + // they work like temps, initialize with tex coords, and the + // ps_1_1 TEX opcode expects to overwrite it. + if (!shader_version_atleast(ctx, 1, 4)) + { + output_line(ctx, "%s %s;", arb1_float_temp(ctx), varname); + push_output(ctx, &ctx->mainline_top); + output_line(ctx, "MOV %s, fragment.texcoord[%d];", + varname, regnum); + pop_output(ctx); + } // if + break; + } // if + + // nv4 replaced address registers with generic int registers. + if (support_nv4(ctx)) + output_line(ctx, "INT TEMP %s;", varname); + else + { + // nv2 has four-component address already, but stock arb1 has + // to emulate it in a temporary, and move components to the + // scalar ADDRESS register on demand. + output_line(ctx, "ADDRESS %s;", varname); + if (!support_nv2(ctx)) + output_line(ctx, "TEMP addr%d;", regnum); + } // else + break; + + //case REG_TYPE_PREDICATE: + // output_line(ctx, "bvec4 %s;", varname); + // break; + case REG_TYPE_TEMP: + output_line(ctx, "%s %s;", arb1_float_temp(ctx), varname); + break; + //case REG_TYPE_LOOP: + // break; // no-op. We declare these in for loops at the moment. + //case REG_TYPE_LABEL: + // break; // no-op. If we see it here, it means we optimized it out. + default: + fail(ctx, "BUG: we used a register we don't know how to define."); + break; + } // switch + pop_output(ctx); +} // emit_ARB1_global + +void emit_ARB1_array(Context *ctx, VariableList *var) +{ + // All uniforms are now packed tightly into the program.local array, + // instead of trying to map them to the d3d registers. So this needs to + // map to the next piece of the array we haven't used yet. Thankfully, + // arb1 lets you make a PARAM array that maps to a subset of another + // array; we don't need to do offsets, since myarray[0] can map to + // program.local[5] without any extra math from us. + const int base = var->index; + const int size = var->count; + const int arb1base = ctx->uniform_float4_count + + ctx->uniform_int4_count + + ctx->uniform_bool_count; + char varname[64]; + get_ARB1_const_array_varname_in_buf(ctx, base, size, varname, sizeof (varname)); + push_output(ctx, &ctx->globals); + output_line(ctx, "PARAM %s[%d] = { program.local[%d..%d] };", varname, + size, arb1base, (arb1base + size) - 1); + pop_output(ctx); + var->emit_position = arb1base; +} // emit_ARB1_array + +void emit_ARB1_const_array(Context *ctx, const ConstantsList *clist, + int base, int size) +{ + char varname[64]; + get_ARB1_const_array_varname_in_buf(ctx, base, size, varname, sizeof (varname)); + int i; + + push_output(ctx, &ctx->globals); + output_line(ctx, "PARAM %s[%d] = {", varname, size); + ctx->indent++; + + for (i = 0; i < size; i++) + { + while (clist->constant.type != MOJOSHADER_UNIFORM_FLOAT) + clist = clist->next; + assert(clist->constant.index == (base + i)); + + char val0[32]; + char val1[32]; + char val2[32]; + char val3[32]; + floatstr(ctx, val0, sizeof (val0), clist->constant.value.f[0], 1); + floatstr(ctx, val1, sizeof (val1), clist->constant.value.f[1], 1); + floatstr(ctx, val2, sizeof (val2), clist->constant.value.f[2], 1); + floatstr(ctx, val3, sizeof (val3), clist->constant.value.f[3], 1); + + output_line(ctx, "{ %s, %s, %s, %s }%s", val0, val1, val2, val3, + (i < (size-1)) ? "," : ""); + + clist = clist->next; + } // for + + ctx->indent--; + output_line(ctx, "};"); + pop_output(ctx); +} // emit_ARB1_const_array + +void emit_ARB1_uniform(Context *ctx, RegisterType regtype, int regnum, + const VariableList *var) +{ + // We pack these down into the program.local array, so if we only use + // register c439, it'll actually map to program.local[0]. This will + // prevent overflows when we actually have enough resources to run. + + const char *arrayname = "program.local"; + int index = 0; + + char varname[64]; + get_ARB1_varname_in_buf(ctx, regtype, regnum, varname, sizeof (varname)); + + push_output(ctx, &ctx->globals); + + if (var == NULL) + { + // all types share one array (rather, all types convert to float4). + index = ctx->uniform_float4_count + ctx->uniform_int4_count + + ctx->uniform_bool_count; + } // if + + else + { + const int arraybase = var->index; + if (var->constant) + { + const int arraysize = var->count; + arrayname = get_ARB1_const_array_varname_in_buf(ctx, arraybase, + arraysize, (char *) alloca(64), 64); + index = (regnum - arraybase); + } // if + else + { + assert(var->emit_position != -1); + index = (regnum - arraybase) + var->emit_position; + } // else + } // else + + output_line(ctx, "PARAM %s = %s[%d];", varname, arrayname, index); + pop_output(ctx); +} // emit_ARB1_uniform + +void emit_ARB1_sampler(Context *ctx,int stage,TextureType ttype,int tb) +{ + // this is mostly a no-op...you don't predeclare samplers in arb1. + + if (tb) // This sampler used a ps_1_1 TEXBEM opcode? + { + const int index = ctx->uniform_float4_count + ctx->uniform_int4_count + + ctx->uniform_bool_count; + char var[64]; + get_ARB1_varname_in_buf(ctx, REG_TYPE_SAMPLER, stage, var, sizeof(var)); + push_output(ctx, &ctx->globals); + output_line(ctx, "PARAM %s_texbem = program.local[%d];", var, index); + output_line(ctx, "PARAM %s_texbeml = program.local[%d];", var, index+1); + pop_output(ctx); + ctx->uniform_float4_count += 2; + } // if +} // emit_ARB1_sampler + +// !!! FIXME: a lot of cut-and-paste here from emit_GLSL_attribute(). +void emit_ARB1_attribute(Context *ctx, RegisterType regtype, int regnum, + MOJOSHADER_usage usage, int index, int wmask, + int flags) +{ + // !!! FIXME: this function doesn't deal with write masks at all yet! + const char *usage_str = NULL; + const char *arrayleft = ""; + const char *arrayright = ""; + char index_str[16] = { '\0' }; + + char varname[64]; + get_ARB1_varname_in_buf(ctx, regtype, regnum, varname, sizeof (varname)); + + //assert((flags & MOD_PP) == 0); // !!! FIXME: is PP allowed? + + if (index != 0) // !!! FIXME: a lot of these MUST be zero. + snprintf(index_str, sizeof (index_str), "%u", (uint) index); + + if (shader_is_vertex(ctx)) + { + // pre-vs3 output registers. + // these don't ever happen in DCL opcodes, I think. Map to vs_3_* + // output registers. + if (!shader_version_atleast(ctx, 3, 0)) + { + if (regtype == REG_TYPE_RASTOUT) + { + regtype = REG_TYPE_OUTPUT; + index = regnum; + switch ((const RastOutType) regnum) + { + case RASTOUT_TYPE_POSITION: + usage = MOJOSHADER_USAGE_POSITION; + break; + case RASTOUT_TYPE_FOG: + usage = MOJOSHADER_USAGE_FOG; + break; + case RASTOUT_TYPE_POINT_SIZE: + usage = MOJOSHADER_USAGE_POINTSIZE; + break; + } // switch + } // if + + else if (regtype == REG_TYPE_ATTROUT) + { + regtype = REG_TYPE_OUTPUT; + usage = MOJOSHADER_USAGE_COLOR; + index = regnum; + } // else if + + else if (regtype == REG_TYPE_TEXCRDOUT) + { + regtype = REG_TYPE_OUTPUT; + usage = MOJOSHADER_USAGE_TEXCOORD; + index = regnum; + } // else if + } // if + + // to avoid limitations of various GL entry points for input + // attributes (glSecondaryColorPointer() can only take 3 component + // items, glVertexPointer() can't do GL_UNSIGNED_BYTE, many other + // issues), we set up all inputs as generic vertex attributes, so we + // can pass data in just about any form, and ignore the built-in GLSL + // attributes like gl_SecondaryColor. Output needs to use the the + // built-ins, though, but we don't have to worry about the GL entry + // point limitations there. + + if (regtype == REG_TYPE_INPUT) + { + const int attr = ctx->assigned_vertex_attributes++; + push_output(ctx, &ctx->globals); + output_line(ctx, "ATTRIB %s = vertex.attrib[%d];", varname, attr); + pop_output(ctx); + } // if + + else if (regtype == REG_TYPE_OUTPUT) + { + switch (usage) + { + case MOJOSHADER_USAGE_POSITION: + ctx->arb1_wrote_position = 1; + usage_str = "result.position"; + break; + case MOJOSHADER_USAGE_POINTSIZE: + usage_str = "result.pointsize"; + break; + case MOJOSHADER_USAGE_COLOR: + index_str[0] = '\0'; // no explicit number. + if (index == 0) + usage_str = "result.color.primary"; + else if (index == 1) + usage_str = "result.color.secondary"; + break; + case MOJOSHADER_USAGE_FOG: + usage_str = "result.fogcoord"; + break; + case MOJOSHADER_USAGE_TEXCOORD: + snprintf(index_str, sizeof (index_str), "%u", (uint) index); + usage_str = "result.texcoord"; + arrayleft = "["; + arrayright = "]"; + break; + default: + // !!! FIXME: we need to deal with some more built-in varyings here. + break; + } // switch + + // !!! FIXME: the #define is a little hacky, but it means we don't + // !!! FIXME: have to track these separately if this works. + push_output(ctx, &ctx->globals); + // no mapping to built-in var? Just make it a regular global, pray. + if (usage_str == NULL) + output_line(ctx, "%s %s;", arb1_float_temp(ctx), varname); + else + { + output_line(ctx, "OUTPUT %s = %s%s%s%s;", varname, usage_str, + arrayleft, index_str, arrayright); + } // else + pop_output(ctx); + } // else if + + else + { + fail(ctx, "unknown vertex shader attribute register"); + } // else + } // if + + else if (shader_is_pixel(ctx)) + { + const char *paramtype_str = "ATTRIB"; + + // samplers DCLs get handled in emit_ARB1_sampler(). + + if (flags & MOD_CENTROID) + { + if (!support_nv4(ctx)) // GL_NV_fragment_program4 adds centroid. + { + // !!! FIXME: should we just wing it without centroid here? + failf(ctx, "centroid unsupported in %s profile", + ctx->profile->name); + return; + } // if + + paramtype_str = "CENTROID ATTRIB"; + } // if + + if (regtype == REG_TYPE_COLOROUT) + { + paramtype_str = "OUTPUT"; + usage_str = "result.color"; + if (ctx->have_multi_color_outputs) + { + // We have to gamble that you have GL_ARB_draw_buffers. + // You probably do at this point if you have a sane setup. + snprintf(index_str, sizeof (index_str), "%u", (uint) regnum); + arrayleft = "["; + arrayright = "]"; + } // if + } // if + + else if (regtype == REG_TYPE_DEPTHOUT) + { + paramtype_str = "OUTPUT"; + usage_str = "result.depth"; + } // else if + + // !!! FIXME: can you actualy have a texture register with COLOR usage? + else if ((regtype == REG_TYPE_TEXTURE) || (regtype == REG_TYPE_INPUT)) + { + if (usage == MOJOSHADER_USAGE_TEXCOORD) + { + // ps_1_1 does a different hack for this attribute. + // Refer to emit_ARB1_global()'s REG_TYPE_TEXTURE code. + if (shader_version_atleast(ctx, 1, 4)) + { + snprintf(index_str, sizeof (index_str), "%u", (uint) index); + usage_str = "fragment.texcoord"; + arrayleft = "["; + arrayright = "]"; + } // if + } // if + + else if (usage == MOJOSHADER_USAGE_COLOR) + { + index_str[0] = '\0'; // no explicit number. + if (index == 0) + usage_str = "fragment.color.primary"; + else if (index == 1) + usage_str = "fragment.color.secondary"; + else + fail(ctx, "unsupported color index"); + } // else if + } // else if + + else if (regtype == REG_TYPE_MISCTYPE) + { + const MiscTypeType mt = (MiscTypeType) regnum; + if (mt == MISCTYPE_TYPE_FACE) + { + if (support_nv4(ctx)) // FINALLY, a vFace equivalent in nv4! + { + index_str[0] = '\0'; // no explicit number. + usage_str = "fragment.facing"; + } // if + else + { + failf(ctx, "vFace unsupported in %s profile", + ctx->profile->name); + } // else + } // if + else if (mt == MISCTYPE_TYPE_POSITION) + { + index_str[0] = '\0'; // no explicit number. + usage_str = "fragment.position"; // !!! FIXME: is this the same coord space as D3D? + } // else if + else + { + fail(ctx, "BUG: unhandled misc register"); + } // else + } // else if + + else + { + fail(ctx, "unknown pixel shader attribute register"); + } // else + + if (usage_str != NULL) + { + push_output(ctx, &ctx->globals); + output_line(ctx, "%s %s = %s%s%s%s;", paramtype_str, varname, + usage_str, arrayleft, index_str, arrayright); + pop_output(ctx); + } // if + } // else if + + else + { + fail(ctx, "Unknown shader type"); // state machine should catch this. + } // else +} // emit_ARB1_attribute + +void emit_ARB1_RESERVED(Context *ctx) { /* no-op. */ } + +void emit_ARB1_NOP(Context *ctx) +{ + // There is no NOP in arb1. Just don't output anything here. +} // emit_ARB1_NOP + +EMIT_ARB1_OPCODE_DS_FUNC(MOV) +EMIT_ARB1_OPCODE_DSS_FUNC(ADD) +EMIT_ARB1_OPCODE_DSS_FUNC(SUB) +EMIT_ARB1_OPCODE_DSSS_FUNC(MAD) +EMIT_ARB1_OPCODE_DSS_FUNC(MUL) +EMIT_ARB1_OPCODE_DS_FUNC(RCP) + +void emit_ARB1_RSQ(Context *ctx) +{ + // nv4 doesn't force abs() on this, so negative values will generate NaN. + // The spec says you should force the abs() yourself. + if (!support_nv4(ctx)) + { + emit_ARB1_opcode_ds(ctx, "RSQ"); // pre-nv4 implies ABS. + return; + } // if + + // we can optimize this to use nv2's |abs| construct in some cases. + if ( (ctx->source_args[0].src_mod == SRCMOD_NONE) || + (ctx->source_args[0].src_mod == SRCMOD_NEGATE) || + (ctx->source_args[0].src_mod == SRCMOD_ABSNEGATE) ) + ctx->source_args[0].src_mod = SRCMOD_ABS; + + char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); + char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); + + if (ctx->source_args[0].src_mod == SRCMOD_ABS) + output_line(ctx, "RSQ%s, %s;", dst, src0); + else + { + char buf[64]; allocate_ARB1_scratch_reg_name(ctx, buf, sizeof (buf)); + output_line(ctx, "ABS %s, %s;", buf, src0); + output_line(ctx, "RSQ%s, %s.x;", dst, buf); + } // else + + emit_ARB1_dest_modifiers(ctx); +} // emit_ARB1_RSQ + +EMIT_ARB1_OPCODE_DSS_FUNC(DP3) +EMIT_ARB1_OPCODE_DSS_FUNC(DP4) +EMIT_ARB1_OPCODE_DSS_FUNC(MIN) +EMIT_ARB1_OPCODE_DSS_FUNC(MAX) +EMIT_ARB1_OPCODE_DSS_FUNC(SLT) +EMIT_ARB1_OPCODE_DSS_FUNC(SGE) + +void emit_ARB1_EXP(Context *ctx) { emit_ARB1_opcode_ds(ctx, "EX2"); } + +static void arb1_log(Context *ctx, const char *opcode) +{ + // !!! FIXME: SRCMOD_NEGATE can be made into SRCMOD_ABS here, too + // we can optimize this to use nv2's |abs| construct in some cases. + if ( (ctx->source_args[0].src_mod == SRCMOD_NONE) || + (ctx->source_args[0].src_mod == SRCMOD_ABSNEGATE) ) + ctx->source_args[0].src_mod = SRCMOD_ABS; + + char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); + char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); + + if (ctx->source_args[0].src_mod == SRCMOD_ABS) + output_line(ctx, "%s%s, %s;", opcode, dst, src0); + else + { + char buf[64]; allocate_ARB1_scratch_reg_name(ctx, buf, sizeof (buf)); + output_line(ctx, "ABS %s, %s;", buf, src0); + output_line(ctx, "%s%s, %s.x;", opcode, dst, buf); + } // else + + emit_ARB1_dest_modifiers(ctx); +} // arb1_log + + +void emit_ARB1_LOG(Context *ctx) +{ + arb1_log(ctx, "LG2"); +} // emit_ARB1_LOG + + +EMIT_ARB1_OPCODE_DS_FUNC(LIT) +EMIT_ARB1_OPCODE_DSS_FUNC(DST) + +void emit_ARB1_LRP(Context *ctx) +{ + if (shader_is_pixel(ctx)) // fragment shaders have a matching LRP opcode. + emit_ARB1_opcode_dsss(ctx, "LRP"); + else + { + char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); + char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_ARB1_srcarg_string(ctx, 1, src1, sizeof (src1)); + char src2[64]; make_ARB1_srcarg_string(ctx, 2, src2, sizeof (src2)); + char buf[64]; allocate_ARB1_scratch_reg_name(ctx, buf, sizeof (buf)); + + // LRP is: dest = src2 + src0 * (src1 - src2) + output_line(ctx, "SUB %s, %s, %s;", buf, src1, src2); + output_line(ctx, "MAD%s, %s, %s, %s;", dst, buf, src0, src2); + emit_ARB1_dest_modifiers(ctx); + } // else +} // emit_ARB1_LRP + +EMIT_ARB1_OPCODE_DS_FUNC(FRC) + +static void arb1_MxXy(Context *ctx, const int x, const int y) +{ + DestArgInfo *dstarg = &ctx->dest_arg; + const int origmask = dstarg->writemask; + char src0[64]; + int i; + + make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); + + for (i = 0; i < y; i++) + { + char dst[64]; + char row[64]; + make_ARB1_srcarg_string(ctx, i + 1, row, sizeof (row)); + set_dstarg_writemask(dstarg, 1 << i); + make_ARB1_destarg_string(ctx, dst, sizeof (dst)); + output_line(ctx, "DP%d%s, %s, %s;", x, dst, src0, row); + } // for + + set_dstarg_writemask(dstarg, origmask); + emit_ARB1_dest_modifiers(ctx); +} // arb1_MxXy + +void emit_ARB1_M4X4(Context *ctx) { arb1_MxXy(ctx, 4, 4); } +void emit_ARB1_M4X3(Context *ctx) { arb1_MxXy(ctx, 4, 3); } +void emit_ARB1_M3X4(Context *ctx) { arb1_MxXy(ctx, 3, 4); } +void emit_ARB1_M3X3(Context *ctx) { arb1_MxXy(ctx, 3, 3); } +void emit_ARB1_M3X2(Context *ctx) { arb1_MxXy(ctx, 3, 2); } + +void emit_ARB1_CALL(Context *ctx) +{ + if (!support_nv2(ctx)) // no branching in stock ARB1. + { + failf(ctx, "branching unsupported in %s profile", ctx->profile->name); + return; + } // if + + char labelstr[64]; + get_ARB1_srcarg_varname(ctx, 0, labelstr, sizeof (labelstr)); + output_line(ctx, "CAL %s;", labelstr); +} // emit_ARB1_CALL + +void emit_ARB1_CALLNZ(Context *ctx) +{ + // !!! FIXME: if src1 is a constbool that's true, we can remove the + // !!! FIXME: if. If it's false, we can make this a no-op. + + if (!support_nv2(ctx)) // no branching in stock ARB1. + failf(ctx, "branching unsupported in %s profile", ctx->profile->name); + else + { + // !!! FIXME: double-check this. + char labelstr[64]; + char scratch[64]; + char src1[64]; + get_ARB1_srcarg_varname(ctx, 0, labelstr, sizeof (labelstr)); + get_ARB1_srcarg_varname(ctx, 1, src1, sizeof (src1)); + allocate_ARB1_scratch_reg_name(ctx, scratch, sizeof (scratch)); + output_line(ctx, "MOVC %s, %s;", scratch, src1); + output_line(ctx, "CAL %s (NE.x);", labelstr); + } // else +} // emit_ARB1_CALLNZ + +// !!! FIXME: needs BRA in nv2, LOOP in nv2 fragment progs, and REP in nv4. +EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(LOOP) + +void emit_ARB1_RET(Context *ctx) +{ + // don't fail() if no nv2...maybe we're just ending the mainline? + // if we're ending a LABEL that had no CALL, this would all be written + // to ctx->ignore anyhow, so this should be "safe" ... arb1 profile will + // just end up throwing all this code out. + if (support_nv2(ctx)) // no branching in stock ARB1. + output_line(ctx, "RET;"); + set_output(ctx, &ctx->mainline); // in case we were ignoring this function. +} // emit_ARB1_RET + + +EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(ENDLOOP) + +void emit_ARB1_LABEL(Context *ctx) +{ + if (!support_nv2(ctx)) // no branching in stock ARB1. + return; // don't fail()...maybe we never use it, but do fail in CALL. + + const int label = ctx->source_args[0].regnum; + RegisterList *reg = reglist_find(&ctx->used_registers, REG_TYPE_LABEL, label); + + // MSDN specs say CALL* has to come before the LABEL, so we know if we + // can ditch the entire function here as unused. + if (reg == NULL) + set_output(ctx, &ctx->ignore); // Func not used. Parse, but don't output. + + // !!! FIXME: it would be nice if we could determine if a function is + // !!! FIXME: only called once and, if so, forcibly inline it. + + //const char *uses_loopreg = ((reg) && (reg->misc == 1)) ? "int aL" : ""; + char labelstr[64]; + get_ARB1_srcarg_varname(ctx, 0, labelstr, sizeof (labelstr)); + output_line(ctx, "%s:", labelstr); +} // emit_ARB1_LABEL + + +void emit_ARB1_POW(Context *ctx) +{ + // we can optimize this to use nv2's |abs| construct in some cases. + if ( (ctx->source_args[0].src_mod == SRCMOD_NONE) || + (ctx->source_args[0].src_mod == SRCMOD_ABSNEGATE) ) + ctx->source_args[0].src_mod = SRCMOD_ABS; + + char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); + char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_ARB1_srcarg_string(ctx, 1, src1, sizeof (src1)); + + if (ctx->source_args[0].src_mod == SRCMOD_ABS) + output_line(ctx, "POW%s, %s, %s;", dst, src0, src1); + else + { + char buf[64]; allocate_ARB1_scratch_reg_name(ctx, buf, sizeof (buf)); + output_line(ctx, "ABS %s, %s;", buf, src0); + output_line(ctx, "POW%s, %s.x, %s;", dst, buf, src1); + } // else + + emit_ARB1_dest_modifiers(ctx); +} // emit_ARB1_POW + +void emit_ARB1_CRS(Context *ctx) { emit_ARB1_opcode_dss(ctx, "XPD"); } + +void emit_ARB1_SGN(Context *ctx) +{ + if (support_nv2(ctx)) + emit_ARB1_opcode_ds(ctx, "SSG"); + else + { + char dst[64]; + char src0[64]; + char scratch1[64]; + char scratch2[64]; + make_ARB1_destarg_string(ctx, dst, sizeof (dst)); + make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); + allocate_ARB1_scratch_reg_name(ctx, scratch1, sizeof (scratch1)); + allocate_ARB1_scratch_reg_name(ctx, scratch2, sizeof (scratch2)); + output_line(ctx, "SLT %s, %s, 0.0;", scratch1, src0); + output_line(ctx, "SLT %s, -%s, 0.0;", scratch2, src0); + output_line(ctx, "ADD%s -%s, %s;", dst, scratch1, scratch2); + emit_ARB1_dest_modifiers(ctx); + } // else +} // emit_ARB1_SGN + +EMIT_ARB1_OPCODE_DS_FUNC(ABS) + +void emit_ARB1_NRM(Context *ctx) +{ + // nv2 fragment programs (and anything nv4) have a real NRM. + if ( (support_nv4(ctx)) || ((support_nv2(ctx)) && (shader_is_pixel(ctx))) ) + emit_ARB1_opcode_ds(ctx, "NRM"); + else + { + char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); + char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); + char buf[64]; allocate_ARB1_scratch_reg_name(ctx, buf, sizeof (buf)); + output_line(ctx, "DP3 %s.w, %s, %s;", buf, src0, src0); + output_line(ctx, "RSQ %s.w, %s.w;", buf, buf); + output_line(ctx, "MUL%s, %s.w, %s;", dst, buf, src0); + emit_ARB1_dest_modifiers(ctx); + } // else +} // emit_ARB1_NRM + + +void emit_ARB1_SINCOS(Context *ctx) +{ + // we don't care about the temp registers that <= sm2 demands; ignore them. + const int mask = ctx->dest_arg.writemask; + + // arb1 fragment programs and everything nv4 have sin/cos/sincos opcodes. + if ((shader_is_pixel(ctx)) || (support_nv4(ctx))) + { + char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); + char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); + if (writemask_x(mask)) + output_line(ctx, "COS%s, %s;", dst, src0); + else if (writemask_y(mask)) + output_line(ctx, "SIN%s, %s;", dst, src0); + else if (writemask_xy(mask)) + output_line(ctx, "SCS%s, %s;", dst, src0); + } // if + + // nv2+ profiles have sin and cos opcodes. + else if (support_nv2(ctx)) + { + char dst[64]; get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); + char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); + if (writemask_x(mask)) + output_line(ctx, "COS %s.x, %s;", dst, src0); + else if (writemask_y(mask)) + output_line(ctx, "SIN %s.y, %s;", dst, src0); + else if (writemask_xy(mask)) + { + output_line(ctx, "SIN %s.x, %s;", dst, src0); + output_line(ctx, "COS %s.y, %s;", dst, src0); + } // else if + } // if + + else // big nasty. + { + char dst[64]; get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); + char src0[64]; get_ARB1_srcarg_varname(ctx, 0, src0, sizeof (src0)); + const int need_sin = (writemask_x(mask) || writemask_xy(mask)); + const int need_cos = (writemask_y(mask) || writemask_xy(mask)); + char scratch[64]; + + if (need_sin || need_cos) + allocate_ARB1_scratch_reg_name(ctx, scratch, sizeof (scratch)); + + // These sin() and cos() approximations originally found here: + // http://www.devmaster.net/forums/showthread.php?t=5784 + // + // const float B = 4.0f / M_PI; + // const float C = -4.0f / (M_PI * M_PI); + // float y = B * x + C * x * fabs(x); + // + // // optional better precision... + // const float P = 0.225f; + // y = P * (y * fabs(y) - y) + y; + // + // + // That first thing can be reduced to: + // const float y = ((1.2732395447351626861510701069801f * x) + + // ((-0.40528473456935108577551785283891f * x) * fabs(x))); + + if (need_sin) + { + // !!! FIXME: use SRCMOD_ABS here? + output_line(ctx, "ABS %s.x, %s.x;", dst, src0); + output_line(ctx, "MUL %s.x, %s.x, -0.40528473456935108577551785283891;", dst, dst); + output_line(ctx, "MUL %s.x, %s.x, 1.2732395447351626861510701069801;", scratch, src0); + output_line(ctx, "MAD %s.x, %s.x, %s.x, %s.x;", dst, dst, src0, scratch); + } // if + + // cosine is sin(x + M_PI/2), but you have to wrap x to pi: + // if (x+(M_PI/2) > M_PI) + // x -= 2 * M_PI; + // + // which is... + // if (x+(1.57079637050628662109375) > 3.1415927410125732421875) + // x += -6.283185482025146484375; + + if (need_cos) + { + output_line(ctx, "ADD %s.x, %s.x, 1.57079637050628662109375;", scratch, src0); + output_line(ctx, "SGE %s.y, %s.x, 3.1415927410125732421875;", scratch, scratch); + output_line(ctx, "MAD %s.x, %s.y, -6.283185482025146484375, %s.x;", scratch, scratch, scratch); + output_line(ctx, "ABS %s.x, %s.x;", dst, src0); + output_line(ctx, "MUL %s.x, %s.x, -0.40528473456935108577551785283891;", dst, dst); + output_line(ctx, "MUL %s.x, %s.x, 1.2732395447351626861510701069801;", scratch, src0); + output_line(ctx, "MAD %s.y, %s.x, %s.x, %s.x;", dst, dst, src0, scratch); + } // if + } // else + + // !!! FIXME: might not have done anything. Don't emit if we didn't. + if (!(ctx->isfail)) + emit_ARB1_dest_modifiers(ctx); +} // emit_ARB1_SINCOS + + +void emit_ARB1_REP(Context *ctx) +{ + char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); + + // nv2 fragment programs (and everything nv4) have a real REP. + if ( (support_nv4(ctx)) || ((support_nv2(ctx)) && (shader_is_pixel(ctx))) ) + output_line(ctx, "REP %s;", src0); + + else if (support_nv2(ctx)) + { + // no REP, but we can use branches. + char failbranch[32]; + char topbranch[32]; + const int toplabel = allocate_branch_label(ctx); + const int faillabel = allocate_branch_label(ctx); + get_ARB1_branch_label_name(ctx,faillabel,failbranch,sizeof(failbranch)); + get_ARB1_branch_label_name(ctx,toplabel,topbranch,sizeof(topbranch)); + + assert(((size_t) ctx->branch_labels_stack_index) < + STATICARRAYLEN(ctx->branch_labels_stack)-1); + + ctx->branch_labels_stack[ctx->branch_labels_stack_index++] = toplabel; + ctx->branch_labels_stack[ctx->branch_labels_stack_index++] = faillabel; + + char scratch[32]; + snprintf(scratch, sizeof (scratch), "rep%d", ctx->reps); + output_line(ctx, "MOVC %s.x, %s;", scratch, src0); + output_line(ctx, "BRA %s (LE.x);", failbranch); + output_line(ctx, "%s:", topbranch); + } // else if + + else // stock ARB1 has no branching. + { + fail(ctx, "branching unsupported in this profile"); + } // else +} // emit_ARB1_REP + + +void emit_ARB1_ENDREP(Context *ctx) +{ + // nv2 fragment programs (and everything nv4) have a real ENDREP. + if ( (support_nv4(ctx)) || ((support_nv2(ctx)) && (shader_is_pixel(ctx))) ) + output_line(ctx, "ENDREP;"); + + else if (support_nv2(ctx)) + { + // no ENDREP, but we can use branches. + assert(ctx->branch_labels_stack_index >= 2); + + char failbranch[32]; + char topbranch[32]; + const int faillabel = ctx->branch_labels_stack[--ctx->branch_labels_stack_index]; + const int toplabel = ctx->branch_labels_stack[--ctx->branch_labels_stack_index]; + get_ARB1_branch_label_name(ctx,faillabel,failbranch,sizeof(failbranch)); + get_ARB1_branch_label_name(ctx,toplabel,topbranch,sizeof(topbranch)); + + char scratch[32]; + snprintf(scratch, sizeof (scratch), "rep%d", ctx->reps); + output_line(ctx, "SUBC %s.x, %s.x, 1.0;", scratch, scratch); + output_line(ctx, "BRA %s (GT.x);", topbranch); + output_line(ctx, "%s:", failbranch); + } // else if + + else // stock ARB1 has no branching. + { + fail(ctx, "branching unsupported in this profile"); + } // else +} // emit_ARB1_ENDREP + + +void nv2_if(Context *ctx) +{ + // The condition code register MUST be set up before this! + // nv2 fragment programs (and everything nv4) have a real IF. + if ( (support_nv4(ctx)) || (shader_is_pixel(ctx)) ) + output_line(ctx, "IF EQ.x;"); + else + { + // there's no IF construct, but we can use a branch to a label. + char failbranch[32]; + const int label = allocate_branch_label(ctx); + get_ARB1_branch_label_name(ctx, label, failbranch, sizeof (failbranch)); + + assert(((size_t) ctx->branch_labels_stack_index) + < STATICARRAYLEN(ctx->branch_labels_stack)); + + ctx->branch_labels_stack[ctx->branch_labels_stack_index++] = label; + + // !!! FIXME: should this be NE? (EQ would jump to the ELSE for the IF condition, right?). + output_line(ctx, "BRA %s (EQ.x);", failbranch); + } // else +} // nv2_if + + +void emit_ARB1_IF(Context *ctx) +{ + if (support_nv2(ctx)) + { + char buf[64]; allocate_ARB1_scratch_reg_name(ctx, buf, sizeof (buf)); + char src0[64]; get_ARB1_srcarg_varname(ctx, 0, src0, sizeof (src0)); + output_line(ctx, "MOVC %s.x, %s;", buf, src0); + nv2_if(ctx); + } // if + + else // stock ARB1 has no branching. + { + failf(ctx, "branching unsupported in %s profile", ctx->profile->name); + } // else +} // emit_ARB1_IF + + +void emit_ARB1_ELSE(Context *ctx) +{ + // nv2 fragment programs (and everything nv4) have a real ELSE. + if ( (support_nv4(ctx)) || ((support_nv2(ctx)) && (shader_is_pixel(ctx))) ) + output_line(ctx, "ELSE;"); + + else if (support_nv2(ctx)) + { + // there's no ELSE construct, but we can use a branch to a label. + assert(ctx->branch_labels_stack_index > 0); + + // At the end of the IF block, unconditionally jump to the ENDIF. + const int endlabel = allocate_branch_label(ctx); + char endbranch[32]; + get_ARB1_branch_label_name(ctx,endlabel,endbranch,sizeof (endbranch)); + output_line(ctx, "BRA %s;", endbranch); + + // Now mark the ELSE section with a lable. + const int elselabel = ctx->branch_labels_stack[ctx->branch_labels_stack_index-1]; + char elsebranch[32]; + get_ARB1_branch_label_name(ctx,elselabel,elsebranch,sizeof(elsebranch)); + output_line(ctx, "%s:", elsebranch); + + // Replace the ELSE label with the ENDIF on the label stack. + ctx->branch_labels_stack[ctx->branch_labels_stack_index-1] = endlabel; + } // else if + + else // stock ARB1 has no branching. + { + failf(ctx, "branching unsupported in %s profile", ctx->profile->name); + } // else +} // emit_ARB1_ELSE + + +void emit_ARB1_ENDIF(Context *ctx) +{ + // nv2 fragment programs (and everything nv4) have a real ENDIF. + if ( (support_nv4(ctx)) || ((support_nv2(ctx)) && (shader_is_pixel(ctx))) ) + output_line(ctx, "ENDIF;"); + + else if (support_nv2(ctx)) + { + // there's no ENDIF construct, but we can use a branch to a label. + assert(ctx->branch_labels_stack_index > 0); + const int endlabel = ctx->branch_labels_stack[--ctx->branch_labels_stack_index]; + char endbranch[32]; + get_ARB1_branch_label_name(ctx,endlabel,endbranch,sizeof (endbranch)); + output_line(ctx, "%s:", endbranch); + } // if + + else // stock ARB1 has no branching. + { + failf(ctx, "branching unsupported in %s profile", ctx->profile->name); + } // else +} // emit_ARB1_ENDIF + + +void emit_ARB1_BREAK(Context *ctx) +{ + // nv2 fragment programs (and everything nv4) have a real BREAK. + if ( (support_nv4(ctx)) || ((support_nv2(ctx)) && (shader_is_pixel(ctx))) ) + output_line(ctx, "BRK;"); + + else if (support_nv2(ctx)) + { + // no BREAK, but we can use branches. + assert(ctx->branch_labels_stack_index >= 2); + const int faillabel = ctx->branch_labels_stack[ctx->branch_labels_stack_index]; + char failbranch[32]; + get_ARB1_branch_label_name(ctx,faillabel,failbranch,sizeof(failbranch)); + output_line(ctx, "BRA %s;", failbranch); + } // else if + + else // stock ARB1 has no branching. + { + failf(ctx, "branching unsupported in %s profile", ctx->profile->name); + } // else +} // emit_ARB1_BREAK + + +void emit_ARB1_MOVA(Context *ctx) +{ + // nv2 and nv3 can use the ARR opcode. + // But nv4 removed ARR (and ADDRESS registers!). Just ROUND to an INT. + if (support_nv4(ctx)) + emit_ARB1_opcode_ds(ctx, "ROUND.S"); // !!! FIXME: don't use a modifier here. + else if ((support_nv2(ctx)) || (support_nv3(ctx))) + emit_ARB1_opcode_ds(ctx, "ARR"); + else + { + char src0[64]; + char scratch[64]; + char addr[32]; + + make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); + allocate_ARB1_scratch_reg_name(ctx, scratch, sizeof (scratch)); + snprintf(addr, sizeof (addr), "addr%d", ctx->dest_arg.regnum); + + // !!! FIXME: we can optimize this if src_mod is ABS or ABSNEGATE. + + // ARL uses floor(), but D3D expects round-to-nearest. + // There is probably a more efficient way to do this. + if (shader_is_pixel(ctx)) // CMP only exists in fragment programs. :/ + output_line(ctx, "CMP %s, %s, -1.0, 1.0;", scratch, src0); + else + { + output_line(ctx, "SLT %s, %s, 0.0;", scratch, src0); + output_line(ctx, "MAD %s, %s, -2.0, 1.0;", scratch, scratch); + } // else + + output_line(ctx, "ABS %s, %s;", addr, src0); + output_line(ctx, "ADD %s, %s, 0.5;", addr, addr); + output_line(ctx, "FLR %s, %s;", addr, addr); + output_line(ctx, "MUL %s, %s, %s;", addr, addr, scratch); + + // we don't handle these right now, since emit_ARB1_dest_modifiers(ctx) + // wants to look at dest_arg, not our temp register. + assert(ctx->dest_arg.result_mod == 0); + assert(ctx->dest_arg.result_shift == 0); + + // we assign to the actual address register as needed. + ctx->last_address_reg_component = -1; + } // else +} // emit_ARB1_MOVA + + +void emit_ARB1_TEXKILL(Context *ctx) +{ + // d3d kills on xyz, arb1 kills on xyzw. Fix the swizzle. + // We just map the x component to w. If it's negative, the fragment + // would discard anyhow, otherwise, it'll pass through okay. This saves + // us a temp register. + char dst[64]; + get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); + output_line(ctx, "KIL %s.xyzx;", dst); +} // emit_ARB1_TEXKILL + +static void arb1_texbem(Context *ctx, const int luminance) +{ + // !!! FIXME: this code counts on the register not having swizzles, etc. + const int stage = ctx->dest_arg.regnum; + char dst[64]; get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); + char src[64]; get_ARB1_srcarg_varname(ctx, 0, src, sizeof (src)); + char tmp[64]; allocate_ARB1_scratch_reg_name(ctx, tmp, sizeof (tmp)); + char sampler[64]; + get_ARB1_varname_in_buf(ctx, REG_TYPE_SAMPLER, stage, + sampler, sizeof (sampler)); + + output_line(ctx, "MUL %s, %s_texbem.xzyw, %s.xyxy;", tmp, sampler, src); + output_line(ctx, "ADD %s.xy, %s.xzxx, %s.ywxx;", tmp, tmp, tmp); + output_line(ctx, "ADD %s.xy, %s, %s;", tmp, tmp, dst); + output_line(ctx, "TEX %s, %s, texture[%d], 2D;", dst, tmp, stage); + + if (luminance) // TEXBEML, not just TEXBEM? + { + output_line(ctx, "MAD %s, %s.zzzz, %s_texbeml.xxxx, %s_texbeml.yyyy;", + tmp, src, sampler, sampler); + output_line(ctx, "MUL %s, %s, %s;", dst, dst, tmp); + } // if + + emit_ARB1_dest_modifiers(ctx); +} // arb1_texbem + +void emit_ARB1_TEXBEM(Context *ctx) +{ + arb1_texbem(ctx, 0); +} // emit_ARB1_TEXBEM + +void emit_ARB1_TEXBEML(Context *ctx) +{ + arb1_texbem(ctx, 1); +} // emit_ARB1_TEXBEML + +EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2AR) +EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2GB) + + +void emit_ARB1_TEXM3X2PAD(Context *ctx) +{ + // no-op ... work happens in emit_ARB1_TEXM3X2TEX(). +} // emit_ARB1_TEXM3X2PAD + +void emit_ARB1_TEXM3X2TEX(Context *ctx) +{ + if (ctx->texm3x2pad_src0 == -1) + return; + + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + + // !!! FIXME: this code counts on the register not having swizzles, etc. + const int stage = ctx->dest_arg.regnum; + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x2pad_src0, + src0, sizeof (src0)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x2pad_dst0, + src1, sizeof (src1)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src2, sizeof (src2)); + get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); + + output_line(ctx, "DP3 %s.y, %s, %s;", dst, src2, dst); + output_line(ctx, "DP3 %s.x, %s, %s;", dst, src0, src1); + output_line(ctx, "TEX %s, %s, texture[%d], 2D;", dst, dst, stage); + emit_ARB1_dest_modifiers(ctx); +} // emit_ARB1_TEXM3X2TEX + + +void emit_ARB1_TEXM3X3PAD(Context *ctx) +{ + // no-op ... work happens in emit_ARB1_TEXM3X3*(). +} // emit_ARB1_TEXM3X3PAD + + +void emit_ARB1_TEXM3X3TEX(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char src3[64]; + char src4[64]; + + // !!! FIXME: this code counts on the register not having swizzles, etc. + const int stage = ctx->dest_arg.regnum; + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, + src0, sizeof (src0)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, + src1, sizeof (src1)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, + src2, sizeof (src2)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, + src3, sizeof (src3)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src4, sizeof (src4)); + get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); + + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, stage); + const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); + const char *ttypestr = (ttype == TEXTURE_TYPE_CUBE) ? "CUBE" : "3D"; + + output_line(ctx, "DP3 %s.z, %s, %s;", dst, dst, src4); + output_line(ctx, "DP3 %s.x, %s, %s;", dst, src0, src1); + output_line(ctx, "DP3 %s.y, %s, %s;", dst, src2, src3); + output_line(ctx, "TEX %s, %s, texture[%d], %s;", dst, dst, stage, ttypestr); + emit_ARB1_dest_modifiers(ctx); +} // emit_ARB1_TEXM3X3TEX + +void emit_ARB1_TEXM3X3SPEC(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char src3[64]; + char src4[64]; + char src5[64]; + char tmp[64]; + char tmp2[64]; + + // !!! FIXME: this code counts on the register not having swizzles, etc. + const int stage = ctx->dest_arg.regnum; + allocate_ARB1_scratch_reg_name(ctx, tmp, sizeof (tmp)); + allocate_ARB1_scratch_reg_name(ctx, tmp2, sizeof (tmp2)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, + src0, sizeof (src0)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, + src1, sizeof (src1)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, + src2, sizeof (src2)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, + src3, sizeof (src3)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src4, sizeof (src4)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[1].regnum, + src5, sizeof (src5)); + get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); + + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, stage); + const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); + const char *ttypestr = (ttype == TEXTURE_TYPE_CUBE) ? "CUBE" : "3D"; + + output_line(ctx, "DP3 %s.z, %s, %s;", dst, dst, src4); + output_line(ctx, "DP3 %s.x, %s, %s;", dst, src0, src1); + output_line(ctx, "DP3 %s.y, %s, %s;", dst, src2, src3); + output_line(ctx, "MUL %s, %s, %s;", tmp, dst, dst); // normal * normal + output_line(ctx, "MUL %s, %s, %s;", tmp2, dst, src5); // normal * eyeray + + // !!! FIXME: This is goofy. There's got to be a way to do vector-wide + // !!! FIXME: divides or reciprocals...right? + output_line(ctx, "RCP %s.x, %s.x;", tmp2, tmp2); + output_line(ctx, "RCP %s.y, %s.y;", tmp2, tmp2); + output_line(ctx, "RCP %s.z, %s.z;", tmp2, tmp2); + output_line(ctx, "RCP %s.w, %s.w;", tmp2, tmp2); + output_line(ctx, "MUL %s, %s, %s;", tmp, tmp, tmp2); + + output_line(ctx, "MUL %s, %s, { 2.0, 2.0, 2.0, 2.0 };", tmp, tmp); + output_line(ctx, "MAD %s, %s, %s, -%s;", tmp, tmp, dst, src5); + output_line(ctx, "TEX %s, %s, texture[%d], %s;", dst, tmp, stage, ttypestr); + emit_ARB1_dest_modifiers(ctx); +} // emit_ARB1_TEXM3X3SPEC + +void emit_ARB1_TEXM3X3VSPEC(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char src3[64]; + char src4[64]; + char tmp[64]; + char tmp2[64]; + char tmp3[64]; + + // !!! FIXME: this code counts on the register not having swizzles, etc. + const int stage = ctx->dest_arg.regnum; + allocate_ARB1_scratch_reg_name(ctx, tmp, sizeof (tmp)); + allocate_ARB1_scratch_reg_name(ctx, tmp2, sizeof (tmp2)); + allocate_ARB1_scratch_reg_name(ctx, tmp3, sizeof (tmp3)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, + src0, sizeof (src0)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, + src1, sizeof (src1)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, + src2, sizeof (src2)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, + src3, sizeof (src3)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src4, sizeof (src4)); + get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); + + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, stage); + const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); + const char *ttypestr = (ttype == TEXTURE_TYPE_CUBE) ? "CUBE" : "3D"; + + output_line(ctx, "MOV %s.x, %s.w;", tmp3, src0); + output_line(ctx, "MOV %s.y, %s.w;", tmp3, src2); + output_line(ctx, "MOV %s.z, %s.w;", tmp3, dst); + output_line(ctx, "DP3 %s.z, %s, %s;", dst, dst, src4); + output_line(ctx, "DP3 %s.x, %s, %s;", dst, src0, src1); + output_line(ctx, "DP3 %s.y, %s, %s;", dst, src2, src3); + output_line(ctx, "MUL %s, %s, %s;", tmp, dst, dst); // normal * normal + output_line(ctx, "MUL %s, %s, %s;", tmp2, dst, tmp3); // normal * eyeray + + // !!! FIXME: This is goofy. There's got to be a way to do vector-wide + // !!! FIXME: divides or reciprocals...right? + output_line(ctx, "RCP %s.x, %s.x;", tmp2, tmp2); + output_line(ctx, "RCP %s.y, %s.y;", tmp2, tmp2); + output_line(ctx, "RCP %s.z, %s.z;", tmp2, tmp2); + output_line(ctx, "RCP %s.w, %s.w;", tmp2, tmp2); + output_line(ctx, "MUL %s, %s, %s;", tmp, tmp, tmp2); + + output_line(ctx, "MUL %s, %s, { 2.0, 2.0, 2.0, 2.0 };", tmp, tmp); + output_line(ctx, "MAD %s, %s, %s, -%s;", tmp, tmp, dst, tmp3); + output_line(ctx, "TEX %s, %s, texture[%d], %s;", dst, tmp, stage, ttypestr); + emit_ARB1_dest_modifiers(ctx); +} // emit_ARB1_TEXM3X3VSPEC + +void emit_ARB1_EXPP(Context *ctx) { emit_ARB1_opcode_ds(ctx, "EX2"); } +void emit_ARB1_LOGP(Context *ctx) { arb1_log(ctx, "LG2"); } + +void emit_ARB1_CND(Context *ctx) +{ + char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); + char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_ARB1_srcarg_string(ctx, 1, src1, sizeof (src1)); + char src2[64]; make_ARB1_srcarg_string(ctx, 2, src2, sizeof (src2)); + char tmp[64]; allocate_ARB1_scratch_reg_name(ctx, tmp, sizeof (tmp)); + + // CND compares against 0.5, but we need to compare against 0.0... + // ...subtract to make up the difference. + output_line(ctx, "SUB %s, %s, { 0.5, 0.5, 0.5, 0.5 };", tmp, src0); + // D3D tests (src0 >= 0.0), but ARB1 tests (src0 < 0.0) ... so just + // switch src1 and src2 to get the same results. + output_line(ctx, "CMP%s, %s, %s, %s;", dst, tmp, src2, src1); + emit_ARB1_dest_modifiers(ctx); +} // emit_ARB1_CND + +EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2RGB) +EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(TEXDP3TEX) +EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(TEXM3X2DEPTH) +EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(TEXDP3) + +void emit_ARB1_TEXM3X3(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char src3[64]; + char src4[64]; + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, + src0, sizeof (src0)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, + src1, sizeof (src1)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, + src2, sizeof (src2)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, + src3, sizeof (src3)); + get_ARB1_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src4, sizeof (src4)); + get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); + + output_line(ctx, "DP3 %s.z, %s, %s;", dst, dst, src4); + output_line(ctx, "DP3 %s.x, %s, %s;", dst, src0, src1); + output_line(ctx, "DP3 %s.y, %s, %s;", dst, src2, src3); + output_line(ctx, "MOV %s.w, { 1.0, 1.0, 1.0, 1.0 };", dst); + emit_ARB1_dest_modifiers(ctx); +} // emit_ARB1_TEXM3X3 + +EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(TEXDEPTH) + +void emit_ARB1_CMP(Context *ctx) +{ + char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); + char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_ARB1_srcarg_string(ctx, 1, src1, sizeof (src1)); + char src2[64]; make_ARB1_srcarg_string(ctx, 2, src2, sizeof (src2)); + // D3D tests (src0 >= 0.0), but ARB1 tests (src0 < 0.0) ... so just + // switch src1 and src2 to get the same results. + output_line(ctx, "CMP%s, %s, %s, %s;", dst, src0, src2, src1); + emit_ARB1_dest_modifiers(ctx); +} // emit_ARB1_CMP + +EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(BEM) + + +void emit_ARB1_DP2ADD(Context *ctx) +{ + if (support_nv4(ctx)) // nv4 has a built-in equivalent to DP2ADD. + emit_ARB1_opcode_dsss(ctx, "DP2A"); + else + { + char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); + char src0[64]; make_ARB1_srcarg_string(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_ARB1_srcarg_string(ctx, 1, src1, sizeof (src1)); + char src2[64]; make_ARB1_srcarg_string(ctx, 2, src2, sizeof (src2)); + char scratch[64]; + + // DP2ADD is: + // dst = (src0.r * src1.r) + (src0.g * src1.g) + src2.replicate_swiz + allocate_ARB1_scratch_reg_name(ctx, scratch, sizeof (scratch)); + output_line(ctx, "MUL %s, %s, %s;", scratch, src0, src1); + output_line(ctx, "ADD %s, %s.x, %s.y;", scratch, scratch, scratch); + output_line(ctx, "ADD%s, %s.x, %s;", dst, scratch, src2); + emit_ARB1_dest_modifiers(ctx); + } // else +} // emit_ARB1_DP2ADD + + +void emit_ARB1_DSX(Context *ctx) +{ + if (support_nv2(ctx)) // nv2 has a built-in equivalent to DSX. + emit_ARB1_opcode_ds(ctx, "DDX"); + else + failf(ctx, "DSX unsupported in %s profile", ctx->profile->name); +} // emit_ARB1_DSX + + +void emit_ARB1_DSY(Context *ctx) +{ + if (support_nv2(ctx)) // nv2 has a built-in equivalent to DSY. + emit_ARB1_opcode_ds(ctx, "DDY"); + else + failf(ctx, "DSY unsupported in %s profile", ctx->profile->name); +} // emit_ARB1_DSY + +static void arb1_texld(Context *ctx, const char *opcode, const int texldd) +{ + // !!! FIXME: Hack: "TEXH" is invalid in nv4. Fix this more cleanly. + if ((ctx->dest_arg.result_mod & MOD_PP) && (support_nv4(ctx))) + ctx->dest_arg.result_mod &= ~MOD_PP; + + char dst[64]; make_ARB1_destarg_string(ctx, dst, sizeof (dst)); + + const int sm1 = !shader_version_atleast(ctx, 1, 4); + const int regnum = sm1 ? ctx->dest_arg.regnum : ctx->source_args[1].regnum; + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, regnum); + + const char *ttype = NULL; + char src0[64]; + if (sm1) + get_ARB1_destarg_varname(ctx, src0, sizeof (src0)); + else + get_ARB1_srcarg_varname(ctx, 0, src0, sizeof (src0)); + //char src1[64]; get_ARB1_srcarg_varname(ctx, 1, src1, sizeof (src1)); // !!! FIXME: SRC_MOD? + + char src2[64] = { 0 }; + char src3[64] = { 0 }; + + if (texldd) + { + make_ARB1_srcarg_string(ctx, 2, src2, sizeof (src2)); + make_ARB1_srcarg_string(ctx, 3, src3, sizeof (src3)); + } // if + + // !!! FIXME: this should be in state_TEXLD, not in the arb1/glsl emitters. + if (sreg == NULL) + { + fail(ctx, "TEXLD using undeclared sampler"); + return; + } // if + + // SM1 only specifies dst, so don't check swizzle there. + if ( !sm1 && (!no_swizzle(ctx->source_args[1].swizzle)) ) + { + // !!! FIXME: does this ever actually happen? + fail(ctx, "BUG: can't handle TEXLD with sampler swizzle at the moment"); + } // if + + switch ((const TextureType) sreg->index) + { + case TEXTURE_TYPE_2D: ttype = "2D"; break; // !!! FIXME: "RECT"? + case TEXTURE_TYPE_CUBE: ttype = "CUBE"; break; + case TEXTURE_TYPE_VOLUME: ttype = "3D"; break; + default: fail(ctx, "unknown texture type"); return; + } // switch + + if (texldd) + { + output_line(ctx, "%s%s, %s, %s, %s, texture[%d], %s;", opcode, dst, + src0, src2, src3, regnum, ttype); + } // if + else + { + output_line(ctx, "%s%s, %s, texture[%d], %s;", opcode, dst, src0, + regnum, ttype); + } // else +} // arb1_texld + + +void emit_ARB1_TEXLDD(Context *ctx) +{ + // With GL_NV_fragment_program2, we can use the TXD opcode. + // In stock arb1, we can settle for a standard texld, which isn't + // perfect, but oh well. + if (support_nv2(ctx)) + arb1_texld(ctx, "TXD", 1); + else + arb1_texld(ctx, "TEX", 0); +} // emit_ARB1_TEXLDD + + +void emit_ARB1_TEXLDL(Context *ctx) +{ + if ((shader_is_vertex(ctx)) && (!support_nv3(ctx))) + { + failf(ctx, "Vertex shader TEXLDL unsupported in %s profile", + ctx->profile->name); + return; + } // if + + else if ((shader_is_pixel(ctx)) && (!support_nv2(ctx))) + { + failf(ctx, "Pixel shader TEXLDL unsupported in %s profile", + ctx->profile->name); + return; + } // if + + // !!! FIXME: this doesn't map exactly to TEXLDL. Review this. + arb1_texld(ctx, "TXL", 0); +} // emit_ARB1_TEXLDL + + +EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(BREAKP) +EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(BREAKC) + +void emit_ARB1_IFC(Context *ctx) +{ + if (support_nv2(ctx)) + { + const char *comps[] = { + "", "SGTC", "SEQC", "SGEC", "SGTC", "SNEC", "SLEC" + }; + + if (ctx->instruction_controls >= STATICARRAYLEN(comps)) + { + fail(ctx, "unknown comparison control"); + return; + } // if + + char src0[64]; + char src1[64]; + char scratch[64]; + + const char *comp = comps[ctx->instruction_controls]; + get_ARB1_srcarg_varname(ctx, 0, src0, sizeof (src0)); + get_ARB1_srcarg_varname(ctx, 1, src1, sizeof (src1)); + allocate_ARB1_scratch_reg_name(ctx, scratch, sizeof (scratch)); + output_line(ctx, "%s %s.x, %s, %s;", comp, scratch, src0, src1); + nv2_if(ctx); + } // if + + else // stock ARB1 has no branching. + { + failf(ctx, "branching unsupported in %s profile", ctx->profile->name); + } // else +} // emit_ARB1_IFC + + +EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(SETP) + +void emit_ARB1_DEF(Context *ctx) +{ + const float *val = (const float *) ctx->dwords; // !!! FIXME: could be int? + char dst[64]; get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); + char val0[32]; floatstr(ctx, val0, sizeof (val0), val[0], 1); + char val1[32]; floatstr(ctx, val1, sizeof (val1), val[1], 1); + char val2[32]; floatstr(ctx, val2, sizeof (val2), val[2], 1); + char val3[32]; floatstr(ctx, val3, sizeof (val3), val[3], 1); + + push_output(ctx, &ctx->globals); + output_line(ctx, "PARAM %s = { %s, %s, %s, %s };", + dst, val0, val1, val2, val3); + pop_output(ctx); +} // emit_ARB1_DEF + +void emit_ARB1_DEFI(Context *ctx) +{ + char dst[64]; get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); + const int32 *x = (const int32 *) ctx->dwords; + push_output(ctx, &ctx->globals); + output_line(ctx, "PARAM %s = { %d, %d, %d, %d };", + dst, (int) x[0], (int) x[1], (int) x[2], (int) x[3]); + pop_output(ctx); +} // emit_ARB1_DEFI + +void emit_ARB1_DEFB(Context *ctx) +{ + char dst[64]; get_ARB1_destarg_varname(ctx, dst, sizeof (dst)); + push_output(ctx, &ctx->globals); + output_line(ctx, "PARAM %s = %d;", dst, ctx->dwords[0] ? 1 : 0); + pop_output(ctx); +} // emit_ARB1_DEFB + +void emit_ARB1_DCL(Context *ctx) +{ + // no-op. We do this in our emit_attribute() and emit_uniform(). +} // emit_ARB1_DCL + +EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC(TEXCRD) + +void emit_ARB1_TEXLD(Context *ctx) +{ + if (!shader_version_atleast(ctx, 1, 4)) + { + arb1_texld(ctx, "TEX", 0); + return; + } // if + + else if (!shader_version_atleast(ctx, 2, 0)) + { + // ps_1_4 is different, too! + fail(ctx, "TEXLD == Shader Model 1.4 unimplemented."); // !!! FIXME + return; + } // if + + // !!! FIXME: do texldb and texldp map between OpenGL and D3D correctly? + if (ctx->instruction_controls == CONTROL_TEXLD) + arb1_texld(ctx, "TEX", 0); + else if (ctx->instruction_controls == CONTROL_TEXLDP) + arb1_texld(ctx, "TXP", 0); + else if (ctx->instruction_controls == CONTROL_TEXLDB) + arb1_texld(ctx, "TXB", 0); +} // emit_ARB1_TEXLD + +#undef EMIT_ARB1_OPCODE_FUNC +#undef EMIT_ARB1_OPCODE_D_FUNC +#undef EMIT_ARB1_OPCODE_S_FUNC +#undef EMIT_ARB1_OPCODE_SS_FUNC +#undef EMIT_ARB1_OPCODE_DS_FUNC +#undef EMIT_ARB1_OPCODE_DSS_FUNC +#undef EMIT_ARB1_OPCODE_DSSS_FUNC +#undef EMIT_ARB1_OPCODE_DSSSS_FUNC +#undef EMIT_ARB1_OPCODE_UNIMPLEMENTED_FUNC + +#endif // SUPPORT_PROFILE_ARB1 + +#pragma GCC visibility pop diff --git a/mojoshader/profiles/mojoshader_profile_bytecode.c b/mojoshader/profiles/mojoshader_profile_bytecode.c new file mode 100644 index 0000000..5b867e5 --- /dev/null +++ b/mojoshader/profiles/mojoshader_profile_bytecode.c @@ -0,0 +1,152 @@ +/** + * MojoShader; generate shader programs from bytecode of compiled + * Direct3D shaders. + * + * Please see the file LICENSE.txt in the source's root directory. + * + * This file written by Ryan C. Gordon. + */ + +#define __MOJOSHADER_INTERNAL__ 1 +#include "mojoshader_profile.h" + +#pragma GCC visibility push(hidden) + +#if SUPPORT_PROFILE_BYTECODE + +void emit_BYTECODE_start(Context *ctx, const char *profilestr) +{ + ctx->ignores_ctab = 1; +} // emit_BYTECODE_start + +void emit_BYTECODE_finalize(Context *ctx) +{ + // just copy the whole token stream and make all other emitters no-ops. + if (set_output(ctx, &ctx->mainline)) + { + const size_t len = ((size_t) (ctx->tokens - ctx->orig_tokens)) * sizeof (uint32); + buffer_append(ctx->mainline, (const char *) ctx->orig_tokens, len); + } // if +} // emit_BYTECODE_finalize + +void emit_BYTECODE_end(Context *ctx) {} +void emit_BYTECODE_phase(Context *ctx) {} +void emit_BYTECODE_global(Context *ctx, RegisterType t, int n) {} +void emit_BYTECODE_array(Context *ctx, VariableList *var) {} +void emit_BYTECODE_sampler(Context *c, int s, TextureType t, int tb) {} +void emit_BYTECODE_const_array(Context *ctx, const ConstantsList *c, + int base, int size) {} +void emit_BYTECODE_uniform(Context *ctx, RegisterType t, int n, + const VariableList *var) {} +void emit_BYTECODE_attribute(Context *ctx, RegisterType t, int n, + MOJOSHADER_usage u, int i, int w, + int f) {} + +const char *get_BYTECODE_varname(Context *ctx, RegisterType rt, int regnum) +{ + char regnum_str[16]; + const char *regtype_str = get_D3D_register_string(ctx, rt, regnum, + regnum_str, sizeof (regnum_str)); + char buf[64]; + snprintf(buf, sizeof (buf), "%s%s", regtype_str, regnum_str); + return StrDup(ctx, buf); +} // get_BYTECODE_varname + +const char *get_BYTECODE_const_array_varname(Context *ctx, int base, int size) +{ + char buf[64]; + snprintf(buf, sizeof (buf), "c_array_%d_%d", base, size); + return StrDup(ctx, buf); +} // get_BYTECODE_const_array_varname + +#define EMIT_BYTECODE_OPCODE_FUNC(op) \ + void emit_BYTECODE_##op(Context *ctx) {} + +EMIT_BYTECODE_OPCODE_FUNC(RESERVED) +EMIT_BYTECODE_OPCODE_FUNC(NOP) +EMIT_BYTECODE_OPCODE_FUNC(MOV) +EMIT_BYTECODE_OPCODE_FUNC(ADD) +EMIT_BYTECODE_OPCODE_FUNC(SUB) +EMIT_BYTECODE_OPCODE_FUNC(MAD) +EMIT_BYTECODE_OPCODE_FUNC(MUL) +EMIT_BYTECODE_OPCODE_FUNC(RCP) +EMIT_BYTECODE_OPCODE_FUNC(RSQ) +EMIT_BYTECODE_OPCODE_FUNC(DP3) +EMIT_BYTECODE_OPCODE_FUNC(DP4) +EMIT_BYTECODE_OPCODE_FUNC(MIN) +EMIT_BYTECODE_OPCODE_FUNC(MAX) +EMIT_BYTECODE_OPCODE_FUNC(SLT) +EMIT_BYTECODE_OPCODE_FUNC(SGE) +EMIT_BYTECODE_OPCODE_FUNC(EXP) +EMIT_BYTECODE_OPCODE_FUNC(LOG) +EMIT_BYTECODE_OPCODE_FUNC(LIT) +EMIT_BYTECODE_OPCODE_FUNC(DST) +EMIT_BYTECODE_OPCODE_FUNC(LRP) +EMIT_BYTECODE_OPCODE_FUNC(FRC) +EMIT_BYTECODE_OPCODE_FUNC(M4X4) +EMIT_BYTECODE_OPCODE_FUNC(M4X3) +EMIT_BYTECODE_OPCODE_FUNC(M3X4) +EMIT_BYTECODE_OPCODE_FUNC(M3X3) +EMIT_BYTECODE_OPCODE_FUNC(M3X2) +EMIT_BYTECODE_OPCODE_FUNC(CALL) +EMIT_BYTECODE_OPCODE_FUNC(CALLNZ) +EMIT_BYTECODE_OPCODE_FUNC(LOOP) +EMIT_BYTECODE_OPCODE_FUNC(RET) +EMIT_BYTECODE_OPCODE_FUNC(ENDLOOP) +EMIT_BYTECODE_OPCODE_FUNC(LABEL) +EMIT_BYTECODE_OPCODE_FUNC(POW) +EMIT_BYTECODE_OPCODE_FUNC(CRS) +EMIT_BYTECODE_OPCODE_FUNC(SGN) +EMIT_BYTECODE_OPCODE_FUNC(ABS) +EMIT_BYTECODE_OPCODE_FUNC(NRM) +EMIT_BYTECODE_OPCODE_FUNC(SINCOS) +EMIT_BYTECODE_OPCODE_FUNC(REP) +EMIT_BYTECODE_OPCODE_FUNC(ENDREP) +EMIT_BYTECODE_OPCODE_FUNC(IF) +EMIT_BYTECODE_OPCODE_FUNC(ELSE) +EMIT_BYTECODE_OPCODE_FUNC(ENDIF) +EMIT_BYTECODE_OPCODE_FUNC(BREAK) +EMIT_BYTECODE_OPCODE_FUNC(MOVA) +EMIT_BYTECODE_OPCODE_FUNC(TEXKILL) +EMIT_BYTECODE_OPCODE_FUNC(TEXBEM) +EMIT_BYTECODE_OPCODE_FUNC(TEXBEML) +EMIT_BYTECODE_OPCODE_FUNC(TEXREG2AR) +EMIT_BYTECODE_OPCODE_FUNC(TEXREG2GB) +EMIT_BYTECODE_OPCODE_FUNC(TEXM3X2PAD) +EMIT_BYTECODE_OPCODE_FUNC(TEXM3X2TEX) +EMIT_BYTECODE_OPCODE_FUNC(TEXM3X3PAD) +EMIT_BYTECODE_OPCODE_FUNC(TEXM3X3TEX) +EMIT_BYTECODE_OPCODE_FUNC(TEXM3X3SPEC) +EMIT_BYTECODE_OPCODE_FUNC(TEXM3X3VSPEC) +EMIT_BYTECODE_OPCODE_FUNC(EXPP) +EMIT_BYTECODE_OPCODE_FUNC(LOGP) +EMIT_BYTECODE_OPCODE_FUNC(CND) +EMIT_BYTECODE_OPCODE_FUNC(TEXREG2RGB) +EMIT_BYTECODE_OPCODE_FUNC(TEXDP3TEX) +EMIT_BYTECODE_OPCODE_FUNC(TEXM3X2DEPTH) +EMIT_BYTECODE_OPCODE_FUNC(TEXDP3) +EMIT_BYTECODE_OPCODE_FUNC(TEXM3X3) +EMIT_BYTECODE_OPCODE_FUNC(TEXDEPTH) +EMIT_BYTECODE_OPCODE_FUNC(CMP) +EMIT_BYTECODE_OPCODE_FUNC(BEM) +EMIT_BYTECODE_OPCODE_FUNC(DP2ADD) +EMIT_BYTECODE_OPCODE_FUNC(DSX) +EMIT_BYTECODE_OPCODE_FUNC(DSY) +EMIT_BYTECODE_OPCODE_FUNC(TEXLDD) +EMIT_BYTECODE_OPCODE_FUNC(TEXLDL) +EMIT_BYTECODE_OPCODE_FUNC(BREAKP) +EMIT_BYTECODE_OPCODE_FUNC(BREAKC) +EMIT_BYTECODE_OPCODE_FUNC(IFC) +EMIT_BYTECODE_OPCODE_FUNC(SETP) +EMIT_BYTECODE_OPCODE_FUNC(DEF) +EMIT_BYTECODE_OPCODE_FUNC(DEFI) +EMIT_BYTECODE_OPCODE_FUNC(DEFB) +EMIT_BYTECODE_OPCODE_FUNC(DCL) +EMIT_BYTECODE_OPCODE_FUNC(TEXCRD) +EMIT_BYTECODE_OPCODE_FUNC(TEXLD) + +#undef EMIT_BYTECODE_OPCODE_FUNC + +#endif // SUPPORT_PROFILE_BYTECODE + +#pragma GCC visibility pop diff --git a/mojoshader/profiles/mojoshader_profile_common.c b/mojoshader/profiles/mojoshader_profile_common.c new file mode 100644 index 0000000..e456c07 --- /dev/null +++ b/mojoshader/profiles/mojoshader_profile_common.c @@ -0,0 +1,508 @@ +/** + * MojoShader; generate shader programs from bytecode of compiled + * Direct3D shaders. + * + * Please see the file LICENSE.txt in the source's root directory. + * + * This file written by Ryan C. Gordon. + */ + +#define __MOJOSHADER_INTERNAL__ 1 +#include "mojoshader_profile.h" + +#pragma GCC visibility push(hidden) + +// Common Utilities + +void out_of_memory(Context *ctx) +{ + ctx->isfail = ctx->out_of_memory = 1; +} // out_of_memory + +void *Malloc(Context *ctx, const size_t len) +{ + void *retval = ctx->malloc((int) len, ctx->malloc_data); + if (retval == NULL) + out_of_memory(ctx); + return retval; +} // Malloc + +char *StrDup(Context *ctx, const char *str) +{ + char *retval = (char *) Malloc(ctx, strlen(str) + 1); + if (retval != NULL) + strcpy(retval, str); + return retval; +} // StrDup + +void Free(Context *ctx, void *ptr) +{ + ctx->free(ptr, ctx->malloc_data); +} // Free + +void * MOJOSHADERCALL MallocBridge(int bytes, void *data) +{ + return Malloc((Context *) data, (size_t) bytes); +} // MallocBridge + +void MOJOSHADERCALL FreeBridge(void *ptr, void *data) +{ + Free((Context *) data, ptr); +} // FreeBridge + +// Jump between output sections in the context... + +int set_output(Context *ctx, Buffer **section) +{ + // only create output sections on first use. + if (*section == NULL) + { + *section = buffer_create(256, MallocBridge, FreeBridge, ctx); + if (*section == NULL) + return 0; + } // if + + ctx->output = *section; + return 1; +} // set_output + +void push_output(Context *ctx, Buffer **section) +{ + assert(ctx->output_stack_len < (int) (STATICARRAYLEN(ctx->output_stack))); + ctx->output_stack[ctx->output_stack_len] = ctx->output; + ctx->indent_stack[ctx->output_stack_len] = ctx->indent; + ctx->output_stack_len++; + if (!set_output(ctx, section)) + return; + ctx->indent = 0; +} // push_output + +void pop_output(Context *ctx) +{ + assert(ctx->output_stack_len > 0); + ctx->output_stack_len--; + ctx->output = ctx->output_stack[ctx->output_stack_len]; + ctx->indent = ctx->indent_stack[ctx->output_stack_len]; +} // pop_output + +// Shader model version magic... + +uint32 ver_ui32(const uint8 major, const uint8 minor) +{ + return ( (((uint32) major) << 16) | (((minor) == 0xFF) ? 1 : (minor)) ); +} // version_ui32 + +int shader_version_supported(const uint8 maj, const uint8 min) +{ + return (ver_ui32(maj,min) <= ver_ui32(MAX_SHADER_MAJOR, MAX_SHADER_MINOR)); +} // shader_version_supported + +int shader_version_atleast(const Context *ctx, const uint8 maj, + const uint8 min) +{ + return (ver_ui32(ctx->major_ver, ctx->minor_ver) >= ver_ui32(maj, min)); +} // shader_version_atleast + +int shader_version_exactly(const Context *ctx, const uint8 maj, + const uint8 min) +{ + return ((ctx->major_ver == maj) && (ctx->minor_ver == min)); +} // shader_version_exactly + +int shader_is_pixel(const Context *ctx) +{ + return (ctx->shader_type == MOJOSHADER_TYPE_PIXEL); +} // shader_is_pixel + +int shader_is_vertex(const Context *ctx) +{ + return (ctx->shader_type == MOJOSHADER_TYPE_VERTEX); +} // shader_is_vertex + +// Fail... + +int isfail(const Context *ctx) +{ + return ctx->isfail; +} // isfail + +void failf(Context *ctx, const char *fmt, ...) ISPRINTF(2,3); +void failf(Context *ctx, const char *fmt, ...) +{ + ctx->isfail = 1; + if (ctx->out_of_memory) + return; + + // no filename at this level (we pass a NULL to errorlist_add_va()...) + va_list ap; + va_start(ap, fmt); + errorlist_add_va(ctx->errors, NULL, ctx->current_position, fmt, ap); + va_end(ap); +} // failf + +void fail(Context *ctx, const char *reason) +{ + failf(ctx, "%s", reason); +} // fail + +// Output Lines... + +void output_line(Context *ctx, const char *fmt, ...) ISPRINTF(2,3); +void output_line(Context *ctx, const char *fmt, ...) +{ + assert(ctx->output != NULL); + if (isfail(ctx)) + return; // we failed previously, don't go on... + + const int indent = ctx->indent; + if (indent > 0) + { + char *indentbuf = (char *) alloca(indent); + memset(indentbuf, '\t', indent); + buffer_append(ctx->output, indentbuf, indent); + } // if + + va_list ap; + va_start(ap, fmt); + buffer_append_va(ctx->output, fmt, ap); + va_end(ap); + + buffer_append(ctx->output, ctx->endline, ctx->endline_len); +} // output_line + +void output_blank_line(Context *ctx) +{ + assert(ctx->output != NULL); + if (!isfail(ctx)) + buffer_append(ctx->output, ctx->endline, ctx->endline_len); +} // output_blank_line + +// !!! FIXME: this is sort of nasty. +void floatstr(Context *ctx, char *buf, size_t bufsize, float f, + int leavedecimal) +{ + const size_t len = MOJOSHADER_printFloat(buf, bufsize, f); + if ((len+2) >= bufsize) + fail(ctx, "BUG: internal buffer is too small"); + else + { + char *end = buf + len; + char *ptr = strchr(buf, '.'); + if (ptr == NULL) + { + if (leavedecimal) + strcat(buf, ".0"); + return; // done. + } // if + + while (--end != ptr) + { + if (*end != '0') + { + end++; + break; + } // if + } // while + if ((leavedecimal) && (end == ptr)) + end += 2; + *end = '\0'; // chop extra '0' or all decimal places off. + } // else +} // floatstr + +// Deal with register lists... + +static inline uint32 reg_to_ui32(const RegisterType regtype, const int regnum) +{ + return ( ((uint32) regnum) | (((uint32) regtype) << 16) ); +} // reg_to_uint32 + +// !!! FIXME: ditch this for a hash table. +RegisterList *reglist_insert(Context *ctx, RegisterList *prev, + const RegisterType regtype, + const int regnum) +{ + const uint32 newval = reg_to_ui32(regtype, regnum); + RegisterList *item = prev->next; + while (item != NULL) + { + const uint32 val = reg_to_ui32(item->regtype, item->regnum); + if (newval == val) + return item; // already set, so we're done. + else if (newval < val) // insert it here. + break; + else // if (newval > val) + { + // keep going, we're not to the insertion point yet. + prev = item; + item = item->next; + } // else + } // while + + // we need to insert an entry after (prev). + item = (RegisterList *) Malloc(ctx, sizeof (RegisterList)); + if (item != NULL) + { + item->regtype = regtype; + item->regnum = regnum; + item->usage = MOJOSHADER_USAGE_UNKNOWN; + item->index = 0; + item->writemask = 0; + item->misc = 0; + item->written = 0; +#if SUPPORT_PROFILE_SPIRV + item->spirv.iddecl = 0; + item->spirv.is_ssa = 0; +#endif + item->array = NULL; + item->next = prev->next; + prev->next = item; + } // if + + return item; +} // reglist_insert + +RegisterList *reglist_find(const RegisterList *prev, + const RegisterType rtype, + const int regnum) +{ + const uint32 newval = reg_to_ui32(rtype, regnum); + RegisterList *item = prev->next; + while (item != NULL) + { + const uint32 val = reg_to_ui32(item->regtype, item->regnum); + if (newval == val) + return item; // here it is. + else if (newval < val) // should have been here if it existed. + return NULL; + else // if (newval > val) + item = item->next; + } // while + + return NULL; // wasn't in the list. +} // reglist_find + +RegisterList *set_used_register(Context *ctx, + const RegisterType regtype, + const int regnum, + const int written) +{ + RegisterList *reg = NULL; + if ((regtype == REG_TYPE_COLOROUT) && (regnum > 0)) + ctx->have_multi_color_outputs = 1; + + reg = reglist_insert(ctx, &ctx->used_registers, regtype, regnum); + if (reg && written) + reg->written = 1; + return reg; +} // set_used_register + +void set_defined_register(Context *ctx, const RegisterType rtype, + const int regnum) +{ + reglist_insert(ctx, &ctx->defined_registers, rtype, regnum); +} // set_defined_register + +// Writemasks + +int writemask_xyzw(const int writemask) +{ + return (writemask == 0xF); // 0xF == 1111. No explicit mask (full!). +} // writemask_xyzw + +int writemask_xyz(const int writemask) +{ + return (writemask == 0x7); // 0x7 == 0111. (that is: xyz) +} // writemask_xyz + +int writemask_xy(const int writemask) +{ + return (writemask == 0x3); // 0x3 == 0011. (that is: xy) +} // writemask_xy + +int writemask_x(const int writemask) +{ + return (writemask == 0x1); // 0x1 == 0001. (that is: x) +} // writemask_x + +int writemask_y(const int writemask) +{ + return (writemask == 0x2); // 0x2 == 0010. (that is: y) +} // writemask_y + +int replicate_swizzle(const int swizzle) +{ + // elements 1|2 match 3|4 and element 1 matches element 2. + return ( (((swizzle >> 4) & 0xF) == ((swizzle >> 0) & 0xF)) && + (((swizzle >> 0) & 0x3) == ((swizzle >> 2) & 0x3)) ); +} // replicate_swizzle + +int no_swizzle(const int swizzle) +{ + return (swizzle == 0xE4); // 0xE4 == 11100100 ... 0 1 2 3. No swizzle. +} // no_swizzle + +int vecsize_from_writemask(const int m) +{ + return (m & 1) + ((m >> 1) & 1) + ((m >> 2) & 1) + ((m >> 3) & 1); +} // vecsize_from_writemask + +void set_dstarg_writemask(DestArgInfo *dst, const int mask) +{ + dst->writemask = mask; + dst->writemask0 = ((mask >> 0) & 1); + dst->writemask1 = ((mask >> 1) & 1); + dst->writemask2 = ((mask >> 2) & 1); + dst->writemask3 = ((mask >> 3) & 1); +} // set_dstarg_writemask + +// D3D stuff that's used in more than just the d3d profile... + +int isscalar(Context *ctx, const MOJOSHADER_shaderType shader_type, + const RegisterType rtype, const int rnum) +{ + const int uses_psize = ctx->uses_pointsize; + const int uses_fog = ctx->uses_fog; + if ( (rtype == REG_TYPE_OUTPUT) && ((uses_psize) || (uses_fog)) ) + { + const RegisterList *reg = reglist_find(&ctx->attributes, rtype, rnum); + if (reg != NULL) + { + const MOJOSHADER_usage usage = reg->usage; + return ( (uses_psize && (usage == MOJOSHADER_USAGE_POINTSIZE)) || + (uses_fog && (usage == MOJOSHADER_USAGE_FOG)) ); + } // if + } // if + + return scalar_register(shader_type, rtype, rnum); +} // isscalar + +const char *get_D3D_register_string(Context *ctx, + RegisterType regtype, + int regnum, char *regnum_str, + size_t regnum_size) +{ + const char *retval = NULL; + int has_number = 1; + + switch (regtype) + { + case REG_TYPE_TEMP: + retval = "r"; + break; + + case REG_TYPE_INPUT: + retval = "v"; + break; + + case REG_TYPE_CONST: + retval = "c"; + break; + + case REG_TYPE_ADDRESS: // (or REG_TYPE_TEXTURE, same value.) + retval = shader_is_vertex(ctx) ? "a" : "t"; + break; + + case REG_TYPE_RASTOUT: + switch ((RastOutType) regnum) + { + case RASTOUT_TYPE_POSITION: retval = "oPos"; break; + case RASTOUT_TYPE_FOG: retval = "oFog"; break; + case RASTOUT_TYPE_POINT_SIZE: retval = "oPts"; break; + } // switch + has_number = 0; + break; + + case REG_TYPE_ATTROUT: + retval = "oD"; + break; + + case REG_TYPE_OUTPUT: // (or REG_TYPE_TEXCRDOUT, same value.) + if (shader_is_vertex(ctx) && shader_version_atleast(ctx, 3, 0)) + retval = "o"; + else + retval = "oT"; + break; + + case REG_TYPE_CONSTINT: + retval = "i"; + break; + + case REG_TYPE_COLOROUT: + retval = "oC"; + break; + + case REG_TYPE_DEPTHOUT: + retval = "oDepth"; + has_number = 0; + break; + + case REG_TYPE_SAMPLER: + retval = "s"; + break; + + case REG_TYPE_CONSTBOOL: + retval = "b"; + break; + + case REG_TYPE_LOOP: + retval = "aL"; + has_number = 0; + break; + + case REG_TYPE_MISCTYPE: + switch ((const MiscTypeType) regnum) + { + case MISCTYPE_TYPE_POSITION: retval = "vPos"; break; + case MISCTYPE_TYPE_FACE: retval = "vFace"; break; + } // switch + has_number = 0; + break; + + case REG_TYPE_LABEL: + retval = "l"; + break; + + case REG_TYPE_PREDICATE: + retval = "p"; + break; + + //case REG_TYPE_TEMPFLOAT16: // !!! FIXME: don't know this asm string + default: + fail(ctx, "unknown register type"); + retval = "???"; + has_number = 0; + break; + } // switch + + if (has_number) + snprintf(regnum_str, regnum_size, "%u", (uint) regnum); + else + regnum_str[0] = '\0'; + + return retval; +} // get_D3D_register_string + +// !!! FIXME: These should stay in the mojoshader_profile_d3d file +// !!! FIXME: but ARB1 relies on them, so we have to move them here. +// !!! FIXME: If/when we kill off ARB1, we can move these back. + +const char *get_D3D_varname_in_buf(Context *ctx, RegisterType rt, + int regnum, char *buf, + const size_t len) +{ + char regnum_str[16]; + const char *regtype_str = get_D3D_register_string(ctx, rt, regnum, + regnum_str, sizeof (regnum_str)); + snprintf(buf,len,"%s%s", regtype_str, regnum_str); + return buf; +} // get_D3D_varname_in_buf + + +const char *get_D3D_varname(Context *ctx, RegisterType rt, int regnum) +{ + char buf[64]; + get_D3D_varname_in_buf(ctx, rt, regnum, buf, sizeof (buf)); + return StrDup(ctx, buf); +} // get_D3D_varname + +#pragma GCC visibility pop diff --git a/mojoshader/profiles/mojoshader_profile_d3d.c b/mojoshader/profiles/mojoshader_profile_d3d.c new file mode 100644 index 0000000..a2d1842 --- /dev/null +++ b/mojoshader/profiles/mojoshader_profile_d3d.c @@ -0,0 +1,686 @@ +/** + * MojoShader; generate shader programs from bytecode of compiled + * Direct3D shaders. + * + * Please see the file LICENSE.txt in the source's root directory. + * + * This file written by Ryan C. Gordon. + */ + +#define __MOJOSHADER_INTERNAL__ 1 +#include "mojoshader_profile.h" + +#pragma GCC visibility push(hidden) + +#if SUPPORT_PROFILE_D3D + +const char *make_D3D_srcarg_string_in_buf(Context *ctx, + const SourceArgInfo *arg, + char *buf, size_t buflen) +{ + const char *premod_str = ""; + const char *postmod_str = ""; + switch (arg->src_mod) + { + case SRCMOD_NEGATE: + premod_str = "-"; + break; + + case SRCMOD_BIASNEGATE: + premod_str = "-"; + // fall through. + case SRCMOD_BIAS: + postmod_str = "_bias"; + break; + + case SRCMOD_SIGNNEGATE: + premod_str = "-"; + // fall through. + case SRCMOD_SIGN: + postmod_str = "_bx2"; + break; + + case SRCMOD_COMPLEMENT: + premod_str = "1-"; + break; + + case SRCMOD_X2NEGATE: + premod_str = "-"; + // fall through. + case SRCMOD_X2: + postmod_str = "_x2"; + break; + + case SRCMOD_DZ: + postmod_str = "_dz"; + break; + + case SRCMOD_DW: + postmod_str = "_dw"; + break; + + case SRCMOD_ABSNEGATE: + premod_str = "-"; + // fall through. + case SRCMOD_ABS: + postmod_str = "_abs"; + break; + + case SRCMOD_NOT: + premod_str = "!"; + break; + + case SRCMOD_NONE: + case SRCMOD_TOTAL: + break; // stop compiler whining. + } // switch + + + char regnum_str[16]; + const char *regtype_str = get_D3D_register_string(ctx, arg->regtype, + arg->regnum, regnum_str, + sizeof (regnum_str)); + + if (regtype_str == NULL) + { + fail(ctx, "Unknown source register type."); + *buf = '\0'; + return buf; + } // if + + const char *rel_lbracket = ""; + const char *rel_rbracket = ""; + char rel_swizzle[4] = { '\0' }; + char rel_regnum_str[16] = { '\0' }; + const char *rel_regtype_str = ""; + if (arg->relative) + { + if (arg->relative_regtype == REG_TYPE_LOOP) + { + rel_swizzle[0] = '\0'; + rel_swizzle[1] = '\0'; + rel_swizzle[2] = '\0'; + } // if + else + { + rel_swizzle[0] = '.'; + rel_swizzle[1] = swizzle_channels[arg->relative_component]; + rel_swizzle[2] = '\0'; + } // else + + rel_lbracket = "["; + rel_rbracket = "]"; + rel_regtype_str = get_D3D_register_string(ctx, arg->relative_regtype, + arg->relative_regnum, + rel_regnum_str, + sizeof (rel_regnum_str)); + + if (regtype_str == NULL) + { + fail(ctx, "Unknown relative source register type."); + *buf = '\0'; + return buf; + } // if + } // if + + char swizzle_str[6]; + size_t i = 0; + const int scalar = isscalar(ctx, ctx->shader_type, arg->regtype, arg->regnum); + if (!scalar && !no_swizzle(arg->swizzle)) + { + swizzle_str[i++] = '.'; + swizzle_str[i++] = swizzle_channels[arg->swizzle_x]; + swizzle_str[i++] = swizzle_channels[arg->swizzle_y]; + swizzle_str[i++] = swizzle_channels[arg->swizzle_z]; + swizzle_str[i++] = swizzle_channels[arg->swizzle_w]; + + // .xyzz is the same as .xyz, .z is the same as .zzzz, etc. + while (swizzle_str[i-1] == swizzle_str[i-2]) + i--; + } // if + swizzle_str[i] = '\0'; + assert(i < sizeof (swizzle_str)); + + // !!! FIXME: c12[a0.x] actually needs to be c[a0.x + 12] + snprintf(buf, buflen, "%s%s%s%s%s%s%s%s%s%s", + premod_str, regtype_str, regnum_str, postmod_str, + rel_lbracket, rel_regtype_str, rel_regnum_str, rel_swizzle, + rel_rbracket, swizzle_str); + // !!! FIXME: make sure the scratch buffer was large enough. + return buf; +} // make_D3D_srcarg_string_in_buf + + +const char *make_D3D_destarg_string(Context *ctx, char *buf, + const size_t buflen) +{ + const DestArgInfo *arg = &ctx->dest_arg; + + const char *result_shift_str = ""; + switch (arg->result_shift) + { + case 0x1: result_shift_str = "_x2"; break; + case 0x2: result_shift_str = "_x4"; break; + case 0x3: result_shift_str = "_x8"; break; + case 0xD: result_shift_str = "_d8"; break; + case 0xE: result_shift_str = "_d4"; break; + case 0xF: result_shift_str = "_d2"; break; + } // switch + + const char *sat_str = (arg->result_mod & MOD_SATURATE) ? "_sat" : ""; + const char *pp_str = (arg->result_mod & MOD_PP) ? "_pp" : ""; + const char *cent_str = (arg->result_mod & MOD_CENTROID) ? "_centroid" : ""; + + char regnum_str[16]; + const char *regtype_str = get_D3D_register_string(ctx, arg->regtype, + arg->regnum, regnum_str, + sizeof (regnum_str)); + if (regtype_str == NULL) + { + fail(ctx, "Unknown destination register type."); + *buf = '\0'; + return buf; + } // if + + char writemask_str[6]; + size_t i = 0; + const int scalar = isscalar(ctx, ctx->shader_type, arg->regtype, arg->regnum); + if (!scalar && !writemask_xyzw(arg->writemask)) + { + writemask_str[i++] = '.'; + if (arg->writemask0) writemask_str[i++] = 'x'; + if (arg->writemask1) writemask_str[i++] = 'y'; + if (arg->writemask2) writemask_str[i++] = 'z'; + if (arg->writemask3) writemask_str[i++] = 'w'; + } // if + writemask_str[i] = '\0'; + assert(i < sizeof (writemask_str)); + + const char *pred_left = ""; + const char *pred_right = ""; + char pred[32] = { '\0' }; + if (ctx->predicated) + { + pred_left = "("; + pred_right = ") "; + make_D3D_srcarg_string_in_buf(ctx, &ctx->predicate_arg, + pred, sizeof (pred)); + } // if + + // may turn out something like "_x2_sat_pp_centroid (!p0.x) r0.xyzw" ... + snprintf(buf, buflen, "%s%s%s%s %s%s%s%s%s%s", + result_shift_str, sat_str, pp_str, cent_str, + pred_left, pred, pred_right, + regtype_str, regnum_str, writemask_str); + // !!! FIXME: make sure the scratch buffer was large enough. + return buf; +} // make_D3D_destarg_string + + +const char *make_D3D_srcarg_string(Context *ctx, const size_t idx, + char *buf, size_t buflen) +{ + if (idx >= STATICARRAYLEN(ctx->source_args)) + { + fail(ctx, "Too many source args"); + *buf = '\0'; + return buf; + } // if + + const SourceArgInfo *arg = &ctx->source_args[idx]; + return make_D3D_srcarg_string_in_buf(ctx, arg, buf, buflen); +} // make_D3D_srcarg_string + +const char *get_D3D_const_array_varname(Context *ctx, int base, int size) +{ + char buf[64]; + snprintf(buf, sizeof (buf), "c_array_%d_%d", base, size); + return StrDup(ctx, buf); +} // get_D3D_const_array_varname + + +void emit_D3D_start(Context *ctx, const char *profilestr) +{ + const uint major = (uint) ctx->major_ver; + const uint minor = (uint) ctx->minor_ver; + char minor_str[16]; + + ctx->ignores_ctab = 1; + + if (minor == 0xFF) + strcpy(minor_str, "sw"); + else if ((major > 1) && (minor == 1)) + strcpy(minor_str, "x"); // for >= SM2, apparently this is "x". Weird. + else + snprintf(minor_str, sizeof (minor_str), "%u", (uint) minor); + + output_line(ctx, "%s_%u_%s", ctx->shader_type_str, major, minor_str); +} // emit_D3D_start + + +void emit_D3D_end(Context *ctx) +{ + output_line(ctx, "end"); +} // emit_D3D_end + + +void emit_D3D_phase(Context *ctx) +{ + output_line(ctx, "phase"); +} // emit_D3D_phase + + +void emit_D3D_finalize(Context *ctx) +{ + // no-op. +} // emit_D3D_finalize + + +void emit_D3D_global(Context *ctx, RegisterType regtype, int regnum) +{ + // no-op. +} // emit_D3D_global + + +void emit_D3D_array(Context *ctx, VariableList *var) +{ + // no-op. +} // emit_D3D_array + + +void emit_D3D_const_array(Context *ctx, const ConstantsList *clist, + int base, int size) +{ + // no-op. +} // emit_D3D_const_array + + +void emit_D3D_uniform(Context *ctx, RegisterType regtype, int regnum, + const VariableList *var) +{ + // no-op. +} // emit_D3D_uniform + + +void emit_D3D_sampler(Context *ctx, int s, TextureType ttype, int tb) +{ + // no-op. +} // emit_D3D_sampler + + +void emit_D3D_attribute(Context *ctx, RegisterType regtype, int regnum, + MOJOSHADER_usage usage, int index, int wmask, + int flags) +{ + // no-op. +} // emit_D3D_attribute + + +void emit_D3D_RESERVED(Context *ctx) +{ + // do nothing; fails in the state machine. +} // emit_D3D_RESERVED + + +// Generic D3D opcode emitters. A list of macros generate all the entry points +// that call into these... + +char *lowercase(char *dst, const char *src) +{ + int i = 0; + do + { + const char ch = src[i]; + dst[i] = (((ch >= 'A') && (ch <= 'Z')) ? (ch - ('A' - 'a')) : ch); + } while (src[i++]); + return dst; +} // lowercase + + +void emit_D3D_opcode_d(Context *ctx, const char *opcode) +{ + char dst[64]; make_D3D_destarg_string(ctx, dst, sizeof (dst)); + opcode = lowercase((char *) alloca(strlen(opcode) + 1), opcode); + output_line(ctx, "%s%s%s", ctx->coissue ? "+" : "", opcode, dst); +} // emit_D3D_opcode_d + + +void emit_D3D_opcode_s(Context *ctx, const char *opcode) +{ + char src0[64]; make_D3D_srcarg_string(ctx, 0, src0, sizeof (src0)); + opcode = lowercase((char *) alloca(strlen(opcode) + 1), opcode); + output_line(ctx, "%s%s %s", ctx->coissue ? "+" : "", opcode, src0); +} // emit_D3D_opcode_s + + +void emit_D3D_opcode_ss(Context *ctx, const char *opcode) +{ + char src0[64]; make_D3D_srcarg_string(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_D3D_srcarg_string(ctx, 1, src1, sizeof (src1)); + opcode = lowercase((char *) alloca(strlen(opcode) + 1), opcode); + output_line(ctx, "%s%s %s, %s", ctx->coissue ? "+" : "", opcode, src0, src1); +} // emit_D3D_opcode_ss + + +void emit_D3D_opcode_ds(Context *ctx, const char *opcode) +{ + char dst[64]; make_D3D_destarg_string(ctx, dst, sizeof (dst)); + char src0[64]; make_D3D_srcarg_string(ctx, 0, src0, sizeof (src0)); + opcode = lowercase((char *) alloca(strlen(opcode) + 1), opcode); + output_line(ctx, "%s%s%s, %s", ctx->coissue ? "+" : "", opcode, dst, src0); +} // emit_D3D_opcode_ds + + +void emit_D3D_opcode_dss(Context *ctx, const char *opcode) +{ + char dst[64]; make_D3D_destarg_string(ctx, dst, sizeof (dst)); + char src0[64]; make_D3D_srcarg_string(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_D3D_srcarg_string(ctx, 1, src1, sizeof (src1)); + opcode = lowercase((char *) alloca(strlen(opcode) + 1), opcode); + output_line(ctx, "%s%s%s, %s, %s", ctx->coissue ? "+" : "", + opcode, dst, src0, src1); +} // emit_D3D_opcode_dss + + +void emit_D3D_opcode_dsss(Context *ctx, const char *opcode) +{ + char dst[64]; make_D3D_destarg_string(ctx, dst, sizeof (dst)); + char src0[64]; make_D3D_srcarg_string(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_D3D_srcarg_string(ctx, 1, src1, sizeof (src1)); + char src2[64]; make_D3D_srcarg_string(ctx, 2, src2, sizeof (src2)); + opcode = lowercase((char *) alloca(strlen(opcode) + 1), opcode); + output_line(ctx, "%s%s%s, %s, %s, %s", ctx->coissue ? "+" : "", + opcode, dst, src0, src1, src2); +} // emit_D3D_opcode_dsss + + +void emit_D3D_opcode_dssss(Context *ctx, const char *opcode) +{ + char dst[64]; make_D3D_destarg_string(ctx, dst, sizeof (dst)); + char src0[64]; make_D3D_srcarg_string(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_D3D_srcarg_string(ctx, 1, src1, sizeof (src1)); + char src2[64]; make_D3D_srcarg_string(ctx, 2, src2, sizeof (src2)); + char src3[64]; make_D3D_srcarg_string(ctx, 3, src3, sizeof (src3)); + opcode = lowercase((char *) alloca(strlen(opcode) + 1), opcode); + output_line(ctx,"%s%s%s, %s, %s, %s, %s", ctx->coissue ? "+" : "", + opcode, dst, src0, src1, src2, src3); +} // emit_D3D_opcode_dssss + + +void emit_D3D_opcode(Context *ctx, const char *opcode) +{ + opcode = lowercase((char *) alloca(strlen(opcode) + 1), opcode); + output_line(ctx, "%s%s", ctx->coissue ? "+" : "", opcode); +} // emit_D3D_opcode + + +#define EMIT_D3D_OPCODE_FUNC(op) \ + void emit_D3D_##op(Context *ctx) { \ + emit_D3D_opcode(ctx, #op); \ + } +#define EMIT_D3D_OPCODE_D_FUNC(op) \ + void emit_D3D_##op(Context *ctx) { \ + emit_D3D_opcode_d(ctx, #op); \ + } +#define EMIT_D3D_OPCODE_S_FUNC(op) \ + void emit_D3D_##op(Context *ctx) { \ + emit_D3D_opcode_s(ctx, #op); \ + } +#define EMIT_D3D_OPCODE_SS_FUNC(op) \ + void emit_D3D_##op(Context *ctx) { \ + emit_D3D_opcode_ss(ctx, #op); \ + } +#define EMIT_D3D_OPCODE_DS_FUNC(op) \ + void emit_D3D_##op(Context *ctx) { \ + emit_D3D_opcode_ds(ctx, #op); \ + } +#define EMIT_D3D_OPCODE_DSS_FUNC(op) \ + void emit_D3D_##op(Context *ctx) { \ + emit_D3D_opcode_dss(ctx, #op); \ + } +#define EMIT_D3D_OPCODE_DSSS_FUNC(op) \ + void emit_D3D_##op(Context *ctx) { \ + emit_D3D_opcode_dsss(ctx, #op); \ + } +#define EMIT_D3D_OPCODE_DSSSS_FUNC(op) \ + void emit_D3D_##op(Context *ctx) { \ + emit_D3D_opcode_dssss(ctx, #op); \ + } + +EMIT_D3D_OPCODE_FUNC(NOP) +EMIT_D3D_OPCODE_DS_FUNC(MOV) +EMIT_D3D_OPCODE_DSS_FUNC(ADD) +EMIT_D3D_OPCODE_DSS_FUNC(SUB) +EMIT_D3D_OPCODE_DSSS_FUNC(MAD) +EMIT_D3D_OPCODE_DSS_FUNC(MUL) +EMIT_D3D_OPCODE_DS_FUNC(RCP) +EMIT_D3D_OPCODE_DS_FUNC(RSQ) +EMIT_D3D_OPCODE_DSS_FUNC(DP3) +EMIT_D3D_OPCODE_DSS_FUNC(DP4) +EMIT_D3D_OPCODE_DSS_FUNC(MIN) +EMIT_D3D_OPCODE_DSS_FUNC(MAX) +EMIT_D3D_OPCODE_DSS_FUNC(SLT) +EMIT_D3D_OPCODE_DSS_FUNC(SGE) +EMIT_D3D_OPCODE_DS_FUNC(EXP) +EMIT_D3D_OPCODE_DS_FUNC(LOG) +EMIT_D3D_OPCODE_DS_FUNC(LIT) +EMIT_D3D_OPCODE_DSS_FUNC(DST) +EMIT_D3D_OPCODE_DSSS_FUNC(LRP) +EMIT_D3D_OPCODE_DS_FUNC(FRC) +EMIT_D3D_OPCODE_DSS_FUNC(M4X4) +EMIT_D3D_OPCODE_DSS_FUNC(M4X3) +EMIT_D3D_OPCODE_DSS_FUNC(M3X4) +EMIT_D3D_OPCODE_DSS_FUNC(M3X3) +EMIT_D3D_OPCODE_DSS_FUNC(M3X2) +EMIT_D3D_OPCODE_S_FUNC(CALL) +EMIT_D3D_OPCODE_SS_FUNC(CALLNZ) +EMIT_D3D_OPCODE_SS_FUNC(LOOP) +EMIT_D3D_OPCODE_FUNC(RET) +EMIT_D3D_OPCODE_FUNC(ENDLOOP) +EMIT_D3D_OPCODE_S_FUNC(LABEL) +EMIT_D3D_OPCODE_DSS_FUNC(POW) +EMIT_D3D_OPCODE_DSS_FUNC(CRS) +EMIT_D3D_OPCODE_DSSS_FUNC(SGN) +EMIT_D3D_OPCODE_DS_FUNC(ABS) +EMIT_D3D_OPCODE_DS_FUNC(NRM) +EMIT_D3D_OPCODE_S_FUNC(REP) +EMIT_D3D_OPCODE_FUNC(ENDREP) +EMIT_D3D_OPCODE_S_FUNC(IF) +EMIT_D3D_OPCODE_FUNC(ELSE) +EMIT_D3D_OPCODE_FUNC(ENDIF) +EMIT_D3D_OPCODE_FUNC(BREAK) +EMIT_D3D_OPCODE_DS_FUNC(MOVA) +EMIT_D3D_OPCODE_D_FUNC(TEXKILL) +EMIT_D3D_OPCODE_DS_FUNC(TEXBEM) +EMIT_D3D_OPCODE_DS_FUNC(TEXBEML) +EMIT_D3D_OPCODE_DS_FUNC(TEXREG2AR) +EMIT_D3D_OPCODE_DS_FUNC(TEXREG2GB) +EMIT_D3D_OPCODE_DS_FUNC(TEXM3X2PAD) +EMIT_D3D_OPCODE_DS_FUNC(TEXM3X2TEX) +EMIT_D3D_OPCODE_DS_FUNC(TEXM3X3PAD) +EMIT_D3D_OPCODE_DS_FUNC(TEXM3X3TEX) +EMIT_D3D_OPCODE_DSS_FUNC(TEXM3X3SPEC) +EMIT_D3D_OPCODE_DS_FUNC(TEXM3X3VSPEC) +EMIT_D3D_OPCODE_DS_FUNC(EXPP) +EMIT_D3D_OPCODE_DS_FUNC(LOGP) +EMIT_D3D_OPCODE_DSSS_FUNC(CND) +EMIT_D3D_OPCODE_DS_FUNC(TEXREG2RGB) +EMIT_D3D_OPCODE_DS_FUNC(TEXDP3TEX) +EMIT_D3D_OPCODE_DS_FUNC(TEXM3X2DEPTH) +EMIT_D3D_OPCODE_DS_FUNC(TEXDP3) +EMIT_D3D_OPCODE_DS_FUNC(TEXM3X3) +EMIT_D3D_OPCODE_D_FUNC(TEXDEPTH) +EMIT_D3D_OPCODE_DSSS_FUNC(CMP) +EMIT_D3D_OPCODE_DSS_FUNC(BEM) +EMIT_D3D_OPCODE_DSSS_FUNC(DP2ADD) +EMIT_D3D_OPCODE_DS_FUNC(DSX) +EMIT_D3D_OPCODE_DS_FUNC(DSY) +EMIT_D3D_OPCODE_DSSSS_FUNC(TEXLDD) +EMIT_D3D_OPCODE_DSS_FUNC(TEXLDL) +EMIT_D3D_OPCODE_S_FUNC(BREAKP) + +// special cases for comparison opcodes... +const char *get_D3D_comparison_string(Context *ctx) +{ + const char *comps[] = { + "", "_gt", "_eq", "_ge", "_lt", "_ne", "_le" + }; + + if (ctx->instruction_controls >= STATICARRAYLEN(comps)) + { + fail(ctx, "unknown comparison control"); + return ""; + } // if + + return comps[ctx->instruction_controls]; +} // get_D3D_comparison_string + +void emit_D3D_BREAKC(Context *ctx) +{ + char op[16]; + snprintf(op, sizeof (op), "break%s", get_D3D_comparison_string(ctx)); + emit_D3D_opcode_ss(ctx, op); +} // emit_D3D_BREAKC + +void emit_D3D_IFC(Context *ctx) +{ + char op[16]; + snprintf(op, sizeof (op), "if%s", get_D3D_comparison_string(ctx)); + emit_D3D_opcode_ss(ctx, op); +} // emit_D3D_IFC + +void emit_D3D_SETP(Context *ctx) +{ + char op[16]; + snprintf(op, sizeof (op), "setp%s", get_D3D_comparison_string(ctx)); + emit_D3D_opcode_dss(ctx, op); +} // emit_D3D_SETP + +void emit_D3D_DEF(Context *ctx) +{ + char dst[64]; + make_D3D_destarg_string(ctx, dst, sizeof (dst)); + const float *val = (const float *) ctx->dwords; // !!! FIXME: could be int? + char val0[32]; + char val1[32]; + char val2[32]; + char val3[32]; + floatstr(ctx, val0, sizeof (val0), val[0], 0); + floatstr(ctx, val1, sizeof (val1), val[1], 0); + floatstr(ctx, val2, sizeof (val2), val[2], 0); + floatstr(ctx, val3, sizeof (val3), val[3], 0); + output_line(ctx, "def%s, %s, %s, %s, %s", dst, val0, val1, val2, val3); +} // emit_D3D_DEF + +void emit_D3D_DEFI(Context *ctx) +{ + char dst[64]; + make_D3D_destarg_string(ctx, dst, sizeof (dst)); + const int32 *x = (const int32 *) ctx->dwords; + output_line(ctx, "defi%s, %d, %d, %d, %d", dst, + (int) x[0], (int) x[1], (int) x[2], (int) x[3]); +} // emit_D3D_DEFI + +void emit_D3D_DEFB(Context *ctx) +{ + char dst[64]; + make_D3D_destarg_string(ctx, dst, sizeof (dst)); + output_line(ctx, "defb%s, %s", dst, ctx->dwords[0] ? "true" : "false"); +} // emit_D3D_DEFB + + +static const char *usagestrs[] = { + "_position", "_blendweight", "_blendindices", "_normal", "_psize", + "_texcoord", "_tangent", "_binormal", "_tessfactor", "_positiont", + "_color", "_fog", "_depth", "_sample" +}; + +void emit_D3D_DCL(Context *ctx) +{ + char dst[64]; + make_D3D_destarg_string(ctx, dst, sizeof (dst)); + const DestArgInfo *arg = &ctx->dest_arg; + const char *usage_str = ""; + char index_str[16] = { '\0' }; + + if (arg->regtype == REG_TYPE_SAMPLER) + { + switch ((const TextureType) ctx->dwords[0]) + { + case TEXTURE_TYPE_2D: usage_str = "_2d"; break; + case TEXTURE_TYPE_CUBE: usage_str = "_cube"; break; + case TEXTURE_TYPE_VOLUME: usage_str = "_volume"; break; + default: fail(ctx, "unknown sampler texture type"); return; + } // switch + } // if + + else if (arg->regtype == REG_TYPE_MISCTYPE) + { + switch ((const MiscTypeType) arg->regnum) + { + case MISCTYPE_TYPE_POSITION: + case MISCTYPE_TYPE_FACE: + usage_str = ""; // just become "dcl vFace" or whatever. + break; + default: fail(ctx, "unknown misc register type"); return; + } // switch + } // else if + + else + { + const uint32 usage = ctx->dwords[0]; + const uint32 index = ctx->dwords[1]; + usage_str = usagestrs[usage]; + if (index != 0) + snprintf(index_str, sizeof (index_str), "%u", (uint) index); + } // else + + output_line(ctx, "dcl%s%s%s", usage_str, index_str, dst); +} // emit_D3D_DCL + + +void emit_D3D_TEXCRD(Context *ctx) +{ + // this opcode looks and acts differently depending on the shader model. + if (shader_version_atleast(ctx, 1, 4)) + emit_D3D_opcode_ds(ctx, "texcrd"); + else + emit_D3D_opcode_d(ctx, "texcoord"); +} // emit_D3D_TEXCOORD + +void emit_D3D_TEXLD(Context *ctx) +{ + // this opcode looks and acts differently depending on the shader model. + if (shader_version_atleast(ctx, 2, 0)) + { + if (ctx->instruction_controls == CONTROL_TEXLD) + emit_D3D_opcode_dss(ctx, "texld"); + else if (ctx->instruction_controls == CONTROL_TEXLDP) + emit_D3D_opcode_dss(ctx, "texldp"); + else if (ctx->instruction_controls == CONTROL_TEXLDB) + emit_D3D_opcode_dss(ctx, "texldb"); + } // if + + else if (shader_version_atleast(ctx, 1, 4)) + { + emit_D3D_opcode_ds(ctx, "texld"); + } // else if + + else + { + emit_D3D_opcode_d(ctx, "tex"); + } // else +} // emit_D3D_TEXLD + +void emit_D3D_SINCOS(Context *ctx) +{ + // this opcode needs extra registers for sm2 and lower. + if (!shader_version_atleast(ctx, 3, 0)) + emit_D3D_opcode_dsss(ctx, "sincos"); + else + emit_D3D_opcode_ds(ctx, "sincos"); +} // emit_D3D_SINCOS + +#endif // SUPPORT_PROFILE_D3D + +#pragma GCC visibility pop diff --git a/mojoshader/profiles/mojoshader_profile_glsl.c b/mojoshader/profiles/mojoshader_profile_glsl.c new file mode 100644 index 0000000..319e3cb --- /dev/null +++ b/mojoshader/profiles/mojoshader_profile_glsl.c @@ -0,0 +1,2504 @@ +/** + * MojoShader; generate shader programs from bytecode of compiled + * Direct3D shaders. + * + * Please see the file LICENSE.txt in the source's root directory. + * + * This file written by Ryan C. Gordon. + */ + +#define __MOJOSHADER_INTERNAL__ 1 +#include "mojoshader_profile.h" + +#pragma GCC visibility push(hidden) + +#if SUPPORT_PROFILE_GLSL + +#define EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(op) \ + void emit_GLSL_##op(Context *ctx) { \ + fail(ctx, #op " unimplemented in glsl profile"); \ + } + +static inline const char *get_GLSL_register_string(Context *ctx, + const RegisterType regtype, const int regnum, + char *regnum_str, const size_t regnum_size) +{ + // turns out these are identical at the moment. + return get_D3D_register_string(ctx,regtype,regnum,regnum_str,regnum_size); +} // get_GLSL_register_string + +const char *get_GLSL_uniform_type(Context *ctx, const RegisterType rtype) +{ + switch (rtype) + { + case REG_TYPE_CONST: return "vec4"; + case REG_TYPE_CONSTINT: return "ivec4"; + case REG_TYPE_CONSTBOOL: return "bool"; + default: fail(ctx, "BUG: used a uniform we don't know how to define."); + } // switch + + return NULL; +} // get_GLSL_uniform_type + +const char *get_GLSL_varname_in_buf(Context *ctx, RegisterType rt, + int regnum, char *buf, + const size_t len) +{ + char regnum_str[16]; + const char *regtype_str = get_GLSL_register_string(ctx, rt, regnum, + regnum_str, sizeof (regnum_str)); + snprintf(buf,len,"%s_%s%s", ctx->shader_type_str, regtype_str, regnum_str); + return buf; +} // get_GLSL_varname_in_buf + + +const char *get_GLSL_varname(Context *ctx, RegisterType rt, int regnum) +{ + char buf[64]; + get_GLSL_varname_in_buf(ctx, rt, regnum, buf, sizeof (buf)); + return StrDup(ctx, buf); +} // get_GLSL_varname + + +static inline const char *get_GLSL_const_array_varname_in_buf(Context *ctx, + const int base, const int size, + char *buf, const size_t buflen) +{ + const char *type = ctx->shader_type_str; + snprintf(buf, buflen, "%s_const_array_%d_%d", type, base, size); + return buf; +} // get_GLSL_const_array_varname_in_buf + +const char *get_GLSL_const_array_varname(Context *ctx, int base, int size) +{ + char buf[64]; + get_GLSL_const_array_varname_in_buf(ctx, base, size, buf, sizeof (buf)); + return StrDup(ctx, buf); +} // get_GLSL_const_array_varname + + +static inline const char *get_GLSL_input_array_varname(Context *ctx, + char *buf, const size_t buflen) +{ + snprintf(buf, buflen, "%s", "vertex_input_array"); + return buf; +} // get_GLSL_input_array_varname + + +const char *get_GLSL_uniform_array_varname(Context *ctx, + const RegisterType regtype, + char *buf, const size_t len) +{ + const char *shadertype = ctx->shader_type_str; + const char *type = get_GLSL_uniform_type(ctx, regtype); + snprintf(buf, len, "%s_uniforms_%s", shadertype, type); + return buf; +} // get_GLSL_uniform_array_varname + +const char *get_GLSL_destarg_varname(Context *ctx, char *buf, size_t len) +{ + const DestArgInfo *arg = &ctx->dest_arg; + return get_GLSL_varname_in_buf(ctx, arg->regtype, arg->regnum, buf, len); +} // get_GLSL_destarg_varname + +const char *get_GLSL_srcarg_varname(Context *ctx, const size_t idx, + char *buf, size_t len) +{ + if (idx >= STATICARRAYLEN(ctx->source_args)) + { + fail(ctx, "Too many source args"); + *buf = '\0'; + return buf; + } // if + + const SourceArgInfo *arg = &ctx->source_args[idx]; + return get_GLSL_varname_in_buf(ctx, arg->regtype, arg->regnum, buf, len); +} // get_GLSL_srcarg_varname + + +const char *make_GLSL_destarg_assign(Context *, char *, const size_t, + const char *, ...) ISPRINTF(4,5); + +const char *make_GLSL_destarg_assign(Context *ctx, char *buf, + const size_t buflen, + const char *fmt, ...) +{ + int need_parens = 0; + const DestArgInfo *arg = &ctx->dest_arg; + + if (arg->writemask == 0) + { + *buf = '\0'; + return buf; // no writemask? It's a no-op. + } // if + + char clampbuf[32] = { '\0' }; + const char *clampleft = ""; + const char *clampright = ""; + if (arg->result_mod & MOD_SATURATE) + { + const int vecsize = vecsize_from_writemask(arg->writemask); + clampleft = "clamp("; + if (vecsize == 1) + clampright = ", 0.0, 1.0)"; + else + { + snprintf(clampbuf, sizeof (clampbuf), + ", vec%d(0.0), vec%d(1.0))", vecsize, vecsize); + clampright = clampbuf; + } // else + } // if + + // MSDN says MOD_PP is a hint and many implementations ignore it. So do we. + + // CENTROID only allowed in DCL opcodes, which shouldn't come through here. + assert((arg->result_mod & MOD_CENTROID) == 0); + + if (ctx->predicated) + { + fail(ctx, "predicated destinations unsupported"); // !!! FIXME + *buf = '\0'; + return buf; + } // if + + char operation[256]; + va_list ap; + va_start(ap, fmt); + const int len = vsnprintf(operation, sizeof (operation), fmt, ap); + va_end(ap); + if (len >= sizeof (operation)) + { + fail(ctx, "operation string too large"); // I'm lazy. :P + *buf = '\0'; + return buf; + } // if + + const char *result_shift_str = ""; + switch (arg->result_shift) + { + case 0x1: result_shift_str = " * 2.0"; break; + case 0x2: result_shift_str = " * 4.0"; break; + case 0x3: result_shift_str = " * 8.0"; break; + case 0xD: result_shift_str = " / 8.0"; break; + case 0xE: result_shift_str = " / 4.0"; break; + case 0xF: result_shift_str = " / 2.0"; break; + } // switch + need_parens |= (result_shift_str[0] != '\0'); + + char regnum_str[16]; + const char *regtype_str = get_GLSL_register_string(ctx, arg->regtype, + arg->regnum, regnum_str, + sizeof (regnum_str)); + char writemask_str[6]; + size_t i = 0; + const int scalar = isscalar(ctx, ctx->shader_type, arg->regtype, arg->regnum); + if (!scalar && !writemask_xyzw(arg->writemask)) + { + writemask_str[i++] = '.'; + if (arg->writemask0) writemask_str[i++] = 'x'; + if (arg->writemask1) writemask_str[i++] = 'y'; + if (arg->writemask2) writemask_str[i++] = 'z'; + if (arg->writemask3) writemask_str[i++] = 'w'; + } // if + writemask_str[i] = '\0'; + assert(i < sizeof (writemask_str)); + + const char *leftparen = (need_parens) ? "(" : ""; + const char *rightparen = (need_parens) ? ")" : ""; + + snprintf(buf, buflen, "%s_%s%s%s = %s%s%s%s%s%s;", + ctx->shader_type_str, regtype_str, regnum_str, writemask_str, + clampleft, leftparen, operation, rightparen, result_shift_str, + clampright); + // !!! FIXME: make sure the scratch buffer was large enough. + return buf; +} // make_GLSL_destarg_assign + + +char *make_GLSL_swizzle_string(char *swiz_str, const size_t strsize, + const int swizzle, const int writemask) +{ + size_t i = 0; + if ( (!no_swizzle(swizzle)) || (!writemask_xyzw(writemask)) ) + { + const int writemask0 = (writemask >> 0) & 0x1; + const int writemask1 = (writemask >> 1) & 0x1; + const int writemask2 = (writemask >> 2) & 0x1; + const int writemask3 = (writemask >> 3) & 0x1; + + const int swizzle_x = (swizzle >> 0) & 0x3; + const int swizzle_y = (swizzle >> 2) & 0x3; + const int swizzle_z = (swizzle >> 4) & 0x3; + const int swizzle_w = (swizzle >> 6) & 0x3; + + swiz_str[i++] = '.'; + if (writemask0) swiz_str[i++] = swizzle_channels[swizzle_x]; + if (writemask1) swiz_str[i++] = swizzle_channels[swizzle_y]; + if (writemask2) swiz_str[i++] = swizzle_channels[swizzle_z]; + if (writemask3) swiz_str[i++] = swizzle_channels[swizzle_w]; + } // if + assert(i < strsize); + swiz_str[i] = '\0'; + return swiz_str; +} // make_GLSL_swizzle_string + + +const char *make_GLSL_srcarg_string(Context *ctx, const size_t idx, + const int writemask, char *buf, + const size_t buflen) +{ + *buf = '\0'; + + if (idx >= STATICARRAYLEN(ctx->source_args)) + { + fail(ctx, "Too many source args"); + return buf; + } // if + + const SourceArgInfo *arg = &ctx->source_args[idx]; + + const char *premod_str = ""; + const char *postmod_str = ""; + switch (arg->src_mod) + { + case SRCMOD_NEGATE: + premod_str = "-"; + break; + + case SRCMOD_BIASNEGATE: + premod_str = "-("; + postmod_str = " - 0.5)"; + break; + + case SRCMOD_BIAS: + premod_str = "("; + postmod_str = " - 0.5)"; + break; + + case SRCMOD_SIGNNEGATE: + premod_str = "-(("; + postmod_str = " - 0.5) * 2.0)"; + break; + + case SRCMOD_SIGN: + premod_str = "(("; + postmod_str = " - 0.5) * 2.0)"; + break; + + case SRCMOD_COMPLEMENT: + premod_str = "(1.0 - "; + postmod_str = ")"; + break; + + case SRCMOD_X2NEGATE: + premod_str = "-("; + postmod_str = " * 2.0)"; + break; + + case SRCMOD_X2: + premod_str = "("; + postmod_str = " * 2.0)"; + break; + + case SRCMOD_DZ: + fail(ctx, "SRCMOD_DZ unsupported"); return buf; // !!! FIXME + postmod_str = "_dz"; + break; + + case SRCMOD_DW: + fail(ctx, "SRCMOD_DW unsupported"); return buf; // !!! FIXME + postmod_str = "_dw"; + break; + + case SRCMOD_ABSNEGATE: + premod_str = "-abs("; + postmod_str = ")"; + break; + + case SRCMOD_ABS: + premod_str = "abs("; + postmod_str = ")"; + break; + + case SRCMOD_NOT: + premod_str = "!"; + break; + + case SRCMOD_NONE: + case SRCMOD_TOTAL: + break; // stop compiler whining. + } // switch + + const char *regtype_str = NULL; + + if (!arg->relative) + { + regtype_str = get_GLSL_varname_in_buf(ctx, arg->regtype, arg->regnum, + (char *) alloca(64), 64); + } // if + + const char *rel_lbracket = ""; + char rel_offset[32] = { '\0' }; + const char *rel_rbracket = ""; + char rel_swizzle[4] = { '\0' }; + const char *rel_regtype_str = ""; + if (arg->relative) + { + if (arg->regtype == REG_TYPE_INPUT) + regtype_str=get_GLSL_input_array_varname(ctx,(char*)alloca(64),64); + else + { + assert(arg->regtype == REG_TYPE_CONST); + const int arrayidx = arg->relative_array->index; + const int offset = arg->regnum - arrayidx; + assert(offset >= 0); + if (arg->relative_array->constant) + { + const int arraysize = arg->relative_array->count; + regtype_str = get_GLSL_const_array_varname_in_buf(ctx, + arrayidx, arraysize, (char *) alloca(64), 64); + if (offset != 0) + snprintf(rel_offset, sizeof (rel_offset), "%d + ", offset); + } // if + else + { + regtype_str = get_GLSL_uniform_array_varname(ctx, arg->regtype, + (char *) alloca(64), 64); + if (offset == 0) + { + snprintf(rel_offset, sizeof (rel_offset), + "ARRAYBASE_%d + ", arrayidx); + } // if + else + { + snprintf(rel_offset, sizeof (rel_offset), + "(ARRAYBASE_%d + %d) + ", arrayidx, offset); + } // else + } // else + } // else + + rel_lbracket = "["; + + if (arg->relative_regtype == REG_TYPE_LOOP) + { + rel_regtype_str = "aL"; + rel_swizzle[0] = '\0'; + rel_swizzle[1] = '\0'; + rel_swizzle[2] = '\0'; + } // if + else + { + rel_regtype_str = get_GLSL_varname_in_buf(ctx, arg->relative_regtype, + arg->relative_regnum, + (char *) alloca(64), 64); + rel_swizzle[0] = '.'; + rel_swizzle[1] = swizzle_channels[arg->relative_component]; + rel_swizzle[2] = '\0'; + } // else + rel_rbracket = "]"; + } // if + + char swiz_str[6] = { '\0' }; + if (!isscalar(ctx, ctx->shader_type, arg->regtype, arg->regnum)) + { + make_GLSL_swizzle_string(swiz_str, sizeof (swiz_str), + arg->swizzle, writemask); + } // if + + if (regtype_str == NULL) + { + fail(ctx, "Unknown source register type."); + return buf; + } // if + + snprintf(buf, buflen, "%s%s%s%s%s%s%s%s%s", + premod_str, regtype_str, rel_lbracket, rel_offset, + rel_regtype_str, rel_swizzle, rel_rbracket, swiz_str, + postmod_str); + // !!! FIXME: make sure the scratch buffer was large enough. + return buf; +} // make_GLSL_srcarg_string + +// generate some convenience functions. +#define MAKE_GLSL_SRCARG_STRING_(mask, bitmask) \ + static inline const char *make_GLSL_srcarg_string_##mask(Context *ctx, \ + const size_t idx, char *buf, \ + const size_t buflen) { \ + return make_GLSL_srcarg_string(ctx, idx, bitmask, buf, buflen); \ + } +MAKE_GLSL_SRCARG_STRING_(x, (1 << 0)) +MAKE_GLSL_SRCARG_STRING_(y, (1 << 1)) +MAKE_GLSL_SRCARG_STRING_(z, (1 << 2)) +MAKE_GLSL_SRCARG_STRING_(w, (1 << 3)) +MAKE_GLSL_SRCARG_STRING_(scalar, (1 << 0)) +MAKE_GLSL_SRCARG_STRING_(full, 0xF) +MAKE_GLSL_SRCARG_STRING_(masked, ctx->dest_arg.writemask) +MAKE_GLSL_SRCARG_STRING_(vec3, 0x7) +MAKE_GLSL_SRCARG_STRING_(vec2, 0x3) +#undef MAKE_GLSL_SRCARG_STRING_ + +// special cases for comparison opcodes... + +const char *get_GLSL_comparison_string_scalar(Context *ctx) +{ + const char *comps[] = { "", ">", "==", ">=", "<", "!=", "<=" }; + if (ctx->instruction_controls >= STATICARRAYLEN(comps)) + { + fail(ctx, "unknown comparison control"); + return ""; + } // if + + return comps[ctx->instruction_controls]; +} // get_GLSL_comparison_string_scalar + +const char *get_GLSL_comparison_string_vector(Context *ctx) +{ + const char *comps[] = { + "", "greaterThan", "equal", "greaterThanEqual", "lessThan", + "notEqual", "lessThanEqual" + }; + + if (ctx->instruction_controls >= STATICARRAYLEN(comps)) + { + fail(ctx, "unknown comparison control"); + return ""; + } // if + + return comps[ctx->instruction_controls]; +} // get_GLSL_comparison_string_vector + +// special extensions needed for texldd/texldl... + +static void prepend_glsl_texlod_extensions(Context *ctx) +{ + // !!! FIXME: + // GLSL 1.30 introduced textureGrad() for this, but it looks like the + // functions are overloaded instead of texture2DGrad() (etc). + + // !!! FIXME: + // The spec says we can't use GLSL's texture*Lod() built-ins from fragment + // shaders for some inexplicable reason. + // For now, you'll just have to suffer with the potentially wrong mipmap + // until I can figure something out. + + // ARB_shader_texture_lod and EXT_gpu_shader4 added texture2DLod/Grad*(), + // so we'll use them if available. Failing that, we'll just fallback + // to a regular texture2D call and hope the mipmap it chooses is close + // enough. + if (!ctx->glsl_generated_texlod_setup && !support_glsles3(ctx)) + { + ctx->glsl_generated_texlod_setup = 1; + push_output(ctx, &ctx->preflight); + output_line(ctx, "#if GL_ARB_shader_texture_lod"); + output_line(ctx, "#extension GL_ARB_shader_texture_lod : enable"); + output_line(ctx, "#define texture2DGrad texture2DGradARB"); + output_line(ctx, "#define texture2DProjGrad texture2DProjARB"); + output_line(ctx, "#elif GL_EXT_gpu_shader4"); + output_line(ctx, "#extension GL_EXT_gpu_shader4 : enable"); + output_line(ctx, "#else"); + output_line(ctx, "#define texture2DGrad(a,b,c,d) texture2D(a,b)"); + output_line(ctx, "#define texture2DProjGrad(a,b,c,d) texture2DProj(a,b)"); + if (shader_is_pixel(ctx)) + output_line(ctx, "#define texture2DLod(a,b,c) texture2D(a,b)"); + output_line(ctx, "#endif"); + output_blank_line(ctx); + pop_output(ctx); + } // if +} // prepend_glsl_texlod_extensions + + +void emit_GLSL_start(Context *ctx, const char *profilestr) +{ + if (!shader_is_vertex(ctx) && !shader_is_pixel(ctx)) + { + failf(ctx, "Shader type %u unsupported in this profile.", + (uint) ctx->shader_type); + return; + } // if + + else if (strcmp(profilestr, MOJOSHADER_PROFILE_GLSL) == 0) + { + // No gl_FragData[] before GLSL 1.10, so we have to force the version. + push_output(ctx, &ctx->preflight); + output_line(ctx, "#version 110"); + pop_output(ctx); + } // else if + + #if SUPPORT_PROFILE_GLSL120 + else if (strcmp(profilestr, MOJOSHADER_PROFILE_GLSL120) == 0) + { + ctx->profile_supports_glsl120 = 1; + push_output(ctx, &ctx->preflight); + output_line(ctx, "#version 120"); + pop_output(ctx); + } // else if + #endif + + #if SUPPORT_PROFILE_GLSLES3 + else if (strcmp(profilestr, MOJOSHADER_PROFILE_GLSLES3) == 0) + { + ctx->profile_supports_glsles3 = 1; + push_output(ctx, &ctx->preflight); + output_line(ctx, "#version 300 es"); + output_line(ctx, "#define texture2D texture"); + output_line(ctx, "#define texture2DLod textureLod"); + output_line(ctx, "#define texture2DProj textureProj"); + output_line(ctx, "#define texture2DGrad textureGrad"); + output_line(ctx, "#define texture2DProjGrad textureProjGrad"); + output_line(ctx, "#define texture3D texture"); + output_line(ctx, "#define texture3DLod textureLod"); + output_line(ctx, "#define textureCube texture"); + output_line(ctx, "#define textureCubeLod textureLod"); + output_line(ctx, "#define texture2DRect texture"); + output_line(ctx, "#define texture2DRectProj textureProj"); + output_line(ctx, "#define texture2DRectLod textureLod"); + if (shader_is_vertex(ctx)) + output_line(ctx, "precision highp float;"); + else + output_line(ctx, "precision mediump float;"); + output_line(ctx, "precision mediump int;"); + pop_output(ctx); + } // else if + #endif + + #if SUPPORT_PROFILE_GLSLES + else if (strcmp(profilestr, MOJOSHADER_PROFILE_GLSLES) == 0) + { + ctx->profile_supports_glsles = 1; + push_output(ctx, &ctx->preflight); + output_line(ctx, "#version 100"); + if (shader_is_vertex(ctx)) + output_line(ctx, "precision highp float;"); + else + output_line(ctx, "precision mediump float;"); + output_line(ctx, "precision mediump int;"); + pop_output(ctx); + } // else if + #endif + + else + { + failf(ctx, "Profile '%s' unsupported or unknown.", profilestr); + return; + } // else + + push_output(ctx, &ctx->mainline_intro); + output_line(ctx, "void main()"); + output_line(ctx, "{"); + pop_output(ctx); + + set_output(ctx, &ctx->mainline); + ctx->indent++; +} // emit_GLSL_start + +void emit_GLSL_RET(Context *ctx); +void emit_GLSL_end(Context *ctx) +{ + // ps_1_* writes color to r0 instead oC0. We move it to the right place. + // We don't have to worry about a RET opcode messing this up, since + // RET isn't available before ps_2_0. + if (shader_is_pixel(ctx) && !shader_version_atleast(ctx, 2, 0)) + { + const char *shstr = ctx->shader_type_str; + set_used_register(ctx, REG_TYPE_COLOROUT, 0, 1); + output_line(ctx, "%s_oC0 = %s_r0;", shstr, shstr); + } // if + else if (shader_is_vertex(ctx)) + { +#ifdef MOJOSHADER_FLIP_RENDERTARGET + output_line(ctx, "gl_Position.y = gl_Position.y * vpFlip;"); +#endif +#ifdef MOJOSHADER_DEPTH_CLIPPING + output_line(ctx, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;"); +#endif + } // else if + + // force a RET opcode if we're at the end of the stream without one. + if (ctx->previous_opcode != OPCODE_RET) + emit_GLSL_RET(ctx); +} // emit_GLSL_end + +void emit_GLSL_phase(Context *ctx) +{ + // no-op in GLSL. +} // emit_GLSL_phase + +void output_GLSL_uniform_array(Context *ctx, const RegisterType regtype, + const int size) +{ + if (size > 0) + { + char buf[64]; + get_GLSL_uniform_array_varname(ctx, regtype, buf, sizeof (buf)); + const char *typ; + switch (regtype) + { + case REG_TYPE_CONST: typ = "vec4"; break; + case REG_TYPE_CONSTINT: typ ="ivec4"; break; + case REG_TYPE_CONSTBOOL: typ = "bool"; break; + default: + { + fail(ctx, "BUG: used a uniform we don't know how to define."); + return; + } // default + } // switch + output_line(ctx, "uniform %s %s[%d];", typ, buf, size); + } // if +} // output_GLSL_uniform_array + +void emit_GLSL_finalize(Context *ctx) +{ + // throw some blank lines around to make source more readable. + push_output(ctx, &ctx->globals); + output_blank_line(ctx); + pop_output(ctx); + + // If we had a relative addressing of REG_TYPE_INPUT, we need to build + // an array for it at the start of main(). GLSL doesn't let you specify + // arrays of attributes. + //vec4 blah_array[BIGGEST_ARRAY]; + if (ctx->have_relative_input_registers) // !!! FIXME + fail(ctx, "Relative addressing of input registers not supported."); + + push_output(ctx, &ctx->preflight); + output_GLSL_uniform_array(ctx, REG_TYPE_CONST, ctx->uniform_float4_count); + output_GLSL_uniform_array(ctx, REG_TYPE_CONSTINT, ctx->uniform_int4_count); + output_GLSL_uniform_array(ctx, REG_TYPE_CONSTBOOL, ctx->uniform_bool_count); +#ifdef MOJOSHADER_FLIP_RENDERTARGET + if (shader_is_vertex(ctx)) + output_line(ctx, "uniform float vpFlip;"); +#endif + if (ctx->need_max_float) + output_line(ctx, "const float FLT_MAX = 1e38;"); + pop_output(ctx); +} // emit_GLSL_finalize + +void emit_GLSL_global(Context *ctx, RegisterType regtype, int regnum) +{ + char varname[64]; + get_GLSL_varname_in_buf(ctx, regtype, regnum, varname, sizeof (varname)); + + push_output(ctx, &ctx->globals); + switch (regtype) + { + case REG_TYPE_ADDRESS: + if (shader_is_vertex(ctx)) + output_line(ctx, "ivec4 %s;", varname); + else if (shader_is_pixel(ctx)) // actually REG_TYPE_TEXTURE. + { + // We have to map texture registers to temps for ps_1_1, since + // they work like temps, initialize with tex coords, and the + // ps_1_1 TEX opcode expects to overwrite it. + if (!shader_version_atleast(ctx, 1, 4)) + { + // GLSL ES does not have gl_TexCoord! + // Also, gl_TexCoord[4+] is unreliable! +#if SUPPORT_PROFILE_GLSLES + const int skipGLTexCoord = support_glsles(ctx) || (regnum >= 4); +#else + const int skipGLTexCoord = (regnum >= 4); +#endif + if (skipGLTexCoord) + output_line(ctx, "vec4 %s = io_%i_%i;", + varname, MOJOSHADER_USAGE_TEXCOORD, regnum); + else + output_line(ctx, "vec4 %s = gl_TexCoord[%d];", + varname, regnum); + } // if + } // else if + break; + case REG_TYPE_PREDICATE: + output_line(ctx, "bvec4 %s;", varname); + break; + case REG_TYPE_TEMP: + output_line(ctx, "vec4 %s;", varname); + break; + case REG_TYPE_LOOP: + break; // no-op. We declare these in for loops at the moment. + case REG_TYPE_LABEL: + break; // no-op. If we see it here, it means we optimized it out. + default: + fail(ctx, "BUG: we used a register we don't know how to define."); + break; + } // switch + pop_output(ctx); +} // emit_GLSL_global + +void emit_GLSL_array(Context *ctx, VariableList *var) +{ + // All uniforms (except constant arrays, which only get pushed once at + // compile time) are now packed into a single array, so we can batch + // the uniform transfers. So this doesn't actually define an array + // here; the one, big array is emitted during finalization instead. + // However, we need to #define the offset into the one, big array here, + // and let dereferences use that #define. + const int base = var->index; + const int glslbase = ctx->uniform_float4_count; + push_output(ctx, &ctx->globals); + output_line(ctx, "#define ARRAYBASE_%d %d", base, glslbase); + pop_output(ctx); + var->emit_position = glslbase; +} // emit_GLSL_array + +void emit_GLSL_const_array(Context *ctx, const ConstantsList *clist, + int base, int size) +{ + char varname[64]; + get_GLSL_const_array_varname_in_buf(ctx,base,size,varname,sizeof(varname)); + +#if 0 + // !!! FIXME: fails on Nvidia's and Apple's GL, even with #version 120. + // !!! FIXME: (the 1.20 spec says it should work, though, I think...) + if (support_glsl120(ctx)) + { + // GLSL 1.20 can do constant arrays. + const char *cstr = NULL; + push_output(ctx, &ctx->globals); + output_line(ctx, "const vec4 %s[%d] = vec4[%d](", varname, size, size); + ctx->indent++; + + int i; + for (i = 0; i < size; i++) + { + while (clist->constant.type != MOJOSHADER_UNIFORM_FLOAT) + clist = clist->next; + assert(clist->constant.index == (base + i)); + + char val0[32]; + char val1[32]; + char val2[32]; + char val3[32]; + floatstr(ctx, val0, sizeof (val0), clist->constant.value.f[0], 1); + floatstr(ctx, val1, sizeof (val1), clist->constant.value.f[1], 1); + floatstr(ctx, val2, sizeof (val2), clist->constant.value.f[2], 1); + floatstr(ctx, val3, sizeof (val3), clist->constant.value.f[3], 1); + + output_line(ctx, "vec4(%s, %s, %s, %s)%s", val0, val1, val2, val3, + (i < (size-1)) ? "," : ""); + + clist = clist->next; + } // for + + ctx->indent--; + output_line(ctx, ");"); + pop_output(ctx); + } // if + + else +#endif + { + // stock GLSL 1.0 can't do constant arrays, so make a uniform array + // and have the OpenGL glue assign it at link time. Lame! + push_output(ctx, &ctx->globals); + output_line(ctx, "uniform vec4 %s[%d];", varname, size); + pop_output(ctx); + } // else +} // emit_GLSL_const_array + +void emit_GLSL_uniform(Context *ctx, RegisterType regtype, int regnum, + const VariableList *var) +{ + // Now that we're pushing all the uniforms as one big array, pack these + // down, so if we only use register c439, it'll actually map to + // glsl_uniforms_vec4[0]. As we push one big array, this will prevent + // uploading unused data. + + char varname[64]; + char name[64]; + int index = 0; + + get_GLSL_varname_in_buf(ctx, regtype, regnum, varname, sizeof (varname)); + + push_output(ctx, &ctx->globals); + + if (var == NULL) + { + get_GLSL_uniform_array_varname(ctx, regtype, name, sizeof (name)); + + if (regtype == REG_TYPE_CONST) + index = ctx->uniform_float4_count; + else if (regtype == REG_TYPE_CONSTINT) + index = ctx->uniform_int4_count; + else if (regtype == REG_TYPE_CONSTBOOL) + index = ctx->uniform_bool_count; + else // get_GLSL_uniform_array_varname() would have called fail(). + assert(!(ctx->isfail)); + + output_line(ctx, "#define %s %s[%d]", varname, name, index); + } // if + + else + { + const int arraybase = var->index; + if (var->constant) + { + get_GLSL_const_array_varname_in_buf(ctx, arraybase, var->count, + name, sizeof (name)); + index = (regnum - arraybase); + } // if + else + { + assert(var->emit_position != -1); + get_GLSL_uniform_array_varname(ctx, regtype, name, sizeof (name)); + index = (regnum - arraybase) + var->emit_position; + } // else + + output_line(ctx, "#define %s %s[%d]", varname, name, index); + } // else + + pop_output(ctx); +} // emit_GLSL_uniform + +void emit_GLSL_sampler(Context *ctx,int stage,TextureType ttype,int tb) +{ + const char *type = ""; + switch (ttype) + { + case TEXTURE_TYPE_2D: type = "sampler2D"; break; + case TEXTURE_TYPE_CUBE: type = "samplerCube"; break; + case TEXTURE_TYPE_VOLUME: type = "sampler3D"; break; + default: fail(ctx, "BUG: used a sampler we don't know how to define."); + } // switch + + char var[64]; + get_GLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, stage, var, sizeof (var)); + + push_output(ctx, &ctx->globals); + output_line(ctx, "uniform %s %s;", type, var); + if (tb) // This sampler used a ps_1_1 TEXBEM opcode? + { + char name[64]; + const int index = ctx->uniform_float4_count; + ctx->uniform_float4_count += 2; + get_GLSL_uniform_array_varname(ctx, REG_TYPE_CONST, name, sizeof (name)); + output_line(ctx, "#define %s_texbem %s[%d]", var, name, index); + output_line(ctx, "#define %s_texbeml %s[%d]", var, name, index+1); + } // if + pop_output(ctx); +} // emit_GLSL_sampler + +void emit_GLSL_attribute(Context *ctx, RegisterType regtype, int regnum, + MOJOSHADER_usage usage, int index, int wmask, + int flags) +{ + // !!! FIXME: this function doesn't deal with write masks at all yet! + const char *qualifier_in; + const char *qualifier_out; + const char *usage_str = NULL; + const char *arrayleft = ""; + const char *arrayright = ""; + char index_str[16] = { '\0' }; + char var[64]; + + get_GLSL_varname_in_buf(ctx, regtype, regnum, var, sizeof (var)); + + //assert((flags & MOD_PP) == 0); // !!! FIXME: is PP allowed? + + if (index != 0) // !!! FIXME: a lot of these MUST be zero. + snprintf(index_str, sizeof (index_str), "%u", (uint) index); + + if (shader_is_vertex(ctx)) + { + if (support_glsles3(ctx)) + { + qualifier_in = "in"; + qualifier_out = "out"; + } + else + { + qualifier_in = "attribute"; + qualifier_out = "varying"; + } + + // pre-vs3 output registers. + // these don't ever happen in DCL opcodes, I think. Map to vs_3_* + // output registers. + if (!shader_version_atleast(ctx, 3, 0)) + { + if (regtype == REG_TYPE_RASTOUT) + { + regtype = REG_TYPE_OUTPUT; + index = regnum; + switch ((const RastOutType) regnum) + { + case RASTOUT_TYPE_POSITION: + usage = MOJOSHADER_USAGE_POSITION; + break; + case RASTOUT_TYPE_FOG: + usage = MOJOSHADER_USAGE_FOG; + break; + case RASTOUT_TYPE_POINT_SIZE: + usage = MOJOSHADER_USAGE_POINTSIZE; + break; + } // switch + } // if + + else if (regtype == REG_TYPE_ATTROUT) + { + regtype = REG_TYPE_OUTPUT; + usage = MOJOSHADER_USAGE_COLOR; + index = regnum; + } // else if + + else if (regtype == REG_TYPE_TEXCRDOUT) + { + regtype = REG_TYPE_OUTPUT; + usage = MOJOSHADER_USAGE_TEXCOORD; + index = regnum; + } // else if + } // if + + // to avoid limitations of various GL entry points for input + // attributes (glSecondaryColorPointer() can only take 3 component + // items, glVertexPointer() can't do GL_UNSIGNED_BYTE, many other + // issues), we set up all inputs as generic vertex attributes, so we + // can pass data in just about any form, and ignore the built-in GLSL + // attributes like gl_SecondaryColor. Output needs to use the the + // built-ins, though, but we don't have to worry about the GL entry + // point limitations there. + + if (regtype == REG_TYPE_INPUT) + { + push_output(ctx, &ctx->globals); + output_line(ctx, "%s vec4 %s;", qualifier_in, var); + pop_output(ctx); + } // if + + else if (regtype == REG_TYPE_OUTPUT) + { + switch (usage) + { + case MOJOSHADER_USAGE_POSITION: + if (index == 0) + { + usage_str = "gl_Position"; + } // if + break; + case MOJOSHADER_USAGE_POINTSIZE: + if (index == 0) + { + usage_str = "gl_PointSize"; + } // if + else + { + push_output(ctx, &ctx->globals); +#if SUPPORT_PROFILE_GLSLES + if (support_glsles(ctx)) + output_line(ctx, "%s highp float io_%i_%i;", qualifier_out, usage, index); + else +#endif + output_line(ctx, "varying float io_%i_%i;", usage, index); + output_line(ctx, "#define %s io_%i_%i", var, usage, index); + pop_output(ctx); + return; + } + break; + case MOJOSHADER_USAGE_COLOR: +#if SUPPORT_PROFILE_GLSLES + if (support_glsles(ctx)) + break; // GLSL ES does not have gl_FrontColor +#endif + index_str[0] = '\0'; // no explicit number. + if (index == 0) + { + usage_str = "gl_FrontColor"; + } // if + else if (index == 1) + { + usage_str = "gl_FrontSecondaryColor"; + } // else if + break; + case MOJOSHADER_USAGE_FOG: +#if SUPPORT_PROFILE_GLSLES + if (support_glsles(ctx)) + break; // GLSL ES does not have gl_FogFragCoord +#endif + if (index == 0) + { + usage_str = "gl_FogFragCoord"; + } // if + else + { + push_output(ctx, &ctx->globals); +#if SUPPORT_PROFILE_GLSLES + if (support_glsles(ctx)) + output_line(ctx, "%s highp float io_%i_%i;", qualifier_out, usage, index); + else +#endif + output_line(ctx, "varying float io_%i_%i;", usage, index); + output_line(ctx, "#define %s io_%i_%i", var, usage, index); + pop_output(ctx); + return; + } + break; + case MOJOSHADER_USAGE_TEXCOORD: +#if SUPPORT_PROFILE_GLSLES + if (support_glsles(ctx)) + break; // GLSL ES does not have gl_TexCoord +#endif + if (index >= 4) + break; // gl_TexCoord[4+] is unreliable! + snprintf(index_str, sizeof (index_str), "%u", (uint) index); + usage_str = "gl_TexCoord"; + arrayleft = "["; + arrayright = "]"; + break; + default: + // !!! FIXME: we need to deal with some more built-in varyings here. + break; + } // switch + + // !!! FIXME: the #define is a little hacky, but it means we don't + // !!! FIXME: have to track these separately if this works. + push_output(ctx, &ctx->globals); + // no mapping to built-in var? Just make it a regular global, pray. + if (usage_str == NULL) + { +#if SUPPORT_PROFILE_GLSLES + if (support_glsles(ctx)) + output_line(ctx, "%s highp vec4 io_%i_%i;", qualifier_out, usage, index); + else +#endif + output_line(ctx, "varying vec4 io_%i_%i;", usage, index); + output_line(ctx, "#define %s io_%i_%i", var, usage, index); + } // if + else + { + output_line(ctx, "#define %s %s%s%s%s", var, usage_str, + arrayleft, index_str, arrayright); + } // else + pop_output(ctx); + } // else if + + else + { + fail(ctx, "unknown vertex shader attribute register"); + } // else + } // if + + else if (shader_is_pixel(ctx)) + { + if (support_glsles3(ctx)) + qualifier_in = "in"; + else + qualifier_in = "varying"; + + // samplers DCLs get handled in emit_GLSL_sampler(). + + if (flags & MOD_CENTROID) // !!! FIXME + { + failf(ctx, "centroid unsupported in %s profile", ctx->profile->name); + return; + } // if + + if (regtype == REG_TYPE_COLOROUT) + { + // gl_FragColor/FragData were deprecated in favor of manually + // defining your own output variables, GLSL ES 3.x enforces the new + // syntax, so let's use it. + if (support_glsles3(ctx)) + { + usage_str = "_gl_FragData"; + snprintf(index_str, sizeof (index_str), "_%u", (uint) regnum ); + + push_output(ctx, &ctx->globals); + output_line(ctx, "layout(location = %u) out highp vec4 %s%s;", regnum, usage_str, index_str); + pop_output(ctx); + } + else + { + if (!ctx->have_multi_color_outputs) + usage_str = "gl_FragColor"; // maybe faster? + else + { + snprintf(index_str, sizeof (index_str), "%u", (uint) regnum); + usage_str = "gl_FragData"; + arrayleft = "["; + arrayright = "]"; + } // else + } // else + } // if + + else if (regtype == REG_TYPE_DEPTHOUT) + usage_str = "gl_FragDepth"; + + // !!! FIXME: can you actualy have a texture register with COLOR usage? + else if ((regtype == REG_TYPE_TEXTURE) || (regtype == REG_TYPE_INPUT)) + { +#if SUPPORT_PROFILE_GLSLES + if (!support_glsles(ctx)) + { +#endif + if (usage == MOJOSHADER_USAGE_TEXCOORD) + { + // ps_1_1 does a different hack for this attribute. + // Refer to emit_GLSL_global()'s REG_TYPE_ADDRESS code. + if (!shader_version_atleast(ctx, 1, 4)) + return; + else if (index < 4) // gl_TexCoord[4+] is unreliable! + { + snprintf(index_str, sizeof (index_str), "%u", (uint) index); + usage_str = "gl_TexCoord"; + arrayleft = "["; + arrayright = "]"; + } // else if + } // if + + else if (usage == MOJOSHADER_USAGE_COLOR) + { + index_str[0] = '\0'; // no explicit number. + if (index == 0) + { + usage_str = "gl_Color"; + } // if + else if (index == 1) + { + usage_str = "gl_SecondaryColor"; + } // else if + // FIXME: Does this even matter when we have varyings? -flibit + // else + // fail(ctx, "unsupported color index"); + } // else if +#if SUPPORT_PROFILE_GLSLES + } // if +#endif + } // else if + + else if (regtype == REG_TYPE_MISCTYPE) + { + const MiscTypeType mt = (MiscTypeType) regnum; + if (mt == MISCTYPE_TYPE_FACE) + { + push_output(ctx, &ctx->mainline_intro); + ctx->indent++; + output_line(ctx, "float %s = gl_FrontFacing ? 1.0 : -1.0;", var); + pop_output(ctx); + return; + } // if + else if (mt == MISCTYPE_TYPE_POSITION) + { + push_output(ctx, &ctx->globals); + output_line(ctx, "uniform vec2 vposFlip;"); + pop_output(ctx); + + // TODO: For half-pixel offset compensation, floor() this value! + push_output(ctx, &ctx->mainline_intro); + ctx->indent++; + output_line(ctx, "vec4 %s = vec4(gl_FragCoord.x, (gl_FragCoord.y * vposFlip.x) + vposFlip.y, gl_FragCoord.z, gl_FragCoord.w);", var); + pop_output(ctx); + return; + } // else if + else + { + fail(ctx, "BUG: unhandled misc register"); + } // else + } // else if + + else + { + fail(ctx, "unknown pixel shader attribute register"); + } // else + + push_output(ctx, &ctx->globals); + // no mapping to built-in var? Just make it a regular global, pray. + if (usage_str == NULL) + { +#if SUPPORT_PROFILE_GLSLES + if (support_glsles(ctx)) + output_line(ctx, "%s highp vec4 io_%i_%i;", qualifier_in, usage, index); + else +#endif + output_line(ctx, "varying vec4 io_%i_%i;", usage, index); + output_line(ctx, "#define %s io_%i_%i", var, usage, index); + } // if + else + { + output_line(ctx, "#define %s %s%s%s%s", var, usage_str, + arrayleft, index_str, arrayright); + } // else + pop_output(ctx); + } // else if + + else + { + fail(ctx, "Unknown shader type"); // state machine should catch this. + } // else +} // emit_GLSL_attribute + +void emit_GLSL_NOP(Context *ctx) +{ + // no-op is a no-op. :) +} // emit_GLSL_NOP + +void emit_GLSL_MOV(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "%s", src0); + output_line(ctx, "%s", code); +} // emit_GLSL_MOV + +void emit_GLSL_ADD(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "%s + %s", src0, src1); + output_line(ctx, "%s", code); +} // emit_GLSL_ADD + +void emit_GLSL_SUB(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "%s - %s", src0, src1); + output_line(ctx, "%s", code); +} // emit_GLSL_SUB + +void emit_GLSL_MAD(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char src2[64]; make_GLSL_srcarg_string_masked(ctx, 2, src2, sizeof (src2)); + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "(%s * %s) + %s", src0, src1, src2); + output_line(ctx, "%s", code); +} // emit_GLSL_MAD + +void emit_GLSL_MUL(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "%s * %s", src0, src1); + output_line(ctx, "%s", code); +} // emit_GLSL_MUL + +void emit_GLSL_RCP(Context *ctx) +{ + const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); + char cast[16] = { '\0' }; + if (vecsize != 1) + snprintf(cast, sizeof (cast), "vec%d", vecsize); + char src0[64]; make_GLSL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + char code[128]; + ctx->need_max_float = 1; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "%s((%s == 0.0) ? FLT_MAX : 1.0 / %s)", cast, src0, src0); + output_line(ctx, "%s", code); +} // emit_GLSL_RCP + +void emit_GLSL_RSQ(Context *ctx) +{ + const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); + char cast[16] = { '\0' }; + if (vecsize != 1) + snprintf(cast, sizeof (cast), "vec%d", vecsize); + + char src0[64]; make_GLSL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + char code[128]; + ctx->need_max_float = 1; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "%s((%s == 0.0) ? FLT_MAX : inversesqrt(abs(%s)))", cast, src0, src0); + output_line(ctx, "%s", code); +} // emit_GLSL_RSQ + +void emit_GLSL_dotprod(Context *ctx, const char *src0, const char *src1, + const char *extra) +{ + const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); + char castleft[16] = { '\0' }; + const char *castright = ""; + if (vecsize != 1) + { + snprintf(castleft, sizeof (castleft), "vec%d(", vecsize); + castright = ")"; + } // if + + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "%sdot(%s, %s)%s%s", + castleft, src0, src1, extra, castright); + output_line(ctx, "%s", code); +} // emit_GLSL_dotprod + +void emit_GLSL_DP3(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_GLSL_srcarg_string_vec3(ctx, 1, src1, sizeof (src1)); + emit_GLSL_dotprod(ctx, src0, src1, ""); +} // emit_GLSL_DP3 + +void emit_GLSL_DP4(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_GLSL_srcarg_string_full(ctx, 1, src1, sizeof (src1)); + emit_GLSL_dotprod(ctx, src0, src1, ""); +} // emit_GLSL_DP4 + +void emit_GLSL_MIN(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "min(%s, %s)", src0, src1); + output_line(ctx, "%s", code); +} // emit_GLSL_MIN + +void emit_GLSL_MAX(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "max(%s, %s)", src0, src1); + output_line(ctx, "%s", code); +} // emit_GLSL_MAX + +void emit_GLSL_SLT(Context *ctx) +{ + const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + + // float(bool) or vec(bvec) results in 0.0 or 1.0, like SLT wants. + if (vecsize == 1) + make_GLSL_destarg_assign(ctx, code, sizeof (code), "float(%s < %s)", src0, src1); + else + { + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "vec%d(lessThan(%s, %s))", + vecsize, src0, src1); + } // else + output_line(ctx, "%s", code); +} // emit_GLSL_SLT + +void emit_GLSL_SGE(Context *ctx) +{ + const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + + // float(bool) or vec(bvec) results in 0.0 or 1.0, like SGE wants. + if (vecsize == 1) + { + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "float(%s >= %s)", src0, src1); + } // if + else + { + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "vec%d(greaterThanEqual(%s, %s))", + vecsize, src0, src1); + } // else + output_line(ctx, "%s", code); +} // emit_GLSL_SGE + +void emit_GLSL_EXP(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "exp2(%s)", src0); + output_line(ctx, "%s", code); +} // emit_GLSL_EXP + +void emit_GLSL_LOG(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "log2(%s)", src0); + output_line(ctx, "%s", code); +} // emit_GLSL_LOG + +void emit_GLSL_LIT_helper(Context *ctx) +{ + const char *maxp = "127.9961"; // value from the dx9 reference. + + if (ctx->glsl_generated_lit_helper) + return; + + ctx->glsl_generated_lit_helper = 1; + + push_output(ctx, &ctx->helpers); + output_line(ctx, "vec4 LIT(const vec4 src)"); + output_line(ctx, "{"); ctx->indent++; + output_line(ctx, "float power = clamp(src.w, -%s, %s);",maxp,maxp); + output_line(ctx, "vec4 retval = vec4(1.0, 0.0, 0.0, 1.0);"); + output_line(ctx, "if (src.x > 0.0) {"); ctx->indent++; + output_line(ctx, "retval.y = src.x;"); + output_line(ctx, "if (src.y > 0.0) {"); ctx->indent++; + output_line(ctx, "retval.z = pow(src.y, power);"); ctx->indent--; + output_line(ctx, "}"); ctx->indent--; + output_line(ctx, "}"); + output_line(ctx, "return retval;"); ctx->indent--; + output_line(ctx, "}"); + output_blank_line(ctx); + pop_output(ctx); +} // emit_GLSL_LIT_helper + +void emit_GLSL_LIT(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); + char code[128]; + emit_GLSL_LIT_helper(ctx); + make_GLSL_destarg_assign(ctx, code, sizeof (code), "LIT(%s)", src0); + output_line(ctx, "%s", code); +} // emit_GLSL_LIT + +void emit_GLSL_DST(Context *ctx) +{ + // !!! FIXME: needs to take ctx->dst_arg.writemask into account. + char src0_y[64]; make_GLSL_srcarg_string_y(ctx, 0, src0_y, sizeof (src0_y)); + char src1_y[64]; make_GLSL_srcarg_string_y(ctx, 1, src1_y, sizeof (src1_y)); + char src0_z[64]; make_GLSL_srcarg_string_z(ctx, 0, src0_z, sizeof (src0_z)); + char src1_w[64]; make_GLSL_srcarg_string_w(ctx, 1, src1_w, sizeof (src1_w)); + + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "vec4(1.0, %s * %s, %s, %s)", + src0_y, src1_y, src0_z, src1_w); + output_line(ctx, "%s", code); +} // emit_GLSL_DST + +void emit_GLSL_LRP(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char src2[64]; make_GLSL_srcarg_string_masked(ctx, 2, src2, sizeof (src2)); + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "mix(%s, %s, %s)", + src2, src1, src0); + output_line(ctx, "%s", code); +} // emit_GLSL_LRP + +void emit_GLSL_FRC(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "fract(%s)", src0); + output_line(ctx, "%s", code); +} // emit_GLSL_FRC + +void emit_GLSL_M4X4(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); + char row0[64]; make_GLSL_srcarg_string_full(ctx, 1, row0, sizeof (row0)); + char row1[64]; make_GLSL_srcarg_string_full(ctx, 2, row1, sizeof (row1)); + char row2[64]; make_GLSL_srcarg_string_full(ctx, 3, row2, sizeof (row2)); + char row3[64]; make_GLSL_srcarg_string_full(ctx, 4, row3, sizeof (row3)); + char code[256]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "vec4(dot(%s, %s), dot(%s, %s), dot(%s, %s), dot(%s, %s))", + src0, row0, src0, row1, src0, row2, src0, row3); + output_line(ctx, "%s", code); +} // emit_GLSL_M4X4 + +void emit_GLSL_M4X3(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); + char row0[64]; make_GLSL_srcarg_string_full(ctx, 1, row0, sizeof (row0)); + char row1[64]; make_GLSL_srcarg_string_full(ctx, 2, row1, sizeof (row1)); + char row2[64]; make_GLSL_srcarg_string_full(ctx, 3, row2, sizeof (row2)); + char code[256]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "vec3(dot(%s, %s), dot(%s, %s), dot(%s, %s))", + src0, row0, src0, row1, src0, row2); + output_line(ctx, "%s", code); +} // emit_GLSL_M4X3 + +void emit_GLSL_M3X4(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + char row0[64]; make_GLSL_srcarg_string_vec3(ctx, 1, row0, sizeof (row0)); + char row1[64]; make_GLSL_srcarg_string_vec3(ctx, 2, row1, sizeof (row1)); + char row2[64]; make_GLSL_srcarg_string_vec3(ctx, 3, row2, sizeof (row2)); + char row3[64]; make_GLSL_srcarg_string_vec3(ctx, 4, row3, sizeof (row3)); + + char code[256]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "vec4(dot(%s, %s), dot(%s, %s), " + "dot(%s, %s), dot(%s, %s))", + src0, row0, src0, row1, + src0, row2, src0, row3); + output_line(ctx, "%s", code); +} // emit_GLSL_M3X4 + +void emit_GLSL_M3X3(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + char row0[64]; make_GLSL_srcarg_string_vec3(ctx, 1, row0, sizeof (row0)); + char row1[64]; make_GLSL_srcarg_string_vec3(ctx, 2, row1, sizeof (row1)); + char row2[64]; make_GLSL_srcarg_string_vec3(ctx, 3, row2, sizeof (row2)); + char code[256]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "vec3(dot(%s, %s), dot(%s, %s), dot(%s, %s))", + src0, row0, src0, row1, src0, row2); + output_line(ctx, "%s", code); +} // emit_GLSL_M3X3 + +void emit_GLSL_M3X2(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + char row0[64]; make_GLSL_srcarg_string_vec3(ctx, 1, row0, sizeof (row0)); + char row1[64]; make_GLSL_srcarg_string_vec3(ctx, 2, row1, sizeof (row1)); + + char code[256]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "vec2(dot(%s, %s), dot(%s, %s))", + src0, row0, src0, row1); + output_line(ctx, "%s", code); +} // emit_GLSL_M3X2 + +void emit_GLSL_CALL(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + if (ctx->loops > 0) + output_line(ctx, "%s(aL);", src0); + else + output_line(ctx, "%s();", src0); +} // emit_GLSL_CALL + +void emit_GLSL_CALLNZ(Context *ctx) +{ + // !!! FIXME: if src1 is a constbool that's true, we can remove the + // !!! FIXME: if. If it's false, we can make this a no-op. + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + + if (ctx->loops > 0) + output_line(ctx, "if (%s) { %s(aL); }", src1, src0); + else + output_line(ctx, "if (%s) { %s(); }", src1, src0); +} // emit_GLSL_CALLNZ + +void emit_GLSL_LOOP(Context *ctx) +{ + // !!! FIXME: swizzle? + char var[64]; get_GLSL_srcarg_varname(ctx, 1, var, sizeof (var)); + assert(ctx->source_args[0].regnum == 0); // in case they add aL1 someday. + output_line(ctx, "{"); + ctx->indent++; + output_line(ctx, "const int aLend = %s.x + %s.y;", var, var); + output_line(ctx, "for (int aL = %s.y; aL < aLend; aL += %s.z) {", var, var); + ctx->indent++; +} // emit_GLSL_LOOP + +void emit_GLSL_RET(Context *ctx) +{ + // thankfully, the MSDN specs say a RET _has_ to end a function...no + // early returns. So if you hit one, you know you can safely close + // a high-level function. + ctx->indent--; + output_line(ctx, "}"); + output_blank_line(ctx); + set_output(ctx, &ctx->subroutines); // !!! FIXME: is this for LABEL? Maybe set it there so we don't allocate unnecessarily. +} // emit_GLSL_RET + +void emit_GLSL_ENDLOOP(Context *ctx) +{ + ctx->indent--; + output_line(ctx, "}"); + ctx->indent--; + output_line(ctx, "}"); +} // emit_GLSL_ENDLOOP + +void emit_GLSL_LABEL(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + const int label = ctx->source_args[0].regnum; + RegisterList *reg = reglist_find(&ctx->used_registers, REG_TYPE_LABEL, label); + assert(ctx->output == ctx->subroutines); // not mainline, etc. + assert(ctx->indent == 0); // we shouldn't be in the middle of a function. + + // MSDN specs say CALL* has to come before the LABEL, so we know if we + // can ditch the entire function here as unused. + if (reg == NULL) + set_output(ctx, &ctx->ignore); // Func not used. Parse, but don't output. + + // !!! FIXME: it would be nice if we could determine if a function is + // !!! FIXME: only called once and, if so, forcibly inline it. + + const char *uses_loopreg = ((reg) && (reg->misc == 1)) ? "int aL" : ""; + output_line(ctx, "void %s(%s)", src0, uses_loopreg); + output_line(ctx, "{"); + ctx->indent++; +} // emit_GLSL_LABEL + +void emit_GLSL_DCL(Context *ctx) +{ + // no-op. We do this in our emit_attribute() and emit_uniform(). +} // emit_GLSL_DCL + +void emit_GLSL_POW(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "pow(abs(%s), %s)", src0, src1); + output_line(ctx, "%s", code); +} // emit_GLSL_POW + +void emit_GLSL_CRS(Context *ctx) +{ + // !!! FIXME: needs to take ctx->dst_arg.writemask into account. + char src0[64]; make_GLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_GLSL_srcarg_string_vec3(ctx, 1, src1, sizeof (src1)); + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "cross(%s, %s)", src0, src1); + output_line(ctx, "%s", code); +} // emit_GLSL_CRS + +void emit_GLSL_SGN(Context *ctx) +{ + // (we don't need the temporary registers specified for the D3D opcode.) + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "sign(%s)", src0); + output_line(ctx, "%s", code); +} // emit_GLSL_SGN + +void emit_GLSL_ABS(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "abs(%s)", src0); + output_line(ctx, "%s", code); +} // emit_GLSL_ABS + +void emit_GLSL_NRM(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "normalize(%s)", src0); + output_line(ctx, "%s", code); +} // emit_GLSL_NRM + +void emit_GLSL_SINCOS(Context *ctx) +{ + // we don't care about the temp registers that <= sm2 demands; ignore them. + // sm2 also talks about what components are left untouched vs. undefined, + // but we just leave those all untouched with GLSL write masks (which + // would fulfill the "undefined" requirement, too). + const int mask = ctx->dest_arg.writemask; + char src0[64]; make_GLSL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + char code[128] = { '\0' }; + + if (writemask_x(mask)) + make_GLSL_destarg_assign(ctx, code, sizeof (code), "cos(%s)", src0); + else if (writemask_y(mask)) + make_GLSL_destarg_assign(ctx, code, sizeof (code), "sin(%s)", src0); + else if (writemask_xy(mask)) + { + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "vec2(cos(%s), sin(%s))", src0, src0); + } // else if + + output_line(ctx, "%s", code); +} // emit_GLSL_SINCOS + +void emit_GLSL_REP(Context *ctx) +{ + // !!! FIXME: + // msdn docs say legal loop values are 0 to 255. We can check DEFI values + // at parse time, but if they are pulling a value from a uniform, do + // we clamp here? + // !!! FIXME: swizzle is legal here, right? + char src0[64]; make_GLSL_srcarg_string_x(ctx, 0, src0, sizeof (src0)); + const uint rep = (uint) ctx->reps; + output_line(ctx, "for (int rep%u = 0; rep%u < %s; rep%u++) {", + rep, rep, src0, rep); + ctx->indent++; +} // emit_GLSL_REP + +void emit_GLSL_ENDREP(Context *ctx) +{ + ctx->indent--; + output_line(ctx, "}"); +} // emit_GLSL_ENDREP + +void emit_GLSL_IF(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + output_line(ctx, "if (%s) {", src0); + ctx->indent++; +} // emit_GLSL_IF + +void emit_GLSL_IFC(Context *ctx) +{ + const char *comp = get_GLSL_comparison_string_scalar(ctx); + char src0[64]; make_GLSL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_GLSL_srcarg_string_scalar(ctx, 1, src1, sizeof (src1)); + output_line(ctx, "if (%s %s %s) {", src0, comp, src1); + ctx->indent++; +} // emit_GLSL_IFC + +void emit_GLSL_ELSE(Context *ctx) +{ + ctx->indent--; + output_line(ctx, "} else {"); + ctx->indent++; +} // emit_GLSL_ELSE + +void emit_GLSL_ENDIF(Context *ctx) +{ + ctx->indent--; + output_line(ctx, "}"); +} // emit_GLSL_ENDIF + +void emit_GLSL_BREAK(Context *ctx) +{ + output_line(ctx, "break;"); +} // emit_GLSL_BREAK + +void emit_GLSL_BREAKC(Context *ctx) +{ + const char *comp = get_GLSL_comparison_string_scalar(ctx); + char src0[64]; make_GLSL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_GLSL_srcarg_string_scalar(ctx, 1, src1, sizeof (src1)); + output_line(ctx, "if (%s %s %s) { break; }", src0, comp, src1); +} // emit_GLSL_BREAKC + +void emit_GLSL_MOVA(Context *ctx) +{ + const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + + if (vecsize == 1) + { + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "int(floor(abs(%s) + 0.5) * sign(%s))", + src0, src0); + } // if + + else + { + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s))", + vecsize, src0, vecsize, src0); + } // else + + output_line(ctx, "%s", code); +} // emit_GLSL_MOVA + +void emit_GLSL_DEFB(Context *ctx) +{ + char varname[64]; get_GLSL_destarg_varname(ctx, varname, sizeof (varname)); + push_output(ctx, &ctx->globals); + output_line(ctx, "const bool %s = %s;", + varname, ctx->dwords[0] ? "true" : "false"); + pop_output(ctx); +} // emit_GLSL_DEFB + +void emit_GLSL_DEFI(Context *ctx) +{ + char varname[64]; get_GLSL_destarg_varname(ctx, varname, sizeof (varname)); + const int32 *x = (const int32 *) ctx->dwords; + push_output(ctx, &ctx->globals); + output_line(ctx, "const ivec4 %s = ivec4(%d, %d, %d, %d);", + varname, (int) x[0], (int) x[1], (int) x[2], (int) x[3]); + pop_output(ctx); +} // emit_GLSL_DEFI + +EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXCRD) + +void emit_GLSL_TEXKILL(Context *ctx) +{ + char dst[64]; get_GLSL_destarg_varname(ctx, dst, sizeof (dst)); + output_line(ctx, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;", dst); +} // emit_GLSL_TEXKILL + +void emit_GLSL_TEXLD(Context *ctx) +{ + if (!shader_version_atleast(ctx, 1, 4)) + { + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; + char sampler[64]; + char code[128] = {0}; + + RegisterList *sreg; + sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, info->regnum); + const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_GLSL_destarg_varname(ctx, dst, sizeof (dst)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + + if (ttype == TEXTURE_TYPE_2D) + { + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "texture2D(%s, %s.xy)", + sampler, dst); + } + else if (ttype == TEXTURE_TYPE_CUBE) + { + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "textureCube(%s, %s.xyz)", + sampler, dst); + } + else if (ttype == TEXTURE_TYPE_VOLUME) + { + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "texture3D(%s, %s.xyz)", + sampler, dst); + } + else + { + fail(ctx, "unexpected texture type"); + } // else + output_line(ctx, "%s", code); + } // if + + else if (!shader_version_atleast(ctx, 2, 0)) + { + // ps_1_4 is different, too! + fail(ctx, "TEXLD == Shader Model 1.4 unimplemented."); // !!! FIXME + return; + } // else if + + else + { + const SourceArgInfo *samp_arg = &ctx->source_args[1]; + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, + samp_arg->regnum); + const char *funcname = NULL; + char src0[64] = { '\0' }; + char src1[64]; get_GLSL_srcarg_varname(ctx, 1, src1, sizeof (src1)); // !!! FIXME: SRC_MOD? + + if (sreg == NULL) + { + fail(ctx, "TEXLD using undeclared sampler"); + return; + } // if + + // !!! FIXME: does the d3d bias value map directly to GLSL? + const char *biassep = ""; + char bias[64] = { '\0' }; + if (ctx->instruction_controls == CONTROL_TEXLDB) + { + biassep = ", "; + make_GLSL_srcarg_string_w(ctx, 0, bias, sizeof (bias)); + } // if + + switch ((const TextureType) sreg->index) + { + case TEXTURE_TYPE_2D: + if (ctx->instruction_controls == CONTROL_TEXLDP) + { + funcname = "texture2DProj"; + make_GLSL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); + } // if + else // texld/texldb + { + funcname = "texture2D"; + make_GLSL_srcarg_string_vec2(ctx, 0, src0, sizeof (src0)); + } // else + break; + case TEXTURE_TYPE_CUBE: + if (ctx->instruction_controls == CONTROL_TEXLDP) + fail(ctx, "TEXLDP on a cubemap"); // !!! FIXME: is this legal? + funcname = "textureCube"; + make_GLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + break; + case TEXTURE_TYPE_VOLUME: + if (ctx->instruction_controls == CONTROL_TEXLDP) + { + funcname = "texture3DProj"; + make_GLSL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); + } // if + else // texld/texldb + { + funcname = "texture3D"; + make_GLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + } // else + break; + default: + fail(ctx, "unknown texture type"); + return; + } // switch + + assert(!isscalar(ctx, ctx->shader_type, samp_arg->regtype, samp_arg->regnum)); + char swiz_str[6] = { '\0' }; + make_GLSL_swizzle_string(swiz_str, sizeof (swiz_str), + samp_arg->swizzle, ctx->dest_arg.writemask); + + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "%s(%s, %s%s%s)%s", funcname, + src1, src0, biassep, bias, swiz_str); + + output_line(ctx, "%s", code); + } // else +} // emit_GLSL_TEXLD + + +void emit_GLSL_TEXBEM(Context *ctx) +{ + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; get_GLSL_destarg_varname(ctx, dst, sizeof (dst)); + char src[64]; get_GLSL_srcarg_varname(ctx, 0, src, sizeof (src)); + char sampler[64]; + char code[512]; + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_GLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "texture2D(%s, vec2(%s.x + (%s_texbem.x * %s.x) + (%s_texbem.z * %s.y)," + " %s.y + (%s_texbem.y * %s.x) + (%s_texbem.w * %s.y)))", + sampler, + dst, sampler, src, sampler, src, + dst, sampler, src, sampler, src); + + output_line(ctx, "%s", code); +} // emit_GLSL_TEXBEM + + +void emit_GLSL_TEXBEML(Context *ctx) +{ + // !!! FIXME: this code counts on the register not having swizzles, etc. + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; get_GLSL_destarg_varname(ctx, dst, sizeof (dst)); + char src[64]; get_GLSL_srcarg_varname(ctx, 0, src, sizeof (src)); + char sampler[64]; + char code[512]; + + get_GLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "(texture2D(%s, vec2(%s.x + (%s_texbem.x * %s.x) + (%s_texbem.z * %s.y)," + " %s.y + (%s_texbem.y * %s.x) + (%s_texbem.w * %s.y)))) *" + " ((%s.z * %s_texbeml.x) + %s_texbem.y)", + sampler, + dst, sampler, src, sampler, src, + dst, sampler, src, sampler, src, + src, sampler, sampler); + + output_line(ctx, "%s", code); +} // emit_GLSL_TEXBEML + +EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2AR) // !!! FIXME +EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2GB) // !!! FIXME + + +void emit_GLSL_TEXM3X2PAD(Context *ctx) +{ + // no-op ... work happens in emit_GLSL_TEXM3X2TEX(). +} // emit_GLSL_TEXM3X2PAD + +void emit_GLSL_TEXM3X2TEX(Context *ctx) +{ + if (ctx->texm3x2pad_src0 == -1) + return; + + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char sampler[64]; + char code[512]; + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_GLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x2pad_src0, + src0, sizeof (src0)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x2pad_dst0, + src1, sizeof (src1)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src2, sizeof (src2)); + get_GLSL_destarg_varname(ctx, dst, sizeof (dst)); + + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "texture2D(%s, vec2(dot(%s.xyz, %s.xyz), dot(%s.xyz, %s.xyz)))", + sampler, src0, src1, src2, dst); + + output_line(ctx, "%s", code); +} // emit_GLSL_TEXM3X2TEX + +void emit_GLSL_TEXM3X3PAD(Context *ctx) +{ + // no-op ... work happens in emit_GLSL_TEXM3X3*(). +} // emit_GLSL_TEXM3X3PAD + +void emit_GLSL_TEXM3X3TEX(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char src3[64]; + char src4[64]; + char sampler[64]; + char code[512]; + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_GLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, + src0, sizeof (src0)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, + src1, sizeof (src1)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, + src2, sizeof (src2)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, + src3, sizeof (src3)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src4, sizeof (src4)); + get_GLSL_destarg_varname(ctx, dst, sizeof (dst)); + + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, + info->regnum); + const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); + const char *ttypestr = (ttype == TEXTURE_TYPE_CUBE) ? "Cube" : "3D"; + + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "texture%s(%s," + " vec3(dot(%s.xyz, %s.xyz)," + " dot(%s.xyz, %s.xyz)," + " dot(%s.xyz, %s.xyz)))", + ttypestr, sampler, src0, src1, src2, src3, dst, src4); + + output_line(ctx, "%s", code); +} // emit_GLSL_TEXM3X3TEX + +void emit_GLSL_TEXM3X3SPEC_helper(Context *ctx) +{ + if (ctx->glsl_generated_texm3x3spec_helper) + return; + + ctx->glsl_generated_texm3x3spec_helper = 1; + + push_output(ctx, &ctx->helpers); + output_line(ctx, "vec3 TEXM3X3SPEC_reflection(const vec3 normal, const vec3 eyeray)"); + output_line(ctx, "{"); ctx->indent++; + output_line(ctx, "return (2.0 * ((normal * eyeray) / (normal * normal)) * normal) - eyeray;"); ctx->indent--; + output_line(ctx, "}"); + output_blank_line(ctx); + pop_output(ctx); +} // emit_GLSL_TEXM3X3SPEC_helper + +void emit_GLSL_TEXM3X3SPEC(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char src3[64]; + char src4[64]; + char src5[64]; + char sampler[64]; + char code[512]; + + emit_GLSL_TEXM3X3SPEC_helper(ctx); + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_GLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, + src0, sizeof (src0)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, + src1, sizeof (src1)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, + src2, sizeof (src2)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, + src3, sizeof (src3)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src4, sizeof (src4)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[1].regnum, + src5, sizeof (src5)); + get_GLSL_destarg_varname(ctx, dst, sizeof (dst)); + + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, + info->regnum); + const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); + const char *ttypestr = (ttype == TEXTURE_TYPE_CUBE) ? "Cube" : "3D"; + + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "texture%s(%s, " + "TEXM3X3SPEC_reflection(" + "vec3(" + "dot(%s.xyz, %s.xyz), " + "dot(%s.xyz, %s.xyz), " + "dot(%s.xyz, %s.xyz)" + ")," + "%s.xyz," + ")" + ")", + ttypestr, sampler, src0, src1, src2, src3, dst, src4, src5); + + output_line(ctx, "%s", code); +} // emit_GLSL_TEXM3X3SPEC + +void emit_GLSL_TEXM3X3VSPEC(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char src3[64]; + char src4[64]; + char sampler[64]; + char code[512]; + + emit_GLSL_TEXM3X3SPEC_helper(ctx); + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_GLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, + src0, sizeof (src0)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, + src1, sizeof (src1)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, + src2, sizeof (src2)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, + src3, sizeof (src3)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src4, sizeof (src4)); + get_GLSL_destarg_varname(ctx, dst, sizeof (dst)); + + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, + info->regnum); + const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); + const char *ttypestr = (ttype == TEXTURE_TYPE_CUBE) ? "Cube" : "3D"; + + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "texture%s(%s, " + "TEXM3X3SPEC_reflection(" + "vec3(" + "dot(%s.xyz, %s.xyz), " + "dot(%s.xyz, %s.xyz), " + "dot(%s.xyz, %s.xyz)" + "), " + "vec3(%s.w, %s.w, %s.w)" + ")" + ")", + ttypestr, sampler, src0, src1, src2, src3, dst, src4, src0, src2, dst); + + output_line(ctx, "%s", code); +} // emit_GLSL_TEXM3X3VSPEC + +void emit_GLSL_EXPP(Context *ctx) +{ + // !!! FIXME: msdn's asm docs don't list this opcode, I'll have to check the driver documentation. + emit_GLSL_EXP(ctx); // I guess this is just partial precision EXP? +} // emit_GLSL_EXPP + +void emit_GLSL_LOGP(Context *ctx) +{ + // LOGP is just low-precision LOG, but we'll take the higher precision. + emit_GLSL_LOG(ctx); +} // emit_GLSL_LOGP + +// common code between CMP and CND. +void emit_GLSL_comparison_operations(Context *ctx, const char *cmp) +{ + int i, j; + DestArgInfo *dst = &ctx->dest_arg; + const SourceArgInfo *srcarg0 = &ctx->source_args[0]; + const int origmask = dst->writemask; + int used_swiz[4] = { 0, 0, 0, 0 }; + const int writemask[4] = { dst->writemask0, dst->writemask1, + dst->writemask2, dst->writemask3 }; + const int src0swiz[4] = { srcarg0->swizzle_x, srcarg0->swizzle_y, + srcarg0->swizzle_z, srcarg0->swizzle_w }; + + for (i = 0; i < 4; i++) + { + int mask = (1 << i); + + if (!writemask[i]) continue; + if (used_swiz[i]) continue; + + // This is a swizzle we haven't checked yet. + used_swiz[i] = 1; + + // see if there are any other elements swizzled to match (.yyyy) + for (j = i + 1; j < 4; j++) + { + if (!writemask[j]) continue; + if (src0swiz[i] != src0swiz[j]) continue; + mask |= (1 << j); + used_swiz[j] = 1; + } // for + + // okay, (mask) should be the writemask of swizzles we like. + + //return make_GLSL_srcarg_string(ctx, idx, (1 << 0)); + + char src0[64]; + char src1[64]; + char src2[64]; + make_GLSL_srcarg_string(ctx, 0, (1 << i), src0, sizeof (src0)); + make_GLSL_srcarg_string(ctx, 1, mask, src1, sizeof (src1)); + make_GLSL_srcarg_string(ctx, 2, mask, src2, sizeof (src2)); + + set_dstarg_writemask(dst, mask); + + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "((%s %s) ? %s : %s)", + src0, cmp, src1, src2); + output_line(ctx, "%s", code); + } // for + + set_dstarg_writemask(dst, origmask); +} // emit_GLSL_comparison_operations + +void emit_GLSL_CND(Context *ctx) +{ + emit_GLSL_comparison_operations(ctx, "> 0.5"); +} // emit_GLSL_CND + +void emit_GLSL_DEF(Context *ctx) +{ + const float *val = (const float *) ctx->dwords; // !!! FIXME: could be int? + char varname[64]; get_GLSL_destarg_varname(ctx, varname, sizeof (varname)); + char val0[32]; floatstr(ctx, val0, sizeof (val0), val[0], 1); + char val1[32]; floatstr(ctx, val1, sizeof (val1), val[1], 1); + char val2[32]; floatstr(ctx, val2, sizeof (val2), val[2], 1); + char val3[32]; floatstr(ctx, val3, sizeof (val3), val[3], 1); + + push_output(ctx, &ctx->globals); + output_line(ctx, "const vec4 %s = vec4(%s, %s, %s, %s);", + varname, val0, val1, val2, val3); + pop_output(ctx); +} // emit_GLSL_DEF + +EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2RGB) // !!! FIXME +EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXDP3TEX) // !!! FIXME +EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXM3X2DEPTH) // !!! FIXME +EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXDP3) // !!! FIXME + +void emit_GLSL_TEXM3X3(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char src3[64]; + char src4[64]; + char code[512]; + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, + src0, sizeof (src0)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, + src1, sizeof (src1)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, + src2, sizeof (src2)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, + src3, sizeof (src3)); + get_GLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src4, sizeof (src4)); + get_GLSL_destarg_varname(ctx, dst, sizeof (dst)); + + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "vec4(dot(%s.xyz, %s.xyz), dot(%s.xyz, %s.xyz), dot(%s.xyz, %s.xyz), 1.0)", + src0, src1, src2, src3, dst, src4); + + output_line(ctx, "%s", code); +} // emit_GLSL_TEXM3X3 + +EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXDEPTH) // !!! FIXME + +void emit_GLSL_CMP(Context *ctx) +{ + emit_GLSL_comparison_operations(ctx, ">= 0.0"); +} // emit_GLSL_CMP + +EMIT_GLSL_OPCODE_UNIMPLEMENTED_FUNC(BEM) // !!! FIXME + +void emit_GLSL_DP2ADD(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_vec2(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_GLSL_srcarg_string_vec2(ctx, 1, src1, sizeof (src1)); + char src2[64]; make_GLSL_srcarg_string_scalar(ctx, 2, src2, sizeof (src2)); + char extra[128]; snprintf(extra, sizeof (extra), " + %s", src2); + emit_GLSL_dotprod(ctx, src0, src1, extra); +} // emit_GLSL_DP2ADD + +void emit_GLSL_DSX(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "dFdx(%s)", src0); + output_line(ctx, "%s", code); +} // emit_GLSL_DSX + +void emit_GLSL_DSY(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), "dFdy(%s)", src0); + output_line(ctx, "%s", code); +} // emit_GLSL_DSY + +void emit_GLSL_TEXLDD(Context *ctx) +{ + const SourceArgInfo *samp_arg = &ctx->source_args[1]; + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, + samp_arg->regnum); + const char *funcname = NULL; + char src0[64] = { '\0' }; + char src1[64]; get_GLSL_srcarg_varname(ctx, 1, src1, sizeof (src1)); // !!! FIXME: SRC_MOD? + char src2[64] = { '\0' }; + char src3[64] = { '\0' }; + + if (sreg == NULL) + { + fail(ctx, "TEXLDD using undeclared sampler"); + return; + } // if + + switch ((const TextureType) sreg->index) + { + case TEXTURE_TYPE_2D: + funcname = "texture2D"; + make_GLSL_srcarg_string_vec2(ctx, 0, src0, sizeof (src0)); + make_GLSL_srcarg_string_vec2(ctx, 2, src2, sizeof (src2)); + make_GLSL_srcarg_string_vec2(ctx, 3, src3, sizeof (src3)); + break; + case TEXTURE_TYPE_CUBE: + funcname = "textureCube"; + make_GLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + make_GLSL_srcarg_string_vec3(ctx, 2, src2, sizeof (src2)); + make_GLSL_srcarg_string_vec3(ctx, 3, src3, sizeof (src3)); + break; + case TEXTURE_TYPE_VOLUME: + funcname = "texture3D"; + make_GLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + make_GLSL_srcarg_string_vec3(ctx, 2, src2, sizeof (src2)); + make_GLSL_srcarg_string_vec3(ctx, 3, src3, sizeof (src3)); + break; + default: + fail(ctx, "unknown texture type"); + return; + } // switch + + assert(!isscalar(ctx, ctx->shader_type, samp_arg->regtype, samp_arg->regnum)); + char swiz_str[6] = { '\0' }; + make_GLSL_swizzle_string(swiz_str, sizeof (swiz_str), + samp_arg->swizzle, ctx->dest_arg.writemask); + + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "%sGrad(%s, %s, %s, %s)%s", funcname, + src1, src0, src2, src3, swiz_str); + + prepend_glsl_texlod_extensions(ctx); + output_line(ctx, "%s", code); +} // emit_GLSL_TEXLDD + +void emit_GLSL_SETP(Context *ctx) +{ + const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); + char src0[64]; make_GLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_GLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + + // destination is always predicate register (which is type bvec4). + if (vecsize == 1) + { + const char *comp = get_GLSL_comparison_string_scalar(ctx); + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "(%s %s %s)", src0, comp, src1); + } // if + else + { + const char *comp = get_GLSL_comparison_string_vector(ctx); + make_GLSL_destarg_assign(ctx, code, sizeof (code), + "%s(%s, %s)", comp, src0, src1); + } // else + + output_line(ctx, "%s", code); +} // emit_GLSL_SETP + +void emit_GLSL_TEXLDL(Context *ctx) +{ + const SourceArgInfo *samp_arg = &ctx->source_args[1]; + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, + samp_arg->regnum); + const char *pattern = NULL; + char src0[64]; + char src1[64]; + make_GLSL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); + get_GLSL_srcarg_varname(ctx, 1, src1, sizeof (src1)); // !!! FIXME: SRC_MOD? + + if (sreg == NULL) + { + fail(ctx, "TEXLDL using undeclared sampler"); + return; + } // if + + // HLSL tex2dlod accepts (sampler, uv.xyz, uv.w) where uv.w is the LOD + // GLSL seems to want the dimensionality to match the sampler (.xy vs .xyz) + // so we vary the swizzle accordingly + switch ((const TextureType) sreg->index) + { + case TEXTURE_TYPE_2D: + pattern = "texture2DLod(%s, %s.xy, %s.w)%s"; + break; + case TEXTURE_TYPE_CUBE: + pattern = "textureCubeLod(%s, %s.xyz, %s.w)%s"; + break; + case TEXTURE_TYPE_VOLUME: + pattern = "texture3DLod(%s, %s.xyz, %s.w)%s"; + break; + default: + fail(ctx, "unknown texture type"); + return; + } // switch + + assert(!isscalar(ctx, ctx->shader_type, samp_arg->regtype, samp_arg->regnum)); + char swiz_str[6] = { '\0' }; + make_GLSL_swizzle_string(swiz_str, sizeof (swiz_str), + samp_arg->swizzle, ctx->dest_arg.writemask); + + char code[128]; + make_GLSL_destarg_assign(ctx, code, sizeof(code), + pattern, src1, src0, src0, swiz_str); + + prepend_glsl_texlod_extensions(ctx); + output_line(ctx, "%s", code); +} // emit_GLSL_TEXLDL + +void emit_GLSL_BREAKP(Context *ctx) +{ + char src0[64]; make_GLSL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + output_line(ctx, "if (%s) { break; }", src0); +} // emit_GLSL_BREAKP + +void emit_GLSL_RESERVED(Context *ctx) +{ + // do nothing; fails in the state machine. +} // emit_GLSL_RESERVED + +#endif // SUPPORT_PROFILE_GLSL + +#pragma GCC visibility pop diff --git a/mojoshader/profiles/mojoshader_profile_hlsl.c b/mojoshader/profiles/mojoshader_profile_hlsl.c new file mode 100644 index 0000000..41b94ba --- /dev/null +++ b/mojoshader/profiles/mojoshader_profile_hlsl.c @@ -0,0 +1,2287 @@ +/** + * MojoShader; generate shader programs from bytecode of compiled + * Direct3D shaders. + * + * Please see the file LICENSE.txt in the source's root directory. + * + * This file written by Ryan C. Gordon. + */ + +#define __MOJOSHADER_INTERNAL__ 1 +#include "mojoshader_profile.h" + +#pragma GCC visibility push(hidden) + +// !!! FIXME: A lot of this is cut-and-paste from the GLSL/Metal versions. +#if SUPPORT_PROFILE_HLSL + +#define EMIT_HLSL_OPCODE_UNIMPLEMENTED_FUNC(op) \ + void emit_HLSL_##op(Context *ctx) { \ + fail(ctx, #op " unimplemented in hlsl profile"); \ + } + +static inline const char *get_HLSL_register_string(Context *ctx, + const RegisterType regtype, const int regnum, + char *regnum_str, const size_t regnum_size) +{ + // turns out these are identical at the moment. + return get_D3D_register_string(ctx,regtype,regnum,regnum_str,regnum_size); +} // get_HLSL_register_string + +const char *get_HLSL_uniform_type(Context *ctx, const RegisterType rtype) +{ + switch (rtype) + { + case REG_TYPE_CONST: return "float4"; + case REG_TYPE_CONSTINT: return "int4"; + case REG_TYPE_CONSTBOOL: return "bool"; + default: fail(ctx, "BUG: used a uniform we don't know how to define."); + } // switch + + return NULL; +} // get_HLSL_uniform_type + +const char *get_HLSL_varname_in_buf(Context *ctx, RegisterType rt, + int regnum, char *buf, + const size_t len) +{ + char regnum_str[16]; + const char *regtype_str = get_HLSL_register_string(ctx, rt, regnum, + regnum_str, sizeof (regnum_str)); + snprintf(buf,len,"%s%s", regtype_str, regnum_str); + return buf; +} // get_HLSL_varname_in_buf + +const char *get_HLSL_varname(Context *ctx, RegisterType rt, int regnum) +{ + char buf[64]; + get_HLSL_varname_in_buf(ctx, rt, regnum, buf, sizeof(buf)); + return StrDup(ctx, buf); +} // get_HLSL_varname + +static inline const char *get_HLSL_const_array_varname_in_buf(Context *ctx, + const int base, const int size, + char *buf, const size_t buflen) +{ + snprintf(buf, buflen, "const_array_%d_%d", base, size); + return buf; +} // get_HLSL_const_array_varname_in_buf + +const char *get_HLSL_const_array_varname(Context *ctx, int base, int size) +{ + char buf[64]; + get_HLSL_const_array_varname_in_buf(ctx, base, size, buf, sizeof(buf)); + return StrDup(ctx, buf); +} // get_HLSL_const_array_varname + +static inline const char *get_HLSL_input_array_varname(Context *ctx, + char *buf, const size_t buflen) +{ + snprintf(buf, buflen, "%s", "vertex_input_array"); + return buf; +} // get_HLSL_input_array_varname + +const char *get_HLSL_uniform_array_varname(Context *ctx, + const RegisterType regtype, + char *buf, const size_t len) +{ + const char *type = get_HLSL_uniform_type(ctx, regtype); + snprintf(buf, len, "uniforms_%s", type); + return buf; +} // get_HLSL_uniform_array_varname + +const char *get_HLSL_destarg_varname(Context *ctx, char *buf, size_t len) +{ + const DestArgInfo *arg = &ctx->dest_arg; + return get_HLSL_varname_in_buf(ctx, arg->regtype, arg->regnum, buf, len); +} // get_HLSL_destarg_varname + +const char *get_HLSL_srcarg_varname(Context *ctx, const size_t idx, + char *buf, size_t len) +{ + if (idx >= STATICARRAYLEN(ctx->source_args)) + { + fail(ctx, "Too many source args"); + *buf = '\0'; + return buf; + } // if + + const SourceArgInfo *arg = &ctx->source_args[idx]; + return get_HLSL_varname_in_buf(ctx, arg->regtype, arg->regnum, buf, len); +} // get_HLSL_srcarg_varname + +const char *make_HLSL_destarg_assign(Context *, char *, const size_t, + const char *, ...) ISPRINTF(4,5); + +const char *make_HLSL_destarg_assign(Context *ctx, char *buf, + const size_t buflen, + const char *fmt, ...) +{ + int need_parens = 0; + const DestArgInfo *arg = &ctx->dest_arg; + + if (arg->writemask == 0) + { + *buf = '\0'; + return buf; // no writemask? It's a no-op. + } // if + + const char *clampleft = ""; + const char *clampright = ""; + if (arg->result_mod & MOD_SATURATE) + { + clampleft = "saturate("; + clampright = ")"; + } // if + + // MSDN says MOD_PP is a hint and many implementations ignore it. So do we. + + // CENTROID only allowed in DCL opcodes, which shouldn't come through here. + assert((arg->result_mod & MOD_CENTROID) == 0); + + if (ctx->predicated) + { + fail(ctx, "predicated destinations unsupported"); // !!! FIXME + *buf = '\0'; + return buf; + } // if + + char operation[256]; + va_list ap; + va_start(ap, fmt); + const int len = vsnprintf(operation, sizeof (operation), fmt, ap); + va_end(ap); + if (len >= sizeof (operation)) + { + fail(ctx, "operation string too large"); // I'm lazy. :P + *buf = '\0'; + return buf; + } // if + + const char *result_shift_str = ""; + switch (arg->result_shift) + { + case 0x1: result_shift_str = " * 2.0"; break; + case 0x2: result_shift_str = " * 4.0"; break; + case 0x3: result_shift_str = " * 8.0"; break; + case 0xD: result_shift_str = " / 8.0"; break; + case 0xE: result_shift_str = " / 4.0"; break; + case 0xF: result_shift_str = " / 2.0"; break; + } // switch + need_parens |= (result_shift_str[0] != '\0'); + + char regnum_str[16]; + const char *regtype_str = get_HLSL_register_string(ctx, arg->regtype, + arg->regnum, regnum_str, + sizeof (regnum_str)); + char writemask_str[6]; + size_t i = 0; + const int scalar = isscalar(ctx, ctx->shader_type, arg->regtype, arg->regnum); + if (!scalar && !writemask_xyzw(arg->writemask)) + { + writemask_str[i++] = '.'; + if (arg->writemask0) writemask_str[i++] = 'x'; + if (arg->writemask1) writemask_str[i++] = 'y'; + if (arg->writemask2) writemask_str[i++] = 'z'; + if (arg->writemask3) writemask_str[i++] = 'w'; + } // if + writemask_str[i] = '\0'; + assert(i < sizeof (writemask_str)); + + const char *leftparen = (need_parens) ? "(" : ""; + const char *rightparen = (need_parens) ? ")" : ""; + + snprintf(buf, buflen, "%s%s%s = %s%s%s%s%s%s;", regtype_str, + regnum_str, writemask_str,clampleft, leftparen, + operation, rightparen, result_shift_str, clampright); + // !!! FIXME: make sure the scratch buffer was large enough. + return buf; +} // make_HLSL_destarg_assign + + +char *make_HLSL_swizzle_string(char *swiz_str, const size_t strsize, + const int swizzle, const int writemask) +{ + size_t i = 0; + if ( (!no_swizzle(swizzle)) || (!writemask_xyzw(writemask)) ) + { + const int writemask0 = (writemask >> 0) & 0x1; + const int writemask1 = (writemask >> 1) & 0x1; + const int writemask2 = (writemask >> 2) & 0x1; + const int writemask3 = (writemask >> 3) & 0x1; + + const int swizzle_x = (swizzle >> 0) & 0x3; + const int swizzle_y = (swizzle >> 2) & 0x3; + const int swizzle_z = (swizzle >> 4) & 0x3; + const int swizzle_w = (swizzle >> 6) & 0x3; + + swiz_str[i++] = '.'; + if (writemask0) swiz_str[i++] = swizzle_channels[swizzle_x]; + if (writemask1) swiz_str[i++] = swizzle_channels[swizzle_y]; + if (writemask2) swiz_str[i++] = swizzle_channels[swizzle_z]; + if (writemask3) swiz_str[i++] = swizzle_channels[swizzle_w]; + } // if + assert(i < strsize); + swiz_str[i] = '\0'; + return swiz_str; +} // make_HLSL_swizzle_string + + +const char *make_HLSL_srcarg_string(Context *ctx, const size_t idx, + const int writemask, char *buf, + const size_t buflen) +{ + *buf = '\0'; + + if (idx >= STATICARRAYLEN(ctx->source_args)) + { + fail(ctx, "Too many source args"); + return buf; + } // if + + const SourceArgInfo *arg = &ctx->source_args[idx]; + + const char *premod_str = ""; + const char *postmod_str = ""; + switch (arg->src_mod) + { + case SRCMOD_NEGATE: + premod_str = "-"; + break; + + case SRCMOD_BIASNEGATE: + premod_str = "-("; + postmod_str = " - 0.5)"; + break; + + case SRCMOD_BIAS: + premod_str = "("; + postmod_str = " - 0.5)"; + break; + + case SRCMOD_SIGNNEGATE: + premod_str = "-(("; + postmod_str = " - 0.5) * 2.0)"; + break; + + case SRCMOD_SIGN: + premod_str = "(("; + postmod_str = " - 0.5) * 2.0)"; + break; + + case SRCMOD_COMPLEMENT: + premod_str = "(1.0 - "; + postmod_str = ")"; + break; + + case SRCMOD_X2NEGATE: + premod_str = "-("; + postmod_str = " * 2.0)"; + break; + + case SRCMOD_X2: + premod_str = "("; + postmod_str = " * 2.0)"; + break; + + case SRCMOD_DZ: + fail(ctx, "SRCMOD_DZ unsupported"); return buf; // !!! FIXME + postmod_str = "_dz"; + break; + + case SRCMOD_DW: + fail(ctx, "SRCMOD_DW unsupported"); return buf; // !!! FIXME + postmod_str = "_dw"; + break; + + case SRCMOD_ABSNEGATE: + premod_str = "-abs("; + postmod_str = ")"; + break; + + case SRCMOD_ABS: + premod_str = "abs("; + postmod_str = ")"; + break; + + case SRCMOD_NOT: + premod_str = "!"; + break; + + case SRCMOD_NONE: + case SRCMOD_TOTAL: + break; // stop compiler whining. + } // switch + + const char *regtype_str = NULL; + + if (!arg->relative) + { + regtype_str = get_HLSL_varname_in_buf(ctx, arg->regtype, arg->regnum, + (char *) alloca(64), 64); + } // if + + const char *rel_lbracket = ""; + char rel_offset[32] = { '\0' }; + const char *rel_rbracket = ""; + char rel_swizzle[4] = { '\0' }; + const char *rel_regtype_str = ""; + if (arg->relative) + { + if (arg->regtype == REG_TYPE_INPUT) + regtype_str=get_HLSL_input_array_varname(ctx,(char*)alloca(64),64); + else + { + assert(arg->regtype == REG_TYPE_CONST); + const int arrayidx = arg->relative_array->index; + const int offset = arg->regnum - arrayidx; + assert(offset >= 0); + if (arg->relative_array->constant) + { + const int arraysize = arg->relative_array->count; + regtype_str = get_HLSL_const_array_varname_in_buf(ctx, + arrayidx, arraysize, (char *) alloca(64), 64); + if (offset != 0) + snprintf(rel_offset, sizeof (rel_offset), "%d + ", offset); + } // if + else + { + regtype_str = get_HLSL_uniform_array_varname(ctx, arg->regtype, + (char *) alloca(64), 64); + if (offset == 0) + { + snprintf(rel_offset, sizeof (rel_offset), + "ARRAYBASE_%d + ", arrayidx); + } // if + else + { + snprintf(rel_offset, sizeof (rel_offset), + "(ARRAYBASE_%d + %d) + ", arrayidx, offset); + } // else + } // else + } // else + + rel_lbracket = "["; + + rel_regtype_str = get_HLSL_varname_in_buf(ctx, arg->relative_regtype, + arg->relative_regnum, + (char *) alloca(64), 64); + rel_swizzle[0] = '.'; + rel_swizzle[1] = swizzle_channels[arg->relative_component]; + rel_swizzle[2] = '\0'; + rel_rbracket = "]"; + } // if + + char swiz_str[6] = { '\0' }; + if (!isscalar(ctx, ctx->shader_type, arg->regtype, arg->regnum)) + { + make_HLSL_swizzle_string(swiz_str, sizeof (swiz_str), + arg->swizzle, writemask); + } // if + + if (regtype_str == NULL) + { + fail(ctx, "Unknown source register type."); + return buf; + } // if + + snprintf(buf, buflen, "%s%s%s%s%s%s%s%s%s", + premod_str, regtype_str, rel_lbracket, rel_offset, + rel_regtype_str, rel_swizzle, rel_rbracket, swiz_str, + postmod_str); + // !!! FIXME: make sure the scratch buffer was large enough. + return buf; +} // make_HLSL_srcarg_string + +// generate some convenience functions. +#define MAKE_HLSL_SRCARG_STRING_(mask, bitmask) \ + static inline const char *make_HLSL_srcarg_string_##mask(Context *ctx, \ + const size_t idx, char *buf, \ + const size_t buflen) { \ + return make_HLSL_srcarg_string(ctx, idx, bitmask, buf, buflen); \ + } +MAKE_HLSL_SRCARG_STRING_(x, (1 << 0)) +MAKE_HLSL_SRCARG_STRING_(y, (1 << 1)) +MAKE_HLSL_SRCARG_STRING_(z, (1 << 2)) +MAKE_HLSL_SRCARG_STRING_(w, (1 << 3)) +MAKE_HLSL_SRCARG_STRING_(scalar, (1 << 0)) +MAKE_HLSL_SRCARG_STRING_(full, 0xF) +MAKE_HLSL_SRCARG_STRING_(masked, ctx->dest_arg.writemask) +MAKE_HLSL_SRCARG_STRING_(vec3, 0x7) +MAKE_HLSL_SRCARG_STRING_(vec2, 0x3) +#undef MAKE_HLSL_SRCARG_STRING_ + +// special cases for comparison opcodes... + +const char *get_HLSL_comparison_string_scalar(Context *ctx) +{ + const char *comps[] = { "", ">", "==", ">=", "<", "!=", "<=" }; + if (ctx->instruction_controls >= STATICARRAYLEN(comps)) + { + fail(ctx, "unknown comparison control"); + return ""; + } // if + + return comps[ctx->instruction_controls]; +} // get_HLSL_comparison_string_scalar + +const char *get_HLSL_comparison_string_vector(Context *ctx) +{ + return get_HLSL_comparison_string_scalar(ctx); // standard C operators work for vectors in HLSL. +} // get_HLSL_comparison_string_vector + + +void emit_HLSL_start(Context *ctx, const char *profilestr) +{ + if (!shader_is_vertex(ctx) && !shader_is_pixel(ctx)) + { + failf(ctx, "Shader type %u unsupported in this profile.", + (uint) ctx->shader_type); + return; + } // if + + if (!ctx->mainfn) + { + if (shader_is_vertex(ctx)) + ctx->mainfn = StrDup(ctx, "VertexShader"); + else if (shader_is_pixel(ctx)) + ctx->mainfn = StrDup(ctx, "PixelShader"); + } // if + + set_output(ctx, &ctx->mainline); + ctx->indent++; +} // emit_HLSL_start + +void emit_HLSL_RET(Context *ctx); +void emit_HLSL_end(Context *ctx) +{ + // !!! FIXME: maybe handle this at a higher level? + // ps_1_* writes color to r0 instead oC0. We move it to the right place. + // We don't have to worry about a RET opcode messing this up, since + // RET isn't available before ps_2_0. + if (shader_is_pixel(ctx) && !shader_version_atleast(ctx, 2, 0)) + { + set_used_register(ctx, REG_TYPE_COLOROUT, 0, 1); + output_line(ctx, "oC0 = r0;"); + } // if + + // !!! FIXME: maybe handle this at a higher level? + // force a RET opcode if we're at the end of the stream without one. + if (ctx->previous_opcode != OPCODE_RET) + emit_HLSL_RET(ctx); +} // emit_HLSL_end + +void emit_HLSL_phase(Context *ctx) +{ + // no-op in HLSL. +} // emit_HLSL_phase + +void output_HLSL_uniform_array(Context *ctx, const RegisterType regtype, + const int size) +{ + if (size > 0) + { + char buf[64]; + get_HLSL_uniform_array_varname(ctx, regtype, buf, sizeof (buf)); + const char *typ; + switch (regtype) + { + case REG_TYPE_CONST: typ = "float4"; break; + case REG_TYPE_CONSTINT: typ = "int4"; break; + case REG_TYPE_CONSTBOOL: typ = "bool"; break; + default: + { + fail(ctx, "BUG: used a uniform we don't know how to define."); + return; + } // default + } // switch + output_line(ctx, "%s %s[%d];", typ, buf, size); + } // if +} // output_HLSL_uniform_array + +void emit_HLSL_finalize(Context *ctx) +{ + if (ctx->have_relative_input_registers) // !!! FIXME + fail(ctx, "Relative addressing of input registers not supported."); + + // Check uniform_float4_count too since TEXBEM affects it + if (ctx->uniform_count > 0 || ctx->uniform_float4_count > 0) + { + push_output(ctx, &ctx->preflight); + output_line(ctx, "cbuffer %s_Uniforms : register(b0)", ctx->mainfn); + output_line(ctx, "{"); + ctx->indent++; + output_HLSL_uniform_array(ctx, REG_TYPE_CONST, ctx->uniform_float4_count); + output_HLSL_uniform_array(ctx, REG_TYPE_CONSTINT, ctx->uniform_int4_count); + output_HLSL_uniform_array(ctx, REG_TYPE_CONSTBOOL, ctx->uniform_bool_count); + ctx->indent--; + output_line(ctx, "};"); + output_blank_line(ctx); + pop_output(ctx); + } // if + + // Fill in the shader's mainline function signature. + push_output(ctx, &ctx->mainline_intro); + output_line(ctx, "%s%s %s(%s%s%s)", + ctx->outputs ? ctx->mainfn : "void", + ctx->outputs ? "_Output" : "", + ctx->mainfn, + ctx->inputs ? ctx->mainfn : "", + ctx->inputs ? "_Input" : "", + ctx->inputs ? " input" : ""); + output_line(ctx, "{"); + + if (ctx->outputs) + { + ctx->indent++; + output_line(ctx, "%s%s output = (%s%s) 0;", + ctx->mainfn, "_Output", ctx->mainfn, "_Output"); + + push_output(ctx, &ctx->mainline); + ctx->indent++; + output_line(ctx, "return output;"); + pop_output(ctx); + } // if + pop_output(ctx); + + if (ctx->inputs) + { + push_output(ctx, &ctx->inputs); + output_line(ctx, "};"); + output_blank_line(ctx); + pop_output(ctx); + } // if + + if (ctx->outputs) + { + push_output(ctx, &ctx->outputs); + + // !!! FIXME: Maybe have a better check for this? + if (ctx->hlsl_outpos_name[0] != '\0') + { + output_line(ctx, "\tfloat4 m_%s : SV_Position;", + ctx->hlsl_outpos_name); + } // if + + output_line(ctx, "};"); + output_blank_line(ctx); + pop_output(ctx); + } // if + + // throw some blank lines around to make source more readable. + if (ctx->globals) // don't add a blank line if the section is empty. + { + push_output(ctx, &ctx->globals); + output_blank_line(ctx); + pop_output(ctx); + } // if + + if (ctx->need_max_float) + { + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + output_line(ctx, "#define FLT_MAX 1e38"); + ctx->indent--; + pop_output(ctx); + } // if +} // emit_HLSL_finalize + +void emit_HLSL_global(Context *ctx, RegisterType regtype, int regnum) +{ + char varname[64]; + get_HLSL_varname_in_buf(ctx, regtype, regnum, varname, sizeof (varname)); + + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + + switch (regtype) + { + case REG_TYPE_ADDRESS: + if (shader_is_vertex(ctx)) + output_line(ctx, "int4 %s;", varname); + else if (shader_is_pixel(ctx)) // actually REG_TYPE_TEXTURE. + { + // We have to map texture registers to temps for ps_1_1, since + // they work like temps, initialize with tex coords, and the + // ps_1_1 TEX opcode expects to overwrite it. + if (!shader_version_atleast(ctx, 1, 4)) + output_line(ctx, "float4 %s = input.m_%s;",varname,varname); + } // else if + break; + case REG_TYPE_PREDICATE: + output_line(ctx, "bool4 %s;", varname); + break; + case REG_TYPE_TEMP: + output_line(ctx, "float4 %s;", varname); + break; + case REG_TYPE_LOOP: + break; // no-op. We declare these in for loops at the moment. + case REG_TYPE_LABEL: + break; // no-op. If we see it here, it means we optimized it out. + default: + fail(ctx, "BUG: we used a register we don't know how to define."); + break; + } // switch + + pop_output(ctx); +} // emit_HLSL_global + +void emit_HLSL_array(Context *ctx, VariableList *var) +{ + // All uniforms (except constant arrays, which are literally constant + // data embedded in HLSL shaders) are now packed into a single array, + // so we can batch the uniform transfers. So this doesn't actually + // define an array here; the one, big array is emitted during + // finalization instead. + // However, we need to #define the offset into the one, big array here, + // and let dereferences use that #define. + const int base = var->index; + const int hlslbase = ctx->uniform_float4_count; + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + output_line(ctx, "const int ARRAYBASE_%d = %d;", base, hlslbase); + pop_output(ctx); + var->emit_position = hlslbase; +} // emit_HLSL_array + +void emit_HLSL_const_array(Context *ctx, const ConstantsList *clist, + int base, int size) +{ + char varname[64]; + get_HLSL_const_array_varname_in_buf(ctx,base,size,varname,sizeof(varname)); + + const char *cstr = NULL; + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + output_line(ctx, "const float4 %s[%d] = {", varname, size); + ctx->indent++; + + int i; + for (i = 0; i < size; i++) + { + while (clist->constant.type != MOJOSHADER_UNIFORM_FLOAT) + clist = clist->next; + assert(clist->constant.index == (base + i)); + + char val0[32]; + char val1[32]; + char val2[32]; + char val3[32]; + floatstr(ctx, val0, sizeof (val0), clist->constant.value.f[0], 1); + floatstr(ctx, val1, sizeof (val1), clist->constant.value.f[1], 1); + floatstr(ctx, val2, sizeof (val2), clist->constant.value.f[2], 1); + floatstr(ctx, val3, sizeof (val3), clist->constant.value.f[3], 1); + + output_line(ctx, "float4(%s, %s, %s, %s)%s", val0, val1, val2, val3, + (i < (size-1)) ? "," : ""); + + clist = clist->next; + } // for + + ctx->indent--; + output_line(ctx, "};"); + pop_output(ctx); +} // emit_HLSL_const_array + +void emit_HLSL_uniform(Context *ctx, RegisterType regtype, int regnum, + const VariableList *var) +{ + // Now that we're pushing all the uniforms as one big array, pack these + // down, so if we only use register c439, it'll actually map to + // HLSL_uniforms_vec4[0]. As we push one big array, this will prevent + // uploading unused data. + + char varname[64]; + char name[64]; + int index = 0; + + get_HLSL_varname_in_buf(ctx, regtype, regnum, varname, sizeof (varname)); + + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + + if (var == NULL) + { + get_HLSL_uniform_array_varname(ctx, regtype, name, sizeof (name)); + + if (regtype == REG_TYPE_CONST) + index = ctx->uniform_float4_count; + else if (regtype == REG_TYPE_CONSTINT) + index = ctx->uniform_int4_count; + else if (regtype == REG_TYPE_CONSTBOOL) + index = ctx->uniform_bool_count; + else // get_HLSL_uniform_array_varname() would have called fail(). + assert(!(ctx->isfail)); + + output_line(ctx, "#define %s %s[%d]", varname, name, index); + push_output(ctx, &ctx->mainline); + ctx->indent++; + output_line(ctx, "#undef %s", varname); // !!! FIXME: gross. + pop_output(ctx); + } // if + + else + { + const int arraybase = var->index; + if (var->constant) + { + get_HLSL_const_array_varname_in_buf(ctx, arraybase, var->count, + name, sizeof (name)); + index = (regnum - arraybase); + } // if + else + { + assert(var->emit_position != -1); + get_HLSL_uniform_array_varname(ctx, regtype, name, sizeof (name)); + index = (regnum - arraybase) + var->emit_position; + } // else + + output_line(ctx, "#define %s %s[%d];", varname, name, index); + push_output(ctx, &ctx->mainline); + ctx->indent++; + output_line(ctx, "#undef %s", varname); // !!! FIXME: gross. + pop_output(ctx); + } // else + + pop_output(ctx); +} // emit_HLSL_uniform + +void emit_HLSL_sampler(Context *ctx,int stage,TextureType ttype,int tb) +{ + char var[64]; + const char *texsuffix = NULL; + switch (ttype) + { + case TEXTURE_TYPE_2D: texsuffix = "2D"; break; + case TEXTURE_TYPE_CUBE: texsuffix = "Cube"; break; + case TEXTURE_TYPE_VOLUME: texsuffix = "3D"; break; + default: assert(!"unexpected texture type"); return; + } // switch + + get_HLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, stage, var, sizeof(var)); + + push_output(ctx, &ctx->globals); + output_line(ctx, "Texture%s %s_texture : register(t%d);", texsuffix, var, stage); + output_line(ctx, "SamplerState %s : register(%s);", var, var); + pop_output(ctx); + + if (tb) // This sampler used a ps_1_1 TEXBEM opcode? + { + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + char name[64]; + const int index = ctx->uniform_float4_count; + ctx->uniform_float4_count += 2; + get_HLSL_uniform_array_varname(ctx, REG_TYPE_CONST, name, sizeof(name)); + output_line(ctx, "const float4 %s_texbem = %s[%d];", var, name, index); + output_line(ctx, "const float4 %s_texbeml = %s[%d];", var, name, index + 1); + pop_output(ctx); + } // if +} // emit_HLSL_sampler + + +void emit_HLSL_attribute(Context *ctx, RegisterType regtype, int regnum, + MOJOSHADER_usage usage, int index, int wmask, + int flags) +{ + // !!! FIXME: this function doesn't deal with write masks at all yet! + const char *usage_str = NULL; + char index_str[16] = { '\0' }; + char var[64]; + char a[256]; + + get_HLSL_varname_in_buf(ctx, regtype, regnum, var, sizeof (var)); + + //assert((flags & MOD_PP) == 0); // !!! FIXME: is PP allowed? + + if (index != 0) // !!! FIXME: a lot of these MUST be zero. + snprintf(index_str, sizeof (index_str), "%u", (uint) index); + + if (shader_is_vertex(ctx)) + { + // pre-vs3 output registers. + // these don't ever happen in DCL opcodes, I think. Map to vs_3_* + // output registers. + if (!shader_version_atleast(ctx, 3, 0)) + { + if (regtype == REG_TYPE_RASTOUT) + { + regtype = REG_TYPE_OUTPUT; + index = regnum; + switch ((const RastOutType) regnum) + { + case RASTOUT_TYPE_POSITION: + usage = MOJOSHADER_USAGE_POSITION; + break; + case RASTOUT_TYPE_FOG: + usage = MOJOSHADER_USAGE_FOG; + break; + case RASTOUT_TYPE_POINT_SIZE: + usage = MOJOSHADER_USAGE_POINTSIZE; + break; + } // switch + } // if + + else if (regtype == REG_TYPE_ATTROUT) + { + regtype = REG_TYPE_OUTPUT; + usage = MOJOSHADER_USAGE_COLOR; + index = regnum; + } // else if + + else if (regtype == REG_TYPE_TEXCRDOUT) + { + regtype = REG_TYPE_OUTPUT; + usage = MOJOSHADER_USAGE_TEXCOORD; + index = regnum; + } // else if + } // if + + if (regtype == REG_TYPE_INPUT) + { + push_output(ctx, &ctx->inputs); + if (buffer_size(ctx->inputs) == 0) + { + output_line(ctx, "struct %s_Input", ctx->mainfn); + output_line(ctx, "{"); + } // if + + ctx->indent++; + switch (usage) + { + case MOJOSHADER_USAGE_BINORMAL: + output_line(ctx, "float4 m_%s : BINORMAL%d;", var, index); + break; + case MOJOSHADER_USAGE_BLENDINDICES: + output_line(ctx, "float4 m_%s : BLENDINDICES%d;", var, index); + break; + case MOJOSHADER_USAGE_BLENDWEIGHT: + output_line(ctx, "float4 m_%s : BLENDWEIGHT%d;", var, index); + break; + case MOJOSHADER_USAGE_COLOR: + output_line(ctx, "float4 m_%s : COLOR%d;", var, index); + break; + case MOJOSHADER_USAGE_NORMAL: + output_line(ctx, "float4 m_%s : NORMAL%d;", var, index); + break; + case MOJOSHADER_USAGE_POSITION: + output_line(ctx, "float4 m_%s : POSITION%d;", var, index); + break; + case MOJOSHADER_USAGE_POSITIONT: + output_line(ctx, "float4 m_%s : POSITIONT;", var); + break; + case MOJOSHADER_USAGE_POINTSIZE: + output_line(ctx, "float4 m_%s : PSIZE;", var); + break; + case MOJOSHADER_USAGE_TANGENT: + output_line(ctx, "float4 m_%s : TANGENT%d;", var, index); + break; + case MOJOSHADER_USAGE_TEXCOORD: + output_line(ctx, "float4 m_%s : TEXCOORD%d;", var, index); + break; + default: + fail(ctx, "Unknown vertex input semantic type!"); + break; + } // case + pop_output(ctx); + + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + output_line(ctx, "#define %s input.m_%s", var, var); + pop_output(ctx); + push_output(ctx, &ctx->mainline); + ctx->indent++; + output_line(ctx, "#undef %s", var); // !!! FIXME: gross. + pop_output(ctx); + } // if + + else if (regtype == REG_TYPE_OUTPUT) + { + push_output(ctx, &ctx->outputs); + if (buffer_size(ctx->outputs) == 0) + { + output_line(ctx, "struct %s_Output", ctx->mainfn); + output_line(ctx, "{"); + } // if + + ctx->indent++; + + switch (usage) + { + case MOJOSHADER_USAGE_BINORMAL: + output_line(ctx, "float4 m_%s : BINORMAL%d;", var, index); + break; + case MOJOSHADER_USAGE_BLENDINDICES: + output_line(ctx, "float4 m_%s : BLENDINDICES%d;", var, index); + break; + case MOJOSHADER_USAGE_BLENDWEIGHT: + output_line(ctx, "float4 m_%s : BLENDWEIGHT%d;", var, index); + break; + case MOJOSHADER_USAGE_COLOR: + output_line(ctx, "float4 m_%s : COLOR%d;", var, index); + break; + case MOJOSHADER_USAGE_FOG: + output_line(ctx, "float m_%s : FOG;", var); + break; + case MOJOSHADER_USAGE_NORMAL: + output_line(ctx, "float4 m_%s : NORMAL%d;", var, index); + break; + case MOJOSHADER_USAGE_POSITION: + if (index == 0) + snprintf(ctx->hlsl_outpos_name, + sizeof(ctx->hlsl_outpos_name), "%s", var); + else + output_line(ctx, "float4 m_%s : POSITION%d;", var, index); + break; + case MOJOSHADER_USAGE_POSITIONT: + output_line(ctx, "float4 m_%s : POSITIONT;", var); + break; + case MOJOSHADER_USAGE_POINTSIZE: + output_line(ctx, "float m_%s : PSIZE;", var); + break; + case MOJOSHADER_USAGE_TANGENT: + output_line(ctx, "float4 m_%s : TANGENT%d;", var, index); + break; + case MOJOSHADER_USAGE_TESSFACTOR: + output_line(ctx, "float m_%s : TESSFACTOR%d;", var, index); + break; + case MOJOSHADER_USAGE_TEXCOORD: + output_line(ctx, "float4 m_%s : TEXCOORD%d;", var, index); + break; + default: + snprintf(a, sizeof(a), "Invalid vertex output semantic %d", usage); + fail(ctx, a); + break; + } // switch + + pop_output(ctx); + + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + output_line(ctx, "#define %s output.m_%s", var, var); + pop_output(ctx); + push_output(ctx, &ctx->mainline); + ctx->indent++; + output_line(ctx, "#undef %s", var); // !!! FIXME: gross. + pop_output(ctx); + } // else if + + else + { + fail(ctx, "unknown vertex shader attribute register"); + } // else + } // if + + else if (shader_is_pixel(ctx)) + { + // samplers DCLs get handled in emit_HLSL_sampler(). + + if (flags & MOD_CENTROID) // !!! FIXME + { + failf(ctx, "centroid unsupported in %s profile", ctx->profile->name); + return; + } // if + + if ((regtype == REG_TYPE_COLOROUT) || (regtype == REG_TYPE_DEPTHOUT)) + { + push_output(ctx, &ctx->outputs); + if (buffer_size(ctx->outputs) == 0) + { + output_line(ctx, "struct %s_Output", ctx->mainfn); + output_line(ctx, "{"); + } // if + ctx->indent++; + + if (regtype == REG_TYPE_COLOROUT) + output_line(ctx, "float4 m_%s : SV_Target%d;", var, regnum); + else if (regtype == REG_TYPE_DEPTHOUT) + output_line(ctx, "float m_%s : SV_Depth;", var); + + pop_output(ctx); + + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + output_line(ctx, "#define %s output.m_%s", var, var); + pop_output(ctx); + push_output(ctx, &ctx->mainline); + ctx->indent++; + output_line(ctx, "#undef %s", var); // !!! FIXME: gross. + pop_output(ctx); + } // if + + // !!! FIXME: can you actualy have a texture register with COLOR usage? + else if ((regtype == REG_TYPE_TEXTURE) || + (regtype == REG_TYPE_INPUT) || + (regtype == REG_TYPE_MISCTYPE)) + { + int skipreference = 0; + const char *define_start = ""; + const char *define_end = ""; + + push_output(ctx, &ctx->inputs); + if (buffer_size(ctx->inputs) == 0) + { + output_line(ctx, "struct %s_Input", ctx->mainfn); + output_line(ctx, "{"); + output_line(ctx, "\t// This must match the vertex output!"); + output_line(ctx, "\t// Rewrite at link time if needed!"); + } // if + ctx->indent++; + + if (regtype == REG_TYPE_MISCTYPE) + { + const MiscTypeType mt = (MiscTypeType) regnum; + if (mt == MISCTYPE_TYPE_FACE) + { + // In SM 3.0, VFACE was a float whose sign determined + // face direction. In SM 4.0+, it's just a bool, so + // we convert the value when we output the #define. + output_line(ctx, "bool m_%s : SV_IsFrontFace;", var); + define_start = "("; + define_end = " ? 1 : -1)"; + } // if + else if (mt == MISCTYPE_TYPE_POSITION) + output_line(ctx, "float4 m_%s : SV_Position;", var); + else + fail(ctx, "BUG: unhandled misc register"); + } // else if + + else + { + switch (usage) + { + case MOJOSHADER_USAGE_TEXCOORD: + // ps_1_1 does a different hack for this attribute. + // Refer to emit_HLSL_global()'s REG_TYPE_ADDRESS code. + if (!shader_version_atleast(ctx, 1, 4)) + skipreference = 1; + output_line(ctx, "float4 m_%s : TEXCOORD%d;", var, index); + break; + case MOJOSHADER_USAGE_COLOR: + output_line(ctx, "float4 m_%s : COLOR%d;", var, index); + break; + case MOJOSHADER_USAGE_FOG: + output_line(ctx, "float m_%s : FOG;", var); + break; + case MOJOSHADER_USAGE_NORMAL: + output_line(ctx, "float4 m_%s : NORMAL;", var); + break; + case MOJOSHADER_USAGE_POSITION: + output_line(ctx, "float4 m_%s : POSITION%d;", var, index); + break; + default: + fail(ctx, "BUG: unhandled pixel shader input"); + break; + } // switch + } // else + + pop_output(ctx); + + if (!skipreference) + { + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + output_line(ctx, "#define %s %sinput.m_%s%s", var, + define_start, var, define_end); + pop_output(ctx); + push_output(ctx, &ctx->mainline); + ctx->indent++; + output_line(ctx, "#undef %s", var); // !!! FIXME: gross. + pop_output(ctx); + } // if + } // else if + + else + { + fail(ctx, "unknown pixel shader attribute register"); + } // else + } // else if + + else + { + fail(ctx, "Unknown shader type"); // state machine should catch this. + } // else +} // emit_HLSL_attribute + +void emit_HLSL_NOP(Context *ctx) +{ + // no-op is a no-op. :) +} // emit_HLSL_NOP + +void emit_HLSL_MOV(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), "%s", src0); + output_line(ctx, "%s", code); +} // emit_HLSL_MOV + +void emit_HLSL_ADD(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_HLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), "%s + %s", src0, src1); + output_line(ctx, "%s", code); +} // emit_HLSL_ADD + +void emit_HLSL_SUB(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_HLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), "%s - %s", src0, src1); + output_line(ctx, "%s", code); +} // emit_HLSL_SUB + +void emit_HLSL_MAD(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_HLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char src2[64]; make_HLSL_srcarg_string_masked(ctx, 2, src2, sizeof (src2)); + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), "(%s * %s) + %s", src0, src1, src2); + output_line(ctx, "%s", code); +} // emit_HLSL_MAD + +void emit_HLSL_MUL(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_HLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), "%s * %s", src0, src1); + output_line(ctx, "%s", code); +} // emit_HLSL_MUL + +void emit_HLSL_RCP(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + ctx->need_max_float = 1; + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "(%s == 0.0) ? FLT_MAX : 1.0 / %s", src0, src0); + output_line(ctx, "%s", code); +} // emit_HLSL_RCP + +void emit_HLSL_RSQ(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + ctx->need_max_float = 1; + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "(%s == 0.0) ? FLT_MAX : rsqrt(abs(%s))", + src0, src0); + output_line(ctx, "%s", code); +} // emit_HLSL_RSQ + +void emit_HLSL_dotprod(Context *ctx, const char *src0, const char *src1, + const char *extra) +{ + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), "dot(%s, %s)%s", + src0, src1, extra); + output_line(ctx, "%s", code); +} // emit_HLSL_dotprod + +void emit_HLSL_DP3(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_HLSL_srcarg_string_vec3(ctx, 1, src1, sizeof (src1)); + emit_HLSL_dotprod(ctx, src0, src1, ""); +} // emit_HLSL_DP3 + +void emit_HLSL_DP4(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_HLSL_srcarg_string_full(ctx, 1, src1, sizeof (src1)); + emit_HLSL_dotprod(ctx, src0, src1, ""); +} // emit_HLSL_DP4 + +void emit_HLSL_MIN(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_HLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), "min(%s, %s)", src0, src1); + output_line(ctx, "%s", code); +} // emit_HLSL_MIN + +void emit_HLSL_MAX(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_HLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), "max(%s, %s)", src0, src1); + output_line(ctx, "%s", code); +} // emit_HLSL_MAX + +void emit_HLSL_SLT(Context *ctx) +{ + const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_HLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + + // float(bool) results in 0.0 or 1.0, like SLT wants. + if (vecsize == 1) + make_HLSL_destarg_assign(ctx, code, sizeof (code), "float(%s < %s)", src0, src1); + else + make_HLSL_destarg_assign(ctx, code, sizeof (code), "%s < %s", src0, src1); + + output_line(ctx, "%s", code); +} // emit_HLSL_SLT + +void emit_HLSL_SGE(Context *ctx) +{ + const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_HLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + + // float(bool) results in 0.0 or 1.0, like SGE wants. + if (vecsize == 1) + make_HLSL_destarg_assign(ctx, code, sizeof (code), "float(%s >= %s)", src0, src1); + else + make_HLSL_destarg_assign(ctx, code, sizeof (code), "%s >= %s", src0, src1); + + output_line(ctx, "%s", code); +} // emit_HLSL_SGE + +void emit_HLSL_EXP(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), "exp2(%s)", src0); + output_line(ctx, "%s", code); +} // emit_HLSL_EXP + +void emit_HLSL_LOG(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), "log2(%s)", src0); + output_line(ctx, "%s", code); +} // emit_HLSL_LOG + +void emit_HLSL_LIT(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); + char code[128]; + const char *maxp = "127.9961"; // value from the dx9 reference. + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "lit(%s.x, %s.y, clamp(%s.w, -%s, %s))", + src0, src0, src0, maxp, maxp); + output_line(ctx, "%s", code); +} // emit_HLSL_LIT + +void emit_HLSL_DST(Context *ctx) +{ + // !!! FIXME: needs to take ctx->dst_arg.writemask into account + // !!! FIXME: can we use dst() intrinsic instead? -caleb + char src0_y[64]; make_HLSL_srcarg_string_y(ctx, 0, src0_y, sizeof (src0_y)); + char src1_y[64]; make_HLSL_srcarg_string_y(ctx, 1, src1_y, sizeof (src1_y)); + char src0_z[64]; make_HLSL_srcarg_string_z(ctx, 0, src0_z, sizeof (src0_z)); + char src1_w[64]; make_HLSL_srcarg_string_w(ctx, 1, src1_w, sizeof (src1_w)); + + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "float4(1.0, %s * %s, %s, %s)", + src0_y, src1_y, src0_z, src1_w); + output_line(ctx, "%s", code); +} // emit_HLSL_DST + +void emit_HLSL_LRP(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_HLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char src2[64]; make_HLSL_srcarg_string_masked(ctx, 2, src2, sizeof (src2)); + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), "lerp(%s, %s, %s)", + src2, src1, src0); + output_line(ctx, "%s", code); +} // emit_HLSL_LRP + +void emit_HLSL_FRC(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), "frac(%s)", src0); + output_line(ctx, "%s", code); +} // emit_HLSL_FRC + +void emit_HLSL_M4X4(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); + char row0[64]; make_HLSL_srcarg_string_full(ctx, 1, row0, sizeof (row0)); + char row1[64]; make_HLSL_srcarg_string_full(ctx, 2, row1, sizeof (row1)); + char row2[64]; make_HLSL_srcarg_string_full(ctx, 3, row2, sizeof (row2)); + char row3[64]; make_HLSL_srcarg_string_full(ctx, 4, row3, sizeof (row3)); + char code[256]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "float4(dot(%s, %s), dot(%s, %s), dot(%s, %s), dot(%s, %s))", + src0, row0, src0, row1, src0, row2, src0, row3); + output_line(ctx, "%s", code); +} // emit_HLSL_M4X4 + +void emit_HLSL_M4X3(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); + char row0[64]; make_HLSL_srcarg_string_full(ctx, 1, row0, sizeof (row0)); + char row1[64]; make_HLSL_srcarg_string_full(ctx, 2, row1, sizeof (row1)); + char row2[64]; make_HLSL_srcarg_string_full(ctx, 3, row2, sizeof (row2)); + char code[256]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "float3(dot(%s, %s), dot(%s, %s), dot(%s, %s))", + src0, row0, src0, row1, src0, row2); + output_line(ctx, "%s", code); +} // emit_HLSL_M4X3 + +void emit_HLSL_M3X4(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + char row0[64]; make_HLSL_srcarg_string_vec3(ctx, 1, row0, sizeof (row0)); + char row1[64]; make_HLSL_srcarg_string_vec3(ctx, 2, row1, sizeof (row1)); + char row2[64]; make_HLSL_srcarg_string_vec3(ctx, 3, row2, sizeof (row2)); + char row3[64]; make_HLSL_srcarg_string_vec3(ctx, 4, row3, sizeof (row3)); + + char code[256]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "float4(dot(%s, %s), dot(%s, %s), " + "dot(%s, %s), dot(%s, %s))", + src0, row0, src0, row1, + src0, row2, src0, row3); + output_line(ctx, "%s", code); +} // emit_HLSL_M3X4 + +void emit_HLSL_M3X3(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + char row0[64]; make_HLSL_srcarg_string_vec3(ctx, 1, row0, sizeof (row0)); + char row1[64]; make_HLSL_srcarg_string_vec3(ctx, 2, row1, sizeof (row1)); + char row2[64]; make_HLSL_srcarg_string_vec3(ctx, 3, row2, sizeof (row2)); + char code[256]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "float3(dot(%s, %s), dot(%s, %s), dot(%s, %s))", + src0, row0, src0, row1, src0, row2); + output_line(ctx, "%s", code); +} // emit_HLSL_M3X3 + +void emit_HLSL_M3X2(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + char row0[64]; make_HLSL_srcarg_string_vec3(ctx, 1, row0, sizeof (row0)); + char row1[64]; make_HLSL_srcarg_string_vec3(ctx, 2, row1, sizeof (row1)); + + char code[256]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "float2(dot(%s, %s), dot(%s, %s))", + src0, row0, src0, row1); + output_line(ctx, "%s", code); +} // emit_HLSL_M3X2 + +void emit_HLSL_CALL(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + if (ctx->loops > 0) + output_line(ctx, "%s(aL);", src0); + else + output_line(ctx, "%s();", src0); +} // emit_HLSL_CALL + +void emit_HLSL_CALLNZ(Context *ctx) +{ + // !!! FIXME: if src1 is a constbool that's true, we can remove the + // !!! FIXME: if. If it's false, we can make this a no-op. + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_HLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + + if (ctx->loops > 0) + output_line(ctx, "if (%s) { %s(aL); }", src1, src0); + else + output_line(ctx, "if (%s) { %s(); }", src1, src0); +} // emit_HLSL_CALLNZ + +void emit_HLSL_LOOP(Context *ctx) +{ + // !!! FIXME: swizzle? + char var[64]; get_HLSL_srcarg_varname(ctx, 1, var, sizeof (var)); + assert(ctx->source_args[0].regnum == 0); // in case they add aL1 someday. + output_line(ctx, "{"); + ctx->indent++; + output_line(ctx, "const int aLend = %s.x + %s.y;", var, var); + output_line(ctx, "for (int aL = %s.y; aL < aLend; aL += %s.z) {", var, var); + ctx->indent++; +} // emit_HLSL_LOOP + +void emit_HLSL_RET(Context *ctx) +{ + // thankfully, the MSDN specs say a RET _has_ to end a function...no + // early returns. So if you hit one, you know you can safely close + // a high-level function. + push_output(ctx, &ctx->postflight); + output_line(ctx, "}"); + output_blank_line(ctx); + set_output(ctx, &ctx->subroutines); // !!! FIXME: is this for LABEL? Maybe set it there so we don't allocate unnecessarily. +} // emit_HLSL_RET + +void emit_HLSL_ENDLOOP(Context *ctx) +{ + ctx->indent--; + output_line(ctx, "}"); + ctx->indent--; + output_line(ctx, "}"); +} // emit_HLSL_ENDLOOP + +void emit_HLSL_LABEL(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + const int label = ctx->source_args[0].regnum; + RegisterList *reg = reglist_find(&ctx->used_registers, REG_TYPE_LABEL, label); + assert(ctx->output == ctx->subroutines); // not mainline, etc. + assert(ctx->indent == 0); // we shouldn't be in the middle of a function. + + // MSDN specs say CALL* has to come before the LABEL, so we know if we + // can ditch the entire function here as unused. + if (reg == NULL) + set_output(ctx, &ctx->ignore); // Func not used. Parse, but don't output. + + // !!! FIXME: it would be nice if we could determine if a function is + // !!! FIXME: only called once and, if so, forcibly inline it. + + const char *uses_loopreg = ((reg) && (reg->misc == 1)) ? "int aL" : ""; + output_line(ctx, "void %s(%s)", src0, uses_loopreg); + output_line(ctx, "{"); + ctx->indent++; +} // emit_HLSL_LABEL + +void emit_HLSL_DCL(Context *ctx) +{ + // no-op. We do this in our emit_attribute() and emit_uniform(). +} // emit_HLSL_DCL + +void emit_HLSL_POW(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_HLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "pow(abs(%s), %s)", src0, src1); + output_line(ctx, "%s", code); +} // emit_HLSL_POW + +void emit_HLSL_CRS(Context *ctx) +{ + // !!! FIXME: needs to take ctx->dst_arg.writemask into account. + char src0[64]; make_HLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_HLSL_srcarg_string_vec3(ctx, 1, src1, sizeof (src1)); + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "cross(%s, %s)", src0, src1); + output_line(ctx, "%s", code); +} // emit_HLSL_CRS + +void emit_HLSL_SGN(Context *ctx) +{ + // (we don't need the temporary registers specified for the D3D opcode.) + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), "sign(%s)", src0); + output_line(ctx, "%s", code); +} // emit_HLSL_SGN + +void emit_HLSL_ABS(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), "abs(%s)", src0); + output_line(ctx, "%s", code); +} // emit_HLSL_ABS + +void emit_HLSL_NRM(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), "normalize(%s)", src0); + output_line(ctx, "%s", code); +} // emit_HLSL_NRM + +void emit_HLSL_SINCOS(Context *ctx) +{ + // we don't care about the temp registers that <= sm2 demands; ignore them. + // sm2 also talks about what components are left untouched vs. undefined, + // but we just leave those all untouched with HLSL write masks (which + // would fulfill the "undefined" requirement, too). + const int mask = ctx->dest_arg.writemask; + char src0[64]; make_HLSL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + char code[128] = { '\0' }; + + if (writemask_x(mask)) + make_HLSL_destarg_assign(ctx, code, sizeof (code), "cos(%s)", src0); + else if (writemask_y(mask)) + make_HLSL_destarg_assign(ctx, code, sizeof (code), "sin(%s)", src0); + else if (writemask_xy(mask)) + { + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "float2(cos(%s), sin(%s))", src0, src0); + } // else if + + output_line(ctx, "%s", code); +} // emit_HLSL_SINCOS + +void emit_HLSL_REP(Context *ctx) +{ + // !!! FIXME: + // msdn docs say legal loop values are 0 to 255. We can check DEFI values + // at parse time, but if they are pulling a value from a uniform, do + // we clamp here? + // !!! FIXME: swizzle is legal here, right? + char src0[64]; make_HLSL_srcarg_string_x(ctx, 0, src0, sizeof (src0)); + const uint rep = (uint) ctx->reps; + output_line(ctx, "for (int rep%u = 0; rep%u < %s; rep%u++) {", + rep, rep, src0, rep); + ctx->indent++; +} // emit_HLSL_REP + +void emit_HLSL_ENDREP(Context *ctx) +{ + ctx->indent--; + output_line(ctx, "}"); +} // emit_HLSL_ENDREP + +void emit_HLSL_IF(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + output_line(ctx, "if (%s) {", src0); + ctx->indent++; +} // emit_HLSL_IF + +void emit_HLSL_IFC(Context *ctx) +{ + const char *comp = get_HLSL_comparison_string_scalar(ctx); + char src0[64]; make_HLSL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_HLSL_srcarg_string_scalar(ctx, 1, src1, sizeof (src1)); + output_line(ctx, "if (%s %s %s) {", src0, comp, src1); + ctx->indent++; +} // emit_HLSL_IFC + +void emit_HLSL_ELSE(Context *ctx) +{ + ctx->indent--; + output_line(ctx, "} else {"); + ctx->indent++; +} // emit_HLSL_ELSE + +void emit_HLSL_ENDIF(Context *ctx) +{ + ctx->indent--; + output_line(ctx, "}"); +} // emit_HLSL_ENDIF + +void emit_HLSL_BREAK(Context *ctx) +{ + output_line(ctx, "break;"); +} // emit_HLSL_BREAK + +void emit_HLSL_BREAKC(Context *ctx) +{ + const char *comp = get_HLSL_comparison_string_scalar(ctx); + char src0[64]; make_HLSL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_HLSL_srcarg_string_scalar(ctx, 1, src1, sizeof (src1)); + output_line(ctx, "if (%s %s %s) { break; }", src0, comp, src1); +} // emit_HLSL_BREAKC + +void emit_HLSL_MOVA(Context *ctx) +{ + const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + + if (vecsize == 1) + { + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "int(floor(abs(%s) + 0.5) * sign(%s))", + src0, src0); + } // if + + else + { + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "int%d(floor(abs(%s) + 0.5) * sign(%s))", + vecsize, src0, src0); + } // else + + output_line(ctx, "%s", code); +} // emit_HLSL_MOVA + +void emit_HLSL_DEFB(Context *ctx) +{ + char varname[64]; get_HLSL_destarg_varname(ctx, varname, sizeof (varname)); + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + output_line(ctx, "const bool %s = %s;", + varname, ctx->dwords[0] ? "true" : "false"); + ctx->indent--; + pop_output(ctx); +} // emit_HLSL_DEFB + +void emit_HLSL_DEFI(Context *ctx) +{ + char varname[64]; get_HLSL_destarg_varname(ctx, varname, sizeof (varname)); + const int32 *x = (const int32 *) ctx->dwords; + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + output_line(ctx, "const int4 %s = int4(%d, %d, %d, %d);", + varname, (int) x[0], (int) x[1], (int) x[2], (int) x[3]); + ctx->indent--; + pop_output(ctx); +} // emit_HLSL_DEFI + +EMIT_HLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXCRD) + +void emit_HLSL_TEXKILL(Context *ctx) +{ + char dst[64]; get_HLSL_destarg_varname(ctx, dst, sizeof (dst)); + output_line(ctx, "if (any(%s.xyz < 0.0)) discard;", dst); +} // emit_HLSL_TEXKILL + +void emit_HLSL_TEXLD(Context *ctx) +{ + if (!shader_version_atleast(ctx, 1, 4)) + { + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; + char sampler[64]; + char code[128] = {0}; + + RegisterList *sreg; + sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, info->regnum); + const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_HLSL_destarg_varname(ctx, dst, sizeof (dst)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + + if (ttype == TEXTURE_TYPE_2D) + { + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "%s_texture.Sample(%s, %s.xy)", + sampler, sampler, dst); + } // if + else if (ttype == TEXTURE_TYPE_CUBE || ttype == TEXTURE_TYPE_VOLUME) + { + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "%s_texture.Sample(%s, %s.xyz)", + sampler, sampler, dst); + } // else if + else + { + fail(ctx, "unexpected texture type"); + } // else + output_line(ctx, "%s", code); + } // if + + else if (!shader_version_atleast(ctx, 2, 0)) + { + // ps_1_4 is different, too! + fail(ctx, "TEXLD == Shader Model 1.4 unimplemented."); // !!! FIXME + return; + } // else if + + else + { + const SourceArgInfo *samp_arg = &ctx->source_args[1]; + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, + samp_arg->regnum); + const char *funcname = NULL; + char src0[64] = { '\0' }; + char src1[64]; get_HLSL_srcarg_varname(ctx, 1, src1, sizeof (src1)); // !!! FIXME: SRC_MOD? + + if (sreg == NULL) + { + fail(ctx, "TEXLD using undeclared sampler"); + return; + } // if + + const char *projsep = ""; + char proj[64] = { '\0' }; + if (ctx->instruction_controls == CONTROL_TEXLDP) + { + projsep = " / "; + make_HLSL_srcarg_string_w(ctx, 0, proj, sizeof (proj)); + } // if + + // !!! FIXME: does the d3d bias value map directly to HLSL? + const char *biassep = ""; + char bias[64] = { '\0' }; + if (ctx->instruction_controls == CONTROL_TEXLDB) + { + biassep = ", "; + make_HLSL_srcarg_string_w(ctx, 0, bias, sizeof (bias)); + funcname = "SampleBias"; + } // if + else + { + funcname = "Sample"; + } // else + + switch ((const TextureType) sreg->index) + { + case TEXTURE_TYPE_2D: + make_HLSL_srcarg_string_vec2(ctx, 0, src0, sizeof (src0)); + break; + case TEXTURE_TYPE_CUBE: + if (ctx->instruction_controls == CONTROL_TEXLDP) + fail(ctx, "TEXLDP on a cubemap"); // !!! FIXME: is this legal? + make_HLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + break; + case TEXTURE_TYPE_VOLUME: + make_HLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + break; + default: + fail(ctx, "unknown texture type"); + return; + } // switch + + assert(!isscalar(ctx, ctx->shader_type, samp_arg->regtype, samp_arg->regnum)); + char swiz_str[6] = { '\0' }; + make_HLSL_swizzle_string(swiz_str, sizeof (swiz_str), + samp_arg->swizzle, ctx->dest_arg.writemask); + + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "%s_texture.%s(%s, %s%s%s%s%s)%s", src1, funcname, + src1, src0, projsep, proj, biassep, bias, swiz_str); + + output_line(ctx, "%s", code); + } // else +} // emit_HLSL_TEXLD + +void emit_HLSL_TEXBEM(Context *ctx) +{ + // !!! FIXME: this code counts on the register not having swizzles, etc. + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; get_HLSL_destarg_varname(ctx, dst, sizeof (dst)); + char src[64]; get_HLSL_srcarg_varname(ctx, 0, src, sizeof (src)); + char sampler[64]; + char code[512]; + + get_HLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "%s_texture.Sample(%s, float2(%s.x + (%s_texbem.x * %s.x) + (%s_texbem.z * %s.y)," + " %s.y + (%s_texbem.y * %s.x) + (%s_texbem.w * %s.y)))", + sampler, sampler, + dst, sampler, src, sampler, src, + dst, sampler, src, sampler, src); + + output_line(ctx, "%s", code); +} // emit_HLSL_TEXBEM + +void emit_HLSL_TEXBEML(Context *ctx) +{ + // !!! FIXME: this code counts on the register not having swizzles, etc. + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; get_HLSL_destarg_varname(ctx, dst, sizeof (dst)); + char src[64]; get_HLSL_srcarg_varname(ctx, 0, src, sizeof (src)); + char sampler[64]; + char code[512]; + + get_HLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "(%s_texture.Sample(%s, float2(%s.x + (%s_texbem.x * %s.x) + (%s_texbem.z * %s.y)," + " %s.y + (%s_texbem.y * %s.x) + (%s_texbem.w * %s.y)))) *" + " ((%s.z * %s_texbeml.x) + %s_texbem.y)", + sampler, sampler, + dst, sampler, src, sampler, src, + dst, sampler, src, sampler, src, + src, sampler, sampler); + + output_line(ctx, "%s", code); +} // emit_HLSL_TEXBEML + +EMIT_HLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2AR) // !!! FIXME +EMIT_HLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2GB) // !!! FIXME + +void emit_HLSL_TEXM3X2PAD(Context *ctx) +{ + // no-op ... work happens in emit_HLSL_TEXM3X2TEX(). +} // emit_HLSL_TEXM3X2PAD + +void emit_HLSL_TEXM3X2TEX(Context *ctx) +{ + if (ctx->texm3x2pad_src0 == -1) + return; + + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char sampler[64]; + char code[512]; + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_HLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x2pad_src0, + src0, sizeof (src0)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x2pad_dst0, + src1, sizeof (src1)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src2, sizeof (src2)); + get_HLSL_destarg_varname(ctx, dst, sizeof (dst)); + + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "%s_texture.Sample(%s, float2(dot(%s.xyz, %s.xyz), dot(%s.xyz, %s.xyz)))", + sampler, sampler, src0, src1, src2, dst); + + output_line(ctx, "%s", code); +} // emit_HLSL_TEXM3X2TEX + +void emit_HLSL_TEXM3X3PAD(Context *ctx) +{ + // no-op ... work happens in emit_HLSL_TEXM3X3*(). +} // emit_HLSL_TEXM3X3PAD + +void emit_HLSL_TEXM3X3TEX(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char src3[64]; + char src4[64]; + char sampler[64]; + char code[512]; + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_HLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, + src0, sizeof (src0)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, + src1, sizeof (src1)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, + src2, sizeof (src2)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, + src3, sizeof (src3)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src4, sizeof (src4)); + get_HLSL_destarg_varname(ctx, dst, sizeof (dst)); + + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "%s_texture.Sample(%s," + " float3(dot(%s.xyz, %s.xyz)," + " dot(%s.xyz, %s.xyz)," + " dot(%s.xyz, %s.xyz)))", + sampler, sampler, src0, src1, src2, src3, dst, src4); + + output_line(ctx, "%s", code); +} // emit_HLSL_TEXM3X3TEX + +void emit_HLSL_TEXM3X3SPEC_helper(Context *ctx) +{ + if (ctx->glsl_generated_texm3x3spec_helper) + return; + + ctx->glsl_generated_texm3x3spec_helper = 1; + + push_output(ctx, &ctx->helpers); + output_line(ctx, "float3 TEXM3X3SPEC_reflection(const float3 normal, const float3 eyeray)"); + output_line(ctx, "{"); ctx->indent++; + output_line(ctx, "return (2.0 * ((normal * eyeray) / (normal * normal)) * normal) - eyeray;"); ctx->indent--; + output_line(ctx, "}"); + output_blank_line(ctx); + pop_output(ctx); +} // emit_HLSL_TEXM3X3SPEC_helper + +void emit_HLSL_TEXM3X3SPEC(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char src3[64]; + char src4[64]; + char src5[64]; + char sampler[64]; + char code[512]; + + emit_HLSL_TEXM3X3SPEC_helper(ctx); + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_HLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, + src0, sizeof (src0)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, + src1, sizeof (src1)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, + src2, sizeof (src2)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, + src3, sizeof (src3)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src4, sizeof (src4)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[1].regnum, + src5, sizeof (src5)); + get_HLSL_destarg_varname(ctx, dst, sizeof (dst)); + + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "%s_texture.Sample(%s, " + "TEXM3X3SPEC_reflection(" + "float3(" + "dot(%s.xyz, %s.xyz), " + "dot(%s.xyz, %s.xyz), " + "dot(%s.xyz, %s.xyz)" + ")," + "%s.xyz," + ")" + ")", + sampler, sampler, src0, src1, src2, src3, dst, src4, src5); + + output_line(ctx, "%s", code); +} // emit_HLSL_TEXM3X3SPEC + +void emit_HLSL_TEXM3X3VSPEC(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char src3[64]; + char src4[64]; + char sampler[64]; + char code[512]; + + emit_HLSL_TEXM3X3SPEC_helper(ctx); + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_HLSL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, + src0, sizeof (src0)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, + src1, sizeof (src1)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, + src2, sizeof (src2)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, + src3, sizeof (src3)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src4, sizeof (src4)); + get_HLSL_destarg_varname(ctx, dst, sizeof (dst)); + + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "%s_texture.Sample(%s, " + "TEXM3X3SPEC_reflection(" + "float3(" + "dot(%s.xyz, %s.xyz), " + "dot(%s.xyz, %s.xyz), " + "dot(%s.xyz, %s.xyz)" + "), " + "float3(%s.w, %s.w, %s.w)" + ")" + ")", + sampler, sampler, src0, src1, src2, src3, dst, src4, src0, src2, dst); + + output_line(ctx, "%s", code); +} // emit_HLSL_TEXM3X3VSPEC + +void emit_HLSL_EXPP(Context *ctx) +{ + // !!! FIXME: msdn's asm docs don't list this opcode, I'll have to check the driver documentation. + emit_HLSL_EXP(ctx); // I guess this is just partial precision EXP? +} // emit_HLSL_EXPP + +void emit_HLSL_LOGP(Context *ctx) +{ + // LOGP is just low-precision LOG, but we'll take the higher precision. + emit_HLSL_LOG(ctx); +} // emit_HLSL_LOGP + +// common code between CMP and CND. +void emit_HLSL_comparison_operations(Context *ctx, const char *cmp) +{ + int i, j; + DestArgInfo *dst = &ctx->dest_arg; + const SourceArgInfo *srcarg0 = &ctx->source_args[0]; + const int origmask = dst->writemask; + int used_swiz[4] = { 0, 0, 0, 0 }; + const int writemask[4] = { dst->writemask0, dst->writemask1, + dst->writemask2, dst->writemask3 }; + const int src0swiz[4] = { srcarg0->swizzle_x, srcarg0->swizzle_y, + srcarg0->swizzle_z, srcarg0->swizzle_w }; + + for (i = 0; i < 4; i++) + { + int mask = (1 << i); + + if (!writemask[i]) continue; + if (used_swiz[i]) continue; + + // This is a swizzle we haven't checked yet. + used_swiz[i] = 1; + + // see if there are any other elements swizzled to match (.yyyy) + for (j = i + 1; j < 4; j++) + { + if (!writemask[j]) continue; + if (src0swiz[i] != src0swiz[j]) continue; + mask |= (1 << j); + used_swiz[j] = 1; + } // for + + // okay, (mask) should be the writemask of swizzles we like. + + char src0[64]; + char src1[64]; + char src2[64]; + make_HLSL_srcarg_string(ctx, 0, (1 << i), src0, sizeof (src0)); + make_HLSL_srcarg_string(ctx, 1, mask, src1, sizeof (src1)); + make_HLSL_srcarg_string(ctx, 2, mask, src2, sizeof (src2)); + + set_dstarg_writemask(dst, mask); + + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "((%s %s) ? %s : %s)", + src0, cmp, src1, src2); + output_line(ctx, "%s", code); + } // for + + set_dstarg_writemask(dst, origmask); +} // emit_HLSL_comparison_operations + +void emit_HLSL_CND(Context *ctx) +{ + emit_HLSL_comparison_operations(ctx, "> 0.5"); +} // emit_HLSL_CND + +void emit_HLSL_DEF(Context *ctx) +{ + const float *val = (const float *) ctx->dwords; // !!! FIXME: could be int? + char varname[64]; get_HLSL_destarg_varname(ctx, varname, sizeof (varname)); + char val0[32]; floatstr(ctx, val0, sizeof (val0), val[0], 1); + char val1[32]; floatstr(ctx, val1, sizeof (val1), val[1], 1); + char val2[32]; floatstr(ctx, val2, sizeof (val2), val[2], 1); + char val3[32]; floatstr(ctx, val3, sizeof (val3), val[3], 1); + + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + output_line(ctx, "const float4 %s = float4(%s, %s, %s, %s);", + varname, val0, val1, val2, val3); + ctx->indent--; + pop_output(ctx); +} // emit_HLSL_DEF + +EMIT_HLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2RGB) // !!! FIXME +EMIT_HLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXDP3TEX) // !!! FIXME +EMIT_HLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXM3X2DEPTH) // !!! FIXME +EMIT_HLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXDP3) // !!! FIXME + +void emit_HLSL_TEXM3X3(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char src3[64]; + char src4[64]; + char code[512]; + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, + src0, sizeof (src0)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, + src1, sizeof (src1)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, + src2, sizeof (src2)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, + src3, sizeof (src3)); + get_HLSL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src4, sizeof (src4)); + get_HLSL_destarg_varname(ctx, dst, sizeof (dst)); + + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "float4(dot(%s.xyz, %s.xyz), dot(%s.xyz, %s.xyz), dot(%s.xyz, %s.xyz), 1.0)", + src0, src1, src2, src3, dst, src4); + + output_line(ctx, "%s", code); +} // emit_HLSL_TEXM3X3 + +EMIT_HLSL_OPCODE_UNIMPLEMENTED_FUNC(TEXDEPTH) // !!! FIXME + +void emit_HLSL_CMP(Context *ctx) +{ + emit_HLSL_comparison_operations(ctx, ">= 0.0"); +} // emit_HLSL_CMP + +EMIT_HLSL_OPCODE_UNIMPLEMENTED_FUNC(BEM) // !!! FIXME + +void emit_HLSL_DP2ADD(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_vec2(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_HLSL_srcarg_string_vec2(ctx, 1, src1, sizeof (src1)); + char src2[64]; make_HLSL_srcarg_string_scalar(ctx, 2, src2, sizeof (src2)); + char extra[64]; snprintf(extra, sizeof (extra), " + %s", src2); + emit_HLSL_dotprod(ctx, src0, src1, extra); +} // emit_HLSL_DP2ADD + +void emit_HLSL_DSX(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), "ddx(%s)", src0); + output_line(ctx, "%s", code); +} // emit_HLSL_DSX + +void emit_HLSL_DSY(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), "ddy(%s)", src0); + output_line(ctx, "%s", code); +} // emit_HLSL_DSY + +void emit_HLSL_TEXLDD(Context *ctx) +{ + const SourceArgInfo *samp_arg = &ctx->source_args[1]; + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, + samp_arg->regnum); + char src0[64] = { '\0' }; + char src1[64]; get_HLSL_srcarg_varname(ctx, 1, src1, sizeof (src1)); // !!! FIXME: SRC_MOD? + char src2[64] = { '\0' }; + char src3[64] = { '\0' }; + + if (sreg == NULL) + { + fail(ctx, "TEXLDD using undeclared sampler"); + return; + } // if + + switch ((const TextureType) sreg->index) + { + case TEXTURE_TYPE_2D: + make_HLSL_srcarg_string_vec2(ctx, 0, src0, sizeof (src0)); + make_HLSL_srcarg_string_vec2(ctx, 2, src2, sizeof (src2)); + make_HLSL_srcarg_string_vec2(ctx, 3, src3, sizeof (src3)); + break; + case TEXTURE_TYPE_CUBE: + case TEXTURE_TYPE_VOLUME: + make_HLSL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + make_HLSL_srcarg_string_vec3(ctx, 2, src2, sizeof (src2)); + make_HLSL_srcarg_string_vec3(ctx, 3, src3, sizeof (src3)); + break; + default: + fail(ctx, "unknown texture type"); + return; + } // switch + + assert(!isscalar(ctx, ctx->shader_type, samp_arg->regtype, samp_arg->regnum)); + char swiz_str[6] = { '\0' }; + make_HLSL_swizzle_string(swiz_str, sizeof (swiz_str), + samp_arg->swizzle, ctx->dest_arg.writemask); + + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "%s_texture.SampleGrad(%s, %s, %s, %s)%s", + src1, src1, src0, src2, src3, swiz_str); + + output_line(ctx, "%s", code); +} // emit_HLSL_TEXLDD + +void emit_HLSL_SETP(Context *ctx) +{ + const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); + char src0[64]; make_HLSL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_HLSL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + + // destination is always predicate register (which is type bvec4). + const char *comp = (vecsize == 1) ? + get_HLSL_comparison_string_scalar(ctx) : + get_HLSL_comparison_string_vector(ctx); + + make_HLSL_destarg_assign(ctx, code, sizeof (code), + "(%s %s %s)", src0, comp, src1); + output_line(ctx, "%s", code); +} // emit_HLSL_SETP + +void emit_HLSL_TEXLDL(Context *ctx) +{ + const SourceArgInfo *samp_arg = &ctx->source_args[1]; + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, + samp_arg->regnum); + const char *pattern = NULL; + char src0[64]; + char src1[64]; + make_HLSL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); + get_HLSL_srcarg_varname(ctx, 1, src1, sizeof (src1)); // !!! FIXME: SRC_MOD? + + if (sreg == NULL) + { + fail(ctx, "TEXLDL using undeclared sampler"); + return; + } // if + + switch ((const TextureType) sreg->index) + { + case TEXTURE_TYPE_2D: + pattern = "%s_texture.SampleLevel(%s, %s.xy, %s.w)%s"; + break; + case TEXTURE_TYPE_CUBE: + case TEXTURE_TYPE_VOLUME: + pattern = "%s_texture.SampleLevel(%s, %s.xyz, %s.w)%s"; + break; + default: + fail(ctx, "unknown texture type"); + return; + } // switch + + assert(!isscalar(ctx, ctx->shader_type, samp_arg->regtype, samp_arg->regnum)); + char swiz_str[6] = { '\0' }; + make_HLSL_swizzle_string(swiz_str, sizeof (swiz_str), + samp_arg->swizzle, ctx->dest_arg.writemask); + + char code[128]; + make_HLSL_destarg_assign(ctx, code, sizeof(code), + pattern, src1, src1, src0, src0, swiz_str); + + output_line(ctx, "%s", code); +} // emit_HLSL_TEXLDL + +void emit_HLSL_BREAKP(Context *ctx) +{ + char src0[64]; make_HLSL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + output_line(ctx, "if (%s) { break; }", src0); +} // emit_HLSL_BREAKP + +void emit_HLSL_RESERVED(Context *ctx) +{ + // do nothing; fails in the state machine. +} // emit_HLSL_RESERVED + +#endif // SUPPORT_PROFILE_HLSL + +#pragma GCC visibility pop diff --git a/mojoshader/profiles/mojoshader_profile_metal.c b/mojoshader/profiles/mojoshader_profile_metal.c new file mode 100644 index 0000000..f78710f --- /dev/null +++ b/mojoshader/profiles/mojoshader_profile_metal.c @@ -0,0 +1,2319 @@ +/** + * MojoShader; generate shader programs from bytecode of compiled + * Direct3D shaders. + * + * Please see the file LICENSE.txt in the source's root directory. + * + * This file written by Ryan C. Gordon. + */ + +#define __MOJOSHADER_INTERNAL__ 1 +#include "mojoshader_profile.h" + +#pragma GCC visibility push(hidden) + +// !!! FIXME: A lot of this is cut-and-paste from the GLSL version. +#if SUPPORT_PROFILE_METAL + +#define EMIT_METAL_OPCODE_UNIMPLEMENTED_FUNC(op) \ + void emit_METAL_##op(Context *ctx) { \ + fail(ctx, #op " unimplemented in Metal profile"); \ + } + +static inline const char *get_METAL_register_string(Context *ctx, + const RegisterType regtype, const int regnum, + char *regnum_str, const size_t regnum_size) +{ + // turns out these are identical at the moment. + return get_D3D_register_string(ctx,regtype,regnum,regnum_str,regnum_size); +} // get_METAL_register_string + +const char *get_METAL_uniform_type(Context *ctx, const RegisterType rtype) +{ + switch (rtype) + { + case REG_TYPE_CONST: return "float4"; + case REG_TYPE_CONSTINT: return "int4"; + case REG_TYPE_CONSTBOOL: return "bool"; + default: fail(ctx, "BUG: used a uniform we don't know how to define."); + } // switch + + return NULL; +} // get_METAL_uniform_type + +const char *get_METAL_varname_in_buf(Context *ctx, RegisterType rt, + int regnum, char *buf, + const size_t len) +{ + char regnum_str[16]; + const char *regtype_str = get_METAL_register_string(ctx, rt, regnum, + regnum_str, sizeof (regnum_str)); + + // We don't separate vars with vs_ or ps_ here, because, for the most part, + // there are only local vars in Metal shaders. + snprintf(buf, len, "%s%s", regtype_str, regnum_str); + return buf; +} // get_METAL_varname_in_buf + + +const char *get_METAL_varname(Context *ctx, RegisterType rt, int regnum) +{ + char buf[64]; + get_METAL_varname_in_buf(ctx, rt, regnum, buf, sizeof (buf)); + return StrDup(ctx, buf); +} // get_METAL_varname + + +static inline const char *get_METAL_const_array_varname_in_buf(Context *ctx, + const int base, const int size, + char *buf, const size_t buflen) +{ + snprintf(buf, buflen, "const_array_%d_%d", base, size); + return buf; +} // get_METAL_const_array_varname_in_buf + +const char *get_METAL_const_array_varname(Context *ctx, int base, int size) +{ + char buf[64]; + get_METAL_const_array_varname_in_buf(ctx, base, size, buf, sizeof (buf)); + return StrDup(ctx, buf); +} // get_METAL_const_array_varname + + +static inline const char *get_METAL_input_array_varname(Context *ctx, + char *buf, const size_t buflen) +{ + snprintf(buf, buflen, "%s", "vertex_input_array"); + return buf; +} // get_METAL_input_array_varname + + +const char *get_METAL_uniform_array_varname(Context *ctx, + const RegisterType regtype, + char *buf, const size_t len) +{ + const char *shadertype = ctx->shader_type_str; + const char *type = get_METAL_uniform_type(ctx, regtype); + snprintf(buf, len, "uniforms.uniforms_%s", type); + return buf; +} // get_METAL_uniform_array_varname + +const char *get_METAL_destarg_varname(Context *ctx, char *buf, size_t len) +{ + const DestArgInfo *arg = &ctx->dest_arg; + return get_METAL_varname_in_buf(ctx, arg->regtype, arg->regnum, buf, len); +} // get_METAL_destarg_varname + +const char *get_METAL_srcarg_varname(Context *ctx, const size_t idx, + char *buf, size_t len) +{ + if (idx >= STATICARRAYLEN(ctx->source_args)) + { + fail(ctx, "Too many source args"); + *buf = '\0'; + return buf; + } // if + + const SourceArgInfo *arg = &ctx->source_args[idx]; + return get_METAL_varname_in_buf(ctx, arg->regtype, arg->regnum, buf, len); +} // get_METAL_srcarg_varname + + +const char *make_METAL_destarg_assign(Context *, char *, const size_t, + const char *, ...) ISPRINTF(4,5); + +const char *make_METAL_destarg_assign(Context *ctx, char *buf, + const size_t buflen, + const char *fmt, ...) +{ + int need_parens = 0; + const DestArgInfo *arg = &ctx->dest_arg; + + if (arg->writemask == 0) + { + *buf = '\0'; + return buf; // no writemask? It's a no-op. + } // if + + char clampbuf[32] = { '\0' }; + const char *clampleft = ""; + const char *clampright = ""; + if (arg->result_mod & MOD_SATURATE) + { + ctx->metal_need_header_common = 1; + const int vecsize = vecsize_from_writemask(arg->writemask); + clampleft = "clamp("; + if (vecsize == 1) + clampright = ", 0.0, 1.0)"; + else + { + snprintf(clampbuf, sizeof (clampbuf), + ", float%d(0.0), float%d(1.0))", vecsize, vecsize); + clampright = clampbuf; + } // else + } // if + + // MSDN says MOD_PP is a hint and many implementations ignore it. So do we. + + // CENTROID only allowed in DCL opcodes, which shouldn't come through here. + assert((arg->result_mod & MOD_CENTROID) == 0); + + if (ctx->predicated) + { + fail(ctx, "predicated destinations unsupported"); // !!! FIXME + *buf = '\0'; + return buf; + } // if + + char operation[256]; + va_list ap; + va_start(ap, fmt); + const int len = vsnprintf(operation, sizeof (operation), fmt, ap); + va_end(ap); + if (len >= sizeof (operation)) + { + fail(ctx, "operation string too large"); // I'm lazy. :P + *buf = '\0'; + return buf; + } // if + + const char *result_shift_str = ""; + switch (arg->result_shift) + { + case 0x1: result_shift_str = " * 2.0"; break; + case 0x2: result_shift_str = " * 4.0"; break; + case 0x3: result_shift_str = " * 8.0"; break; + case 0xD: result_shift_str = " / 8.0"; break; + case 0xE: result_shift_str = " / 4.0"; break; + case 0xF: result_shift_str = " / 2.0"; break; + } // switch + need_parens |= (result_shift_str[0] != '\0'); + + char regnum_str[16]; + const char *regtype_str = get_METAL_register_string(ctx, arg->regtype, + arg->regnum, regnum_str, + sizeof (regnum_str)); + char writemask_str[6]; + size_t i = 0; + const int scalar = isscalar(ctx, ctx->shader_type, arg->regtype, arg->regnum); + if (!scalar && !writemask_xyzw(arg->writemask)) + { + writemask_str[i++] = '.'; + if (arg->writemask0) writemask_str[i++] = 'x'; + if (arg->writemask1) writemask_str[i++] = 'y'; + if (arg->writemask2) writemask_str[i++] = 'z'; + if (arg->writemask3) writemask_str[i++] = 'w'; + } // if + writemask_str[i] = '\0'; + assert(i < sizeof (writemask_str)); + + const char *leftparen = (need_parens) ? "(" : ""; + const char *rightparen = (need_parens) ? ")" : ""; + + snprintf(buf, buflen, "%s%s%s = %s%s%s%s%s%s;", + regtype_str, regnum_str, writemask_str, + clampleft, leftparen, operation, rightparen, result_shift_str, + clampright); + // !!! FIXME: make sure the scratch buffer was large enough. + return buf; +} // make_METAL_destarg_assign + + +char *make_METAL_swizzle_string(char *swiz_str, const size_t strsize, + const int swizzle, const int writemask) +{ + size_t i = 0; + if ( (!no_swizzle(swizzle)) || (!writemask_xyzw(writemask)) ) + { + const int writemask0 = (writemask >> 0) & 0x1; + const int writemask1 = (writemask >> 1) & 0x1; + const int writemask2 = (writemask >> 2) & 0x1; + const int writemask3 = (writemask >> 3) & 0x1; + + const int swizzle_x = (swizzle >> 0) & 0x3; + const int swizzle_y = (swizzle >> 2) & 0x3; + const int swizzle_z = (swizzle >> 4) & 0x3; + const int swizzle_w = (swizzle >> 6) & 0x3; + + swiz_str[i++] = '.'; + if (writemask0) swiz_str[i++] = swizzle_channels[swizzle_x]; + if (writemask1) swiz_str[i++] = swizzle_channels[swizzle_y]; + if (writemask2) swiz_str[i++] = swizzle_channels[swizzle_z]; + if (writemask3) swiz_str[i++] = swizzle_channels[swizzle_w]; + } // if + assert(i < strsize); + swiz_str[i] = '\0'; + return swiz_str; +} // make_METAL_swizzle_string + + +const char *make_METAL_srcarg_string(Context *ctx, const size_t idx, + const int writemask, char *buf, + const size_t buflen) +{ + *buf = '\0'; + + if (idx >= STATICARRAYLEN(ctx->source_args)) + { + fail(ctx, "Too many source args"); + return buf; + } // if + + const SourceArgInfo *arg = &ctx->source_args[idx]; + + const char *premod_str = ""; + const char *postmod_str = ""; + switch (arg->src_mod) + { + case SRCMOD_NEGATE: + premod_str = "-"; + break; + + case SRCMOD_BIASNEGATE: + premod_str = "-("; + postmod_str = " - 0.5)"; + break; + + case SRCMOD_BIAS: + premod_str = "("; + postmod_str = " - 0.5)"; + break; + + case SRCMOD_SIGNNEGATE: + premod_str = "-(("; + postmod_str = " - 0.5) * 2.0)"; + break; + + case SRCMOD_SIGN: + premod_str = "(("; + postmod_str = " - 0.5) * 2.0)"; + break; + + case SRCMOD_COMPLEMENT: + premod_str = "(1.0 - "; + postmod_str = ")"; + break; + + case SRCMOD_X2NEGATE: + premod_str = "-("; + postmod_str = " * 2.0)"; + break; + + case SRCMOD_X2: + premod_str = "("; + postmod_str = " * 2.0)"; + break; + + case SRCMOD_DZ: + fail(ctx, "SRCMOD_DZ unsupported"); return buf; // !!! FIXME + postmod_str = "_dz"; + break; + + case SRCMOD_DW: + fail(ctx, "SRCMOD_DW unsupported"); return buf; // !!! FIXME + postmod_str = "_dw"; + break; + + case SRCMOD_ABSNEGATE: + ctx->metal_need_header_math = 1; + premod_str = "-abs("; + postmod_str = ")"; + break; + + case SRCMOD_ABS: + ctx->metal_need_header_math = 1; + premod_str = "abs("; + postmod_str = ")"; + break; + + case SRCMOD_NOT: + premod_str = "!"; + break; + + case SRCMOD_NONE: + case SRCMOD_TOTAL: + break; // stop compiler whining. + } // switch + + const char *regtype_str = NULL; + + if (!arg->relative) + { + regtype_str = get_METAL_varname_in_buf(ctx, arg->regtype, arg->regnum, + (char *) alloca(64), 64); + } // if + + const char *rel_lbracket = ""; + char rel_offset[32] = { '\0' }; + const char *rel_rbracket = ""; + char rel_swizzle[4] = { '\0' }; + const char *rel_regtype_str = ""; + if (arg->relative) + { + if (arg->regtype == REG_TYPE_INPUT) + regtype_str=get_METAL_input_array_varname(ctx,(char*)alloca(64),64); + else + { + assert(arg->regtype == REG_TYPE_CONST); + const int arrayidx = arg->relative_array->index; + const int offset = arg->regnum - arrayidx; + assert(offset >= 0); + if (arg->relative_array->constant) + { + const int arraysize = arg->relative_array->count; + regtype_str = get_METAL_const_array_varname_in_buf(ctx, + arrayidx, arraysize, (char *) alloca(64), 64); + if (offset != 0) + snprintf(rel_offset, sizeof (rel_offset), "%d + ", offset); + } // if + else + { + regtype_str = get_METAL_uniform_array_varname(ctx, arg->regtype, + (char *) alloca(64), 64); + if (offset == 0) + { + snprintf(rel_offset, sizeof (rel_offset), + "ARRAYBASE_%d + ", arrayidx); + } // if + else + { + snprintf(rel_offset, sizeof (rel_offset), + "(ARRAYBASE_%d + %d) + ", arrayidx, offset); + } // else + } // else + } // else + + rel_lbracket = "["; + + rel_regtype_str = get_METAL_varname_in_buf(ctx, arg->relative_regtype, + arg->relative_regnum, + (char *) alloca(64), 64); + rel_swizzle[0] = '.'; + rel_swizzle[1] = swizzle_channels[arg->relative_component]; + rel_swizzle[2] = '\0'; + rel_rbracket = "]"; + } // if + + char swiz_str[6] = { '\0' }; + if (!isscalar(ctx, ctx->shader_type, arg->regtype, arg->regnum)) + { + make_METAL_swizzle_string(swiz_str, sizeof (swiz_str), + arg->swizzle, writemask); + } // if + + if (regtype_str == NULL) + { + fail(ctx, "Unknown source register type."); + return buf; + } // if + + snprintf(buf, buflen, "%s%s%s%s%s%s%s%s%s", + premod_str, regtype_str, rel_lbracket, rel_offset, + rel_regtype_str, rel_swizzle, rel_rbracket, swiz_str, + postmod_str); + // !!! FIXME: make sure the scratch buffer was large enough. + return buf; +} // make_METAL_srcarg_string + +// generate some convenience functions. +#define MAKE_METAL_SRCARG_STRING_(mask, bitmask) \ + static inline const char *make_METAL_srcarg_string_##mask(Context *ctx, \ + const size_t idx, char *buf, \ + const size_t buflen) { \ + return make_METAL_srcarg_string(ctx, idx, bitmask, buf, buflen); \ + } +MAKE_METAL_SRCARG_STRING_(x, (1 << 0)) +MAKE_METAL_SRCARG_STRING_(y, (1 << 1)) +MAKE_METAL_SRCARG_STRING_(z, (1 << 2)) +MAKE_METAL_SRCARG_STRING_(w, (1 << 3)) +MAKE_METAL_SRCARG_STRING_(scalar, (1 << 0)) +MAKE_METAL_SRCARG_STRING_(full, 0xF) +MAKE_METAL_SRCARG_STRING_(masked, ctx->dest_arg.writemask) +MAKE_METAL_SRCARG_STRING_(vec3, 0x7) +MAKE_METAL_SRCARG_STRING_(vec2, 0x3) +#undef MAKE_METAL_SRCARG_STRING_ + +// special cases for comparison opcodes... + +const char *get_METAL_comparison_string_scalar(Context *ctx) +{ + const char *comps[] = { "", ">", "==", ">=", "<", "!=", "<=" }; + if (ctx->instruction_controls >= STATICARRAYLEN(comps)) + { + fail(ctx, "unknown comparison control"); + return ""; + } // if + + return comps[ctx->instruction_controls]; +} // get_METAL_comparison_string_scalar + +const char *get_METAL_comparison_string_vector(Context *ctx) +{ + return get_METAL_comparison_string_scalar(ctx); // standard C operators work for vectors in Metal. +} // get_METAL_comparison_string_vector + + +void emit_METAL_start(Context *ctx, const char *profilestr) +{ + if (!shader_is_vertex(ctx) && !shader_is_pixel(ctx)) + { + failf(ctx, "Shader type %u unsupported in this profile.", + (uint) ctx->shader_type); + return; + } // if + + if (!ctx->mainfn) + { + if (shader_is_vertex(ctx)) + ctx->mainfn = StrDup(ctx, "VertexShader"); + else if (shader_is_pixel(ctx)) + ctx->mainfn = StrDup(ctx, "FragmentShader"); + } // if + + set_output(ctx, &ctx->mainline); + ctx->indent++; +} // emit_METAL_start + +void emit_METAL_RET(Context *ctx); +void emit_METAL_end(Context *ctx) +{ + // !!! FIXME: maybe handle this at a higher level? + // ps_1_* writes color to r0 instead oC0. We move it to the right place. + // We don't have to worry about a RET opcode messing this up, since + // RET isn't available before ps_2_0. + if (shader_is_pixel(ctx) && !shader_version_atleast(ctx, 2, 0)) + { + set_used_register(ctx, REG_TYPE_COLOROUT, 0, 1); + output_line(ctx, "oC0 = r0;"); + } // if + + // !!! FIXME: maybe handle this at a higher level? + // force a RET opcode if we're at the end of the stream without one. + if (ctx->previous_opcode != OPCODE_RET) + emit_METAL_RET(ctx); +} // emit_METAL_end + +void emit_METAL_phase(Context *ctx) +{ + // no-op in Metal. +} // emit_METAL_phase + +void emit_METAL_finalize(Context *ctx) +{ + // If we had a relative addressing of REG_TYPE_INPUT, we need to build + // an array for it at the start of main(). GLSL doesn't let you specify + // arrays of attributes. + //float4 blah_array[BIGGEST_ARRAY]; + if (ctx->have_relative_input_registers) // !!! FIXME + fail(ctx, "Relative addressing of input registers not supported."); + + // Insert header includes we need... + push_output(ctx, &ctx->preflight); + #define INC_METAL_HEADER(name) \ + if (ctx->metal_need_header_##name) { \ + output_line(ctx, "#include "); \ + } + INC_METAL_HEADER(common); + INC_METAL_HEADER(math); + INC_METAL_HEADER(relational); + INC_METAL_HEADER(geometric); + INC_METAL_HEADER(graphics); + INC_METAL_HEADER(texture); + #undef INC_METAL_HEADER + output_blank_line(ctx); + output_line(ctx, "using namespace metal;"); + output_blank_line(ctx); + pop_output(ctx); + + // Fill in the shader's mainline function signature. + push_output(ctx, &ctx->mainline_intro); + output_line(ctx, "%s %s%s %s (", + shader_is_vertex(ctx) ? "vertex" : "fragment", + ctx->outputs ? ctx->mainfn : "void", + ctx->outputs ? "_Output" : "", ctx->mainfn); + pop_output(ctx); + + push_output(ctx, &ctx->mainline_arguments); + ctx->indent++; + + const int uniform_count = ctx->uniform_float4_count + ctx->uniform_int4_count + ctx->uniform_bool_count; + int commas = 0; + if (uniform_count) commas++; + if (ctx->inputs) commas++; + if (commas) commas--; + + if (uniform_count > 0) + { + push_output(ctx, &ctx->globals); + output_line(ctx, "struct %s_Uniforms", ctx->mainfn); + output_line(ctx, "{"); + ctx->indent++; + if (ctx->uniform_float4_count > 0) + output_line(ctx, "float4 uniforms_float4[%d];", ctx->uniform_float4_count); + if (ctx->uniform_int4_count > 0) + output_line(ctx, "int4 uniforms_int4[%d];", ctx->uniform_int4_count); + if (ctx->uniform_bool_count > 0) + output_line(ctx, "bool uniforms_bool[%d];", ctx->uniform_bool_count); + ctx->indent--; + output_line(ctx, "};"); + pop_output(ctx); + + output_line(ctx, "constant %s_Uniforms &uniforms [[buffer(0)]]%s", ctx->mainfn, commas ? "," : ""); + commas--; + } // if + + if (ctx->inputs) + { + output_line(ctx, "%s_Input input [[stage_in]]%s", ctx->mainfn, commas ? "," : ""); + commas--; + } // if + + ctx->indent--; + output_line(ctx, ") {"); + if (ctx->outputs) + { + ctx->indent++; + output_line(ctx, "%s_Output output;", ctx->mainfn); + + push_output(ctx, &ctx->mainline); + ctx->indent++; + output_line(ctx, "return output;"); + pop_output(ctx); + } // if + pop_output(ctx); + + if (ctx->inputs) + { + push_output(ctx, &ctx->inputs); + output_line(ctx, "};"); + output_blank_line(ctx); + pop_output(ctx); + } // if + + if (ctx->outputs) + { + push_output(ctx, &ctx->outputs); + output_line(ctx, "};"); + output_blank_line(ctx); + pop_output(ctx); + } // if + + // throw some blank lines around to make source more readable. + if (ctx->globals) // don't add a blank line if the section is empty. + { + push_output(ctx, &ctx->globals); + output_blank_line(ctx); + pop_output(ctx); + } // if +} // emit_METAL_finalize + +void emit_METAL_global(Context *ctx, RegisterType regtype, int regnum) +{ + char varname[64]; + get_METAL_varname_in_buf(ctx, regtype, regnum, varname, sizeof (varname)); + + // These aren't actually global in metal, set them up at top of mainline. + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + + switch (regtype) + { + case REG_TYPE_ADDRESS: + if (shader_is_vertex(ctx)) + output_line(ctx, "int4 %s;", varname); + else if (shader_is_pixel(ctx)) // actually REG_TYPE_TEXTURE. + { + // We have to map texture registers to temps for ps_1_1, since + // they work like temps, initialize with tex coords, and the + // ps_1_1 TEX opcode expects to overwrite it. + if (!shader_version_atleast(ctx, 1, 4)) + output_line(ctx, "float4 %s = input.%s;",varname,varname); + } // else if + break; + case REG_TYPE_PREDICATE: + output_line(ctx, "bool4 %s;", varname); + break; + case REG_TYPE_TEMP: + output_line(ctx, "float4 %s;", varname); + break; + case REG_TYPE_LOOP: + break; // no-op. We declare these in for loops at the moment. + case REG_TYPE_LABEL: + break; // no-op. If we see it here, it means we optimized it out. + default: + fail(ctx, "BUG: we used a register we don't know how to define."); + break; + } // switch + + pop_output(ctx); +} // emit_METAL_global + +void emit_METAL_array(Context *ctx, VariableList *var) +{ + // All uniforms (except constant arrays, which are literally constant + // data embedded in Metal shaders) are now packed into a single array, + // so we can batch the uniform transfers. So this doesn't actually + // define an array here; the one, big array is emitted during + // finalization instead. + // However, we need to #define the offset into the one, big array here, + // and let dereferences use that #define. + const int base = var->index; + const int metalbase = ctx->uniform_float4_count; + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + output_line(ctx, "const int ARRAYBASE_%d = %d;", base, metalbase); + pop_output(ctx); + var->emit_position = metalbase; +} // emit_METAL_array + +void emit_METAL_const_array(Context *ctx, const ConstantsList *clist, + int base, int size) +{ + char varname[64]; + get_METAL_const_array_varname_in_buf(ctx,base,size,varname,sizeof(varname)); + + const char *cstr = NULL; + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + output_line(ctx, "const float4 %s[%d] = {", varname, size); + ctx->indent++; + + int i; + for (i = 0; i < size; i++) + { + while (clist->constant.type != MOJOSHADER_UNIFORM_FLOAT) + clist = clist->next; + assert(clist->constant.index == (base + i)); + + char val0[32]; + char val1[32]; + char val2[32]; + char val3[32]; + floatstr(ctx, val0, sizeof (val0), clist->constant.value.f[0], 1); + floatstr(ctx, val1, sizeof (val1), clist->constant.value.f[1], 1); + floatstr(ctx, val2, sizeof (val2), clist->constant.value.f[2], 1); + floatstr(ctx, val3, sizeof (val3), clist->constant.value.f[3], 1); + + output_line(ctx, "float4(%s, %s, %s, %s)%s", val0, val1, val2, val3, + (i < (size-1)) ? "," : ""); + + clist = clist->next; + } // for + + ctx->indent--; + output_line(ctx, "};"); + output_line(ctx, "(void) %s[0];", varname); // stop compiler warnings. + pop_output(ctx); +} // emit_METAL_const_array + +void emit_METAL_uniform(Context *ctx, RegisterType regtype, int regnum, + const VariableList *var) +{ + // Now that we're pushing all the uniforms as one struct, pack these + // down, so if we only use register c439, it'll actually map to + // uniforms.uniforms_float4[0]. As we push one big struct, this will + // prevent uploading unused data. + + const char *utype = get_METAL_uniform_type(ctx, regtype); + char varname[64]; + char name[64]; + int index = 0; + + get_METAL_varname_in_buf(ctx, regtype, regnum, varname, sizeof (varname)); + + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + + if (var == NULL) + { + get_METAL_uniform_array_varname(ctx, regtype, name, sizeof (name)); + + if (regtype == REG_TYPE_CONST) + index = ctx->uniform_float4_count; + else if (regtype == REG_TYPE_CONSTINT) + index = ctx->uniform_int4_count; + else if (regtype == REG_TYPE_CONSTBOOL) + index = ctx->uniform_bool_count; + else // get_METAL_uniform_array_varname() would have called fail(). + assert(!(ctx->isfail)); + + // !!! FIXME: can cause unused var warnings in Clang... + //output_line(ctx, "constant %s &%s = %s[%d];", utype, varname, name, index); + output_line(ctx, "#define %s %s[%d]", varname, name, index); + push_output(ctx, &ctx->mainline); + ctx->indent++; + output_line(ctx, "#undef %s", varname); // !!! FIXME: gross. + pop_output(ctx); + } // if + + else + { + const int arraybase = var->index; + if (var->constant) + { + get_METAL_const_array_varname_in_buf(ctx, arraybase, var->count, + name, sizeof (name)); + index = (regnum - arraybase); + } // if + else + { + assert(var->emit_position != -1); + get_METAL_uniform_array_varname(ctx, regtype, name, sizeof (name)); + index = (regnum - arraybase) + var->emit_position; + } // else + + // !!! FIXME: might trigger unused var warnings in Clang. + //output_line(ctx, "constant %s &%s = %s[%d];", utype, varname, name, index); + output_line(ctx, "#define %s %s[%d];", varname, name, index); + push_output(ctx, &ctx->mainline); + ctx->indent++; + output_line(ctx, "#undef %s", varname); // !!! FIXME: gross. + pop_output(ctx); + } // else + + pop_output(ctx); +} // emit_METAL_uniform + +void emit_METAL_sampler(Context *ctx,int stage,TextureType ttype,int tb) +{ + char var[64]; + const char *texsuffix = NULL; + switch (ttype) + { + case TEXTURE_TYPE_2D: texsuffix = "2d"; break; + case TEXTURE_TYPE_CUBE: texsuffix = "cube"; break; + case TEXTURE_TYPE_VOLUME: texsuffix = "3d"; break; + default: assert(!"unexpected texture type"); return; + } // switch + + get_METAL_varname_in_buf(ctx, REG_TYPE_SAMPLER, stage, var, sizeof (var)); + + push_output(ctx, &ctx->mainline_arguments); + ctx->indent++; + output_line(ctx, "texture%s %s_texture [[texture(%d)]],", + texsuffix, var, stage); + output_line(ctx, "sampler %s [[sampler(%d)]],", var, stage); + pop_output(ctx); + + if (tb) // This sampler used a ps_1_1 TEXBEM opcode? + { + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + char name[64]; + const int index = ctx->uniform_float4_count; + ctx->uniform_float4_count += 2; + get_METAL_uniform_array_varname(ctx, REG_TYPE_CONST, name, sizeof (name)); + output_line(ctx, "constant float4 &%s_texbem = %s[%d];", var, name, index); + output_line(ctx, "constant float4 &%s_texbeml = %s[%d];", var, name, index+1); + pop_output(ctx); + } // if +} // emit_METAL_sampler + +void emit_METAL_attribute(Context *ctx, RegisterType regtype, int regnum, + MOJOSHADER_usage usage, int index, int wmask, + int flags) +{ + // !!! FIXME: this function doesn't deal with write masks at all yet! + const char *usage_str = NULL; + char index_str[16] = { '\0' }; + char var[64]; + + get_METAL_varname_in_buf(ctx, regtype, regnum, var, sizeof (var)); + + //assert((flags & MOD_PP) == 0); // !!! FIXME: is PP allowed? + + if (index != 0) // !!! FIXME: a lot of these MUST be zero. + snprintf(index_str, sizeof (index_str), "%u", (uint) index); + + if (shader_is_vertex(ctx)) + { + // pre-vs3 output registers. + // these don't ever happen in DCL opcodes, I think. Map to vs_3_* + // output registers. + if (!shader_version_atleast(ctx, 3, 0)) + { + if (regtype == REG_TYPE_RASTOUT) + { + regtype = REG_TYPE_OUTPUT; + index = regnum; + switch ((const RastOutType) regnum) + { + case RASTOUT_TYPE_POSITION: + usage = MOJOSHADER_USAGE_POSITION; + break; + case RASTOUT_TYPE_FOG: + usage = MOJOSHADER_USAGE_FOG; + break; + case RASTOUT_TYPE_POINT_SIZE: + usage = MOJOSHADER_USAGE_POINTSIZE; + break; + } // switch + } // if + + else if (regtype == REG_TYPE_ATTROUT) + { + regtype = REG_TYPE_OUTPUT; + usage = MOJOSHADER_USAGE_COLOR; + index = regnum; + } // else if + + else if (regtype == REG_TYPE_TEXCRDOUT) + { + regtype = REG_TYPE_OUTPUT; + usage = MOJOSHADER_USAGE_TEXCOORD; + index = regnum; + } // else if + } // if + + if (regtype == REG_TYPE_INPUT) + { + push_output(ctx, &ctx->inputs); + if (buffer_size(ctx->inputs) == 0) + { + output_line(ctx, "struct %s_Input", ctx->mainfn); + output_line(ctx, "{"); + } // if + + ctx->indent++; + output_line(ctx, "float4 %s [[attribute(%d)]];", var, regnum); + pop_output(ctx); + + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + // !!! FIXME: might trigger unused var warnings in Clang. + //output_line(ctx, "constant float4 &%s = input.%s;", var, var); + output_line(ctx, "#define %s input.%s", var, var); + pop_output(ctx); + push_output(ctx, &ctx->mainline); + ctx->indent++; + output_line(ctx, "#undef %s", var); // !!! FIXME: gross. + pop_output(ctx); + } // if + + else if (regtype == REG_TYPE_OUTPUT) + { + push_output(ctx, &ctx->outputs); + if (buffer_size(ctx->outputs) == 0) + { + output_line(ctx, "struct %s_Output", ctx->mainfn); + output_line(ctx, "{"); + } // if + + ctx->indent++; + + switch (usage) + { + case MOJOSHADER_USAGE_POSITION: + output_line(ctx, "float4 %s [[position]];", var); + break; + case MOJOSHADER_USAGE_POINTSIZE: + output_line(ctx, "float %s [[point_size]];", var); + break; + case MOJOSHADER_USAGE_COLOR: + output_line(ctx, "float4 %s [[user(color%d)]];", var, index); + break; + case MOJOSHADER_USAGE_FOG: + output_line(ctx, "float4 %s [[user(fog)]];", var); + break; + case MOJOSHADER_USAGE_TEXCOORD: + output_line(ctx, "float4 %s [[user(texcoord%d)]];", var, index); + break; + case MOJOSHADER_USAGE_NORMAL: + output_line(ctx, "float4 %s [[user(normal)]];", var); + default: + // !!! FIXME: we need to deal with some more built-in varyings here. + break; + } // switch + + pop_output(ctx); + + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + // !!! FIXME: this doesn't work. + //output_line(ctx, "float4 &%s = output.%s;", var, var); + output_line(ctx, "#define %s output.%s", var, var); + pop_output(ctx); + push_output(ctx, &ctx->mainline); + ctx->indent++; + output_line(ctx, "#undef %s", var); // !!! FIXME: gross. + pop_output(ctx); + } // else if + + else + { + fail(ctx, "unknown vertex shader attribute register"); + } // else + } // if + + else if (shader_is_pixel(ctx)) + { + // samplers DCLs get handled in emit_METAL_sampler(). + + if (flags & MOD_CENTROID) // !!! FIXME + { + failf(ctx, "centroid unsupported in %s profile", ctx->profile->name); + return; + } // if + + if ((regtype == REG_TYPE_COLOROUT) || (regtype == REG_TYPE_DEPTHOUT)) + { + push_output(ctx, &ctx->outputs); + if (buffer_size(ctx->outputs) == 0) + { + output_line(ctx, "struct %s_Output", ctx->mainfn); + output_line(ctx, "{"); + } // if + ctx->indent++; + + if (regtype == REG_TYPE_COLOROUT) + output_line(ctx, "float4 %s [[color(%d)]];", var, regnum); + else if (regtype == REG_TYPE_DEPTHOUT) + output_line(ctx, "float %s [[depth(any)]];", var); + + pop_output(ctx); + + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + // !!! FIXME: this doesn't work. + //output_line(ctx, "float%s &%s = output.%s;", (regtype == REG_TYPE_DEPTHOUT) ? "" : "4", var, var); + output_line(ctx, "#define %s output.%s", var, var); + pop_output(ctx); + push_output(ctx, &ctx->mainline); + ctx->indent++; + output_line(ctx, "#undef %s", var); // !!! FIXME: gross. + pop_output(ctx); + } // if + + // !!! FIXME: can you actualy have a texture register with COLOR usage? + else if ((regtype == REG_TYPE_TEXTURE) || + (regtype == REG_TYPE_INPUT) || + (regtype == REG_TYPE_MISCTYPE)) + { + int skipreference = 0; + push_output(ctx, &ctx->inputs); + if (buffer_size(ctx->inputs) == 0) + { + output_line(ctx, "struct %s_Input", ctx->mainfn); + output_line(ctx, "{"); + } // if + ctx->indent++; + + if (regtype == REG_TYPE_MISCTYPE) + { + const MiscTypeType mt = (MiscTypeType) regnum; + if (mt == MISCTYPE_TYPE_FACE) + output_line(ctx, "bool %s [[front_facing]];", var); + else if (mt == MISCTYPE_TYPE_POSITION) + output_line(ctx, "float4 %s [[position]];", var); + else + fail(ctx, "BUG: unhandled misc register"); + } // else if + + else + { + if (usage == MOJOSHADER_USAGE_TEXCOORD) + { + // ps_1_1 does a different hack for this attribute. + // Refer to emit_METAL_global()'s REG_TYPE_ADDRESS code. + if (!shader_version_atleast(ctx, 1, 4)) + skipreference = 1; + output_line(ctx, "float4 %s [[user(texcoord%d)]];", var, index); + } // if + + else if (usage == MOJOSHADER_USAGE_COLOR) + output_line(ctx, "float4 %s [[user(color%d)]];", var, index); + + else if (usage == MOJOSHADER_USAGE_FOG) + output_line(ctx, "float4 %s [[user(fog)]];", var); + + else if (usage == MOJOSHADER_USAGE_NORMAL) + output_line(ctx, "float4 %s [[user(normal)]];", var); + } // else + + pop_output(ctx); + + // !!! FIXME: can cause unused var warnings in Clang... + #if 0 + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + if ((regtype == REG_TYPE_MISCTYPE)&&(regnum == MISCTYPE_TYPE_FACE)) + output_line(ctx, "constant bool &%s = input.%s;", var, var); + else if (!skipreference) + output_line(ctx, "constant float4 &%s = input.%s;", var, var); + pop_output(ctx); + #endif + + if (!skipreference) + { + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + output_line(ctx, "#define %s input.%s", var, var); + pop_output(ctx); + push_output(ctx, &ctx->mainline); + ctx->indent++; + output_line(ctx, "#undef %s", var); // !!! FIXME: gross. + pop_output(ctx); + } // if + } // else if + + else + { + fail(ctx, "unknown pixel shader attribute register"); + } // else + } // else if + + else + { + fail(ctx, "Unknown shader type"); // state machine should catch this. + } // else +} // emit_METAL_attribute + +void emit_METAL_NOP(Context *ctx) +{ + // no-op is a no-op. :) +} // emit_METAL_NOP + +void emit_METAL_MOV(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + make_METAL_destarg_assign(ctx, code, sizeof (code), "%s", src0); + output_line(ctx, "%s", code); +} // emit_METAL_MOV + +void emit_METAL_ADD(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_METAL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + make_METAL_destarg_assign(ctx, code, sizeof (code), "%s + %s", src0, src1); + output_line(ctx, "%s", code); +} // emit_METAL_ADD + +void emit_METAL_SUB(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_METAL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + make_METAL_destarg_assign(ctx, code, sizeof (code), "%s - %s", src0, src1); + output_line(ctx, "%s", code); +} // emit_METAL_SUB + +void emit_METAL_MAD(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_METAL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char src2[64]; make_METAL_srcarg_string_masked(ctx, 2, src2, sizeof (src2)); + char code[128]; + make_METAL_destarg_assign(ctx, code, sizeof (code), "(%s * %s) + %s", src0, src1, src2); + output_line(ctx, "%s", code); +} // emit_METAL_MAD + +void emit_METAL_MUL(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_METAL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + make_METAL_destarg_assign(ctx, code, sizeof (code), "%s * %s", src0, src1); + output_line(ctx, "%s", code); +} // emit_METAL_MUL + +void emit_METAL_RCP(Context *ctx) +{ + const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); + char cast[16] = { '\0' }; + if (vecsize != 1) + snprintf(cast, sizeof (cast), "float%d", vecsize); + char src0[64]; make_METAL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + char code[128]; + ctx->metal_need_header_math = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), "%s((%s == 0.0) ? FLT_MAX : 1.0 / %s)", cast, src0, src0); + output_line(ctx, "%s", code); +} // emit_METAL_RCP + +void emit_METAL_RSQ(Context *ctx) +{ + const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); + char cast[16] = { '\0' }; + if (vecsize != 1) + snprintf(cast, sizeof (cast), "float%d", vecsize); + char src0[64]; make_METAL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + char code[128]; + ctx->metal_need_header_math = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), "%s((%s == 0.0) ? FLT_MAX : rsqrt(abs(%s)))", cast, src0, src0); + output_line(ctx, "%s", code); +} // emit_METAL_RSQ + +void emit_METAL_dotprod(Context *ctx, const char *src0, const char *src1, + const char *extra) +{ + const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); + char castleft[16] = { '\0' }; + const char *castright = ""; + if (vecsize != 1) + { + snprintf(castleft, sizeof (castleft), "float%d(", vecsize); + castright = ")"; + } // if + + char code[128]; + ctx->metal_need_header_geometric = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), "%sdot(%s, %s)%s%s", + castleft, src0, src1, extra, castright); + output_line(ctx, "%s", code); +} // emit_METAL_dotprod + +void emit_METAL_DP3(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_METAL_srcarg_string_vec3(ctx, 1, src1, sizeof (src1)); + emit_METAL_dotprod(ctx, src0, src1, ""); +} // emit_METAL_DP3 + +void emit_METAL_DP4(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_METAL_srcarg_string_full(ctx, 1, src1, sizeof (src1)); + emit_METAL_dotprod(ctx, src0, src1, ""); +} // emit_METAL_DP4 + +void emit_METAL_MIN(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_METAL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + ctx->metal_need_header_math = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), "min(%s, %s)", src0, src1); + output_line(ctx, "%s", code); +} // emit_METAL_MIN + +void emit_METAL_MAX(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_METAL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + ctx->metal_need_header_math = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), "max(%s, %s)", src0, src1); + output_line(ctx, "%s", code); +} // emit_METAL_MAX + +void emit_METAL_SLT(Context *ctx) +{ + const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_METAL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + + // float(bool) or vec(bvec) results in 0.0 or 1.0, like SLT wants. + if (vecsize == 1) + make_METAL_destarg_assign(ctx, code, sizeof (code), "float(%s < %s)", src0, src1); + else + { + make_METAL_destarg_assign(ctx, code, sizeof (code), + "float%d(%s < %s)", vecsize, src0, src1); + } // else + output_line(ctx, "%s", code); +} // emit_METAL_SLT + +void emit_METAL_SGE(Context *ctx) +{ + const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_METAL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + + // float(bool) or vec(bvec) results in 0.0 or 1.0, like SGE wants. + if (vecsize == 1) + { + make_METAL_destarg_assign(ctx, code, sizeof (code), + "float(%s >= %s)", src0, src1); + } // if + else + { + make_METAL_destarg_assign(ctx, code, sizeof (code), + "float%d(%s >= %s)", vecsize, src0, src1); + } // else + output_line(ctx, "%s", code); +} // emit_METAL_SGE + +void emit_METAL_EXP(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + ctx->metal_need_header_math = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), "exp2(%s)", src0); + output_line(ctx, "%s", code); +} // emit_METAL_EXP + +void emit_METAL_LOG(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + ctx->metal_need_header_math = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), "log2(%s)", src0); + output_line(ctx, "%s", code); +} // emit_METAL_LOG + +void emit_METAL_LIT_helper(Context *ctx) +{ + const char *maxp = "127.9961"; // value from the dx9 reference. + + if (ctx->glsl_generated_lit_helper) + return; + + ctx->glsl_generated_lit_helper = 1; + ctx->metal_need_header_common = 1; + ctx->metal_need_header_math = 1; + + push_output(ctx, &ctx->helpers); + output_line(ctx, "float4 LIT(const float4 src)"); + output_line(ctx, "{"); ctx->indent++; + output_line(ctx, "const float power = clamp(src.w, -%s, %s);",maxp,maxp); + output_line(ctx, "float4 retval = float4(1.0, 0.0, 0.0, 1.0);"); + output_line(ctx, "if (src.x > 0.0) {"); ctx->indent++; + output_line(ctx, "retval.y = src.x;"); + output_line(ctx, "if (src.y > 0.0) {"); ctx->indent++; + output_line(ctx, "retval.z = pow(src.y, power);"); ctx->indent--; + output_line(ctx, "}"); ctx->indent--; + output_line(ctx, "}"); + output_line(ctx, "return retval;"); ctx->indent--; + output_line(ctx, "}"); + output_blank_line(ctx); + pop_output(ctx); +} // emit_METAL_LIT_helper + +void emit_METAL_LIT(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); + char code[128]; + emit_METAL_LIT_helper(ctx); + make_METAL_destarg_assign(ctx, code, sizeof (code), "LIT(%s)", src0); + output_line(ctx, "%s", code); +} // emit_METAL_LIT + +void emit_METAL_DST(Context *ctx) +{ + // !!! FIXME: needs to take ctx->dst_arg.writemask into account. + char src0_y[64]; make_METAL_srcarg_string_y(ctx, 0, src0_y, sizeof (src0_y)); + char src1_y[64]; make_METAL_srcarg_string_y(ctx, 1, src1_y, sizeof (src1_y)); + char src0_z[64]; make_METAL_srcarg_string_z(ctx, 0, src0_z, sizeof (src0_z)); + char src1_w[64]; make_METAL_srcarg_string_w(ctx, 1, src1_w, sizeof (src1_w)); + + char code[128]; + make_METAL_destarg_assign(ctx, code, sizeof (code), + "float4(1.0, %s * %s, %s, %s)", + src0_y, src1_y, src0_z, src1_w); + output_line(ctx, "%s", code); +} // emit_METAL_DST + +void emit_METAL_LRP(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_METAL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char src2[64]; make_METAL_srcarg_string_masked(ctx, 2, src2, sizeof (src2)); + char code[128]; + ctx->metal_need_header_common = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), "mix(%s, %s, %s)", + src2, src1, src0); + output_line(ctx, "%s", code); +} // emit_METAL_LRP + +void emit_METAL_FRC(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + ctx->metal_need_header_math = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), "fract(%s)", src0); + output_line(ctx, "%s", code); +} // emit_METAL_FRC + +void emit_METAL_M4X4(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); + char row0[64]; make_METAL_srcarg_string_full(ctx, 1, row0, sizeof (row0)); + char row1[64]; make_METAL_srcarg_string_full(ctx, 2, row1, sizeof (row1)); + char row2[64]; make_METAL_srcarg_string_full(ctx, 3, row2, sizeof (row2)); + char row3[64]; make_METAL_srcarg_string_full(ctx, 4, row3, sizeof (row3)); + char code[256]; + ctx->metal_need_header_geometric = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), + "float4(dot(%s, %s), dot(%s, %s), dot(%s, %s), dot(%s, %s))", + src0, row0, src0, row1, src0, row2, src0, row3); + output_line(ctx, "%s", code); +} // emit_METAL_M4X4 + +void emit_METAL_M4X3(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_full(ctx, 0, src0, sizeof (src0)); + char row0[64]; make_METAL_srcarg_string_full(ctx, 1, row0, sizeof (row0)); + char row1[64]; make_METAL_srcarg_string_full(ctx, 2, row1, sizeof (row1)); + char row2[64]; make_METAL_srcarg_string_full(ctx, 3, row2, sizeof (row2)); + char code[256]; + ctx->metal_need_header_geometric = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), + "float3(dot(%s, %s), dot(%s, %s), dot(%s, %s))", + src0, row0, src0, row1, src0, row2); + output_line(ctx, "%s", code); +} // emit_METAL_M4X3 + +void emit_METAL_M3X4(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + char row0[64]; make_METAL_srcarg_string_vec3(ctx, 1, row0, sizeof (row0)); + char row1[64]; make_METAL_srcarg_string_vec3(ctx, 2, row1, sizeof (row1)); + char row2[64]; make_METAL_srcarg_string_vec3(ctx, 3, row2, sizeof (row2)); + char row3[64]; make_METAL_srcarg_string_vec3(ctx, 4, row3, sizeof (row3)); + char code[256]; + ctx->metal_need_header_geometric = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), + "float4(dot(%s, %s), dot(%s, %s), " + "dot(%s, %s), dot(%s, %s))", + src0, row0, src0, row1, + src0, row2, src0, row3); + output_line(ctx, "%s", code); +} // emit_METAL_M3X4 + +void emit_METAL_M3X3(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + char row0[64]; make_METAL_srcarg_string_vec3(ctx, 1, row0, sizeof (row0)); + char row1[64]; make_METAL_srcarg_string_vec3(ctx, 2, row1, sizeof (row1)); + char row2[64]; make_METAL_srcarg_string_vec3(ctx, 3, row2, sizeof (row2)); + char code[256]; + ctx->metal_need_header_geometric = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), + "float3(dot(%s, %s), dot(%s, %s), dot(%s, %s))", + src0, row0, src0, row1, src0, row2); + output_line(ctx, "%s", code); +} // emit_METAL_M3X3 + +void emit_METAL_M3X2(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + char row0[64]; make_METAL_srcarg_string_vec3(ctx, 1, row0, sizeof (row0)); + char row1[64]; make_METAL_srcarg_string_vec3(ctx, 2, row1, sizeof (row1)); + char code[256]; + ctx->metal_need_header_geometric = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), + "float2(dot(%s, %s), dot(%s, %s))", + src0, row0, src0, row1); + output_line(ctx, "%s", code); +} // emit_METAL_M3X2 + +void emit_METAL_CALL(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + if (ctx->loops > 0) + output_line(ctx, "%s(aL);", src0); + else + output_line(ctx, "%s();", src0); +} // emit_METAL_CALL + +void emit_METAL_CALLNZ(Context *ctx) +{ + // !!! FIXME: if src1 is a constbool that's true, we can remove the + // !!! FIXME: if. If it's false, we can make this a no-op. + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_METAL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + + if (ctx->loops > 0) + output_line(ctx, "if (%s) { %s(aL); }", src1, src0); + else + output_line(ctx, "if (%s) { %s(); }", src1, src0); +} // emit_METAL_CALLNZ + +void emit_METAL_LOOP(Context *ctx) +{ + // !!! FIXME: swizzle? + char var[64]; get_METAL_srcarg_varname(ctx, 1, var, sizeof (var)); + assert(ctx->source_args[0].regnum == 0); // in case they add aL1 someday. + output_line(ctx, "{"); + ctx->indent++; + output_line(ctx, "const int aLend = %s.x + %s.y;", var, var); + output_line(ctx, "for (int aL = %s.y; aL < aLend; aL += %s.z) {", var, var); + ctx->indent++; +} // emit_METAL_LOOP + +void emit_METAL_RET(Context *ctx) +{ + // thankfully, the MSDN specs say a RET _has_ to end a function...no + // early returns. So if you hit one, you know you can safely close + // a high-level function. + push_output(ctx, &ctx->postflight); + output_line(ctx, "}"); + output_blank_line(ctx); + set_output(ctx, &ctx->subroutines); // !!! FIXME: is this for LABEL? Maybe set it there so we don't allocate unnecessarily. +} // emit_METAL_RET + +void emit_METAL_ENDLOOP(Context *ctx) +{ + ctx->indent--; + output_line(ctx, "}"); + ctx->indent--; + output_line(ctx, "}"); +} // emit_METAL_ENDLOOP + +void emit_METAL_LABEL(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + const int label = ctx->source_args[0].regnum; + RegisterList *reg = reglist_find(&ctx->used_registers, REG_TYPE_LABEL, label); + assert(ctx->output == ctx->subroutines); // not mainline, etc. + assert(ctx->indent == 0); // we shouldn't be in the middle of a function. + + // MSDN specs say CALL* has to come before the LABEL, so we know if we + // can ditch the entire function here as unused. + if (reg == NULL) + set_output(ctx, &ctx->ignore); // Func not used. Parse, but don't output. + + // !!! FIXME: it would be nice if we could determine if a function is + // !!! FIXME: only called once and, if so, forcibly inline it. + + // !!! FIXME: this worked in GLSL because all our state is global to the shader, + // !!! FIXME: but in metal we kept it local to the shader mainline. + // !!! FIXME: Can we do C++11 lambdas in Metal to have nested functions? :) + + const char *uses_loopreg = ((reg) && (reg->misc == 1)) ? "int aL" : ""; + output_line(ctx, "void %s(%s)", src0, uses_loopreg); + output_line(ctx, "{"); + ctx->indent++; +} // emit_METAL_LABEL + +void emit_METAL_DCL(Context *ctx) +{ + // no-op. We do this in our emit_attribute() and emit_uniform(). +} // emit_METAL_DCL + +void emit_METAL_POW(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_METAL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + ctx->metal_need_header_math = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), + "pow(abs(%s), %s)", src0, src1); + output_line(ctx, "%s", code); +} // emit_METAL_POW + +void emit_METAL_CRS(Context *ctx) +{ + // !!! FIXME: needs to take ctx->dst_arg.writemask into account. + char src0[64]; make_METAL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_METAL_srcarg_string_vec3(ctx, 1, src1, sizeof (src1)); + char code[128]; + ctx->metal_need_header_geometric = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), + "cross(%s, %s)", src0, src1); + output_line(ctx, "%s", code); +} // emit_METAL_CRS + +void emit_METAL_SGN(Context *ctx) +{ + // (we don't need the temporary registers specified for the D3D opcode.) + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + ctx->metal_need_header_common = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), "sign(%s)", src0); + output_line(ctx, "%s", code); +} // emit_METAL_SGN + +void emit_METAL_ABS(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + ctx->metal_need_header_math = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), "abs(%s)", src0); + output_line(ctx, "%s", code); +} // emit_METAL_ABS + +void emit_METAL_NRM(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + ctx->metal_need_header_geometric = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), "normalize(%s)", src0); + output_line(ctx, "%s", code); +} // emit_METAL_NRM + +void emit_METAL_SINCOS(Context *ctx) +{ + // we don't care about the temp registers that <= sm2 demands; ignore them. + // sm2 also talks about what components are left untouched vs. undefined, + // but we just leave those all untouched with Metal write masks (which + // would fulfill the "undefined" requirement, too). + const int mask = ctx->dest_arg.writemask; + char src0[64]; make_METAL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + char code[128] = { '\0' }; + + ctx->metal_need_header_math = 1; + if (writemask_x(mask)) + make_METAL_destarg_assign(ctx, code, sizeof (code), "cos(%s)", src0); + else if (writemask_y(mask)) + make_METAL_destarg_assign(ctx, code, sizeof (code), "sin(%s)", src0); + else if (writemask_xy(mask)) + { + // !!! FIXME: can use sincos(), but need to assign cos to a temp, since it needs a reference. + make_METAL_destarg_assign(ctx, code, sizeof (code), + "float2(cos(%s), sin(%s))", src0, src0); + } // else if + + output_line(ctx, "%s", code); +} // emit_METAL_SINCOS + +void emit_METAL_REP(Context *ctx) +{ + // !!! FIXME: + // msdn docs say legal loop values are 0 to 255. We can check DEFI values + // at parse time, but if they are pulling a value from a uniform, do + // we clamp here? + // !!! FIXME: swizzle is legal here, right? + char src0[64]; make_METAL_srcarg_string_x(ctx, 0, src0, sizeof (src0)); + const uint rep = (uint) ctx->reps; + output_line(ctx, "for (int rep%u = 0; rep%u < %s; rep%u++) {", + rep, rep, src0, rep); + ctx->indent++; +} // emit_METAL_REP + +void emit_METAL_ENDREP(Context *ctx) +{ + ctx->indent--; + output_line(ctx, "}"); +} // emit_METAL_ENDREP + +void emit_METAL_IF(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + output_line(ctx, "if (%s) {", src0); + ctx->indent++; +} // emit_METAL_IF + +void emit_METAL_IFC(Context *ctx) +{ + const char *comp = get_METAL_comparison_string_scalar(ctx); + char src0[64]; make_METAL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_METAL_srcarg_string_scalar(ctx, 1, src1, sizeof (src1)); + output_line(ctx, "if (%s %s %s) {", src0, comp, src1); + ctx->indent++; +} // emit_METAL_IFC + +void emit_METAL_ELSE(Context *ctx) +{ + ctx->indent--; + output_line(ctx, "} else {"); + ctx->indent++; +} // emit_METAL_ELSE + +void emit_METAL_ENDIF(Context *ctx) +{ + ctx->indent--; + output_line(ctx, "}"); +} // emit_METAL_ENDIF + +void emit_METAL_BREAK(Context *ctx) +{ + output_line(ctx, "break;"); +} // emit_METAL_BREAK + +void emit_METAL_BREAKC(Context *ctx) +{ + const char *comp = get_METAL_comparison_string_scalar(ctx); + char src0[64]; make_METAL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_METAL_srcarg_string_scalar(ctx, 1, src1, sizeof (src1)); + output_line(ctx, "if (%s %s %s) { break; }", src0, comp, src1); +} // emit_METAL_BREAKC + +void emit_METAL_MOVA(Context *ctx) +{ + const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + + ctx->metal_need_header_math = 1; + ctx->metal_need_header_common = 1; + + if (vecsize == 1) + { + make_METAL_destarg_assign(ctx, code, sizeof (code), + "int(floor(abs(%s) + 0.5) * sign(%s))", + src0, src0); + } // if + + else + { + make_METAL_destarg_assign(ctx, code, sizeof (code), + "int%d(floor(abs(%s) + float%d(0.5)) * sign(%s))", + vecsize, src0, vecsize, src0); + } // else + + output_line(ctx, "%s", code); +} // emit_METAL_MOVA + +void emit_METAL_DEFB(Context *ctx) +{ + char varname[64]; get_METAL_destarg_varname(ctx, varname, sizeof (varname)); + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + output_line(ctx, "const bool %s = %s;", + varname, ctx->dwords[0] ? "true" : "false"); + pop_output(ctx); +} // emit_METAL_DEFB + +void emit_METAL_DEFI(Context *ctx) +{ + char varname[64]; get_METAL_destarg_varname(ctx, varname, sizeof (varname)); + const int32 *x = (const int32 *) ctx->dwords; + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + output_line(ctx, "const int4 %s = int4(%d, %d, %d, %d);", + varname, (int) x[0], (int) x[1], (int) x[2], (int) x[3]); + pop_output(ctx); +} // emit_METAL_DEFI + +EMIT_METAL_OPCODE_UNIMPLEMENTED_FUNC(TEXCRD) + +void emit_METAL_TEXKILL(Context *ctx) +{ + char dst[64]; get_METAL_destarg_varname(ctx, dst, sizeof (dst)); + ctx->metal_need_header_relational = 1; + ctx->metal_need_header_graphics = 1; + output_line(ctx, "if (any(%s.xyz < float3(0.0))) discard_fragment();", dst); +} // emit_METAL_TEXKILL + +static void metal_texld(Context *ctx, const int texldd) +{ + ctx->metal_need_header_texture = 1; + if (!shader_version_atleast(ctx, 1, 4)) + { + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; + char sampler[64]; + char code[128] = {0}; + + assert(!texldd); + + RegisterList *sreg; + sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, info->regnum); + const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); + + char swizzle[4] = { 'x', 'y', 'z', '\0' }; + if (ttype == TEXTURE_TYPE_2D) + swizzle[2] = '\0'; // "xy" instead of "xyz". + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_METAL_destarg_varname(ctx, dst, sizeof (dst)); + get_METAL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + + make_METAL_destarg_assign(ctx, code, sizeof (code), + "%s_texture.sample(%s, %s.%s)", + sampler, sampler, dst, swizzle); + output_line(ctx, "%s", code); + } // if + + else if (!shader_version_atleast(ctx, 2, 0)) + { + // ps_1_4 is different, too! + fail(ctx, "TEXLD == Shader Model 1.4 unimplemented."); // !!! FIXME + return; + } // else if + + else + { + const SourceArgInfo *samp_arg = &ctx->source_args[1]; + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, + samp_arg->regnum); + const char *funcname = NULL; + char src0[64] = { '\0' }; + char src1[64]; get_METAL_srcarg_varname(ctx, 1, src1, sizeof (src1)); // !!! FIXME: SRC_MOD? + char src2[64] = { '\0' }; + char src3[64] = { '\0' }; + + if (sreg == NULL) + { + fail(ctx, "TEXLD using undeclared sampler"); + return; + } // if + + const char *grad = ""; + if (texldd) + { + switch ((const TextureType) sreg->index) + { + case TEXTURE_TYPE_2D: + grad = "2d"; + make_METAL_srcarg_string_vec2(ctx, 2, src2, sizeof (src2)); + make_METAL_srcarg_string_vec2(ctx, 3, src3, sizeof (src3)); + break; + case TEXTURE_TYPE_VOLUME: + grad = "3d"; + make_METAL_srcarg_string_vec3(ctx, 2, src2, sizeof (src2)); + make_METAL_srcarg_string_vec3(ctx, 3, src3, sizeof (src3)); + break; + case TEXTURE_TYPE_CUBE: + grad = "cube"; + make_METAL_srcarg_string_vec3(ctx, 2, src2, sizeof (src2)); + make_METAL_srcarg_string_vec3(ctx, 3, src3, sizeof (src3)); + break; + } // switch + } // if + + // !!! FIXME: can TEXLDD set instruction_controls? + // !!! FIXME: does the d3d bias value map directly to Metal? + const char *biasleft = ""; + const char *biasright = ""; + char bias[64] = { '\0' }; + if (ctx->instruction_controls == CONTROL_TEXLDB) + { + biasleft = ", bias("; + make_METAL_srcarg_string_w(ctx, 0, bias, sizeof (bias)); + biasright = ")"; + } // if + + // Metal doesn't have a texture2DProj() function, but you just divide + // your texcoords by texcoords.w to achieve it anyhow, so DIY. + const char *projop = ""; + char proj[64] = { '\0' }; + if (ctx->instruction_controls == CONTROL_TEXLDP) + { + if (sreg->index == TEXTURE_TYPE_CUBE) + fail(ctx, "TEXLDP on a cubemap"); // !!! FIXME: is this legal? + projop = " / "; + make_METAL_srcarg_string_w(ctx, 0, proj, sizeof (proj)); + } // if + + switch ((const TextureType) sreg->index) + { + case TEXTURE_TYPE_2D: + make_METAL_srcarg_string_vec2(ctx, 0, src0, sizeof (src0)); + break; + + case TEXTURE_TYPE_CUBE: + case TEXTURE_TYPE_VOLUME: + make_METAL_srcarg_string_vec3(ctx, 0, src0, sizeof (src0)); + break; + + default: + fail(ctx, "unknown texture type"); + return; + } // switch + + assert(!isscalar(ctx, ctx->shader_type, samp_arg->regtype, samp_arg->regnum)); + char swiz_str[6] = { '\0' }; + make_METAL_swizzle_string(swiz_str, sizeof (swiz_str), + samp_arg->swizzle, ctx->dest_arg.writemask); + + char code[128]; + if (texldd) + { + make_METAL_destarg_assign(ctx, code, sizeof (code), + "%s_texture.sample(%s, %s, gradient%s(%s, %s))%s", + src1, src1, src0, grad, src2, src3, swiz_str); + } // if + else + { + make_METAL_destarg_assign(ctx, code, sizeof (code), + "%s_texture.sample(%s, %s%s%s%s%s%s)%s", + src1, src1, src0, projop, proj, + biasleft, bias, biasright, swiz_str); + } // else + + output_line(ctx, "%s", code); + } // else +} // metal_texld + +void emit_METAL_TEXLD(Context *ctx) +{ + metal_texld(ctx, 0); +} // emit_METAL_TEXLD + + +void emit_METAL_TEXBEM(Context *ctx) +{ + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; get_METAL_destarg_varname(ctx, dst, sizeof (dst)); + char src[64]; get_METAL_srcarg_varname(ctx, 0, src, sizeof (src)); + char sampler[64]; + char code[512]; + + ctx->metal_need_header_texture = 1; + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_METAL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + + make_METAL_destarg_assign(ctx, code, sizeof (code), + "%s_texture.sample(%s, float2(%s.x + (%s_texbem.x * %s.x) + (%s_texbem.z * %s.y)," + " %s.y + (%s_texbem.y * %s.x) + (%s_texbem.w * %s.y)))", + sampler, sampler, + dst, sampler, src, sampler, src, + dst, sampler, src, sampler, src); + + output_line(ctx, "%s", code); +} // emit_METAL_TEXBEM + + +void emit_METAL_TEXBEML(Context *ctx) +{ + // !!! FIXME: this code counts on the register not having swizzles, etc. + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; get_METAL_destarg_varname(ctx, dst, sizeof (dst)); + char src[64]; get_METAL_srcarg_varname(ctx, 0, src, sizeof (src)); + char sampler[64]; + char code[512]; + + ctx->metal_need_header_texture = 1; + + get_METAL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + + make_METAL_destarg_assign(ctx, code, sizeof (code), + "(%s_texture.sample(%s, float2(%s.x + (%s_texbem.x * %s.x) + (%s_texbem.z * %s.y)," + " %s.y + (%s_texbem.y * %s.x) + (%s_texbem.w * %s.y)))) *" + " ((%s.z * %s_texbeml.x) + %s_texbem.y)", + sampler, sampler, + dst, sampler, src, sampler, src, + dst, sampler, src, sampler, src, + src, sampler, sampler); + + output_line(ctx, "%s", code); +} // emit_METAL_TEXBEML + +EMIT_METAL_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2AR) // !!! FIXME +EMIT_METAL_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2GB) // !!! FIXME + + +void emit_METAL_TEXM3X2PAD(Context *ctx) +{ + // no-op ... work happens in emit_METAL_TEXM3X2TEX(). +} // emit_METAL_TEXM3X2PAD + +void emit_METAL_TEXM3X2TEX(Context *ctx) +{ + if (ctx->texm3x2pad_src0 == -1) + return; + + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char sampler[64]; + char code[512]; + + ctx->metal_need_header_texture = 1; + ctx->metal_need_header_geometric = 1; + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_METAL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x2pad_src0, + src0, sizeof (src0)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x2pad_dst0, + src1, sizeof (src1)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src2, sizeof (src2)); + get_METAL_destarg_varname(ctx, dst, sizeof (dst)); + + make_METAL_destarg_assign(ctx, code, sizeof (code), + "%s_texture.sample(%s, float2(dot(%s.xyz, %s.xyz), dot(%s.xyz, %s.xyz)))", + sampler, sampler, src0, src1, src2, dst); + + output_line(ctx, "%s", code); +} // emit_METAL_TEXM3X2TEX + +void emit_METAL_TEXM3X3PAD(Context *ctx) +{ + // no-op ... work happens in emit_METAL_TEXM3X3*(). +} // emit_METAL_TEXM3X3PAD + +void emit_METAL_TEXM3X3TEX(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char src3[64]; + char src4[64]; + char sampler[64]; + char code[512]; + + ctx->metal_need_header_texture = 1; + ctx->metal_need_header_geometric = 1; + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_METAL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, + src0, sizeof (src0)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, + src1, sizeof (src1)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, + src2, sizeof (src2)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, + src3, sizeof (src3)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src4, sizeof (src4)); + get_METAL_destarg_varname(ctx, dst, sizeof (dst)); + + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, + info->regnum); + const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); + const char *ttypestr = (ttype == TEXTURE_TYPE_CUBE) ? "Cube" : "3D"; + + make_METAL_destarg_assign(ctx, code, sizeof (code), + "texture%s(%s," + " float3(dot(%s.xyz, %s.xyz)," + " dot(%s.xyz, %s.xyz)," + " dot(%s.xyz, %s.xyz)))", + ttypestr, sampler, src0, src1, src2, src3, dst, src4); + + output_line(ctx, "%s", code); +} // emit_METAL_TEXM3X3TEX + +void emit_METAL_TEXM3X3SPEC_helper(Context *ctx) +{ + if (ctx->glsl_generated_texm3x3spec_helper) + return; + + ctx->glsl_generated_texm3x3spec_helper = 1; + + push_output(ctx, &ctx->helpers); + output_line(ctx, "float3 TEXM3X3SPEC_reflection(const float3 normal, const float3 eyeray)"); + output_line(ctx, "{"); ctx->indent++; + output_line(ctx, "return (2.0 * ((normal * eyeray) / (normal * normal)) * normal) - eyeray;"); ctx->indent--; + output_line(ctx, "}"); + output_blank_line(ctx); + pop_output(ctx); +} // emit_METAL_TEXM3X3SPEC_helper + +void emit_METAL_TEXM3X3SPEC(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char src3[64]; + char src4[64]; + char src5[64]; + char sampler[64]; + char code[512]; + + ctx->metal_need_header_texture = 1; + ctx->metal_need_header_geometric = 1; + + emit_METAL_TEXM3X3SPEC_helper(ctx); + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_METAL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, + src0, sizeof (src0)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, + src1, sizeof (src1)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, + src2, sizeof (src2)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, + src3, sizeof (src3)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src4, sizeof (src4)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[1].regnum, + src5, sizeof (src5)); + get_METAL_destarg_varname(ctx, dst, sizeof (dst)); + + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, + info->regnum); + const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); + const char *ttypestr = (ttype == TEXTURE_TYPE_CUBE) ? "Cube" : "3D"; + + make_METAL_destarg_assign(ctx, code, sizeof (code), + "texture%s(%s, " + "TEXM3X3SPEC_reflection(" + "float3(" + "dot(%s.xyz, %s.xyz), " + "dot(%s.xyz, %s.xyz), " + "dot(%s.xyz, %s.xyz)" + ")," + "%s.xyz," + ")" + ")", + ttypestr, sampler, src0, src1, src2, src3, dst, src4, src5); + + output_line(ctx, "%s", code); +} // emit_METAL_TEXM3X3SPEC + +void emit_METAL_TEXM3X3VSPEC(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + DestArgInfo *info = &ctx->dest_arg; + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char src3[64]; + char src4[64]; + char sampler[64]; + char code[512]; + + ctx->metal_need_header_texture = 1; + ctx->metal_need_header_geometric = 1; + + emit_METAL_TEXM3X3SPEC_helper(ctx); + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_METAL_varname_in_buf(ctx, REG_TYPE_SAMPLER, info->regnum, + sampler, sizeof (sampler)); + + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, + src0, sizeof (src0)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, + src1, sizeof (src1)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, + src2, sizeof (src2)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, + src3, sizeof (src3)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src4, sizeof (src4)); + get_METAL_destarg_varname(ctx, dst, sizeof (dst)); + + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, + info->regnum); + const TextureType ttype = (TextureType) (sreg ? sreg->index : 0); + const char *ttypestr = (ttype == TEXTURE_TYPE_CUBE) ? "Cube" : "3D"; + + make_METAL_destarg_assign(ctx, code, sizeof (code), + "texture%s(%s, " + "TEXM3X3SPEC_reflection(" + "float3(" + "dot(%s.xyz, %s.xyz), " + "dot(%s.xyz, %s.xyz), " + "dot(%s.xyz, %s.xyz)" + "), " + "float3(%s.w, %s.w, %s.w)" + ")" + ")", + ttypestr, sampler, src0, src1, src2, src3, dst, src4, src0, src2, dst); + + output_line(ctx, "%s", code); +} // emit_METAL_TEXM3X3VSPEC + +void emit_METAL_EXPP(Context *ctx) +{ + // !!! FIXME: msdn's asm docs don't list this opcode, I'll have to check the driver documentation. + emit_METAL_EXP(ctx); // I guess this is just partial precision EXP? +} // emit_METAL_EXPP + +void emit_METAL_LOGP(Context *ctx) +{ + // LOGP is just low-precision LOG, but we'll take the higher precision. + emit_METAL_LOG(ctx); +} // emit_METAL_LOGP + +// common code between CMP and CND. +void emit_METAL_comparison_operations(Context *ctx, const char *cmp) +{ + int i, j; + DestArgInfo *dst = &ctx->dest_arg; + const SourceArgInfo *srcarg0 = &ctx->source_args[0]; + const int origmask = dst->writemask; + int used_swiz[4] = { 0, 0, 0, 0 }; + const int writemask[4] = { dst->writemask0, dst->writemask1, + dst->writemask2, dst->writemask3 }; + const int src0swiz[4] = { srcarg0->swizzle_x, srcarg0->swizzle_y, + srcarg0->swizzle_z, srcarg0->swizzle_w }; + + for (i = 0; i < 4; i++) + { + int mask = (1 << i); + + if (!writemask[i]) continue; + if (used_swiz[i]) continue; + + // This is a swizzle we haven't checked yet. + used_swiz[i] = 1; + + // see if there are any other elements swizzled to match (.yyyy) + for (j = i + 1; j < 4; j++) + { + if (!writemask[j]) continue; + if (src0swiz[i] != src0swiz[j]) continue; + mask |= (1 << j); + used_swiz[j] = 1; + } // for + + // okay, (mask) should be the writemask of swizzles we like. + + //return make_METAL_srcarg_string(ctx, idx, (1 << 0)); + + char src0[64]; + char src1[64]; + char src2[64]; + make_METAL_srcarg_string(ctx, 0, (1 << i), src0, sizeof (src0)); + make_METAL_srcarg_string(ctx, 1, mask, src1, sizeof (src1)); + make_METAL_srcarg_string(ctx, 2, mask, src2, sizeof (src2)); + + set_dstarg_writemask(dst, mask); + + char code[128]; + make_METAL_destarg_assign(ctx, code, sizeof (code), + "((%s %s) ? %s : %s)", + src0, cmp, src1, src2); + output_line(ctx, "%s", code); + } // for + + set_dstarg_writemask(dst, origmask); +} // emit_METAL_comparison_operations + +void emit_METAL_CND(Context *ctx) +{ + emit_METAL_comparison_operations(ctx, "> 0.5"); +} // emit_METAL_CND + +void emit_METAL_DEF(Context *ctx) +{ + const float *val = (const float *) ctx->dwords; // !!! FIXME: could be int? + char varname[64]; get_METAL_destarg_varname(ctx, varname, sizeof (varname)); + char val0[32]; floatstr(ctx, val0, sizeof (val0), val[0], 1); + char val1[32]; floatstr(ctx, val1, sizeof (val1), val[1], 1); + char val2[32]; floatstr(ctx, val2, sizeof (val2), val[2], 1); + char val3[32]; floatstr(ctx, val3, sizeof (val3), val[3], 1); + + push_output(ctx, &ctx->mainline_top); + ctx->indent++; + // The "(void) %s;" is to make the compiler not warn if this isn't used. + output_line(ctx, "const float4 %s = float4(%s, %s, %s, %s); (void) %s;", + varname, val0, val1, val2, val3, varname); + pop_output(ctx); +} // emit_METAL_DEF + +EMIT_METAL_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2RGB) // !!! FIXME +EMIT_METAL_OPCODE_UNIMPLEMENTED_FUNC(TEXDP3TEX) // !!! FIXME +EMIT_METAL_OPCODE_UNIMPLEMENTED_FUNC(TEXM3X2DEPTH) // !!! FIXME +EMIT_METAL_OPCODE_UNIMPLEMENTED_FUNC(TEXDP3) // !!! FIXME + +void emit_METAL_TEXM3X3(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + char dst[64]; + char src0[64]; + char src1[64]; + char src2[64]; + char src3[64]; + char src4[64]; + char code[512]; + + ctx->metal_need_header_geometric = 1; + + // !!! FIXME: this code counts on the register not having swizzles, etc. + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0, + src0, sizeof (src0)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0, + src1, sizeof (src1)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1, + src2, sizeof (src2)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1, + src3, sizeof (src3)); + get_METAL_varname_in_buf(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum, + src4, sizeof (src4)); + get_METAL_destarg_varname(ctx, dst, sizeof (dst)); + + make_METAL_destarg_assign(ctx, code, sizeof (code), + "float4(dot(%s.xyz, %s.xyz), dot(%s.xyz, %s.xyz), dot(%s.xyz, %s.xyz), 1.0)", + src0, src1, src2, src3, dst, src4); + + output_line(ctx, "%s", code); +} // emit_METAL_TEXM3X3 + +EMIT_METAL_OPCODE_UNIMPLEMENTED_FUNC(TEXDEPTH) // !!! FIXME + +void emit_METAL_CMP(Context *ctx) +{ + emit_METAL_comparison_operations(ctx, ">= 0.0"); +} // emit_METAL_CMP + +EMIT_METAL_OPCODE_UNIMPLEMENTED_FUNC(BEM) // !!! FIXME + +void emit_METAL_DP2ADD(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_vec2(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_METAL_srcarg_string_vec2(ctx, 1, src1, sizeof (src1)); + char src2[64]; make_METAL_srcarg_string_scalar(ctx, 2, src2, sizeof (src2)); + char extra[64]; snprintf(extra, sizeof (extra), " + %s", src2); + emit_METAL_dotprod(ctx, src0, src1, extra); +} // emit_METAL_DP2ADD + +void emit_METAL_DSX(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + ctx->metal_need_header_graphics = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), "dfdx(%s)", src0); + output_line(ctx, "%s", code); +} // emit_METAL_DSX + +void emit_METAL_DSY(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char code[128]; + ctx->metal_need_header_graphics = 1; + make_METAL_destarg_assign(ctx, code, sizeof (code), "dfdy(%s)", src0); + output_line(ctx, "%s", code); +} // emit_METAL_DSY + +void emit_METAL_TEXLDD(Context *ctx) +{ + metal_texld(ctx, 1); +} // emit_METAL_TEXLDD + +void emit_METAL_SETP(Context *ctx) +{ + const int vecsize = vecsize_from_writemask(ctx->dest_arg.writemask); + char src0[64]; make_METAL_srcarg_string_masked(ctx, 0, src0, sizeof (src0)); + char src1[64]; make_METAL_srcarg_string_masked(ctx, 1, src1, sizeof (src1)); + char code[128]; + + // destination is always predicate register (which is type bvec4). + const char *comp = (vecsize == 1) ? + get_METAL_comparison_string_scalar(ctx) : + get_METAL_comparison_string_vector(ctx); + + make_METAL_destarg_assign(ctx, code, sizeof (code), + "(%s %s %s)", src0, comp, src1); + output_line(ctx, "%s", code); +} // emit_METAL_SETP + +void emit_METAL_TEXLDL(Context *ctx) +{ + // !!! FIXME: The spec says we can't use GLSL's texture*Lod() built-ins + // !!! FIXME: from fragment shaders for some inexplicable reason. + // !!! FIXME: Maybe Metal can do it, but I haven't looked into it yet. + emit_METAL_TEXLD(ctx); +} // emit_METAL_TEXLDL + +void emit_METAL_BREAKP(Context *ctx) +{ + char src0[64]; make_METAL_srcarg_string_scalar(ctx, 0, src0, sizeof (src0)); + output_line(ctx, "if (%s) { break; }", src0); +} // emit_METAL_BREAKP + +void emit_METAL_RESERVED(Context *ctx) +{ + // do nothing; fails in the state machine. +} // emit_METAL_RESERVED + +#endif // SUPPORT_PROFILE_METAL + +#pragma GCC visibility pop diff --git a/mojoshader/profiles/mojoshader_profile_spirv.c b/mojoshader/profiles/mojoshader_profile_spirv.c new file mode 100644 index 0000000..5d5999b --- /dev/null +++ b/mojoshader/profiles/mojoshader_profile_spirv.c @@ -0,0 +1,4403 @@ +/** + * MojoShader; generate shader programs from bytecode of compiled + * Direct3D shaders. + * + * Please see the file LICENSE.txt in the source's root directory. + * + * This file written by Ryan C. Gordon. + */ + +#define __MOJOSHADER_INTERNAL__ 1 +#include "mojoshader_profile.h" + +#pragma GCC visibility push(hidden) + +#if SUPPORT_PROFILE_SPIRV +#include "spirv/spirv.h" +#include "spirv/GLSL.std.450.h" +#include + +static const int SPV_NO_SWIZZLE = 0xE4; // 0xE4 == 11100100 ... 0 1 2 3. No swizzle. + +#define EMIT_SPIRV_OPCODE_UNIMPLEMENTED_FUNC(op) \ + void emit_SPIRV_##op(Context *ctx) { \ + fail(ctx, #op " unimplemented in spirv profile"); \ + } + +typedef struct SpirvTexm3x3SetupResult +{ + // vec4 load results + uint32 id_dst_pad0; + uint32 id_dst_pad1; + uint32 id_dst; + + // float dot results + uint32 id_res_x; + uint32 id_res_y; + uint32 id_res_z; +} SpirvTexm3x3SetupResult; + +static const char *spv_get_uniform_array_varname(Context *ctx, + const RegisterType regtype, + char *buf, const size_t len) +{ + const char *shadertype = ctx->shader_type_str; + const char *type = ""; + switch (regtype) + { + case REG_TYPE_CONST: type = "vec4"; break; + case REG_TYPE_CONSTINT: type = "ivec4"; break; + case REG_TYPE_CONSTBOOL: type = "bool"; break; + default: fail(ctx, "BUG: used a uniform we don't know how to define."); + } // switch + snprintf(buf, len, "%s_uniforms_%s", shadertype, type); + return buf; +} // spv_get_uniform_array_varname + +static uint32 spv_bumpid(Context *ctx) +{ + return (ctx->spirv.idmax += 1); +} // spv_bumpid + +static RegisterList *spv_getreg(Context *ctx, const RegisterType regtype, const int regnum) +{ + RegisterList *r = reglist_find(&ctx->used_registers, regtype, regnum); + if (!r) + { + failf(ctx, "register not found rt=%d, rn=%d", regtype, regnum); + return NULL; + } // if + return r; +} // spv_getreg + +static void spv_componentlist_free(Context *ctx, ComponentList *cl) +{ + ComponentList *next; + while (cl) + { + next = cl->next; + Free(ctx, cl); + cl = next; + } // while +} // spv_componentlist_free + +static ComponentList *spv_componentlist_alloc(Context *ctx) +{ + ComponentList *ret = (ComponentList *) Malloc(ctx, sizeof(ComponentList)); + if (!ret) return NULL; + ret->id = 0; + ret->v.i = 0; + ret->next = NULL; + return ret; +} // spv_componentlist_alloc + +static const char *get_SPIRV_varname_in_buf(Context *ctx, const RegisterType rt, + const int regnum, char *buf, + const size_t buflen) +{ + // turns out these are identical at the moment. + return get_D3D_varname_in_buf(ctx, rt, regnum, buf, buflen); +} // get_SPIRV_varname_in_buf + +const char *get_SPIRV_varname(Context *ctx, const RegisterType rt, + const int regnum) +{ + // turns out these are identical at the moment. + return get_D3D_varname(ctx, rt, regnum); +} // get_SPIRV_varname + + +static inline const char *get_SPIRV_const_array_varname_in_buf(Context *ctx, + const int base, const int size, + char *buf, const size_t buflen) +{ + snprintf(buf, buflen, "c_array_%d_%d", base, size); + return buf; +} // get_SPIRV_const_array_varname_in_buf + + +const char *get_SPIRV_const_array_varname(Context *ctx, int base, int size) +{ + char buf[64]; + get_SPIRV_const_array_varname_in_buf(ctx, base, size, buf, sizeof (buf)); + return StrDup(ctx, buf); +} // get_SPIRV_const_array_varname + +static uint32 spv_get_uniform_array_id(Context *ctx, const RegisterType regtype) +{ + uint32 id; + switch (regtype) + { + case REG_TYPE_CONST: + id = ctx->spirv.uniform_arrays.idvec4; + if (id == 0) + { + id = spv_bumpid(ctx); + ctx->spirv.uniform_arrays.idvec4 = id; + } // if + break; + + case REG_TYPE_CONSTINT: + id = ctx->spirv.uniform_arrays.idivec4; + if (id == 0) + { + id = spv_bumpid(ctx); + ctx->spirv.uniform_arrays.idivec4 = id; + } // if + break; + + case REG_TYPE_CONSTBOOL: + id = ctx->spirv.uniform_arrays.idbool; + if (id == 0) + { + id = spv_bumpid(ctx); + ctx->spirv.uniform_arrays.idbool = id; + } // if + break; + + default: + fail(ctx, "Unexpected register type used to access uniform array."); + id = 0; + } // switch + + return id; +} // spv_get_uniform_array_id + +static void spv_emit_part_va(Context* ctx, uint32 word_count, uint32 argc, SpvOp op, va_list args) +{ + assert(ctx->output != NULL); + if (isfail(ctx)) + return; // we failed previously, don't go on... + + uint32 word = op | (word_count << 16); + buffer_append(ctx->output, &word, sizeof(word)); + while (--argc) + { + word = va_arg(args, uint32); + buffer_append(ctx->output, &word, sizeof(word)); + } // while +} // spv_emit_part_va + +static void spv_emit_part(Context* ctx, uint32 word_count, uint32 argc, SpvOp op, ...) +{ + va_list args; + va_start(args, op); + spv_emit_part_va(ctx, word_count, argc, op, args); + va_end(args); +} // spv_emit_part + +static void spv_emit(Context *ctx, uint32 word_count, SpvOp op, ...) +{ + va_list args; + va_start(args, op); + spv_emit_part_va(ctx, word_count, word_count, op, args); + va_end(args); +} // spv_emit + +static void spv_emit_word(Context *ctx, uint32 word) +{ + assert(ctx->output != NULL); + if (isfail(ctx)) + return; // we failed previously, don't go on... + + buffer_append(ctx->output, &word, sizeof(word)); +} // spv_emit_word + +static void spv_emit_str(Context *ctx, const char *str) +{ + size_t len; + uint32 trail; + assert(ctx->output != NULL); + if (isfail(ctx)) + return; // we failed previously, don't go on... + + if (str == NULL) + return spv_emit_word(ctx, 0); + len = strlen(str) + 1; + buffer_append(ctx->output, str, len); + len = len % 4; + if (len) + { + trail = 0; + buffer_append(ctx->output, &trail, 4 - len); + } // if +} // spv_emit_str + +// get the word count of a string +static uint32 spv_strlen(const char *str) +{ + size_t len = strlen(str); + return (uint32) ((len / 4) + 1); +} // spv_strlen + +// emits an OpName straight into ctx->globals +static void spv_output_name(Context *ctx, uint32 id, const char *str) +{ + if (isfail(ctx)) + return; // we failed previously, don't go on... + + push_output(ctx, &ctx->globals); + spv_emit_part(ctx, 2 + spv_strlen(str), 2, SpvOpName, id); + spv_emit_str(ctx, str); + pop_output(ctx); +} // spv_output_name + +// emit an OpName instruction to identify a register +static void spv_output_regname(Context *ctx, uint32 id, RegisterType regtype, int regnum) +{ + char varname[64]; + snprintf(varname, sizeof(varname), "%s_", ctx->shader_type_str); + size_t offset = strlen(varname); + get_SPIRV_varname_in_buf(ctx, regtype, regnum, varname + offset, sizeof(varname) - offset); + spv_output_name(ctx, id, varname); +} // spv_output_regname + +// emits an OpDecorate BuiltIn straight into ctx->helpers +static void spv_output_builtin(Context *ctx, uint32 id, SpvBuiltIn builtin) +{ + if (isfail(ctx)) + return; // we failed previously, don't go on... + + push_output(ctx, &ctx->helpers); + spv_emit(ctx, 4, SpvOpDecorate, id, SpvDecorationBuiltIn, builtin); + pop_output(ctx); +} // spv_output_builtin + +static uint32 spv_output_location(Context *ctx, uint32 id, uint32 loc) +{ + push_output(ctx, &ctx->helpers); + spv_emit(ctx, 4, SpvOpDecorate, id, SpvDecorationLocation, loc); + pop_output(ctx); + return (buffer_size(ctx->helpers) >> 2) - 1; +} // spv_output_location + +static void spv_output_color_location(Context *ctx, uint32 id, uint32 index) +{ + SpirvPatchTable* table = &ctx->spirv.patch_table; + push_output(ctx, &ctx->helpers); + spv_emit(ctx, 4, SpvOpDecorate, id, SpvDecorationLocation, index); + pop_output(ctx); + table->output_offsets[index] = (buffer_size(ctx->helpers) >> 2) - 1; +} // spv_output_color_location + +static void spv_output_attrib_location(Context *ctx, uint32 id, + MOJOSHADER_usage usage, uint32 index) +{ + SpirvPatchTable* table = &ctx->spirv.patch_table; + push_output(ctx, &ctx->helpers); + spv_emit(ctx, 4, SpvOpDecorate, id, SpvDecorationLocation, 0xDEADBEEF); + pop_output(ctx); + table->attrib_offsets[usage][index] = (buffer_size(ctx->helpers) >> 2) - 1; +} // spv_output_attrib_location + +static void spv_output_sampler_binding(Context *ctx, uint32 id, uint32 binding) +{ + if (isfail(ctx)) + return; + + uint32 set = 0; + if (ctx->spirv.mode == SPIRV_MODE_VK) + { + set = shader_is_vertex(ctx) ? MOJOSHADER_SPIRV_VS_SAMPLER_SET + : MOJOSHADER_SPIRV_PS_SAMPLER_SET; + } // if + + push_output(ctx, &ctx->helpers); + spv_emit(ctx, 4, SpvOpDecorate, id, SpvDecorationDescriptorSet, set); + spv_emit(ctx, 4, SpvOpDecorate, id, SpvDecorationBinding, binding); + pop_output(ctx); +} // spv_output_sampler_binding + +static SpirvTypeIdx spv_change_base_type_vec_dim(SpirvTypeIdx sti, uint32 dim) +{ + uint32 dimSub1 = dim - 1; + assert(STI_CORE_START_ <= sti && sti < STI_CORE_END_); + assert(dimSub1 < 4); + + SpirvTypeIdx sti_base = (SpirvTypeIdx)(sti & ~0x3); + SpirvTypeIdx sti_new = (SpirvTypeIdx)(sti_base | dimSub1); + return sti_new; +} // spv_change_base_type_vec_dim + +static uint32 spv_get_type(Context *ctx, SpirvTypeIdx tidx) +{ + assert(((uint32)tidx) < ((uint32)STI_LENGTH_)); + + uint32 tid = ctx->spirv.tid[tidx]; + if (tid) + return tid; + + push_output(ctx, &ctx->mainline_intro); + if (STI_CORE_START_ <= tidx && tidx < STI_CORE_END_) + { + uint32 dim = tidx & 0x3; + SpirvType type = (SpirvType)((tidx >> 2) & 0x3); + if (dim) + { + uint32 tid_base = spv_get_type(ctx, (SpirvTypeIdx)(tidx - dim)); + tid = spv_bumpid(ctx); + spv_emit(ctx, 4, SpvOpTypeVector, tid, tid_base, dim + 1); + } // if + else + { + tid = spv_bumpid(ctx); + switch (type) + { + case ST_FLOAT: spv_emit(ctx, 3, SpvOpTypeFloat, tid, 32); break; + case ST_SINT: spv_emit(ctx, 4, SpvOpTypeInt, tid, 32, 1); break; + case ST_UINT: spv_emit(ctx, 4, SpvOpTypeInt, tid, 32, 0); break; + case ST_BOOL: spv_emit(ctx, 2, SpvOpTypeBool, tid); break; + default: assert(!"Unexpected value of SpirvType."); break; + } // switch + } // else + } // if + else if (STI_IMAGE2D <= tidx && tidx <= STI_IMAGECUBE) + { + static const SpvDim dim_table[] = {SpvDim2D, SpvDim3D, SpvDimCube}; + SpvDim dim = dim_table[tidx - STI_IMAGE2D]; + uint32 tid_float = spv_get_type(ctx, STI_FLOAT); + uint32 id_image = spv_bumpid(ctx); + tid = spv_bumpid(ctx); + spv_emit(ctx, 9, SpvOpTypeImage, id_image, tid_float, dim, 0, 0, 0, 1, SpvImageFormatUnknown); + spv_emit(ctx, 3, SpvOpTypeSampledImage, tid, id_image); + } // else if + else if (tidx == STI_VOID) + { + tid = spv_bumpid(ctx); + spv_emit(ctx, 2, SpvOpTypeVoid, tid); + } // else if + else if (tidx == STI_FUNC_VOID) + { + uint32 tid_void = spv_get_type(ctx, STI_VOID); + tid = spv_bumpid(ctx); + spv_emit(ctx, 3, SpvOpTypeFunction, tid, tid_void); + } // else if + else if (tidx == STI_FUNC_LIT) + { + uint32 tid_vec4 = spv_get_type(ctx, STI_VEC4); + tid = spv_bumpid(ctx); + spv_emit(ctx, 3 + 1, SpvOpTypeFunction, tid, tid_vec4, tid_vec4); + } // else if + else if (STI_PTR_START_ <= tidx && tidx < STI_PTR_END_) + { + uint32 dim = (tidx & (1 << 4)) ? 3 : 0; + SpirvType type = (SpirvType)((tidx >> 2) & 0x3); + uint32 tid_base = spv_get_type(ctx, (SpirvTypeIdx)((1 << 4) | (type << 2) | dim)); + static const SpvStorageClass sc_map[] = { + SpvStorageClassInput, + SpvStorageClassInput, + SpvStorageClassOutput, + SpvStorageClassOutput, + SpvStorageClassPrivate, + SpvStorageClassPrivate, + SpvStorageClassUniformConstant, + SpvStorageClassUniform, + }; + SpvStorageClass sc = sc_map[((tidx & 0x3) << 1) | (ctx->spirv.mode == SPIRV_MODE_VK)]; + tid = spv_bumpid(ctx); + spv_emit(ctx, 4, SpvOpTypePointer, tid, sc, tid_base); + } // else if + else if (STI_PTR_IMAGE2D <= tidx && tidx <= STI_PTR_IMAGECUBE) + { + uint32 tid_image = spv_get_type(ctx, (SpirvTypeIdx)(tidx - (STI_PTR_IMAGE2D - STI_IMAGE2D))); + tid = spv_bumpid(ctx); + spv_emit(ctx, 4, SpvOpTypePointer, tid, SpvStorageClassUniformConstant, tid_image); + } // else if + else if (tidx == STI_PTR_VEC2_I) + { + uint32 tid_base = spv_get_type(ctx, STI_VEC2); + tid = spv_bumpid(ctx); + spv_emit(ctx, 4, SpvOpTypePointer, tid, SpvStorageClassInput, tid_base); + } // else if + else + assert(!"Unexpected value of type index."); + pop_output(ctx); + + ctx->spirv.tid[tidx] = tid; + return tid; +} // spv_get_type + +static uint32 spv_gettrue(Context *ctx) +{ + if (ctx->spirv.idtrue) + return ctx->spirv.idtrue; + + uint32 tid_bool = spv_get_type(ctx, STI_BOOL); + uint32 id = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline_intro); + spv_emit(ctx, 3, SpvOpConstantTrue, tid_bool, id); + pop_output(ctx); + return ctx->spirv.idtrue = id; +} // spv_gettrue + +static uint32 spv_getfalse(Context *ctx) +{ + if (ctx->spirv.idfalse) + return ctx->spirv.idfalse; + + uint32 tid_bool = spv_get_type(ctx, STI_BOOL); + uint32 id = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline_intro); + spv_emit(ctx, 3, SpvOpConstantFalse, tid_bool, id); + pop_output(ctx); + return ctx->spirv.idfalse = id; +} // spv_getfalse + +static uint32 spv_getext(Context *ctx) +{ + if (ctx->spirv.idext) + return ctx->spirv.idext; + + return ctx->spirv.idext = spv_bumpid(ctx); +} // spv_getext + +static uint32 spv_output_scalar(Context *ctx, ComponentList *cl, + MOJOSHADER_attributeType type) +{ + uint32 idret, idtype; + if (type == MOJOSHADER_ATTRIBUTE_FLOAT) + idtype = spv_get_type(ctx, STI_FLOAT); + else if (type == MOJOSHADER_ATTRIBUTE_INT) + idtype = spv_get_type(ctx, STI_INT); + else if (type == MOJOSHADER_ATTRIBUTE_UINT) + idtype = spv_get_type(ctx, STI_UINT); + else + { + failf(ctx, "spv_output_scalar: invalid attribute type %d", type); + return 0; + } // else + idret = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline_intro); + spv_emit(ctx, 4, SpvOpConstant, idtype, idret, cl->v.u); + pop_output(ctx); + return idret; +} // spv_output_scalar + +// The spv_getscalar* functions retrieve the result id of an OpConstant +// instruction with the corresponding value v, or generate a new one. +static uint32 spv_getscalarf(Context *ctx, float v) +{ + ComponentList *prev = &(ctx->spirv.cl.f), *cl = ctx->spirv.cl.f.next; + while (cl) + { + if (v == cl->v.f) + return cl->id; + else if (v < cl->v.f) + break; + prev = cl; + cl = cl->next; + } // while + cl = spv_componentlist_alloc(ctx); + cl->next = prev->next; + prev->next = cl; + cl->v.f = v; + cl->id = spv_output_scalar(ctx, cl, MOJOSHADER_ATTRIBUTE_FLOAT); + return cl->id; +} // spv_getscalarf + +static uint32 spv_getscalari(Context *ctx, int v) +{ + ComponentList *prev = &(ctx->spirv.cl.i), *cl = ctx->spirv.cl.i.next; + while (cl) + { + if (v == cl->v.i) + return cl->id; + else if (v < cl->v.i) + break; + prev = cl; + cl = cl->next; + } // while + cl = spv_componentlist_alloc(ctx); + cl->next = prev->next; + prev->next = cl; + cl->v.i = v; + cl->id = spv_output_scalar(ctx, cl, MOJOSHADER_ATTRIBUTE_INT); + return cl->id; +} // spv_getscalari + +static uint32 spv_get_constant_composite(Context *ctx, uint32 tid, uint32* cache, float scalar) +{ + uint32 i; + + assert(tid != 0); + uint32 dim = + (tid == ctx->spirv.tid[STI_VEC4]) ? 4 : + (tid == ctx->spirv.tid[STI_VEC3]) ? 3 : + (tid == ctx->spirv.tid[STI_VEC2]) ? 2 : 1; + + uint32 id = cache[dim - 1]; + if (id) + return id; + + uint32 sid = spv_getscalarf(ctx, scalar); + if (dim == 1) + { + cache[0] = sid; + return sid; + } // if + + id = spv_bumpid(ctx); + push_output(ctx, &ctx->mainline_intro); + spv_emit_part(ctx, 3 + dim, 3, SpvOpConstantComposite, tid, id); + for (i = 0; i < dim; i++) + spv_emit_word(ctx, sid); + pop_output(ctx); + cache[dim - 1] = id; + return id; +} // spv_get_constant_composite + +static uint32 spv_get_zero(Context *ctx, uint32 tid) +{ + return spv_get_constant_composite(ctx, tid, ctx->spirv.id_0_0, 0.0f); +} // spv_get_zero + +static uint32 spv_get_one(Context *ctx, uint32 tid) +{ + return spv_get_constant_composite(ctx, tid, ctx->spirv.id_1_0, 1.0f); +} // spv_get_one + +static uint32 spv_get_flt_max(Context *ctx, uint32 tid) +{ + return spv_get_constant_composite(ctx, tid, ctx->spirv.id_flt_max, FLT_MAX); +} // spv_get_one + +static uint32 spv_getvec4_zero(Context *ctx) +{ + return spv_get_constant_composite(ctx, spv_get_type(ctx, STI_VEC4), ctx->spirv.id_0_0, 0.0f); +} // spv_getvec4_zero + +static uint32 spv_getvec4_one(Context *ctx) +{ + return spv_get_constant_composite(ctx, spv_get_type(ctx, STI_VEC4), ctx->spirv.id_1_0, 1.0f); +} // spv_getvec4_one + +// Make a 4-channel vector with a value broadcast across all channels. Roughly equivalent to `vec4(value)` in GLSL +static uint32 spv_vectorbroadcast(Context *ctx, uint32 tid, uint32 value) +{ + uint32 result = spv_bumpid(ctx); + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 3 + 4, SpvOpCompositeConstruct, tid, result, value, value, value, value); + pop_output(ctx); + return result; +} // spv_vectorbroadcast + +static void spv_branch_push(Context *ctx, uint32 id_merge, uint32 patch_offset) +{ + assert(((size_t)ctx->branch_labels_stack_index) < STATICARRAYLEN(ctx->branch_labels_stack)); + int pos = ctx->branch_labels_stack_index++; + ctx->branch_labels_stack[pos] = id_merge; + ctx->branch_labels_patch_stack[pos] = patch_offset; +} // spv_branch_push + +static void spv_branch_get(Context *ctx, uint32* out_id_merge, uint32* out_patch_offset) +{ + assert(ctx->branch_labels_stack_index > 0); + int pos = ctx->branch_labels_stack_index - 1; + *out_id_merge = ctx->branch_labels_stack[pos]; + *out_patch_offset = ctx->branch_labels_patch_stack[pos]; +} // spv_branch_get + +static void spv_branch_pop(Context *ctx, uint32* out_id_merge, uint32* out_patch_offset) +{ + spv_branch_get(ctx, out_id_merge, out_patch_offset); + ctx->branch_labels_stack_index--; +} // spv_branch_pop + +static void spv_loop_push(Context *ctx, const SpirvLoopInfo *loop) +{ + assert(((size_t)ctx->spirv.loop_stack_idx) < STATICARRAYLEN(ctx->spirv.loop_stack)); + int pos = ctx->spirv.loop_stack_idx++; + ctx->spirv.loop_stack[pos] = *loop; +} // spv_loop_push + +static void spv_loop_get(Context *ctx, SpirvLoopInfo *loop) +{ + assert(ctx->spirv.loop_stack_idx > 0); + int pos = ctx->spirv.loop_stack_idx - 1; + *loop = ctx->spirv.loop_stack[pos]; +} // spv_loop_get + +static void spv_loop_pop(Context *ctx, SpirvLoopInfo *loop) +{ + spv_loop_get(ctx, loop); + ctx->spirv.loop_stack_idx--; +} // spv_loop_pop + +static uint32 spv_loop_get_aL(Context *ctx) +{ + int i; + + // Find the first enclosing loop..endloop. There may be rep..endrep nested inside, so it might + // not be at the top of the stack. + for (i = ctx->spirv.loop_stack_idx - 1; i >= 0; i--) + { + uint32 id_aL = ctx->spirv.loop_stack[i].id_aL; + if (id_aL) + return id_aL; + } // for + + assert(!"Referencing loop counter register aL in code not part of loop..endloop region."); + return 0; +} // spv_loop_get_aL + +static SpvOp spv_get_comparison(Context *ctx) +{ + static const SpvOp spv_cmp_ops[] = { + SpvOpUndef, + SpvOpFOrdGreaterThan, + SpvOpFOrdEqual, + SpvOpFOrdGreaterThanEqual, + SpvOpFOrdLessThan, + SpvOpFOrdNotEqual, + SpvOpFOrdLessThanEqual, + }; + + if (ctx->instruction_controls >= STATICARRAYLEN(spv_cmp_ops)) + { + fail(ctx, "unknown comparison control"); + return SpvOpUndef; + } // if + + return spv_cmp_ops[ctx->instruction_controls]; +} // spv_get_comparison + +static void spv_check_read_reg_id(Context *ctx, RegisterList *r) +{ + if (r->spirv.iddecl == 0) + { + assert(r->regtype != REG_TYPE_SAMPLER || (shader_is_pixel(ctx) && !shader_version_atleast(ctx, 1, 4))); + assert(r->regtype != REG_TYPE_TEXTURE || (shader_is_pixel(ctx) && !shader_version_atleast(ctx, 1, 4))); + switch (r->regtype) + { + case REG_TYPE_SAMPLER: // s# (only ps_1_1) + case REG_TYPE_TEXTURE: // t# (only ps_1_1) + case REG_TYPE_INPUT: // v# + case REG_TYPE_TEMP: // r# + case REG_TYPE_CONST: // c# + case REG_TYPE_CONSTINT: // i# + case REG_TYPE_CONSTBOOL: // b# + case REG_TYPE_LABEL: // l# + case REG_TYPE_PREDICATE: // p0 + r->spirv.iddecl = spv_bumpid(ctx); + break; + + case REG_TYPE_LOOP: // aL + r->spirv.iddecl = spv_loop_get_aL(ctx); + break; + + default: + { + char varname[64]; + get_SPIRV_varname_in_buf(ctx, r->regtype, r->regnum, varname, sizeof(varname)); + failf(ctx, "register type %s is unimplemented\n", varname); + break; + } // default + } // switch + } // if +} // spv_check_read_reg_id + +static void spv_check_write_reg_id(Context *ctx, RegisterList *r) +{ + if (r->spirv.iddecl == 0) + { + switch (r->regtype) + { + // These registers require no declarations, so we can just create them as we see them + case REG_TYPE_ADDRESS: + case REG_TYPE_TEMP: + case REG_TYPE_RASTOUT: + case REG_TYPE_COLOROUT: + case REG_TYPE_TEXCRDOUT: + case REG_TYPE_DEPTHOUT: + case REG_TYPE_ATTROUT: + case REG_TYPE_PREDICATE: + r->spirv.iddecl = spv_bumpid(ctx); + break; + + // Other register types should be explicitly declared, so it is an error for them to have iddecl == 0 by now + default: + { + char varname[64]; + get_SPIRV_varname_in_buf(ctx, r->regtype, r->regnum, varname, sizeof(varname)); + failf(ctx, "tried to write to undeclared register %s\n", varname); + break; + } // default + } // switch + } // if +} // spv_check_write_reg_id + +static uint32 spv_ptrimage_from_texturetype(Context *ctx, TextureType ttype) +{ + switch (ttype) + { + case TEXTURE_TYPE_2D: + return spv_get_type(ctx, STI_PTR_IMAGE2D); + case TEXTURE_TYPE_CUBE: + return spv_get_type(ctx, STI_PTR_IMAGECUBE); + case TEXTURE_TYPE_VOLUME: + return spv_get_type(ctx, STI_PTR_IMAGE3D); + default: + fail(ctx, "BUG: used a sampler we don't know how to define."); + return 0; + } // switch +} // spv_ptrimage_from_texturetype + +static uint32 spv_image_from_texturetype(Context *ctx, TextureType ttype) +{ + switch (ttype) + { + case TEXTURE_TYPE_2D: + return spv_get_type(ctx, STI_IMAGE2D); + case TEXTURE_TYPE_CUBE: + return spv_get_type(ctx, STI_IMAGECUBE); + case TEXTURE_TYPE_VOLUME: + return spv_get_type(ctx, STI_IMAGE3D); + default: + fail(ctx, "BUG: used a sampler we don't know how to define."); + return 0; + } // switch +} // spv_ptrimage_from_texturetype + +static uint32 spv_access_uniform(Context *ctx, SpirvTypeIdx sti_ptr, RegisterType regtype, uint32 id_offset) +{ + uint32 tid_ptr = spv_get_type(ctx, sti_ptr); + uint32 id_arr = spv_get_uniform_array_id(ctx, regtype); + uint32 id_access = spv_bumpid(ctx); + push_output(ctx, &ctx->mainline); + if (ctx->spirv.mode == SPIRV_MODE_VK) + { + uint32 id_uniform_block = ctx->spirv.id_uniform_block; + if (id_uniform_block == 0) + { + id_uniform_block = spv_bumpid(ctx); + ctx->spirv.id_uniform_block = id_uniform_block; + } // if + spv_emit(ctx, 4+2, SpvOpAccessChain, tid_ptr, id_access, id_uniform_block, id_arr, id_offset); + } // if + else + { + spv_emit(ctx, 4+1, SpvOpAccessChain, tid_ptr, id_access, id_arr, id_offset); + } // else + pop_output(ctx); + return id_access; +} // spv_access_uniform + +static void spv_add_attrib_fixup(Context *ctx, RegisterList *r, unsigned int type_offset, unsigned int opcode_offset) +{ + uint32* next_types; + uint32* next_opcodes; + + assert(r != NULL); + #define TYPE_LOAD_OFFSET ctx->spirv.patch_table.attrib_type_load_offsets[r->usage][r->index] + + next_types = (uint32*) Malloc(ctx, sizeof(uint32) * (TYPE_LOAD_OFFSET.num_loads + 1)); + next_opcodes = (uint32*) Malloc(ctx, sizeof(uint32) * (TYPE_LOAD_OFFSET.num_loads + 1)); + + memcpy(next_types, TYPE_LOAD_OFFSET.load_types, sizeof(uint32) * TYPE_LOAD_OFFSET.num_loads); + memcpy(next_opcodes, TYPE_LOAD_OFFSET.load_opcodes, sizeof(uint32) * TYPE_LOAD_OFFSET.num_loads); + + Free(ctx, TYPE_LOAD_OFFSET.load_types); + Free(ctx, TYPE_LOAD_OFFSET.load_opcodes); + + TYPE_LOAD_OFFSET.load_types = next_types; + TYPE_LOAD_OFFSET.load_opcodes = next_opcodes; + + TYPE_LOAD_OFFSET.load_types[TYPE_LOAD_OFFSET.num_loads] = type_offset; + TYPE_LOAD_OFFSET.load_opcodes[TYPE_LOAD_OFFSET.num_loads] = opcode_offset; + + TYPE_LOAD_OFFSET.num_loads += 1; + #undef TYPE_LOAD_OFFSET +} // spv_add_attrib_fixup + +static SpirvResult spv_loadreg(Context *ctx, RegisterList *r) +{ + const RegisterType regtype = r->regtype; + uint32 copy_id; + + spv_check_read_reg_id(ctx, r); + + uint32 id_src = r->spirv.iddecl; + SpirvResult result; + if (regtype == REG_TYPE_SAMPLER) + { + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, r->regnum); + result.tid = spv_image_from_texturetype(ctx, (TextureType)sreg->index); + } // if + else if (regtype == REG_TYPE_CONSTBOOL) + { + if (!r->spirv.is_ssa) + id_src = spv_access_uniform(ctx, STI_PTR_INT_U, regtype, r->spirv.iddecl); + + result.tid = spv_get_type(ctx, STI_INT); + } // else if + else if (regtype == REG_TYPE_CONSTINT) + { + if (!r->spirv.is_ssa) + id_src = spv_access_uniform(ctx, STI_PTR_IVEC4_U, regtype, r->spirv.iddecl); + + result.tid = spv_get_type(ctx, STI_IVEC4); + } // else if + else if (regtype == REG_TYPE_CONST) + { + if (!r->spirv.is_ssa) + id_src = spv_access_uniform(ctx, STI_PTR_VEC4_U, regtype, r->spirv.iddecl); + + result.tid = spv_get_type(ctx, STI_VEC4); + } // else if + else if (regtype == REG_TYPE_LOOP) + result.tid = spv_get_type(ctx, STI_INT); + else if (regtype == REG_TYPE_PREDICATE) + result.tid = spv_get_type(ctx, STI_BVEC4); + else + result.tid = spv_get_type(ctx, STI_VEC4); + + // Constants can be used directly, no need to load them. + assert(r->spirv.is_ssa == 0 || r->spirv.is_ssa == 1); + if (r->spirv.is_ssa) + { + result.id = r->spirv.iddecl; + return result; + } // if + + assert(id_src); + result.id = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 4, SpvOpLoad, result.tid, result.id, id_src); + if (shader_is_vertex(ctx) && regtype == REG_TYPE_INPUT) + { + copy_id = spv_bumpid(ctx); + spv_emit(ctx, 4, SpvOpCopyObject, result.tid, copy_id, result.id); + result.id = copy_id; + pop_output(ctx); + + // Store the offsets of: + // - OpLoad's type id, to change the input type + // - OpCopyObject's opcode, to change to OpConvert if needed + spv_add_attrib_fixup(ctx, + reglist_find(&ctx->attributes, r->regtype, r->regnum), + (buffer_size(ctx->mainline) >> 2) - 7, + (buffer_size(ctx->mainline) >> 2) - 4); + } // if + else + { + // Nothing left to do for this register + pop_output(ctx); + } // else + + return result; +} // spv_loadreg + +static uint32 spv_emit_swizzle(Context *ctx, uint32 arg, uint32 rtid, const int swizzle, const int writemask) +{ + uint32 result = spv_bumpid(ctx); + + const int writemask0 = (writemask >> 0) & 0x1; + const int writemask1 = (writemask >> 1) & 0x1; + const int writemask2 = (writemask >> 2) & 0x1; + const int writemask3 = (writemask >> 3) & 0x1; + + const uint32 swizzle_x = (swizzle >> 0) & 0x3; + const uint32 swizzle_y = (swizzle >> 2) & 0x3; + const uint32 swizzle_z = (swizzle >> 4) & 0x3; + const uint32 swizzle_w = (swizzle >> 6) & 0x3; + + push_output(ctx, &ctx->mainline); + // OpVectorShuffle takes two vectors to shuffle, but to do a swizzle + // operation we can just ignore the second argument (meaning it can be + // anything, and I am just making it `arg` for convenience) + uint32 word_count = 5 + writemask0 + writemask1 + writemask2 + writemask3; + spv_emit_part(ctx, word_count, 5, SpvOpVectorShuffle, rtid, result, arg, arg); + if (writemask0) spv_emit_word(ctx, swizzle_x); + if (writemask1) spv_emit_word(ctx, swizzle_y); + if (writemask2) spv_emit_word(ctx, swizzle_z); + if (writemask3) spv_emit_word(ctx, swizzle_w); + pop_output(ctx); + + return result; +} // spv_emit_swizzle + +SpirvResult spv_swizzle(Context *ctx, SpirvResult arg, const int swizzle, const int writemask) +{ + int i; + + // Nothing to do, so return the same SSA value + if (no_swizzle(swizzle) && writemask_xyzw(writemask)) + return arg; + + assert(arg.tid != 0); + assert(writemask == 1 + || writemask == 3 + || writemask == 7 + || writemask == 15 + ); + + SpirvTypeIdx sti_arg = STI_VOID; + for (i = STI_CORE_START_; i < STI_CORE_END_; i++) + { + if (ctx->spirv.tid[i] == arg.tid) + { + sti_arg = (SpirvTypeIdx)i; + break; + } // if + } // for + assert(sti_arg != STI_VOID); + + // We should not leave any value undefined, as it may end up used (eg. dot + // product), which will make everything relying on it's result undefined. + // Therefore, we specifically determine true dimensionality of the result. + int resdim = 0; + switch (writemask) + { + case 1: + resdim = 1; + break; + + case 3: + resdim = 2; + break; + + case 7: + resdim = 3; + break; + + case 15: + resdim = 4; + break; + + default: + failf(ctx, "Unexpected write mask in swizzle: 0x%X"); + assert(0); + break; + } // switch + + SpirvTypeIdx sti_result = spv_change_base_type_vec_dim(sti_arg, resdim); + + SpirvResult result = {0}; + result.id = (resdim != 1 || sti_arg != sti_result) ? spv_bumpid(ctx) : arg.id; + result.tid = spv_get_type(ctx, sti_result); + assert(result.tid != 0); + + push_output(ctx, &ctx->mainline); + if (resdim != 1) + { + // OpVectorShuffle takes two vectors to shuffle, but to do a swizzle + // operation we can just ignore the second argument (meaning it can be + // anything, and I am just making it `arg` for convenience) + spv_emit_part(ctx, 5 + resdim, 5, SpvOpVectorShuffle, result.tid, result.id, arg.id, arg.id); + + for (i = 0; i < resdim; i++) + spv_emit_word(ctx, (swizzle >> (2*i)) & 0x3); + } // if + else if (sti_arg != sti_result) + { + // OpVectorShuffle may not produce a scalar. Instead we use OpCompositeExtract. + spv_emit(ctx, 5, SpvOpCompositeExtract, result.tid, result.id, arg.id, swizzle & 0x3); + } // else if + + pop_output(ctx); + + return result; +} // make_GLSL_swizzle_string + +static SpirvResult spv_load_srcarg(Context *ctx, const size_t idx, const int writemask) +{ + SpirvResult result = {0}; + if (idx >= STATICARRAYLEN(ctx->source_args)) + { + fail(ctx, "Too many source args"); + return result; + } // if + + const SourceArgInfo *arg = &ctx->source_args[idx]; + + RegisterList *reg = spv_getreg(ctx, arg->regtype, arg->regnum); + + if (arg->relative) + { + if (arg->regtype == REG_TYPE_INPUT) + fail(ctx, "relative input array access is unimplemented"); + else + { + assert(arg->regtype == REG_TYPE_CONST); + const int arrayidx = arg->relative_array->index; + const int offset = arg->regnum - arrayidx; + assert(offset >= 0); + + int is_constant = (arg->relative_array->constant != NULL); + uint32 id_array = 0; + if (is_constant) + { + id_array = ctx->spirv.constant_arrays.idvec4; + if (id_array == 0) + { + id_array = spv_bumpid(ctx); + ctx->spirv.constant_arrays.idvec4 = id_array; + } // if + } // if + + RegisterList *reg_rel = spv_getreg(ctx, arg->relative_regtype, arg->relative_regnum); + + spv_check_read_reg_id(ctx, reg_rel); + spv_check_read_reg_id(ctx, reg); + + uint32 id_int = spv_get_type(ctx, STI_INT); + uint32 id_offset; + if (reg_rel->regtype == REG_TYPE_LOOP) + id_offset = reg_rel->spirv.iddecl; + else + { + uint32 id_pint = spv_get_type(ctx, STI_PTR_INT_P); + uint32 id_compidx = spv_getscalari(ctx, arg->relative_component); + uint32 id_pcomp = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpAccessChain, id_pint, id_pcomp, reg_rel->spirv.iddecl, id_compidx); + + id_offset = spv_bumpid(ctx); + spv_emit(ctx, 4, SpvOpLoad, id_int, id_offset, id_pcomp); + } // else + + if (!is_constant) + { + uint32 id_arraybase = reg->spirv.iddecl; + uint32 id_a = id_offset; + uint32 id_b = id_arraybase; + id_offset = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpIAdd, id_int, id_offset, id_a, id_b); + } // if + + if (offset) + { + uint32 id_a = id_offset; + uint32 id_b = spv_getscalari(ctx, offset); + id_offset = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpIAdd, id_int, id_offset, id_a, id_b); + } // if + + uint32 id_pvalue; + if (is_constant) + { + uint32 id_pvec4 = spv_get_type(ctx, STI_PTR_VEC4_P); + id_pvalue = spv_bumpid(ctx); + spv_emit(ctx, 4+1, SpvOpAccessChain, id_pvec4, id_pvalue, id_array, id_offset); + } // if + else + { + id_pvalue = spv_access_uniform(ctx, STI_PTR_VEC4_U, arg->regtype, id_offset); + } // else + + result.tid = spv_get_type(ctx, STI_VEC4); + result.id = spv_bumpid(ctx); + spv_emit(ctx, 4, SpvOpLoad, result.tid, result.id, id_pvalue); + } // else + } // if + else + result = spv_loadreg(ctx, reg); + + result = spv_swizzle(ctx, result, arg->swizzle, writemask); + + switch (arg->src_mod) + { + case SRCMOD_NEGATE: + { + uint32 id_neg = spv_bumpid(ctx); + spv_emit(ctx, 4, SpvOpFNegate, result.tid, id_neg, result.id); + result.id = id_neg; + break; + } // case + + case SRCMOD_BIASNEGATE: + { + uint32 id_half = spv_get_constant_composite(ctx, result.tid, ctx->spirv.id_0_5, 0.5f); + uint32 id_tmp = spv_bumpid(ctx); + uint32 id_new = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpFSub, result.tid, id_tmp, result.id, id_half); + spv_emit(ctx, 4, SpvOpFNegate, result.tid, id_new, id_tmp); + result.id = id_new; + break; + } // case + + case SRCMOD_BIAS: + { + uint32 id_half = spv_get_constant_composite(ctx, result.tid, ctx->spirv.id_0_5, 0.5f); + uint32 id_new = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpFSub, result.tid, id_new, result.id, id_half); + result.id = id_new; + break; + } // case + + case SRCMOD_SIGNNEGATE: + { + uint32 id_half = spv_get_constant_composite(ctx, result.tid, ctx->spirv.id_0_5, 0.5f); + uint32 id_two = spv_get_constant_composite(ctx, result.tid, ctx->spirv.id_2_0, 2.0f); + uint32 id_tmp0 = spv_bumpid(ctx); + uint32 id_tmp1 = spv_bumpid(ctx); + uint32 id_new = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpFSub, result.tid, id_tmp0, result.id, id_half); + spv_emit(ctx, 5, SpvOpFMul, result.tid, id_tmp1, id_tmp0, id_two); + spv_emit(ctx, 4, SpvOpFNegate, result.tid, id_new, id_tmp1); + result.id = id_new; + break; + } // case + + case SRCMOD_SIGN: + { + uint32 id_half = spv_get_constant_composite(ctx, result.tid, ctx->spirv.id_0_5, 0.5f); + uint32 id_two = spv_get_constant_composite(ctx, result.tid, ctx->spirv.id_2_0, 2.0f); + uint32 id_tmp = spv_bumpid(ctx); + uint32 id_new = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpFSub, result.tid, id_tmp, result.id, id_half); + spv_emit(ctx, 5, SpvOpFMul, result.tid, id_new, id_tmp, id_two); + result.id = id_new; + break; + } // case + + case SRCMOD_COMPLEMENT: + { + uint32 id_one = spv_get_constant_composite(ctx, result.tid, ctx->spirv.id_1_0, 1.0f); + uint32 id_new = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpFSub, result.tid, id_new, id_one, result.id); + result.id = id_new; + break; + } // case + + case SRCMOD_X2NEGATE: + { + uint32 id_two = spv_get_constant_composite(ctx, result.tid, ctx->spirv.id_2_0, 2.0f); + uint32 id_tmp = spv_bumpid(ctx); + uint32 id_new = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpFMul, result.tid, id_tmp, result.id, id_two); + spv_emit(ctx, 4, SpvOpFNegate, result.tid, id_new, id_tmp); + result.id = id_new; + break; + } // case + + case SRCMOD_X2: + { + uint32 id_two = spv_get_constant_composite(ctx, result.tid, ctx->spirv.id_2_0, 2.0f); + uint32 id_new = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpFMul, result.tid, id_new, result.id, id_two); + result.id = id_new; + break; + } // case + + // case SRCMOD_DZ: + // fail(ctx, "SRCMOD_DZ unsupported"); return buf; // !!! FIXME + // postmod_str = "_dz"; + // break; + + // case SRCMOD_DW: + // fail(ctx, "SRCMOD_DW unsupported"); return buf; // !!! FIXME + // postmod_str = "_dw"; + // break; + + case SRCMOD_ABSNEGATE: + { + uint32 id_abs = spv_bumpid(ctx); + uint32 id_neg = spv_bumpid(ctx); + spv_emit(ctx, 5 + 1, SpvOpExtInst, result.tid, id_abs, spv_getext(ctx), GLSLstd450FAbs, result.id); + spv_emit(ctx, 4, SpvOpFNegate, result.tid, id_neg, id_abs); + result.id = id_neg; + break; + } // case + + case SRCMOD_ABS: + { + uint32 id_abs = spv_bumpid(ctx); + spv_emit(ctx, 5 + 1, SpvOpExtInst, result.tid, id_abs, spv_getext(ctx), GLSLstd450FAbs, result.id); + result.id = id_abs; + break; + } // case + + case SRCMOD_NOT: + { + // We can't do OpLogicalNot on ints, so do (x ^ 1) instead + uint32 id_one = spv_getscalari(ctx, 1); + uint32 id_not = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpBitwiseXor, result.tid, id_not, result.id, id_one); + result.id = id_not; + break; + } // case + + case SRCMOD_NONE: + case SRCMOD_TOTAL: + break; // stop compiler whining. + + default: + failf(ctx, "unsupported source modifier %d", arg->src_mod); + return result; + } // switch + + return result; +} // spv_load_srcarg + +static inline SpirvResult spv_load_srcarg_full(Context *ctx, const size_t idx) +{ + return spv_load_srcarg(ctx, idx, 0xF); +} // spv_load_srcarg_full + +static void spv_assign_destarg(Context *ctx, SpirvResult value) +{ + const DestArgInfo *arg = &ctx->dest_arg; + RegisterList *reg = spv_getreg(ctx, arg->regtype, arg->regnum); + + spv_check_write_reg_id(ctx, reg); + + if (arg->writemask == 0) + { + // Return without updating the reg->spirv.iddecl (all-zero writemask = no-op) + return; + } // if + + if (arg->result_mod & MOD_SATURATE) + { + uint32 ext, zero, one, new_value; + + // Don't inline these, compilers will run the varargs in different orders + new_value = spv_bumpid(ctx); + one = spv_get_one(ctx, value.tid); + zero = spv_get_zero(ctx, value.tid); + ext = spv_getext(ctx); + + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 5 + 3, SpvOpExtInst, + value.tid, new_value, ext, GLSLstd450FClamp, value.id, zero, one + ); + pop_output(ctx); + value.id = new_value; + } // if + + // MSDN says MOD_PP is a hint and many implementations ignore it. So do we. + + // CENTROID only allowed in DCL opcodes, which shouldn't come through here. + assert((arg->result_mod & MOD_CENTROID) == 0); + + if (ctx->predicated) + { + fail(ctx, "predicated destinations unsupported"); // !!! FIXME + return; + } // if + + if (arg->result_shift) + { + float factor = 1.0f; + uint32* cache = ctx->spirv.id_1_0; + switch (arg->result_shift) + { + case 0x1: factor = 2.0f; cache = ctx->spirv.id_2_0; break; + case 0x2: factor = 4.0f; cache = ctx->spirv.id_4_0; break; + case 0x3: factor = 8.0f; cache = ctx->spirv.id_8_0; break; + case 0xD: factor = 0.125f; cache = ctx->spirv.id_0_125; break; + case 0xE: factor = 0.25f; cache = ctx->spirv.id_0_25; break; + case 0xF: factor = 0.5f; cache = ctx->spirv.id_0_5; break; + default: + failf(ctx, "unexpected result shift %d", arg->result_shift); + } // switch + + uint32 id_factor = spv_get_constant_composite(ctx, value.tid, cache, factor); + push_output(ctx, &ctx->mainline); + uint32 id_new = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpFMul, value.tid, id_new, value.id, id_factor); + pop_output(ctx); + value.id = id_new; + } // if + + if (reg->regtype == REG_TYPE_DEPTHOUT + || isscalar(ctx, ctx->shader_type, arg->regtype, arg->regnum)) + { + assert(arg->writemask == 0x1); + SpirvTypeIdx sti_reg = STI_FLOAT; + uint32 rtid = spv_get_type(ctx, sti_reg); + uint32 new_value = spv_bumpid(ctx); + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 5, SpvOpCompositeExtract, rtid, new_value, value.id, 0); + pop_output(ctx); + value.tid = rtid; + value.id = new_value; + } // if + else if (!writemask_xyzw(arg->writemask)) + { + SpirvTypeIdx sti_reg; + switch (reg->regtype) + { + case REG_TYPE_ADDRESS: sti_reg = STI_IVEC4; break; + case REG_TYPE_PREDICATE: sti_reg = STI_BVEC4; break; + default: sti_reg = STI_VEC4; break; + } // switch + + uint32 rtid = spv_get_type(ctx, sti_reg); + uint32 new_value = spv_bumpid(ctx); + uint32 current_value = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline); + + spv_emit(ctx, 4, SpvOpLoad, rtid, current_value, reg->spirv.iddecl); + + // output id is new_value + // select between current value and new value based on writemask + // in the shuffle, components [0, 3] are the new value, and components + // [4, 7] are the existing value + spv_emit_part(ctx, 5 + 4, 5, SpvOpVectorShuffle, rtid, new_value, value.id, current_value); + if (arg->writemask0) spv_emit_word(ctx, 0); else spv_emit_word(ctx, 4); + if (arg->writemask1) spv_emit_word(ctx, 1); else spv_emit_word(ctx, 5); + if (arg->writemask2) spv_emit_word(ctx, 2); else spv_emit_word(ctx, 6); + if (arg->writemask3) spv_emit_word(ctx, 3); else spv_emit_word(ctx, 7); + + pop_output(ctx); + + value.tid = rtid; + value.id = new_value; + } // if + + switch (reg->regtype) + { + case REG_TYPE_OUTPUT: + case REG_TYPE_ADDRESS: + case REG_TYPE_TEMP: + case REG_TYPE_DEPTHOUT: + case REG_TYPE_COLOROUT: + case REG_TYPE_RASTOUT: + case REG_TYPE_ATTROUT: + case REG_TYPE_PREDICATE: + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 3, SpvOpStore, reg->spirv.iddecl, value.id); + pop_output(ctx); + break; + + default: + { + char varname[64]; + get_SPIRV_varname_in_buf(ctx, reg->regtype, reg->regnum, varname, sizeof(varname)); + failf(ctx, "register %s is unimplemented for storing", varname); + break; + } // default + } // switch +} // spv_assign_destarg + +static void spv_emit_vs_main_end(Context* ctx) +{ +#if SUPPORT_PROFILE_GLSPIRV +#if defined(MOJOSHADER_DEPTH_CLIPPING) || defined(MOJOSHADER_FLIP_RENDERTARGET) + if (!ctx->profile_supports_glspirv || !shader_is_vertex(ctx)) + return; + + uint32 tid_void = spv_get_type(ctx, STI_VOID); + uint32 tid_func = spv_get_type(ctx, STI_FUNC_VOID); + uint32 id_func = ctx->spirv.id_vs_main_end; + uint32 id_label = spv_bumpid(ctx); + assert(id_func != 0); + + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 5, SpvOpFunction, tid_void, id_func, SpvFunctionControlMaskNone, tid_func); + spv_emit(ctx, 2, SpvOpLabel, id_label); + + RegisterList *reg; + for (reg = ctx->used_registers.next; reg != NULL; reg = reg->next) + { + if (reg->usage == MOJOSHADER_USAGE_POSITION && + (reg->regtype == REG_TYPE_RASTOUT || reg->regtype == REG_TYPE_OUTPUT)) + break; + } // for + SpirvResult output = spv_loadreg(ctx, reg); + uint32 tid_float = spv_get_type(ctx, STI_FLOAT); + uint32 id_new_output; + +#ifdef MOJOSHADER_FLIP_RENDERTARGET + // gl_Position.y = gl_Position.y * vpFlip; + uint32 tid_pvpflip = spv_bumpid(ctx); + uint32 id_old_y = spv_bumpid(ctx); + uint32 id_pvpflip = spv_bumpid(ctx); + uint32 id_vpflip = spv_bumpid(ctx); + uint32 id_new_y = spv_bumpid(ctx); + id_new_output = spv_bumpid(ctx); + + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_float, id_old_y, output.id, 1); + spv_emit(ctx, 4, SpvOpLoad, tid_float, id_vpflip, id_pvpflip); + spv_emit(ctx, 5, SpvOpFMul, tid_float, id_new_y, id_old_y, id_vpflip); + spv_emit(ctx, 6, SpvOpCompositeInsert, output.tid, id_new_output, id_new_y, output.id, 1); + output.id = id_new_output; + + push_output(ctx, &ctx->mainline_intro); + spv_emit(ctx, 4, SpvOpTypePointer, tid_pvpflip, SpvStorageClassUniformConstant, tid_float); + spv_emit(ctx, 4, SpvOpVariable, tid_pvpflip, id_pvpflip, SpvStorageClassUniformConstant); + pop_output(ctx); + + spv_output_name(ctx, id_pvpflip, "vpFlip"); + ctx->spirv.patch_table.vpflip.offset = spv_output_location(ctx, id_pvpflip, ~0u); +#endif // MOJOSHADER_FLIP_RENDERTARGET + +#ifdef MOJOSHADER_DEPTH_CLIPPING + // gl_Position.z = gl_Position.z * 2.0 - gl_Position.w; + uint32 id_2 = spv_getscalarf(ctx, 2.0f); + uint32 id_old_z = spv_bumpid(ctx); + uint32 id_old_w = spv_bumpid(ctx); + uint32 id_2z = spv_bumpid(ctx); + uint32 id_new_z = spv_bumpid(ctx); + id_new_output = spv_bumpid(ctx); + + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_float, id_old_z, output.id, 2); + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_float, id_old_w, output.id, 3); + spv_emit(ctx, 5, SpvOpFMul, tid_float, id_2z, id_old_z, id_2); + spv_emit(ctx, 5, SpvOpFSub, tid_float, id_new_z, id_2z, id_old_w); + spv_emit(ctx, 6, SpvOpCompositeInsert, output.tid, id_new_output, id_new_z, output.id, 2); + output.id = id_new_output; +#endif // MOJOSHADER_DEPTH_CLIPPING + + spv_emit(ctx, 3, SpvOpStore, reg->spirv.iddecl, output.id); + spv_emit(ctx, 1, SpvOpReturn); + spv_emit(ctx, 1, SpvOpFunctionEnd); + pop_output(ctx); + + spv_output_name(ctx, id_func, "vs_epilogue"); +#endif // defined(MOJOSHADER_DEPTH_CLIPPING) || defined(MOJOSHADER_FLIP_RENDERTARGET) +#endif // SUPPORT_PROFILE_GLSPIRV +} // spv_emit_vs_main_end + +static void spv_emit_func_lit(Context *ctx) +{ + if (!ctx->spirv.id_func_lit) + return; + + // vec4 LIT(const vec4 src) + // { + // float retval_y, retval_z; + // if (src.x > 0.0) { + // retval_y = src.x; + // if (src.y > 0.0) { + // float power = clamp(src.w, -127.9961, 127.9961); + // retval_z = pow(src.y, power); + // } else { + // retval_z = 0.0; + // } + // } else { + // retval_y = 0.0; + // retval_z = 0.0; + // } + // vec4 retval = vec4(1.0, retval_y, retval_z, 1.0); + // return retval; + // } + + uint32 tid_float = spv_get_type(ctx, STI_FLOAT); + uint32 tid_bool = spv_get_type(ctx, STI_BOOL); + uint32 tid_vec4 = spv_get_type(ctx, STI_VEC4); + uint32 tid_func = spv_get_type(ctx, STI_FUNC_LIT); + uint32 id_func = ctx->spirv.id_func_lit; + uint32 id_src = spv_bumpid(ctx); + uint32 id_block_start = spv_bumpid(ctx); + uint32 id_src_x = spv_bumpid(ctx); + uint32 id_src_x_pos = spv_bumpid(ctx); + uint32 id_0_0 = spv_get_zero(ctx, tid_float); + uint32 id_branch0_true = spv_bumpid(ctx); + uint32 id_src_y = spv_bumpid(ctx); + uint32 id_src_y_pos = spv_bumpid(ctx); + uint32 id_branch1_true = spv_bumpid(ctx); + uint32 id_src_w = spv_bumpid(ctx); + uint32 id_maxp = spv_getscalarf(ctx, 127.9961f); + uint32 id_maxp_neg = spv_getscalarf(ctx, -127.9961f); + uint32 id_power = spv_bumpid(ctx); + uint32 id_pow_result = spv_bumpid(ctx); + uint32 id_branch1_merge = spv_bumpid(ctx); + uint32 id_branch1_result = spv_bumpid(ctx); + uint32 id_branch0_merge = spv_bumpid(ctx); + uint32 id_result_y = spv_bumpid(ctx); + uint32 id_result_z = spv_bumpid(ctx); + uint32 id_1_0 = spv_get_one(ctx, tid_float); + uint32 id_result = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 5, SpvOpFunction, tid_vec4, id_func, SpvFunctionControlMaskNone, tid_func); + spv_emit(ctx, 3, SpvOpFunctionParameter, tid_vec4, id_src); + + // id_block_start + spv_emit(ctx, 2, SpvOpLabel, id_block_start); + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_float, id_src_x, id_src, 0); + spv_emit(ctx, 5, SpvOpFOrdGreaterThan, tid_bool, id_src_x_pos, id_src_x, id_0_0); + spv_emit(ctx, 3, SpvOpSelectionMerge, id_branch0_merge, 0); + spv_emit(ctx, 4, SpvOpBranchConditional, id_src_x_pos, id_branch0_true, id_branch0_merge); + + // id_branch0_true + spv_emit(ctx, 2, SpvOpLabel, id_branch0_true); + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_float, id_src_y, id_src, 1); + spv_emit(ctx, 5, SpvOpFOrdGreaterThan, tid_bool, id_src_y_pos, id_src_y, id_0_0); + spv_emit(ctx, 3, SpvOpSelectionMerge, id_branch1_merge, 0); + spv_emit(ctx, 4, SpvOpBranchConditional, id_src_y_pos, id_branch1_true, id_branch1_merge); + + // id_branch1_true + spv_emit(ctx, 2, SpvOpLabel, id_branch1_true); + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_float, id_src_w, id_src, 3); + spv_emit(ctx, 5 + 3, SpvOpExtInst, + tid_float, id_power, spv_getext(ctx), GLSLstd450FClamp, id_src_w, id_maxp_neg, id_maxp + ); + spv_emit(ctx, 5 + 2, SpvOpExtInst, + tid_float, id_pow_result, spv_getext(ctx), GLSLstd450Pow, id_src_y, id_power + ); + spv_emit(ctx, 2, SpvOpBranch, id_branch1_merge); + + // id_branch1_merge + spv_emit(ctx, 2, SpvOpLabel, id_branch1_merge); + spv_emit(ctx, 7, SpvOpPhi, tid_float, id_branch1_result, + id_pow_result, id_branch1_true, + id_0_0, id_branch0_true + ); + spv_emit(ctx, 2, SpvOpBranch, id_branch0_merge); + + // id_branch0_merge + spv_emit(ctx, 2, SpvOpLabel, id_branch0_merge); + spv_emit(ctx, 7, SpvOpPhi, tid_float, id_result_y, + id_src_x, id_branch1_merge, + id_0_0, id_block_start + ); + spv_emit(ctx, 7, SpvOpPhi, tid_float, id_result_z, + id_branch1_result, id_branch1_merge, + id_0_0, id_block_start + ); + spv_emit(ctx, 3 + 4, SpvOpCompositeConstruct, tid_vec4, id_result, + id_1_0, id_result_y, id_result_z, id_1_0 + ); + spv_emit(ctx, 2, SpvOpReturnValue, id_result); + spv_emit(ctx, 1, SpvOpFunctionEnd); + + pop_output(ctx); + + spv_output_name(ctx, ctx->spirv.id_func_lit, "LIT"); +} // spv_emit_func_lit + +static void spv_emit_func_end(Context *ctx) +{ + push_output(ctx, &ctx->mainline); + +#if SUPPORT_PROFILE_GLSPIRV +#if defined(MOJOSHADER_DEPTH_CLIPPING) || defined(MOJOSHADER_FLIP_RENDERTARGET) + if (ctx->profile_supports_glspirv + && shader_is_vertex(ctx) + && ctx->spirv.id_vs_main_end == 0) + { + ctx->spirv.id_vs_main_end = spv_bumpid(ctx); + uint32 tid_void = spv_get_type(ctx, STI_VOID); + uint32 id_res = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 4, SpvOpFunctionCall, tid_void, id_res, ctx->spirv.id_vs_main_end); + pop_output(ctx); + } // if +#endif // defined(MOJOSHADER_DEPTH_CLIPPING) || defined(MOJOSHADER_FLIP_RENDERTARGET) +#endif // SUPPORT_PROFILE_GLSPIRV + + spv_emit(ctx, 1, SpvOpReturn); + spv_emit(ctx, 1, SpvOpFunctionEnd); + pop_output(ctx); +} // spv_emit_func_end + +static void spv_emit_vpos_glmode(Context *ctx, uint32 id) +{ + // In SM3.0 vPos only has x and y defined, but we should be + // fine to leave the z and w attributes in that + // SpvBuiltInFragCoord gives. + + uint32 tid_float = spv_get_type(ctx, STI_FLOAT); + uint32 tid_vec2 = spv_get_type(ctx, STI_VEC2); + uint32 tid_vec4 = spv_get_type(ctx, STI_VEC4); + uint32 tid_pvec4i = spv_get_type(ctx, STI_PTR_VEC4_I); + uint32 tid_pvec2u = spv_bumpid(ctx); + uint32 tid_pvec4p = spv_get_type(ctx, STI_PTR_VEC4_P); + + uint32 id_var_fragcoord = spv_bumpid(ctx); + uint32 id_var_vposflip = spv_bumpid(ctx); + uint32 id_var_vpos = id; + + uint32 id_fragcoord = spv_bumpid(ctx); + uint32 id_fragcoord_y = spv_bumpid(ctx); + uint32 id_vposflip = spv_bumpid(ctx); + uint32 id_vposflip_x = spv_bumpid(ctx); + uint32 id_vposflip_y = spv_bumpid(ctx); + uint32 id_tmp = spv_bumpid(ctx); + uint32 id_vpos_y = spv_bumpid(ctx); + uint32 id_vpos = spv_bumpid(ctx); + + // vec4 gl_FragCoord = ; + // uniform vec2 vposFlip; + // vec4 ps_vPos = vec4( + // gl_FragCoord.x, + // (gl_FragCoord.y * vposFlip.x) + vposFlip.y, + // gl_FragCoord.z, + // gl_FragCoord.w + // ); + + push_output(ctx, &ctx->mainline_intro); + // Define uniform vec2*. This is the only place that uses it right now. + spv_emit(ctx, 4, SpvOpTypePointer, tid_pvec2u, SpvStorageClassUniformConstant, tid_vec2); + // Define all variables involved. + spv_emit(ctx, 4, SpvOpVariable, tid_pvec4i, id_var_fragcoord, SpvStorageClassInput); + spv_emit(ctx, 4, SpvOpVariable, tid_pvec2u, id_var_vposflip, SpvStorageClassUniformConstant); + spv_emit(ctx, 4, SpvOpVariable, tid_pvec4p, id_var_vpos, SpvStorageClassPrivate); + pop_output(ctx); + + spv_output_builtin(ctx, id_var_fragcoord, SpvBuiltInFragCoord); + spv_output_name(ctx, id_var_vposflip, "vposFlip"); + + // Initialize vPos using vPosFlip and built in FragCoord. + push_output(ctx, &ctx->mainline_top); + spv_emit(ctx, 4, SpvOpLoad, tid_vec4, id_fragcoord, id_var_fragcoord); + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_float, id_fragcoord_y, id_fragcoord, 1); + spv_emit(ctx, 4, SpvOpLoad, tid_vec2, id_vposflip, id_var_vposflip); + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_float, id_vposflip_x, id_vposflip, 0); + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_float, id_vposflip_y, id_vposflip, 1); + spv_emit(ctx, 5, SpvOpFMul, tid_float, id_tmp, id_fragcoord_y, id_vposflip_x); + spv_emit(ctx, 5, SpvOpFAdd, tid_float, id_vpos_y, id_tmp, id_vposflip_y); + spv_emit(ctx, 6, SpvOpCompositeInsert, tid_vec4, id_vpos, id_vpos_y, id_fragcoord, 1); + spv_emit(ctx, 3, SpvOpStore, id_var_vpos, id_vpos); + pop_output(ctx); + + ctx->spirv.id_var_fragcoord = id_var_fragcoord; + ctx->spirv.id_var_vpos = id_var_vpos; + ctx->spirv.patch_table.vpflip.offset = spv_output_location(ctx, id_var_vposflip, ~0u); +} // spv_emit_vpos_glmode + +static void spv_emit_vpos_vkmode(Context *ctx, uint32 id) +{ + // In SM3.0 vPos only has x and y defined, but we should be + // fine to leave the z and w attributes in that + // SpvBuiltInFragCoord gives. + + uint32 tid_vec4 = spv_get_type(ctx, STI_VEC4); + uint32 tid_pvec4i = spv_get_type(ctx, STI_PTR_VEC4_I); + uint32 tid_pvec4p = spv_get_type(ctx, STI_PTR_VEC4_P); + + uint32 id_var_fragcoord = spv_bumpid(ctx); + uint32 id_var_vpos = id; + + uint32 id_fragcoord = spv_bumpid(ctx); + uint32 id_vpos = spv_bumpid(ctx); + + // vec4 gl_FragCoord = ; + // vec4 ps_vPos = gl_FragCoord; + + push_output(ctx, &ctx->mainline_intro); + // Define all variables involved. + spv_emit(ctx, 4, SpvOpVariable, tid_pvec4i, id_var_fragcoord, SpvStorageClassInput); + spv_emit(ctx, 4, SpvOpVariable, tid_pvec4p, id_var_vpos, SpvStorageClassPrivate); + pop_output(ctx); + + spv_output_builtin(ctx, id_var_fragcoord, SpvBuiltInFragCoord); + + // Initialize vPos using built in FragCoord. + push_output(ctx, &ctx->mainline_top); + spv_emit(ctx, 4, SpvOpLoad, tid_vec4, id_fragcoord, id_var_fragcoord); + spv_emit(ctx, 3, SpvOpStore, id_var_vpos, id_fragcoord); + pop_output(ctx); + + ctx->spirv.id_var_fragcoord = id_var_fragcoord; + ctx->spirv.id_var_vpos = id_var_vpos; +} // spv_emit_vpos_vkmode + +static void spv_link_vs_attributes(Context *ctx, uint32 id, + MOJOSHADER_usage usage, int index) +{ + if (usage == MOJOSHADER_USAGE_POSITION && index == 0) + spv_output_builtin(ctx, id, SpvBuiltInPosition); + else if (usage == MOJOSHADER_USAGE_POINTSIZE && index == 0) + { + spv_output_builtin(ctx, id, SpvBuiltInPointSize); + ctx->spirv.patch_table.attrib_offsets[usage][index] = 1; + } // else if + else + spv_output_attrib_location(ctx, id, usage, index); +} // spv_link_vs_attributes + +static void spv_link_ps_attributes(Context *ctx, uint32 id, RegisterType regtype, + MOJOSHADER_usage usage, int index) +{ + switch (regtype) + { + case REG_TYPE_COLOROUT: + // Per KHR_glsl_shader: + // The fragment-stage built-in gl_FragColor, which implies a broadcast to all + // outputs, is not present in SPIR-V. Shaders where writing to gl_FragColor + // is allowed can still write to it, but it only means to write to an output: + // - of the same type as gl_FragColor + // - decorated with location 0 + // - not decorated as a built-in variable. + // There is no implicit broadcast. + spv_output_color_location(ctx, id, index); + break; + case REG_TYPE_INPUT: // v# (MOJOSHADER_USAGE_COLOR aka `oC#` in vertex shader) + spv_output_attrib_location(ctx, id, usage, index); + break; + case REG_TYPE_TEXTURE: // t# (MOJOSHADER_USAGE_TEXCOORD aka `oT#` in vertex shader) + spv_output_attrib_location(ctx, id, MOJOSHADER_USAGE_TEXCOORD, index); + break; + case REG_TYPE_DEPTHOUT: + spv_output_builtin(ctx, id, SpvBuiltInFragDepth); + ctx->spirv.hasdepth = 1; + break; + case REG_TYPE_MISCTYPE: + // inputs + switch ((MiscTypeType)index) + { + case MISCTYPE_TYPE_POSITION: // vPos + { + if (ctx->spirv.mode == SPIRV_MODE_GL) + spv_emit_vpos_glmode(ctx, id); + else + spv_emit_vpos_vkmode(ctx, id); + break; + } // case + + case MISCTYPE_TYPE_FACE: // vFace + { + // The much more wordy equivalent of: + // bool gl_FrontFacing = ; + // vec4 vFace; + // vFace = vec4(gl_FrontFacing ? 1.0 : 0.0); + + uint32 tid_bool = spv_get_type(ctx, STI_BOOL); + uint32 tid_float = spv_get_type(ctx, STI_FLOAT); + uint32 tid_vec4 = spv_get_type(ctx, STI_VEC4); + uint32 tid_pbooli = spv_get_type(ctx, STI_PTR_BOOL_I); + uint32 tid_pvec4p = spv_get_type(ctx, STI_PTR_VEC4_P); + + uint32 id_1_0 = spv_getscalarf(ctx, 1.0f); + uint32 id_n1_0 = spv_getscalarf(ctx, -1.0f); + + uint32 id_var_frontfacing = spv_bumpid(ctx); + uint32 id_var_vface = id; + + uint32 id_frontfacing = spv_bumpid(ctx); + uint32 id_tmp = spv_bumpid(ctx); + uint32 id_vface = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline_intro); + spv_emit(ctx, 4, SpvOpVariable, tid_pbooli, id_var_frontfacing, SpvStorageClassInput); + spv_emit(ctx, 4, SpvOpVariable, tid_pvec4p, id_var_vface, SpvStorageClassPrivate); + pop_output(ctx); + + spv_output_builtin(ctx, id_var_frontfacing, SpvBuiltInFrontFacing); + + push_output(ctx, &ctx->mainline_top); + spv_emit(ctx, 4, SpvOpLoad, tid_bool, id_frontfacing, id_var_frontfacing); + spv_emit(ctx, 6, SpvOpSelect, tid_float, id_tmp, id_frontfacing, id_1_0, id_n1_0); + spv_emit(ctx, 3 + 4, SpvOpCompositeConstruct, tid_vec4, id_vface, id_tmp, id_tmp, id_tmp, id_tmp); + spv_emit(ctx, 3, SpvOpStore, id_var_vface, id_vface); + pop_output(ctx); + + ctx->spirv.id_var_frontfacing = id_var_frontfacing; + ctx->spirv.id_var_vface = id_var_vface; + break; + } // case + } // switch + break; + default: + fail(ctx, "unknown pixel shader attribute register"); + } // switch +} // spv_link_ps_attributes + +static void spv_texbem(Context* ctx, int luminanceCorrection) +{ + DestArgInfo *info = &ctx->dest_arg; + uint32 sampler_idx = info->regnum; + RegisterList *pSReg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, sampler_idx); + RegisterList *pSrc = spv_getreg(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum); + RegisterList *pDst = spv_getreg(ctx, info->regtype, sampler_idx); + + push_output(ctx, &ctx->mainline); + + SpirvResult sampler = spv_loadreg(ctx, pSReg); + SpirvResult src0 = spv_loadreg(ctx, pSrc); + SpirvResult src1 = spv_loadreg(ctx, pDst); + + // = texture( + // , + // vec2( + // (_texbem.x * .x) + (_texbem.z * .y) + .x, + // (_texbem.y * .x) + (_texbem.w * .y) + .y + // ) + // ); + + // Load 2x2 transform matrix from uniform data (stored as vec4). + assert(sampler_idx < 4); + uint32 id_offset = ctx->spirv.sampler_extras[sampler_idx].idtexbem; + if (!id_offset) + { + id_offset = spv_bumpid(ctx); + ctx->spirv.sampler_extras[sampler_idx].idtexbem = id_offset; + } // if + uint32 tid_vec4 = spv_get_type(ctx, STI_VEC4); + uint32 id_pmatrix = spv_access_uniform(ctx, STI_PTR_VEC4_U, REG_TYPE_CONST, id_offset); + SpirvResult matrix; + matrix.tid = tid_vec4; + matrix.id = spv_bumpid(ctx); + spv_emit(ctx, 4, SpvOpLoad, matrix.tid, matrix.id, id_pmatrix); + + // transform src0 using matrix and translate result using src1 + // ie. src0 * matrix + src1 + SpirvResult matrix_xy = spv_swizzle(ctx, matrix, 0x4, 0x3); + SpirvResult matrix_zw = spv_swizzle(ctx, matrix, 0xE, 0x3); + SpirvResult src0_xx = spv_swizzle(ctx, src0, 0x0, 0x3); + SpirvResult src0_yy = spv_swizzle(ctx, src0, 0x5, 0x3); + SpirvResult src1_xy = spv_swizzle(ctx, src1, 0x4, 0x3); + uint32 tid_vec2 = src0_xx.tid; + uint32 id_a = spv_bumpid(ctx); + uint32 id_b = spv_bumpid(ctx); + uint32 id_c = spv_bumpid(ctx); + uint32 id_d = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpFMul, tid_vec2, id_a, matrix_xy.id, src0_xx.id); + spv_emit(ctx, 5, SpvOpFMul, tid_vec2, id_b, matrix_zw.id, src0_yy.id); + spv_emit(ctx, 5, SpvOpFAdd, tid_vec2, id_c, id_a, id_b); + spv_emit(ctx, 5, SpvOpFAdd, tid_vec2, id_d, id_c, src1_xy.id); + + // sample texture + SpirvResult result; + result.tid = tid_vec4; + result.id = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpImageSampleImplicitLod, result.tid, result.id, sampler.id, id_d); + if (luminanceCorrection) + { + uint32 id_l_offset = ctx->spirv.sampler_extras[sampler_idx].idtexbeml; + if (!id_l_offset) + { + id_l_offset = spv_bumpid(ctx); + ctx->spirv.sampler_extras[sampler_idx].idtexbeml = id_l_offset; + } // if + + // = * ((.z * _texbeml.x) + _texbeml.y) + uint32 tid_float = spv_get_type(ctx, STI_FLOAT); + + SpirvResult src0_z = spv_swizzle(ctx, src0, 0x2, 0x1); + uint32 id_l_ptr = spv_access_uniform(ctx, STI_PTR_VEC4_U, REG_TYPE_CONST, id_l_offset); + + SpirvResult l; + l.tid = tid_vec4; + l.id = spv_bumpid(ctx); + + spv_emit(ctx, 4, SpvOpLoad, l.tid, l.id, id_l_ptr); + + SpirvResult l_x = spv_swizzle(ctx, l, 0x0, 0x1); + SpirvResult l_y = spv_swizzle(ctx, l, 0x1, 0x1); + assert(tid_float == l_x.tid); + assert(tid_float == l_y.tid); + assert(tid_float == src0_z.tid); + + uint32 id_e = spv_bumpid(ctx); + uint32 id_f = spv_bumpid(ctx); + uint32 id_ffff = spv_bumpid(ctx); + uint32 id_new = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpFMul, tid_float, id_e, src0_z.id, l_x.id); + spv_emit(ctx, 5, SpvOpFAdd, tid_float, id_f, id_e, l_y.id); + spv_emit(ctx, 3 + 4, SpvOpCompositeConstruct, tid_vec4, id_ffff, + id_f, id_f, id_f, id_f + ); + spv_emit(ctx, 5, SpvOpFMul, tid_vec4, id_new, result.id, id_ffff); + result.id = id_new; + } // if + + pop_output(ctx); + + spv_assign_destarg(ctx, result); +} + +void emit_SPIRV_start(Context *ctx, const char *profilestr) +{ + if (!(shader_is_vertex(ctx) || shader_is_pixel(ctx))) + { + failf(ctx, "Shader type %u unsupported in this profile.", + (uint) ctx->shader_type); + return; + } // if + + memset(&(ctx->spirv), '\0', sizeof(ctx->spirv)); + +#if SUPPORT_PROFILE_GLSPIRV + if (strcmp(profilestr, MOJOSHADER_PROFILE_GLSPIRV) == 0) + { + ctx->profile_supports_glspirv = 1; + ctx->spirv.mode = SPIRV_MODE_GL; + } // if + else +#endif // SUPPORT_PROFILE_GLSPIRV + { + ctx->spirv.mode = SPIRV_MODE_VK; + if (strcmp(profilestr, MOJOSHADER_PROFILE_SPIRV) != 0) + failf(ctx, "Profile '%s' unsupported or unknown.", profilestr); + } // else + + ctx->spirv.idmain = spv_bumpid(ctx); + + // calls spv_getvoid as well + uint32 tid_void = spv_get_type(ctx, STI_VOID); + uint32 tid_func = spv_get_type(ctx, STI_FUNC_VOID); + + // slap the function declaration itself in mainline_top, so we can do type + // declaration in mainline_intro (= before this in the output) + push_output(ctx, &ctx->mainline_top); + spv_emit(ctx, 5, SpvOpFunction, tid_void, ctx->spirv.idmain, SpvFunctionControlMaskNone, tid_func); + spv_emit(ctx, 2, SpvOpLabel, spv_bumpid(ctx)); + pop_output(ctx); + + // also emit the name for the function + spv_output_name(ctx, ctx->spirv.idmain, ctx->mainfn); + + set_output(ctx, &ctx->mainline); +} // emit_SPIRV_start + +void emit_SPIRV_end(Context *ctx) +{ + if (ctx->previous_opcode != OPCODE_RET) + spv_emit_func_end(ctx); +} // emit_SPIRV_end + +void emit_SPIRV_phase(Context *ctx) +{ + // no-op +} // emit_SPIRV_phase + +void emit_SPIRV_global(Context *ctx, RegisterType regtype, int regnum) +{ + RegisterList *r = reglist_find(&ctx->used_registers, regtype, regnum); + + SpvStorageClass sc = SpvStorageClassPrivate; + uint32 tid = 0; + switch (regtype) + { + case REG_TYPE_LABEL: + failf(ctx, "unimplemented regtype %d", regtype); + return; + + case REG_TYPE_LOOP: + // Using SSA id to represent loop counters, instead of a variable. + return; + + case REG_TYPE_PREDICATE: + tid = spv_get_type(ctx, STI_PTR_BVEC4_P); + break; + + case REG_TYPE_ADDRESS: + if (shader_is_vertex(ctx)) + tid = spv_get_type(ctx, STI_PTR_IVEC4_P); + else if (shader_is_pixel(ctx)) // actually REG_TYPE_TEXTURE + { + if (!shader_version_atleast(ctx, 1, 4)) + { + // ps_1_1 texture/address registers work like temporaries. They are initialized + // with tex coords and TEX instruction then reads tex coords from it and writes + // sampling result back into it. Because Input storage class is read-only, we + // create private variable that is initialized to value of input. + + uint32 tid_pvec4_i = spv_get_type(ctx, STI_PTR_VEC4_I); + uint32 tid_pvec4_p = spv_get_type(ctx, STI_PTR_VEC4_P); + uint32 tid_vec4 = spv_get_type(ctx, STI_VEC4); + uint32 id_input_var = spv_bumpid(ctx); + uint32 id_private_var = r->spirv.iddecl; + uint32 id_tmp = spv_bumpid(ctx); + + // Create one Input and one Private variable. Input variable is linked to prev stage. + push_output(ctx, &ctx->mainline_intro); + spv_emit(ctx, 4, SpvOpVariable, tid_pvec4_i, id_input_var, SpvStorageClassInput); + spv_emit(ctx, 4, SpvOpVariable, tid_pvec4_p, id_private_var, SpvStorageClassPrivate); + pop_output(ctx); + spv_link_ps_attributes(ctx, id_input_var, regtype, MOJOSHADER_USAGE_TEXCOORD, regnum); + + // Initialize Private variable with Input variable. + push_output(ctx, &ctx->mainline_top); + spv_emit(ctx, 4, SpvOpLoad, tid_vec4, id_tmp, id_input_var); + spv_emit(ctx, 3, SpvOpStore, id_private_var, id_tmp); + pop_output(ctx); + + // TEX instruction have already been emitted that work with Private variable. + + // Overwrite Private variable with Input variable, so emit_SPIRV_finalize outputs + // OpEntryPoint with correct references to Input and Output variables. + ctx->spirv.id_implicit_input[regnum] = id_input_var; + r->spirv.iddecl = id_input_var; + spv_output_regname(ctx, id_input_var, regtype, regnum); + return; + } // if + tid = spv_get_type(ctx, STI_PTR_VEC4_P); + } // else if + break; + + case REG_TYPE_TEMP: + if (regnum == 0 && shader_is_pixel(ctx) && !shader_version_atleast(ctx, 2, 0)) + { + // Value of r0 is at the end of shader execution is color output. + sc = SpvStorageClassOutput; + tid = spv_get_type(ctx, STI_PTR_VEC4_O); + } + else + tid = spv_get_type(ctx, STI_PTR_VEC4_P); + break; + + default: + fail(ctx, "BUG: Unexpected regtype in emit_SPIRV_global"); + return; + } // switch + + // TODO: If the SSA id for this register is still 0 by this point, that + // means no instructions actually loaded from/stored to this variable... + + if (r->spirv.iddecl == 0) + r->spirv.iddecl = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline_intro); + spv_emit(ctx, 4, SpvOpVariable, tid, r->spirv.iddecl, sc); + pop_output(ctx); + + spv_output_regname(ctx, r->spirv.iddecl, regtype, regnum); +} // emit_SPIRV_global + +void emit_SPIRV_array(Context *ctx, VariableList *var) +{ + var->emit_position = ctx->uniform_float4_count; +} // emit_SPIRV_array + +void emit_SPIRV_const_array(Context *ctx, + const struct ConstantsList *clist, + int base, int size) +{ + int i; + + assert(ctx->spirv.constant_arrays.idvec4 != 0); + + push_output(ctx, &ctx->mainline_intro); + + // FIXME: This code potentially duplicates constants defined using DEF ops. + // FIXME: Multiple constant arrays probably won't work. Are those even possible? + // Maybe it would be better to do this in emit_SPIRV_finalize and use used_registers for it? + uint32 *constituents = (uint32 *)Malloc(ctx, size * sizeof(uint32)); + uint32 tid_constituent = spv_get_type(ctx, STI_VEC4); + for (i = 0; i < size; i++) + { + while (clist->constant.type != MOJOSHADER_UNIFORM_FLOAT) + clist = clist->next; + assert(clist->constant.index == (base + i)); + + uint32 id_x = spv_getscalarf(ctx, clist->constant.value.f[0]); + uint32 id_y = spv_getscalarf(ctx, clist->constant.value.f[1]); + uint32 id_z = spv_getscalarf(ctx, clist->constant.value.f[2]); + uint32 id_w = spv_getscalarf(ctx, clist->constant.value.f[3]); + + uint32 id = spv_bumpid(ctx); + spv_emit(ctx, 3 + 4, SpvOpConstantComposite, tid_constituent, id, id_x, id_y, id_z, id_w); + constituents[i] = id; + + clist = clist->next; + } // for + + uint32 id_array_len = spv_getscalari(ctx, size); + + uint32 tid_array = spv_bumpid(ctx); + spv_emit(ctx, 4, SpvOpTypeArray, tid_array, tid_constituent, id_array_len); + + uint32 id_array = spv_bumpid(ctx); + spv_emit_part(ctx, 3+size, 3, SpvOpConstantComposite, tid_array, id_array); + for (i = 0; i < size; i++) + spv_emit_word(ctx, constituents[i]); + + uint32 tid_parray = spv_bumpid(ctx); + spv_emit(ctx, 4, SpvOpTypePointer, tid_parray, SpvStorageClassPrivate, tid_array); + + uint32 id_array_var = ctx->spirv.constant_arrays.idvec4; + spv_emit(ctx, 5, SpvOpVariable, tid_parray, id_array_var, SpvStorageClassPrivate, id_array); + + Free(ctx, constituents); + pop_output(ctx); +} // emit_SPIRV_const_array + +void emit_SPIRV_uniform(Context *ctx, RegisterType regtype, int regnum, + const VariableList *var) +{ + RegisterList *r = reglist_find(&ctx->uniforms, regtype, regnum); + + // TODO: If the SSA id for this register is still 0 by this point, that means no instructions actually + // loaded from/stored to this variable... + + if (r->spirv.iddecl == 0) + r->spirv.iddecl = spv_bumpid(ctx); + + if (var == NULL) + { + uint32 tid = spv_get_type(ctx, STI_INT); + int offset = 0; + switch (regtype) + { + case REG_TYPE_CONST: + offset = ctx->uniform_float4_count; + break; + + case REG_TYPE_CONSTINT: + offset = ctx->uniform_int4_count; + break; + + case REG_TYPE_CONSTBOOL: + offset = ctx->uniform_bool_count; + break; + + default: + fail(ctx, "BUG: used a uniform we don't know how to define."); + return; + } // switch + + push_output(ctx, &ctx->mainline_intro); + spv_emit(ctx, 4, SpvOpConstant, tid, r->spirv.iddecl, offset); + pop_output(ctx); + + char varname[64]; + get_SPIRV_varname_in_buf(ctx, regtype, regnum, varname, sizeof(varname)); + spv_output_name(ctx, r->spirv.iddecl, varname); + } // if + else + { + if (var->constant) + fail(ctx, "const array not implemented"); + else + { + // Instructions needed to reference this constant before its value was known, so unique + // id had to be generated. Unfortunately, this prevents reusing already emitted + // constants. + assert(var->emit_position != -1); + push_output(ctx, &ctx->mainline_intro); + spv_emit(ctx, 4, SpvOpConstant, spv_get_type(ctx, STI_INT), r->spirv.iddecl, var->emit_position); + pop_output(ctx); + + char varname[64]; + get_SPIRV_varname_in_buf(ctx, regtype, regnum, varname, sizeof(varname)); + spv_output_name(ctx, r->spirv.iddecl, varname); + } // else + } // else +} // emit_SPIRV_uniform + +void emit_SPIRV_sampler(Context *ctx, int stage, TextureType ttype, int texbem) +{ + uint32 type = spv_ptrimage_from_texturetype(ctx, ttype); + + RegisterList *sampler_reg; + // Pre ps_2_0 samplers were not dcl-ed, so we won't find them using spv_getreg(). + if (shader_is_pixel(ctx) && !shader_version_atleast(ctx, 2, 0)) + sampler_reg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, stage); + else + sampler_reg = spv_getreg(ctx, REG_TYPE_SAMPLER, stage); + + uint32 result = sampler_reg->spirv.iddecl; + + push_output(ctx, &ctx->mainline_intro); + spv_emit(ctx, 4, SpvOpVariable, type, result, SpvStorageClassUniformConstant); + if (texbem) // This sampler used a ps_1_1 TEXBEM opcode? + { + uint32 tid_int = spv_get_type(ctx, STI_INT); + uint32 id_texbem = ctx->spirv.sampler_extras[stage].idtexbem; + uint32 id_texbeml = ctx->spirv.sampler_extras[stage].idtexbeml; + const int offset = ctx->uniform_float4_count; + ctx->uniform_float4_count += 2; + if (id_texbem) + spv_emit(ctx, 4, SpvOpConstant, tid_int, id_texbem, offset); + if (id_texbeml) + spv_emit(ctx, 4, SpvOpConstant, tid_int, id_texbeml, offset + 1); + } // if + pop_output(ctx); + + // hnn: specify uniform location for SPIR-V shaders (required per gl_arb_spirv spec) + spv_output_sampler_binding(ctx, result, sampler_reg->regnum); + + if (ctx->spirv.mode == SPIRV_MODE_GL) + { + assert(sampler_reg->regnum < STATICARRAYLEN(ctx->spirv.patch_table.samplers)); + uint32 location_offset = spv_output_location(ctx, result, ~0u); + ctx->spirv.patch_table.samplers[sampler_reg->regnum].offset = location_offset; + } + + spv_output_regname(ctx, result, REG_TYPE_SAMPLER, stage); +} // emit_SPIRV_sampler + +void emit_SPIRV_attribute(Context *ctx, RegisterType regtype, int regnum, + MOJOSHADER_usage usage, int index, int wmask, + int flags) +{ + uint32 tid; + RegisterList *r = spv_getreg(ctx, regtype, regnum); + + ctx->spirv.inoutcount += 1; + + spv_output_regname(ctx, r->spirv.iddecl, regtype, regnum); + + if (shader_is_vertex(ctx)) + { + // pre-vs3 output registers. + // these don't ever happen in DCL opcodes, I think. Map to vs_3_* + // output registers. + if (!shader_version_atleast(ctx, 3, 0)) + { + if (regtype == REG_TYPE_RASTOUT) + { + regtype = REG_TYPE_OUTPUT; + index = regnum; + switch ((const RastOutType) regnum) + { + case RASTOUT_TYPE_POSITION: + usage = MOJOSHADER_USAGE_POSITION; + break; + case RASTOUT_TYPE_FOG: + usage = MOJOSHADER_USAGE_FOG; + break; + case RASTOUT_TYPE_POINT_SIZE: + usage = MOJOSHADER_USAGE_POINTSIZE; + break; + } // switch + } // if + + else if (regtype == REG_TYPE_ATTROUT) + { + regtype = REG_TYPE_OUTPUT; + usage = MOJOSHADER_USAGE_COLOR; + index = regnum; + } // else if + + else if (regtype == REG_TYPE_TEXCRDOUT) + { + regtype = REG_TYPE_OUTPUT; + usage = MOJOSHADER_USAGE_TEXCOORD; + index = regnum; + } // else if + } // if + assert(r->usage == MOJOSHADER_USAGE_UNKNOWN); + r->usage = usage; + + switch (regtype) + { + case REG_TYPE_INPUT: + { + ctx->spirv.patch_table.tid_vec4_p = spv_get_type(ctx, STI_PTR_VEC4_I); + ctx->spirv.patch_table.tid_ivec4_p = spv_get_type(ctx, STI_PTR_IVEC4_I); + ctx->spirv.patch_table.tid_uvec4_p = spv_get_type(ctx, STI_PTR_UVEC4_I); + ctx->spirv.patch_table.tid_vec4 = spv_get_type(ctx, STI_VEC4); + ctx->spirv.patch_table.tid_ivec4 = spv_get_type(ctx, STI_IVEC4); + ctx->spirv.patch_table.tid_uvec4 = spv_get_type(ctx, STI_UVEC4); + + push_output(ctx, &ctx->mainline_intro); + tid = spv_get_type(ctx, STI_PTR_VEC4_I); + spv_emit(ctx, 4, SpvOpVariable, tid, r->spirv.iddecl, SpvStorageClassInput); + pop_output(ctx); + + ctx->spirv.patch_table.attrib_type_offsets[usage][index] = (buffer_size(ctx->mainline_intro) >> 2) - 3; + + // hnn: generate location decorators for the input + spv_output_location(ctx, r->spirv.iddecl, regnum); + break; + } + + case REG_TYPE_OUTPUT: + { + push_output(ctx, &ctx->mainline_intro); + SpirvTypeIdx sti = STI_PTR_VEC4_O; + if (usage == MOJOSHADER_USAGE_POINTSIZE + || usage == MOJOSHADER_USAGE_FOG) + { + sti = STI_PTR_FLOAT_O; + } // if + + tid = spv_get_type(ctx, sti); + spv_emit(ctx, 4, SpvOpVariable, tid, r->spirv.iddecl, SpvStorageClassOutput); + pop_output(ctx); + + spv_link_vs_attributes(ctx, r->spirv.iddecl, usage, index); + break; + } // case + + default: + fail(ctx, "unknown vertex shader attribute register"); + } // switch + } // if + + else if (shader_is_pixel(ctx)) + { + // samplers DCLs get handled in emit_SPIRV_sampler(). + + if (flags & MOD_CENTROID) // !!! FIXME + { + failf(ctx, "centroid unsupported in %s profile", ctx->profile->name); + return; + } // if + + switch (regtype) + { + case REG_TYPE_COLOROUT: + spv_link_ps_attributes(ctx, r->spirv.iddecl, regtype, usage, regnum); + push_output(ctx, &ctx->mainline_intro); + tid = spv_get_type(ctx, STI_PTR_VEC4_O); + spv_emit(ctx, 4, SpvOpVariable, tid, r->spirv.iddecl, SpvStorageClassOutput); + pop_output(ctx); + break; + case REG_TYPE_DEPTHOUT: + // maps to BuiltIn FragDepth + spv_link_ps_attributes(ctx, r->spirv.iddecl, regtype, usage, index); + push_output(ctx, &ctx->mainline_intro); + tid = spv_get_type(ctx, STI_PTR_FLOAT_O); + spv_emit(ctx, 4, SpvOpVariable, tid, r->spirv.iddecl, SpvStorageClassOutput); + pop_output(ctx); + break; + case REG_TYPE_MISCTYPE: + assert((MiscTypeType)regnum == MISCTYPE_TYPE_FACE || (MiscTypeType)regnum == MISCTYPE_TYPE_POSITION); + // SpvBuiltInFrontFacing is a input bool, and for the DX bytecode + // we need to map it to a float that's either -1.0 or 1.0. + // SpvBuiltInFragCoord needs to be modified using vposFlip uniform + // to match vPos. + // Both of these take place in spv_link_ps_attributes() so don't + // create an input variable for it here. + spv_link_ps_attributes(ctx, r->spirv.iddecl, regtype, usage, regnum); + break; + + case REG_TYPE_TEXTURE: + case REG_TYPE_INPUT: + // ps_1_1 is dealt with in emit_SPIRV_global(). + if (usage != MOJOSHADER_USAGE_TEXCOORD || shader_version_atleast(ctx, 1, 4)) + { + if (usage == MOJOSHADER_USAGE_TEXCOORD && index == 0) + { + // This can be either BuiltInPointCoord (vec2) or normal TEXCOORD0 input (vec4). + // To determine correct type, we need to wait until link-time when we can see + // vertex shader outputs and then patch in correct types. To avoid having to + // fix all loads from the input variable, we never access it directly, but + // instead go through private variable that is always vec4. + // Here we generate input and private variables and helper code that gets + // patched at link-time. See SpirvPatchTable for details on patching. + SpirvPatchTable* table = &ctx->spirv.patch_table; + + uint32 tid_pvec2i = spv_get_type(ctx, STI_PTR_VEC2_I); + uint32 tid_pvec4i = spv_get_type(ctx, STI_PTR_VEC4_I); + uint32 tid_pvec4p = spv_get_type(ctx, STI_PTR_VEC4_P); + uint32 tid_vec2 = spv_get_type(ctx, STI_VEC2); + uint32 tid_vec4 = spv_get_type(ctx, STI_VEC4); + + table->tid_pvec2i = tid_pvec2i; + table->tid_vec2 = tid_vec2; + table->tid_pvec4i = tid_pvec4i; + table->tid_vec4 = tid_vec4; + + push_output(ctx, &ctx->mainline_intro); + ctx->spirv.id_var_texcoord0_private = r->spirv.iddecl; + ctx->spirv.id_var_texcoord0_input = spv_bumpid(ctx); + table->pointcoord_var_offset = buffer_size(ctx->mainline_intro) >> 2; + spv_emit(ctx, 4, SpvOpVariable, tid_pvec4i, ctx->spirv.id_var_texcoord0_input, SpvStorageClassInput); + spv_emit(ctx, 4, SpvOpVariable, tid_pvec4p, ctx->spirv.id_var_texcoord0_private, SpvStorageClassPrivate); + pop_output(ctx); + + spv_link_ps_attributes(ctx, ctx->spirv.id_var_texcoord0_input, regtype, usage, index); + spv_output_name(ctx, ctx->spirv.id_var_texcoord0_input, "ps_PointCoordOrTexCoord0"); + + push_output(ctx, &ctx->mainline_top); + uint32 id_loaded = spv_bumpid(ctx); + uint32 id_shuffled = spv_bumpid(ctx); + table->pointcoord_load_offset = buffer_size(ctx->mainline_top) >> 2; + spv_emit(ctx, 4, SpvOpLoad, tid_vec4, id_loaded, ctx->spirv.id_var_texcoord0_input); + spv_emit(ctx, 9, SpvOpVectorShuffle, tid_vec4, id_shuffled, id_loaded, id_loaded, 0, 1, 2, 3); + spv_emit(ctx, 3, SpvOpStore, ctx->spirv.id_var_texcoord0_private, id_shuffled); + pop_output(ctx); + } // if + else + { + spv_link_ps_attributes(ctx, r->spirv.iddecl, regtype, usage, index); + push_output(ctx, &ctx->mainline_intro); + tid = spv_get_type(ctx, STI_PTR_VEC4_I); + spv_emit(ctx, 4, SpvOpVariable, tid, r->spirv.iddecl, SpvStorageClassInput); + pop_output(ctx); + } // else + } // if + break; + default: + fail(ctx, "unknown pixel shader attribute register"); + } // switch + } // else if + + else + fail(ctx, "Unknown shader type"); // state machine should catch this. +} // emit_SPIRV_attribute + +static void spv_emit_uniform_constant_array(Context *ctx, + const RegisterType regtype, + const int size, uint32 id_var, + uint32 id_type_base, + uint32* dst_location_offset) +{ + assert(size > 0); + assert(id_var != 0); + assert(ctx->spirv.mode == SPIRV_MODE_GL); + + uint32 id_size = spv_getscalari(ctx, size); + uint32 id_type = spv_bumpid(ctx); + uint32 id_type_ptr = spv_bumpid(ctx); + push_output(ctx, &ctx->mainline_intro); + spv_emit(ctx, 4, SpvOpTypeArray, id_type, id_type_base, id_size); + spv_emit(ctx, 4, SpvOpTypePointer, id_type_ptr, SpvStorageClassUniformConstant, id_type); + spv_emit(ctx, 4, SpvOpVariable, id_type_ptr, id_var, SpvStorageClassUniformConstant); + pop_output(ctx); + + char buf[64]; + spv_get_uniform_array_varname(ctx, regtype, buf, sizeof(buf)); + spv_output_name(ctx, id_var, buf); + + *dst_location_offset = spv_output_location(ctx, id_var, ~0u); +} // spv_emit_uniform_constant_array + +void emit_SPIRV_finalize(Context *ctx) +{ + size_t i, j, k, max; + + /* The generator's magic number, this could be registered with Khronos + * if we wanted to. 0 is fine though, so use that for now. */ + uint32 genmagic = 0x00000000; + + /* Vertex shader main() function may need to do some position adjustments. However, + position may be written in subroutines, so we can't write position adjust code + at the end of main(), because output register might not be in ctx->used_registers + yet. Instead, we do adjust in a subroutine generated here and called at the + end of main(). */ + spv_emit_vs_main_end(ctx); + spv_emit_func_lit(ctx); + + uint8 emit_vec4 = ctx->uniform_float4_count > 0 && ctx->spirv.uniform_arrays.idvec4; + uint8 emit_ivec4 = ctx->uniform_int4_count > 0 && ctx->spirv.uniform_arrays.idivec4; + uint8 emit_bool = ctx->uniform_bool_count > 0 && ctx->spirv.uniform_arrays.idbool; + uint8 emit_any = emit_vec4 | emit_ivec4 | emit_bool; + if (ctx->spirv.mode == SPIRV_MODE_GL) + { + if (emit_vec4) + spv_emit_uniform_constant_array(ctx, REG_TYPE_CONST, + ctx->uniform_float4_count, + ctx->spirv.uniform_arrays.idvec4, + spv_get_type(ctx, STI_VEC4), + &ctx->spirv.patch_table.array_vec4.offset + ); + + if (emit_ivec4) + spv_emit_uniform_constant_array(ctx, REG_TYPE_CONSTINT, + ctx->uniform_int4_count, + ctx->spirv.uniform_arrays.idivec4, + spv_get_type(ctx, STI_IVEC4), + &ctx->spirv.patch_table.array_ivec4.offset + ); + + if (emit_bool) + spv_emit_uniform_constant_array(ctx, REG_TYPE_CONSTBOOL, + ctx->uniform_bool_count, + ctx->spirv.uniform_arrays.idbool, + spv_get_type(ctx, STI_INT), + &ctx->spirv.patch_table.array_bool.offset + ); + } // if + else if (emit_any) + { + assert(ctx->spirv.mode == SPIRV_MODE_VK); + uint32 member_tid[3]; + uint32 member_offset[3]; + uint32 member_count = 0; + uint32 struct_size = 0; + + uint32 tid_arr_idx = spv_get_type(ctx, STI_INT); + + push_output(ctx, &ctx->mainline_intro); + + if (emit_vec4) + { + int size = ctx->uniform_float4_count; + uint32 id_size = spv_getscalari(ctx, size); + uint32 tid_type_base = spv_get_type(ctx, STI_VEC4); + uint32 tid_array = spv_bumpid(ctx); + spv_emit(ctx, 4, SpvOpTypeArray, tid_array, tid_type_base, id_size); + uint32 i = member_count++; + spv_emit(ctx, 4, SpvOpConstant, tid_arr_idx, ctx->spirv.uniform_arrays.idvec4, i); + member_tid[i] = tid_array; + member_offset[i] = struct_size; + struct_size += size * 16; + } // if + + if (emit_ivec4) + { + int size = ctx->uniform_int4_count; + uint32 id_size = spv_getscalari(ctx, size); + uint32 tid_type_base = spv_get_type(ctx, STI_IVEC4); + uint32 tid_array = spv_bumpid(ctx); + spv_emit(ctx, 4, SpvOpTypeArray, tid_array, tid_type_base, id_size); + uint32 i = member_count++; + spv_emit(ctx, 4, SpvOpConstant, tid_arr_idx, ctx->spirv.uniform_arrays.idivec4, i); + member_tid[i] = tid_array; + member_offset[i] = struct_size; + struct_size += size * 16; + } // if + + if (emit_bool) + { + int size = ctx->uniform_bool_count; + uint32 id_size = spv_getscalari(ctx, size); + uint32 tid_type_base = spv_get_type(ctx, STI_INT); + uint32 tid_array = spv_bumpid(ctx); + spv_emit(ctx, 4, SpvOpTypeArray, tid_array, tid_type_base, id_size); + uint32 i = member_count++; + spv_emit(ctx, 4, SpvOpConstant, tid_arr_idx, ctx->spirv.uniform_arrays.idbool, i); + member_tid[i] = tid_array; + member_offset[i] = struct_size; + struct_size += size * 16; + } // if + + uint32 tid_struct = spv_bumpid(ctx); + uint32 tid_pstruct = spv_bumpid(ctx); + uint32 id_pstruct = ctx->spirv.id_uniform_block; + spv_emit_part(ctx, 2 + member_count, 2, SpvOpTypeStruct, tid_struct); + for (i = 0; i < member_count; i++) + spv_emit_word(ctx, member_tid[i]); + spv_emit(ctx, 4, SpvOpTypePointer, tid_pstruct, SpvStorageClassUniform, tid_struct); + spv_emit(ctx, 4, SpvOpVariable, tid_pstruct, id_pstruct, SpvStorageClassUniform); + + pop_output(ctx); + + char buf[64]; + snprintf(buf, sizeof(buf), "%s_uniforms", ctx->shader_type_str); + spv_output_name(ctx, id_pstruct, buf); + + uint32 set = shader_is_vertex(ctx) ? MOJOSHADER_SPIRV_VS_UNIFORM_SET + : MOJOSHADER_SPIRV_PS_UNIFORM_SET; + push_output(ctx, &ctx->helpers); + spv_emit(ctx, 3+0, SpvOpDecorate, tid_struct, SpvDecorationBlock); + spv_emit(ctx, 3+1, SpvOpDecorate, id_pstruct, SpvDecorationDescriptorSet, set); + spv_emit(ctx, 3+1, SpvOpDecorate, id_pstruct, SpvDecorationBinding, 0); + + for (uint32 i = 0; i < member_count; i++) + { + spv_emit(ctx, 3+1, SpvOpDecorate, member_tid[i], SpvDecorationArrayStride, 16); + spv_emit(ctx, 4+1, SpvOpMemberDecorate, tid_struct, i, SpvDecorationOffset, member_offset[i]); + } // for + + pop_output(ctx); + } // else if + + push_output(ctx, &ctx->preflight); + + spv_emit_word(ctx, SpvMagicNumber); + spv_emit_word(ctx, SpvVersion); + spv_emit_word(ctx, genmagic); + // "Bound: where all s in this module are guaranteed to satisfy 0 < id < Bound" + // `idmax` holds the last id that was given out, so we need to emit `idmax + 1` + spv_emit_word(ctx, ctx->spirv.idmax + 1); + spv_emit_word(ctx, 0); + + spv_emit(ctx, 2, SpvOpCapability, SpvCapabilityShader); + + // only non-zero when actually needed + if (ctx->spirv.idext) + { + const char *extstr = "GLSL.std.450"; + spv_emit_part(ctx, 2 + spv_strlen(extstr), 2, SpvOpExtInstImport, ctx->spirv.idext); + spv_emit_str(ctx, extstr); + } // if + + spv_emit(ctx, 3, SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelSimple); + + assert(shader_is_vertex(ctx) || shader_is_pixel(ctx)); + SpvExecutionModel model = SpvExecutionModelVertex; + if (shader_is_pixel(ctx)) + model = SpvExecutionModelFragment; + + /* 3 is for opcode + exec. model + idmain */ + uint32 inoutcount = ctx->spirv.inoutcount; + + uint32 implicit_input_count = sizeof(ctx->spirv.id_implicit_input) / sizeof(uint32); + if (shader_is_pixel(ctx)) + { + if (!shader_version_atleast(ctx, 1, 4)) + { + for (uint32 i = 0; i < implicit_input_count; i++) + { + if (ctx->spirv.id_implicit_input[i]) + inoutcount += 1; + } // for + } // if + + if (!shader_version_atleast(ctx, 2, 0)) + inoutcount += 1; + } // if + + spv_emit_part(ctx, 3 + spv_strlen(ctx->mainfn) + inoutcount, 3, SpvOpEntryPoint, + model, ctx->spirv.idmain + ); + spv_emit_str(ctx, ctx->mainfn); + + RegisterList *p = &ctx->attributes, *r = NULL; + // !!! FIXME: The first element of the list is always empty and I don't know why! + p = p->next; + while (p) + { + r = spv_getreg(ctx, p->regtype, p->regnum); + if (r) + { + if (r->spirv.iddecl == ctx->spirv.id_var_vpos) + spv_emit_word(ctx, ctx->spirv.id_var_fragcoord); + else if (r->spirv.iddecl == ctx->spirv.id_var_vface) + spv_emit_word(ctx, ctx->spirv.id_var_frontfacing); + else if (r->spirv.iddecl == ctx->spirv.id_var_texcoord0_private) + spv_emit_word(ctx, ctx->spirv.id_var_texcoord0_input); + else + spv_emit_word(ctx, r->spirv.iddecl); + } // if + else + { + char varname[64]; + get_SPIRV_varname_in_buf(ctx, p->regtype, p->regnum, varname, sizeof (varname)); + failf( + ctx, + "missing attribute register %s (rt=%u, rn=%u, u=%u)", + varname, p->regtype, p->regnum, p->usage + ); + } // else + p = p->next; + } // while + + // only applies to pixel shaders + if (shader_is_pixel(ctx)) + { + if (!shader_version_atleast(ctx, 1, 4)) + { + for (uint32 i = 0; i < implicit_input_count; i++) + { + uint32 id = ctx->spirv.id_implicit_input[i]; + if (id) + spv_emit_word(ctx, id); + } // for + } // if + + if (!shader_version_atleast(ctx, 2, 0)) + { + // r0 is used as color output. + r = spv_getreg(ctx, REG_TYPE_TEMP, 0); + spv_emit_word(ctx, r->spirv.iddecl); + } // if + + // vk semantics = default origin is upper left + // gl semantics = default origin is lower left + spv_emit(ctx, 3, SpvOpExecutionMode, ctx->spirv.idmain, SpvExecutionModeOriginUpperLeft); + + // This must be explicitly marked when FragDepth is in use! + if (ctx->spirv.hasdepth) + spv_emit(ctx, 3, SpvOpExecutionMode, ctx->spirv.idmain, SpvExecutionModeDepthReplacing); + } // if + + pop_output(ctx); + + // Generate final patch table. + + uint32 base_offset = 0; + if (ctx->preflight) base_offset += buffer_size(ctx->preflight); + if (ctx->globals) base_offset += buffer_size(ctx->globals); + if (ctx->inputs) base_offset += buffer_size(ctx->inputs); + if (ctx->outputs) base_offset += buffer_size(ctx->outputs); + base_offset >>= 2; + + int32 location_count = 0; + SpirvPatchTable* table = &ctx->spirv.patch_table; + if (table->vpflip.offset) + { + table->vpflip.offset += base_offset; + table->vpflip.location = location_count; + location_count += 1; + } // if + else + table->vpflip.location = -1; + + if (table->array_vec4.offset) + { + table->array_vec4.offset += base_offset; + table->array_vec4.location = location_count; + location_count += ctx->uniform_float4_count; + } // if + else + table->array_vec4.location = -1; + + if (table->array_ivec4.offset) + { + table->array_ivec4.offset += base_offset; + table->array_ivec4.location = location_count; + location_count += ctx->uniform_int4_count; + } // if + else + table->array_ivec4.location = -1; + + if (table->array_bool.offset) + { + table->array_bool.offset += base_offset; + table->array_bool.location = location_count; + location_count += ctx->uniform_bool_count; + } // if + else + table->array_bool.location = -1; + + for (i = 0, max = STATICARRAYLEN(table->samplers); i < max; i++) + { + SpirvPatchEntry* entry = &table->samplers[i]; + if (entry->offset) + { + entry->offset += base_offset; + entry->location = location_count; + location_count++; + } // if + else + entry->location = -1; + } // for + + table->location_count = location_count; + + for (i = 0; i < MOJOSHADER_USAGE_TOTAL; i++) + for (j = 0; j < 16; j++) + if (table->attrib_offsets[i][j]) + table->attrib_offsets[i][j] += base_offset; + for (i = 0; i < 16; i++) + if (table->output_offsets[i]) + table->output_offsets[i] += base_offset; + + base_offset <<= 2; + if (ctx->helpers) base_offset += buffer_size(ctx->helpers); + if (ctx->subroutines) base_offset += buffer_size(ctx->subroutines); + base_offset >>= 2; + + if (table->pointcoord_var_offset) + table->pointcoord_var_offset += base_offset; + + for (i = 0; i < MOJOSHADER_USAGE_TOTAL; i++) + for (j = 0; j < 16; j++) + if (table->attrib_type_offsets[i][j]) + table->attrib_type_offsets[i][j] += base_offset; + + base_offset <<= 2; + if (ctx->mainline_intro) base_offset += buffer_size(ctx->mainline_intro); + if (ctx->mainline_arguments) base_offset += buffer_size(ctx->mainline_arguments); + base_offset >>= 2; + + if (table->pointcoord_load_offset) + table->pointcoord_load_offset += base_offset; + + base_offset <<= 2; + if (ctx->mainline_top) base_offset += buffer_size(ctx->mainline_top); + base_offset >>= 2; + + for (i = 0; i < MOJOSHADER_USAGE_TOTAL; i++) + for (j = 0; j < 16; j++) + if (table->attrib_type_offsets[i][j]) + for (k = 0; k < table->attrib_type_load_offsets[i][j].num_loads; k++) + { + table->attrib_type_load_offsets[i][j].load_types[k] += base_offset; + table->attrib_type_load_offsets[i][j].load_opcodes[k] += base_offset; + } // for + + push_output(ctx, &ctx->postflight); + buffer_append(ctx->output, &ctx->spirv.patch_table, sizeof(ctx->spirv.patch_table)); + pop_output(ctx); + + spv_componentlist_free(ctx, ctx->spirv.cl.f.next); + spv_componentlist_free(ctx, ctx->spirv.cl.i.next); + spv_componentlist_free(ctx, ctx->spirv.cl.u.next); +} // emit_SPIRV_finalize + +void emit_SPIRV_NOP(Context *ctx) +{ + // no-op is a no-op. :) + // TODO: (hnn) SPIR-V has OpNop :O +} // emit_SPIRV_NOP + +void emit_SPIRV_DEF(Context *ctx) +{ + RegisterList *rl; + uint32 val0, val1, val2, val3, idv4; + const float *raw = (const float *) ctx->dwords; + + rl = spv_getreg(ctx, ctx->dest_arg.regtype, ctx->dest_arg.regnum); + rl->spirv.iddecl = spv_bumpid(ctx); + rl->spirv.is_ssa = 1; + + val0 = spv_getscalarf(ctx, raw[0]); + val1 = spv_getscalarf(ctx, raw[1]); + val2 = spv_getscalarf(ctx, raw[2]); + val3 = spv_getscalarf(ctx, raw[3]); + + idv4 = spv_get_type(ctx, STI_VEC4); + + push_output(ctx, &ctx->mainline_intro); + spv_emit(ctx, 3 + 4, SpvOpConstantComposite, idv4, rl->spirv.iddecl, val0, val1, val2, val3); + pop_output(ctx); +} // emit_SPIRV_DEF + +void emit_SPIRV_DEFI(Context *ctx) +{ + RegisterList *rl; + uint32 val0, val1, val2, val3, idiv4; + const int *raw = (const int *) ctx->dwords; + + rl = spv_getreg(ctx, ctx->dest_arg.regtype, ctx->dest_arg.regnum); + rl->spirv.iddecl = spv_bumpid(ctx); + rl->spirv.is_ssa = 1; + + val0 = spv_getscalari(ctx, raw[0]); + val1 = spv_getscalari(ctx, raw[1]); + val2 = spv_getscalari(ctx, raw[2]); + val3 = spv_getscalari(ctx, raw[3]); + + idiv4 = spv_get_type(ctx, STI_IVEC4); + + push_output(ctx, &ctx->mainline_intro); + spv_emit(ctx, 3 + 4, SpvOpConstantComposite, idiv4, rl->spirv.iddecl, val0, val1, val2, val3); + pop_output(ctx); +} // emit_SPIRV_DEFI + +void emit_SPIRV_DEFB(Context *ctx) +{ + RegisterList *rl = spv_getreg(ctx, ctx->dest_arg.regtype, ctx->dest_arg.regnum); + rl->spirv.iddecl = ctx->dwords[0] ? spv_gettrue(ctx) : spv_getfalse(ctx); + rl->spirv.is_ssa = 1; +} // emit_SPIRV_DEFB + +void emit_SPIRV_DCL(Context *ctx) +{ + // state_DCL handles checking if the registers are valid for this + // instruction, and collecting samplers and attribs + RegisterList *reg = spv_getreg(ctx, ctx->dest_arg.regtype, ctx->dest_arg.regnum); + + // This id will be assigned to in emit_SPIRV_attribute, but + // emit_SPIRV_attribute is called after instructions are emitted, + // so we generate the id here so it can be used in instructions + reg->spirv.iddecl = spv_bumpid(ctx); +} // emit_SPIRV_DCL + +static void emit_SPIRV_dotproduct(Context *ctx, SpirvResult src0, SpirvResult src1) +{ + SpirvResult result; + + assert(src0.tid == src1.tid); + + result.tid = spv_get_type(ctx, STI_FLOAT); + result.id = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 5, SpvOpDot, result.tid, result.id, src0.id, src1.id); + + // Broadcast scalar result across all channels of a vec4 + result.tid = spv_get_type(ctx, STI_VEC4); + result.id = spv_vectorbroadcast(ctx, result.tid, result.id); + pop_output(ctx); + + spv_assign_destarg(ctx, result); +} // emit_SPIRV_dotproduct + +void emit_SPIRV_DP4(Context *ctx) +{ + SpirvResult src0 = spv_load_srcarg_full(ctx, 0); + SpirvResult src1 = spv_load_srcarg_full(ctx, 1); + + emit_SPIRV_dotproduct(ctx, src0, src1); +} // emit_SPIRV_DP4 + +void emit_SPIRV_DP3(Context *ctx) +{ + SpirvResult src0 = spv_load_srcarg(ctx, 0, 0x7); + SpirvResult src1 = spv_load_srcarg(ctx, 1, 0x7); + + emit_SPIRV_dotproduct(ctx, src0, src1); +} // emit_SPIRV_DP3 + +static void spv_emit_begin_ds(Context *ctx, SpirvResult* dst, SpirvResult* src) +{ + *src = spv_load_srcarg_full(ctx, 0); + dst->tid = spv_get_type(ctx, STI_VEC4); + dst->id = spv_bumpid(ctx); + push_output(ctx, &ctx->mainline); +} // spv_emit_begin_ds + +static void spv_emit_begin_dss(Context *ctx, SpirvResult* dst, SpirvResult* src0, SpirvResult* src1) +{ + *src0 = spv_load_srcarg_full(ctx, 0); + *src1 = spv_load_srcarg_full(ctx, 1); + dst->tid = spv_get_type(ctx, STI_VEC4); + dst->id = spv_bumpid(ctx); + push_output(ctx, &ctx->mainline); +} // spv_emit_begin_dss + +static void spv_emit_begin_dsss(Context *ctx, SpirvResult* dst, + SpirvResult* src0, SpirvResult* src1, SpirvResult* src2) +{ + *src0 = spv_load_srcarg_full(ctx, 0); + *src1 = spv_load_srcarg_full(ctx, 1); + *src2 = spv_load_srcarg_full(ctx, 2); + dst->tid = spv_get_type(ctx, STI_VEC4); + dst->id = spv_bumpid(ctx); + push_output(ctx, &ctx->mainline); +} // spv_emit_begin_dsss + +static void spv_emit_end(Context *ctx, SpirvResult dst) +{ + pop_output(ctx); + spv_assign_destarg(ctx, dst); +} // spv_emit_end + +static SpirvTexm3x3SetupResult spv_texm3x3_setup(Context *ctx) +{ + SpirvTexm3x3SetupResult result; + + DestArgInfo *pDstInfo = &ctx->dest_arg; + + RegisterList *pSrc0 = spv_getreg(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst0); + RegisterList *pSrc1 = spv_getreg(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src0); + RegisterList *pSrc2 = spv_getreg(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_dst1); + RegisterList *pSrc3 = spv_getreg(ctx, REG_TYPE_TEXTURE, ctx->texm3x3pad_src1); + RegisterList *pSrc4 = spv_getreg(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum); + RegisterList *pDst = spv_getreg(ctx, pDstInfo->regtype, pDstInfo->regnum); + + SpirvResult src0 = spv_loadreg(ctx, pSrc0); + SpirvResult src1 = spv_loadreg(ctx, pSrc1); + SpirvResult src2 = spv_loadreg(ctx, pSrc2); + SpirvResult src3 = spv_loadreg(ctx, pSrc3); + SpirvResult src4 = spv_loadreg(ctx, pSrc4); + SpirvResult dst = spv_loadreg(ctx, pDst); + + result.id_dst_pad0 = src0.id; + result.id_dst_pad1 = src2.id; + result.id_dst = dst.id; + + uint32 tid_float = spv_get_type(ctx, STI_FLOAT); + uint32 tid_vec3 = spv_get_type(ctx, STI_VEC3); + + uint32 id_src0_xyz = spv_bumpid(ctx); + uint32 id_src1_xyz = spv_bumpid(ctx); + uint32 id_src2_xyz = spv_bumpid(ctx); + uint32 id_src3_xyz = spv_bumpid(ctx); + uint32 id_src4_xyz = spv_bumpid(ctx); + uint32 id_dst_xyz = spv_bumpid(ctx); + uint32 id_res_x = spv_bumpid(ctx); + uint32 id_res_y = spv_bumpid(ctx); + uint32 id_res_z = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline); + + spv_emit(ctx, 5 + 3, SpvOpVectorShuffle, tid_vec3, id_src0_xyz, src0.id, src0.id, 0, 1, 2); + spv_emit(ctx, 5 + 3, SpvOpVectorShuffle, tid_vec3, id_src1_xyz, src1.id, src1.id, 0, 1, 2); + spv_emit(ctx, 5 + 3, SpvOpVectorShuffle, tid_vec3, id_src2_xyz, src2.id, src2.id, 0, 1, 2); + spv_emit(ctx, 5 + 3, SpvOpVectorShuffle, tid_vec3, id_src3_xyz, src3.id, src3.id, 0, 1, 2); + spv_emit(ctx, 5 + 3, SpvOpVectorShuffle, tid_vec3, id_src4_xyz, src4.id, src4.id, 0, 1, 2); + spv_emit(ctx, 5 + 3, SpvOpVectorShuffle, tid_vec3, id_dst_xyz, dst.id, dst.id, 0, 1, 2); + + spv_emit(ctx, 5, SpvOpDot, tid_float, id_res_x, id_src0_xyz, id_src1_xyz); + spv_emit(ctx, 5, SpvOpDot, tid_float, id_res_y, id_src2_xyz, id_src3_xyz); + spv_emit(ctx, 5, SpvOpDot, tid_float, id_res_z, id_dst_xyz, id_src4_xyz); + + pop_output(ctx); + + result.id_res_x = id_res_x; + result.id_res_y = id_res_y; + result.id_res_z = id_res_z; + + return result; +} // spv_texm3x3_setup + +static uint32 spv_reflect(Context *ctx, uint32 id_normal, uint32 id_eyeray) +{ + // reflect(E : vec3 = eyeray, N : vec3 = normal) -> vec3 + // 2 * [(N*E) / (N*N)] * N - E + + uint32 tid_vec3 = spv_get_type(ctx, STI_VEC3); + uint32 id_2 = spv_getscalarf(ctx, 2.0f); + uint32 id_2_v3 = spv_bumpid(ctx); + uint32 id_refl_0 = spv_bumpid(ctx); + uint32 id_refl_1 = spv_bumpid(ctx); + uint32 id_refl_2 = spv_bumpid(ctx); + uint32 id_refl_3 = spv_bumpid(ctx); + uint32 id_refl_4 = spv_bumpid(ctx); + uint32 id_reflected = spv_bumpid(ctx); + + spv_emit(ctx, 3 + 3, SpvOpCompositeConstruct, tid_vec3, id_2_v3, id_2, id_2, id_2); + spv_emit(ctx, 5, SpvOpFMul, tid_vec3, id_refl_0, id_normal, id_eyeray); + spv_emit(ctx, 5, SpvOpFMul, tid_vec3, id_refl_1, id_normal, id_normal); + spv_emit(ctx, 5, SpvOpFDiv, tid_vec3, id_refl_2, id_refl_0, id_refl_1); + spv_emit(ctx, 5, SpvOpFMul, tid_vec3, id_refl_3, id_refl_2, id_normal); + spv_emit(ctx, 5, SpvOpFMul, tid_vec3, id_refl_4, id_refl_3, id_2_v3); + spv_emit(ctx, 5, SpvOpFSub, tid_vec3, id_reflected, id_refl_4, id_eyeray); + + return id_reflected; +} // spv_reflect + +void emit_SPIRV_ADD(Context *ctx) +{ + SpirvResult dst, src0, src1; + spv_emit_begin_dss(ctx, &dst, &src0, &src1); + spv_emit(ctx, 5, SpvOpFAdd, dst.tid, dst.id, src0.id, src1.id); + spv_emit_end(ctx, dst); +} // emit_SPIRV_ADD + +void emit_SPIRV_SUB(Context *ctx) +{ + SpirvResult dst, src0, src1; + spv_emit_begin_dss(ctx, &dst, &src0, &src1); + spv_emit(ctx, 5, SpvOpFSub, dst.tid, dst.id, src0.id, src1.id); + spv_emit_end(ctx, dst); +} // emit_SPIRV_SUB + +void emit_SPIRV_MUL(Context *ctx) +{ + SpirvResult dst, src0, src1; + spv_emit_begin_dss(ctx, &dst, &src0, &src1); + spv_emit(ctx, 5, SpvOpFMul, dst.tid, dst.id, src0.id, src1.id); + spv_emit_end(ctx, dst); +} // emit_SPIRV_MUL + +void emit_SPIRV_SLT(Context *ctx) +{ + SpirvResult dst, src0, src1; + spv_emit_begin_dss(ctx, &dst, &src0, &src1); + + // https://msdn.microsoft.com/en-us/library/windows/desktop/cc308050(v=vs.85).aspx + // "The comparisons EQ, GT, GE, LT, and LE, when either or both operands is NaN returns FALSE" + uint32 bool_result = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpFOrdLessThan, spv_get_type(ctx, STI_BVEC4), bool_result, src0.id, src1.id); + + uint32 ones = spv_getvec4_one(ctx); + uint32 zeros = spv_getvec4_zero(ctx); + spv_emit(ctx, 6, SpvOpSelect, dst.tid, dst.id, bool_result, ones, zeros); + + spv_emit_end(ctx, dst); +} // emit_SPIRV_SLT + +void emit_SPIRV_SGE(Context *ctx) +{ + SpirvResult dst, src0, src1; + spv_emit_begin_dss(ctx, &dst, &src0, &src1); + + // https://msdn.microsoft.com/en-us/library/windows/desktop/cc308050(v=vs.85).aspx + // "The comparisons EQ, GT, GE, LT, and LE, when either or both operands is NaN returns FALSE" + uint32 bool_result = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpFOrdGreaterThanEqual, spv_get_type(ctx, STI_BVEC4), bool_result, src0.id, src1.id); + + uint32 ones = spv_getvec4_one(ctx); + uint32 zeros = spv_getvec4_zero(ctx); + + spv_emit(ctx, 6, SpvOpSelect, dst.tid, dst.id, bool_result, ones, zeros); + spv_emit_end(ctx, dst); +} // emit_SPIRV_SGE + +void emit_SPIRV_MIN(Context *ctx) +{ + SpirvResult dst, src0, src1; + spv_emit_begin_dss(ctx, &dst, &src0, &src1); + spv_emit(ctx, 5 + 2, SpvOpExtInst, dst.tid, dst.id, spv_getext(ctx), GLSLstd450FMin, src0.id, src1.id); + spv_emit_end(ctx, dst); +} // emit_SPIRV_MIN + +void emit_SPIRV_MAX(Context *ctx) +{ + SpirvResult dst, src0, src1; + spv_emit_begin_dss(ctx, &dst, &src0, &src1); + spv_emit(ctx, 5 + 2, SpvOpExtInst, dst.tid, dst.id, spv_getext(ctx), GLSLstd450FMax, src0.id, src1.id); + spv_emit_end(ctx, dst); +} // emit_SPIRV_MAX + +void emit_SPIRV_POW(Context *ctx) +{ + SpirvResult dst, src0, src1; + spv_emit_begin_dss(ctx, &dst, &src0, &src1); + uint32 id_abs = spv_bumpid(ctx); + spv_emit(ctx, 5 + 1, SpvOpExtInst, src0.tid, id_abs, spv_getext(ctx), GLSLstd450FAbs, src0.id); + spv_emit(ctx, 5 + 2, SpvOpExtInst, dst.tid, dst.id, spv_getext(ctx), GLSLstd450Pow, id_abs, src1.id); + spv_emit_end(ctx, dst); +} // emit_SPIRV_POW + +static uint32 spv_extract_vec3(Context *ctx, uint32 input) +{ + uint32 vec3 = spv_get_type(ctx, STI_VEC3); + uint32 result = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 5 + 3, SpvOpVectorShuffle, vec3, result, input, input, 0, 1, 2); + pop_output(ctx); + + return result; +} // spv_extract_vec3 + +void emit_SPIRV_CRS(Context *ctx) +{ + SpirvResult dst, src0, src1; + spv_emit_begin_dss(ctx, &dst, &src0, &src1); + + uint32 vec3 = spv_get_type(ctx, STI_VEC3); + uint32 src0_vec3 = spv_extract_vec3(ctx, src0.id); + uint32 src1_vec3 = spv_extract_vec3(ctx, src1.id); + uint32 result_vec3 = spv_bumpid(ctx); + + spv_emit(ctx, 5 + 2, SpvOpExtInst, vec3, result_vec3, spv_getext(ctx), + GLSLstd450Cross, src0_vec3, src1_vec3); + + // According to DirectX docs, CRS doesn't allow `w` in its writemask, so we + // can make this component anything and the code generated by + // `spv_assign_destarg()` will just throw it away. + spv_emit(ctx, 5 + 4, SpvOpVectorShuffle, dst.tid, dst.id, + result_vec3, result_vec3, 0, 1, 2, 0xFFFFFFFF); + + spv_emit_end(ctx, dst); +} // emit_SPIRV_CRS + +void emit_SPIRV_MAD(Context *ctx) +{ + SpirvResult src0 = spv_load_srcarg_full(ctx, 0); + SpirvResult src1 = spv_load_srcarg_full(ctx, 1); + SpirvResult src2 = spv_load_srcarg_full(ctx, 2); + assert(src0.tid == src1.tid); + assert(src0.tid == src2.tid); + uint32 mul_result = spv_bumpid(ctx); + SpirvResult result; + result.tid = src0.tid; + result.id = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 5, SpvOpFMul, src0.tid, mul_result, src0.id, src1.id); + spv_emit(ctx, 5, SpvOpFAdd, src0.tid, result.id, mul_result, src2.id); + pop_output(ctx); + + spv_assign_destarg(ctx, result); +} // emit_SPIRV_MAD + +void emit_SPIRV_TEXKILL(Context *ctx) +{ + const DestArgInfo *pDstInfo = &ctx->dest_arg; + RegisterList *pDst = spv_getreg(ctx, pDstInfo->regtype, pDstInfo->regnum); + SpirvResult dst = spv_loadreg(ctx, pDst); + + uint32 vec3 = spv_get_type(ctx, STI_VEC3); + uint32 bvec3 = spv_get_type(ctx, STI_BVEC3); + + uint32 zeros = spv_get_zero(ctx, vec3); + + push_output(ctx, &ctx->mainline); + uint32 res_swiz = spv_emit_swizzle(ctx, dst.id, vec3, (0 << 0) | (1 << 2) | (2 << 4), 0x7); + uint32 res_lt = spv_bumpid(ctx); + uint32 res_any = spv_bumpid(ctx); + uint32 label_true = spv_bumpid(ctx); + uint32 label_merge = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpFOrdLessThan, bvec3, res_lt, res_swiz, zeros); + spv_emit(ctx, 4, SpvOpAny, spv_get_type(ctx, STI_BOOL), res_any, res_lt); + spv_emit(ctx, 3, SpvOpSelectionMerge, label_merge, 0); + spv_emit(ctx, 4, SpvOpBranchConditional, res_any, label_true, label_merge); + spv_emit(ctx, 2, SpvOpLabel, label_true); + spv_emit(ctx, 1, SpvOpKill); + spv_emit(ctx, 2, SpvOpLabel, label_merge); + pop_output(ctx); +} // emit_SPIRV_TEXKILL + +void emit_SPIRV_DP2ADD(Context *ctx) +{ + SpirvResult src0 = spv_load_srcarg(ctx, 0, 0x3); + SpirvResult src1 = spv_load_srcarg(ctx, 1, 0x3); + SpirvResult src2 = spv_load_srcarg(ctx, 2, 0x1); + + uint32 tid_float = spv_get_type(ctx, STI_FLOAT); + uint32 id_dot = spv_bumpid(ctx); + uint32 id_add = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 5, SpvOpDot, tid_float, id_dot, src0.id, src1.id); + spv_emit(ctx, 5, SpvOpFAdd, tid_float, id_add, id_dot, src2.id); + SpirvResult result; + result.tid = spv_get_type(ctx, STI_VEC4); + result.id = spv_vectorbroadcast(ctx, result.tid, id_add); + pop_output(ctx); + + spv_assign_destarg(ctx, result); +} // emit_SPIRV_DP2ADD + +void emit_SPIRV_MOV(Context *ctx) +{ + SpirvResult src0 = spv_load_srcarg_full(ctx, 0); + spv_assign_destarg(ctx, src0); +} // emit_SPIRV_MOV + +void emit_SPIRV_RCP(Context *ctx) +{ + /* + if (src != 0.0f) + dst = 1.0f / src; + else + dst = FLT_MAX; + */ + + SpirvResult dst, src; + spv_emit_begin_ds(ctx, &dst, &src); + + SpirvTypeIdx sti_bvec = + (src.tid == ctx->spirv.tid[STI_VEC4]) ? STI_BVEC4 : + (src.tid == ctx->spirv.tid[STI_VEC3]) ? STI_BVEC3 : + (src.tid == ctx->spirv.tid[STI_VEC2]) ? STI_BVEC2 : STI_BOOL; + + uint32 tid_bvec = spv_get_type(ctx, sti_bvec); + uint32 id_one = spv_get_one(ctx, src.tid); + uint32 id_zero = spv_get_zero(ctx, src.tid); + uint32 id_flt_max = spv_get_flt_max(ctx, src.tid); + uint32 id_mask = spv_bumpid(ctx); + uint32 id_div = spv_bumpid(ctx); + + spv_emit(ctx, 5, SpvOpFOrdNotEqual, tid_bvec, id_mask, src.id, id_zero); + spv_emit(ctx, 5, SpvOpFDiv, dst.tid, id_div, id_one, src.id); + spv_emit(ctx, 6, SpvOpSelect, dst.tid, dst.id, id_mask, id_div, id_flt_max); + + spv_emit_end(ctx, dst); +} // emit_SPIRV_RCP + +void emit_SPIRV_RSQ(Context *ctx) +{ + /* + if (src != 0.0f) + dst = 1.0f / abs(src); + else + dst = FLT_MAX; + */ + SpirvResult dst, src; + spv_emit_begin_ds(ctx, &dst, &src); + + SpirvTypeIdx sti_bvec = + (src.tid == ctx->spirv.tid[STI_VEC4]) ? STI_BVEC4 : + (src.tid == ctx->spirv.tid[STI_VEC3]) ? STI_BVEC3 : + (src.tid == ctx->spirv.tid[STI_VEC2]) ? STI_BVEC2 : STI_BOOL; + + uint32 tid_bvec = spv_get_type(ctx, sti_bvec); + uint32 id_zero = spv_get_zero(ctx, src.tid); + uint32 id_flt_max = spv_get_flt_max(ctx, src.tid); + uint32 id_mask = spv_bumpid(ctx); + uint32 id_abs = spv_bumpid(ctx); + uint32 id_rsq = spv_bumpid(ctx); + + spv_emit(ctx, 5, SpvOpFOrdNotEqual, tid_bvec, id_mask, src.id, id_zero); + spv_emit(ctx, 5 + 1, SpvOpExtInst, dst.tid, id_abs, spv_getext(ctx), GLSLstd450FAbs, src.id); + spv_emit(ctx, 5 + 1, SpvOpExtInst, dst.tid, id_rsq, spv_getext(ctx), GLSLstd450InverseSqrt, id_abs); + spv_emit(ctx, 6, SpvOpSelect, dst.tid, dst.id, id_mask, id_rsq, id_flt_max); + + spv_emit_end(ctx, dst); +} // emit_SPIRV_RSQ + +void emit_SPIRV_EXP(Context *ctx) +{ + SpirvResult dst, src; + spv_emit_begin_ds(ctx, &dst, &src); + spv_emit(ctx, 5 + 1, SpvOpExtInst, dst.tid, dst.id, spv_getext(ctx), GLSLstd450Exp2, src.id); + spv_emit_end(ctx, dst); +} // emit_SPIRV_EXP + +void emit_SPIRV_SGN(Context *ctx) +{ + SpirvResult dst, src; + spv_emit_begin_ds(ctx, &dst, &src); + + // SGN also takes a src1 and src2 to use for intermediate results, they are + // left undefined after the instruction executes, and as such it is + // perfectly valid for us to not touch those registers in our implementation + spv_emit(ctx, 5 + 1, SpvOpExtInst, dst.tid, dst.id, spv_getext(ctx), GLSLstd450FSign, src.id); + + spv_emit_end(ctx, dst); +} // emit_SPIRV_SGN + +void emit_SPIRV_ABS(Context *ctx) +{ + SpirvResult dst, src; + spv_emit_begin_ds(ctx, &dst, &src); + spv_emit(ctx, 5 + 1, SpvOpExtInst, dst.tid, dst.id, spv_getext(ctx), GLSLstd450FAbs, src.id); + spv_emit_end(ctx, dst); +} // emit_SPIRV_ABS + +void emit_SPIRV_NRM(Context *ctx) +{ + /* + float dot = dot(src, src); + + float f; + if (dot != 0) + f = (float)(1/sqrt(dot)); + else + f = FLT_MAX; + + dst = src0*f; + */ + + SpirvResult src = spv_load_srcarg_full(ctx, 0); + uint32 tid_vec3 = spv_get_type(ctx, STI_VEC3); + uint32 tid_float = spv_get_type(ctx, STI_FLOAT); + uint32 tid_bool = spv_get_type(ctx, STI_BOOL); + uint32 id_zero = spv_getscalarf(ctx, 0.0f); + uint32 id_flt_max = spv_getscalarf(ctx, FLT_MAX); + uint32 id_src_xyz = spv_bumpid(ctx); + uint32 id_dot = spv_bumpid(ctx); + uint32 id_dot_valid = spv_bumpid(ctx); + uint32 id_f = spv_bumpid(ctx); + uint32 id_f_sane = spv_bumpid(ctx); + uint32 id_f_vec = spv_bumpid(ctx); + + SpirvResult dst; + dst.tid = src.tid; + dst.id = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 5 + 3, SpvOpVectorShuffle, tid_vec3, id_src_xyz, src.id, src.id, 0, 1, 2); + spv_emit(ctx, 5, SpvOpDot, tid_float, id_dot, id_src_xyz, id_src_xyz); + spv_emit(ctx, 5, SpvOpFOrdNotEqual, tid_bool, id_dot_valid, id_dot, id_zero); + spv_emit(ctx, 5 + 1, SpvOpExtInst, tid_float, id_f, spv_getext(ctx), GLSLstd450InverseSqrt, id_dot); + spv_emit(ctx, 6, SpvOpSelect, tid_float, id_f_sane, id_dot_valid, id_f, id_flt_max); + spv_emit(ctx, 3 + 4, SpvOpCompositeConstruct, dst.tid, id_f_vec, id_f_sane, id_f_sane, id_f_sane, id_f_sane); + spv_emit(ctx, 5, SpvOpFMul, dst.tid, dst.id, src.id, id_f_vec); + pop_output(ctx); + spv_assign_destarg(ctx, dst); +} // emit_SPIRV_NRM + +void emit_SPIRV_FRC(Context *ctx) +{ + SpirvResult dst, src; + spv_emit_begin_ds(ctx, &dst, &src); + spv_emit(ctx, 5 + 1, SpvOpExtInst, dst.tid, dst.id, spv_getext(ctx), GLSLstd450Fract, src.id); + spv_emit_end(ctx, dst); +} // emit_SPIRV_FRC + +void emit_SPIRV_LOG(Context *ctx) +{ + SpirvResult dst, src; + spv_emit_begin_ds(ctx, &dst, &src); + + // LOG(x) := (x == vec4(0.0)) ? vec4(-FLT_MAX) : log2(abs(x)) + + // abs(x) + uint32 abs_src0 = spv_bumpid(ctx); + spv_emit(ctx, 5 + 1, SpvOpExtInst, dst.tid, abs_src0, spv_getext(ctx), GLSLstd450FAbs, src.id); + + // vec4(0.0) + uint32 vec4_zero = spv_vectorbroadcast(ctx, dst.tid, spv_getscalarf(ctx, 0.0f)); + + // x == vec4(0.0) + uint32 is_zero = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpFOrdEqual, spv_get_type(ctx, STI_BVEC4), is_zero, abs_src0, vec4_zero); + + // log2(abs(x)) + uint32 log2_of_nonzero = spv_bumpid(ctx); + spv_emit(ctx, 5 + 1, SpvOpExtInst, dst.tid, log2_of_nonzero, spv_getext(ctx), GLSLstd450Log2, abs_src0); + + // vec4(-FLT_MAX) + uint32 vec4_neg_flt_max = spv_vectorbroadcast(ctx, dst.tid, spv_getscalarf(ctx, -FLT_MAX)); + + // (x == vec4(0.0)) ? vec4(-FLT_MAX) : log2(abs(x)) + spv_emit(ctx, 6, SpvOpSelect, dst.tid, dst.id, is_zero, vec4_neg_flt_max, log2_of_nonzero); + + spv_emit_end(ctx, dst); +} // emit_SPIRV_LOG + +void emit_SPIRV_SINCOS(Context *ctx) +{ + SpirvResult src = spv_load_srcarg(ctx, 0, 0x1); + + // For vs_2_0 and vs_2_x this instruction also has a src1 and src2 which provide a couple of constants + // We just ignore these in any case + + // float V = src0.x; + + int writemask = ctx->dest_arg.writemask; + uint32 id_zero = spv_get_zero(ctx, src.tid); + + uint32 id_cos; + if (writemask & 1) // .x = cos(V) + { + id_cos = spv_bumpid(ctx); + spv_emit(ctx, 5 + 1, SpvOpExtInst, src.tid, id_cos, spv_getext(ctx), GLSLstd450Cos, src.id); + } // if + else + id_cos = id_zero; + + uint32 id_sin; + if (writemask & 2) // .y = sin(V) + { + id_sin = spv_bumpid(ctx); + spv_emit(ctx, 5 + 1, SpvOpExtInst, src.tid, id_sin, spv_getext(ctx), GLSLstd450Sin, src.id); + } // if + else + id_sin = id_zero; + + SpirvResult dst; + dst.tid = spv_get_type(ctx, STI_VEC4); + dst.id = spv_bumpid(ctx); + spv_emit(ctx, 3 + 4, SpvOpCompositeConstruct, dst.tid, dst.id, id_cos, id_sin, id_zero, id_zero); + + spv_assign_destarg(ctx, dst); +} // emit_SPIRV_SINCOS + +void emit_SPIRV_MOVA(Context *ctx) +{ + SpirvResult src = spv_load_srcarg_full(ctx, 0); + assert(src.tid == spv_get_type(ctx, STI_VEC4)); + + uint32 id_rounded = spv_bumpid(ctx); + + SpirvResult dst; + dst.tid = spv_get_type(ctx, STI_IVEC4); + dst.id = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 5 + 1, SpvOpExtInst, spv_get_type(ctx, STI_VEC4), id_rounded, + spv_getext(ctx), GLSLstd450Round, src.id); + spv_emit(ctx, 4, SpvOpConvertFToS, dst.tid, dst.id, id_rounded); + pop_output(ctx); + + spv_assign_destarg(ctx, dst); +} // emit_SPIRV_MOVA + +void emit_SPIRV_CMP(Context *ctx) +{ + SpirvResult dst, src0, src1, src2; + spv_emit_begin_dsss(ctx, &dst, &src0, &src1, &src2); + uint32 id_0_0 = spv_get_zero(ctx, src0.tid); + + uint32 id_cmp = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpFUnordGreaterThanEqual, spv_get_type(ctx, STI_BVEC4), id_cmp, src0.id, id_0_0); + spv_emit(ctx, 6, SpvOpSelect, dst.tid, dst.id, id_cmp, src1.id, src2.id); + spv_emit_end(ctx, dst); +} // emit_SPIRV_CMP + +void emit_SPIRV_CND(Context *ctx) +{ + SpirvResult dst, src0, src1, src2; + spv_emit_begin_dsss(ctx, &dst, &src0, &src1, &src2); + uint32 id_0_5 = spv_get_constant_composite(ctx, src0.tid, ctx->spirv.id_0_5, 0.5f); + + uint32 id_cmp = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpFUnordGreaterThan, spv_get_type(ctx, STI_BVEC4), id_cmp, src0.id, id_0_5); + spv_emit(ctx, 6, SpvOpSelect, dst.tid, dst.id, id_cmp, src1.id, src2.id); + spv_emit_end(ctx, dst); +} // emit_SPIRV_CND + +void emit_SPIRV_LIT(Context *ctx) +{ + SpirvResult dst, src; + spv_emit_begin_ds(ctx, &dst, &src); + + if (!ctx->spirv.id_func_lit) + ctx->spirv.id_func_lit = spv_bumpid(ctx); + + spv_emit(ctx, 5, SpvOpFunctionCall, dst.tid, dst.id, ctx->spirv.id_func_lit, src.id); + + spv_emit_end(ctx, dst); +} // emit_SPIRV_LIT + +void emit_SPIRV_DST(Context *ctx) +{ + SpirvResult dst, src0, src1; + spv_emit_begin_dss(ctx, &dst, &src0, &src1); + + uint32 tid_float = spv_get_type(ctx, STI_FLOAT); + dst.tid = spv_get_type(ctx, STI_VEC4); + uint32 id_1_0 = spv_getscalarf(ctx, 1.0f); + uint32 id_src0_y = spv_bumpid(ctx); + uint32 id_src1_y = spv_bumpid(ctx); + uint32 id_src0_z = spv_bumpid(ctx); + uint32 id_src1_w = spv_bumpid(ctx); + uint32 id_dst_y = spv_bumpid(ctx); + dst.id = spv_bumpid(ctx); + + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_float, id_src0_y, src0.id, 1); + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_float, id_src1_y, src1.id, 1); + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_float, id_src0_z, src0.id, 2); + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_float, id_src1_w, src1.id, 3); + spv_emit(ctx, 5, SpvOpFMul, tid_float, id_dst_y, id_src0_y, id_src1_y); + spv_emit(ctx, 3 + 4, SpvOpCompositeConstruct, dst.tid, dst.id, id_1_0, id_dst_y, id_src0_z, id_src1_w); + + spv_emit_end(ctx, dst); +} // emit_SPIRV_DST + +void emit_SPIRV_LRP(Context *ctx) +{ + // lerp(x, y, a) = x + a*(y - x) + // = x*(1 - a) + y*a + SpirvResult a = spv_load_srcarg_full(ctx, 0); // 'scale' + SpirvResult y = spv_load_srcarg_full(ctx, 1); // 'end' + SpirvResult x = spv_load_srcarg_full(ctx, 2); // 'start' + assert(x.tid == y.tid); + SpirvResult result; + result.id = spv_bumpid(ctx); + result.tid = x.tid; + + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 5 + 3, SpvOpExtInst, result.tid, result.id, spv_getext(ctx), GLSLstd450FMix, x.id, y.id, a.id); + pop_output(ctx); + + spv_assign_destarg(ctx, result); +} // emit_SPIRV_LRP + +static void spv_emit_vecXmatrix(Context *ctx, int rows, int writemask) +{ + int i; + + assert(rows <= 4); + assert(writemask == 0x7 || writemask == 0xF); + + uint32 src0 = spv_load_srcarg(ctx, 0, writemask).id; + uint32 tid_float = spv_get_type(ctx, STI_FLOAT); + + RegisterType src1type = ctx->source_args[1].regtype; + int src1num = ctx->source_args[1].regnum; + + uint32 result_components[4]; + for (i = 0; i < rows; i++) + { + SpirvResult row = spv_loadreg(ctx, spv_getreg(ctx, src1type, src1num + i)); + row = spv_swizzle(ctx, row, SPV_NO_SWIZZLE, writemask); + uint32 dot_result = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 5, SpvOpDot, tid_float, dot_result, src0, row.id); + pop_output(ctx); + + result_components[i] = dot_result; + } // for + + SpirvResult r; + r.tid = spv_get_type(ctx, STI_VEC4); + r.id = spv_bumpid(ctx); + + uint32 id_zero = 0; + if (rows < 4) + id_zero = spv_getscalarf(ctx, 0.0f); + + push_output(ctx, &ctx->mainline); + spv_emit_part(ctx, 3 + 4, 3, SpvOpCompositeConstruct, r.tid, r.id); + for (i = 0; i < rows; i++) spv_emit_word(ctx, result_components[i]); + for (i = rows; i < 4; i++) spv_emit_word(ctx, id_zero); + pop_output(ctx); + + spv_assign_destarg(ctx, r); +} // spv_emit_vecXmatrix + +void emit_SPIRV_M4X4(Context *ctx) +{ + // float4 * (4 columns, 4 rows) -> float4 + spv_emit_vecXmatrix(ctx, 4, 0xF); +} // emit_SPIRV_M4X4 + +void emit_SPIRV_M4X3(Context *ctx) +{ + // float4 * (4 columns, 3 rows) -> float3 + spv_emit_vecXmatrix(ctx, 3, 0xF); +} // emit_SPIRV_M4X3 + +void emit_SPIRV_M3X4(Context *ctx) +{ + // float3 * (3 columns, 4 rows) -> float4 + spv_emit_vecXmatrix(ctx, 4, 0x7); +} // emit_SPIRV_M3X4 + +void emit_SPIRV_M3X3(Context *ctx) +{ + // float3 * (3 columns, 3 rows) -> float3 + spv_emit_vecXmatrix(ctx, 3, 0x7); +} // emit_SPIRV_M3X3 + +void emit_SPIRV_M3X2(Context *ctx) +{ + // float3 * (3 columns, 2 rows) -> float2 + spv_emit_vecXmatrix(ctx, 2, 0x7); +} // emit_SPIRV_M3X2 + +void emit_SPIRV_TEXLD(Context *ctx) +{ + if (!shader_version_atleast(ctx, 1, 4)) + { + DestArgInfo *dst_info = &ctx->dest_arg; + + RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, dst_info->regnum); + RegisterList *treg = spv_getreg(ctx, dst_info->regtype, dst_info->regnum); + + // Variables are not declared using dcl opcodes, so handle it in this instruction. + assert(sreg->spirv.iddecl == 0); + assert(treg->spirv.iddecl == 0); + + // Prep the result + SpirvResult result; + result.tid = spv_get_type(ctx, STI_VEC4); + result.id = spv_bumpid(ctx); + SpirvResult sampler = spv_loadreg(ctx, sreg); + // OpImageSampleImplicitLod should ignore the components of this argument that + // it doesn't need, so we don't need to mask it + SpirvResult texcoord = spv_loadreg(ctx, treg); + + // Generate the instruction. + // OpImageSampleImplicitLod should ignore the components of the + // texcoord that it doesn't need, so we don't need to mask it. + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 5, SpvOpImageSampleImplicitLod, result.tid, result.id, + sampler.id, texcoord.id); + pop_output(ctx); + + // Emit the result, finally. + assert(!isscalar(ctx, ctx->shader_type, sreg->regtype, sreg->regnum)); + spv_assign_destarg(ctx, result); + } // if + + else if (!shader_version_atleast(ctx, 2, 0)) + { + // ps_1_4 is different, too! + fail(ctx, "TEXLD == Shader Model 1.4 unimplemented."); // !!! FIXME + return; + } // else if + + else + { + const SourceArgInfo *samp_arg = &ctx->source_args[1]; + RegisterList *sampler_reg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, samp_arg->regnum); + const SourceArgInfo *texcoord_arg = &ctx->source_args[0]; + RegisterList *texcoord_reg = spv_getreg(ctx, texcoord_arg->regtype, texcoord_arg->regnum); + + if (sampler_reg == NULL) + { + fail(ctx, "TEXLD using undeclared sampler"); + return; + } // if + + // OpImageSampleImplicitLod should ignore the components of this argument that + // it doesn't need, so we don't need to mask it + uint32 texcoord = spv_load_srcarg_full(ctx, 0).id; + uint32 sampler = spv_load_srcarg_full(ctx, 1).id; + + // Special case for TEXLDB + // !!! FIXME: does the d3d bias value map directly to GLSL? + uint32 bias; + uint32 instruction_length; + if (ctx->instruction_controls == CONTROL_TEXLDB) + { + uint32 float_tid = spv_get_type(ctx, STI_FLOAT); + bias = spv_bumpid(ctx); + instruction_length = 7; + + // The w component of texcoord_reg specifies the bias. Extract it from texcoord_reg + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 4 + 1, SpvOpCompositeExtract, float_tid, bias, texcoord, 3); + pop_output(ctx); + } // if + else + { + bias = 0; + instruction_length = 5; + } // else + + // Determine the opcode + SpvOp opcode; + if (ctx->instruction_controls == CONTROL_TEXLDP) + { + if ((TextureType) sampler_reg->index == TEXTURE_TYPE_CUBE) + fail(ctx, "TEXLDP on a cubemap"); // !!! FIXME: is this legal? + else if ((TextureType) sampler_reg->index == TEXTURE_TYPE_2D) + { + // Need to move w to z, z can be discarded entirely + uint32 vec3_tid = spv_get_type(ctx, STI_VEC3); + texcoord = spv_emit_swizzle(ctx, texcoord, vec3_tid, (0 << 0) | (1 << 2) | (3 << 4), 0x7); + } + opcode = SpvOpImageSampleProjImplicitLod; + } // if + else + opcode = SpvOpImageSampleImplicitLod; + + // Prep the result + uint32 vec4_tid = spv_get_type(ctx, STI_VEC4); + uint32 result = spv_bumpid(ctx); + + // Generate the instruction. + // OpImageSampleImplicitLod should ignore the components of the + // texcoord that it doesn't need, so we don't need to mask it. + push_output(ctx, &ctx->mainline); + spv_emit_part(ctx, instruction_length, 5, opcode, vec4_tid, result, + sampler, texcoord); + if (ctx->instruction_controls == CONTROL_TEXLDB) + { + // ... include the bias operand, if applicable + spv_emit_word(ctx, SpvImageOperandsBiasMask); + spv_emit_word(ctx, bias); + } // if + pop_output(ctx); + + // Emit the result, finally. + assert(!isscalar(ctx, ctx->shader_type, samp_arg->regtype, samp_arg->regnum)); + SpirvResult r; + r.id = result; + r.tid = vec4_tid; + spv_assign_destarg(ctx, r); + } // else +} // emit_SPIRV_TEXLD + +void emit_SPIRV_IF(Context *ctx) +{ + SpirvResult src0 = spv_load_srcarg(ctx, 0, 0x1); + uint32 tid_bool = spv_get_type(ctx, STI_BOOL); + uint32 id_cond = src0.id; + + // Predicate register is already boolean so no need to convert. + if (src0.tid != tid_bool) + { + uint32 id_zero = spv_getscalari(ctx, 0); + id_cond = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpINotEqual, tid_bool, id_cond, src0.id, id_zero); + } // if + + uint32 id_label_branch = spv_bumpid(ctx); + uint32 id_label_merge = spv_bumpid(ctx); + spv_emit(ctx, 3, SpvOpSelectionMerge, id_label_merge, 0); + spv_emit(ctx, 4, SpvOpBranchConditional, id_cond, id_label_branch, id_label_merge); + spv_branch_push(ctx, id_label_merge, buffer_size(ctx->output) - 4); + spv_emit(ctx, 2, SpvOpLabel, id_label_branch); +} // emit_SPIRV_IF + +void emit_SPIRV_IFC(Context *ctx) +{ + SpvOp cmp_op = spv_get_comparison(ctx); + SpirvResult src0 = spv_load_srcarg(ctx, 0, 0x1); + SpirvResult src1 = spv_load_srcarg(ctx, 1, 0x1); + uint32 tid_bool = spv_get_type(ctx, STI_BOOL); + uint32 id_cond = spv_bumpid(ctx); + uint32 id_label_branch = spv_bumpid(ctx); + uint32 id_label_merge = spv_bumpid(ctx); + + spv_emit(ctx, 5, cmp_op, tid_bool, id_cond, src0.id, src1.id); + spv_emit(ctx, 3, SpvOpSelectionMerge, id_label_merge, 0); + spv_emit(ctx, 4, SpvOpBranchConditional, id_cond, id_label_branch, id_label_merge); + spv_branch_push(ctx, id_label_merge, buffer_size(ctx->output) - 4); + spv_emit(ctx, 2, SpvOpLabel, id_label_branch); +} // emit_SPIRV_IFC + +void emit_SPIRV_ELSE(Context *ctx) +{ + uint32 id_label_merge, patch_offset; + spv_branch_get(ctx, &id_label_merge, &patch_offset); + uint32 id_label_else = spv_bumpid(ctx); + + buffer_patch(ctx->output, patch_offset, &id_label_else, sizeof(id_label_else)); + spv_emit(ctx, 2, SpvOpBranch, id_label_merge); + spv_emit(ctx, 2, SpvOpLabel, id_label_else); +} // emit_SPIRV_ELSE + +void emit_SPIRV_ENDIF(Context *ctx) +{ + uint32 id_label_merge, patch_offset; + spv_branch_pop(ctx, &id_label_merge, &patch_offset); + + spv_emit(ctx, 2, SpvOpBranch, id_label_merge); + spv_emit(ctx, 2, SpvOpLabel, id_label_merge); +} // emit_SPIRV_ENDIF + +void emit_SPIRV_REP(Context *ctx) +{ + SpirvLoopInfo loop = {0}; + uint32 id_label_init = spv_bumpid(ctx); + loop.id_label_header = spv_bumpid(ctx); + uint32 id_label_cond = spv_bumpid(ctx); + uint32 id_label_body = spv_bumpid(ctx); + loop.id_label_continue = spv_bumpid(ctx); + loop.id_label_merge = spv_bumpid(ctx); + + // emit end of previous block + spv_emit(ctx, 2, SpvOpBranch, id_label_init); + + // emit loop init block + spv_emit(ctx, 2, SpvOpLabel, id_label_init); + // This block only exists to allow use of SpvOpPhi in loop header block. + // SpvOpPhi needs to refer to predecessor by it's label ID, so insert dummy + // block just so we know what the ID is. + SpirvResult src0 = spv_load_srcarg(ctx, 0, 0x1); + + uint32 tid_bool = spv_get_type(ctx, STI_BOOL); + loop.tid_counter = src0.tid; + loop.id_counter = spv_bumpid(ctx); + loop.id_counter_next = spv_bumpid(ctx); + + uint32 id_cond = spv_bumpid(ctx); + uint32 id_zero = spv_getscalari(ctx, 0); + spv_emit(ctx, 2, SpvOpBranch, loop.id_label_header); + + // emit loop header block + spv_emit(ctx, 2, SpvOpLabel, loop.id_label_header); + spv_emit(ctx, 7, SpvOpPhi, loop.tid_counter, loop.id_counter, + src0.id, id_label_init, + loop.id_counter_next, loop.id_label_continue + ); + spv_emit(ctx, 4, SpvOpLoopMerge, loop.id_label_merge, loop.id_label_continue, 0); + spv_emit(ctx, 2, SpvOpBranch, id_label_cond); + + // emit loop condition block + spv_emit(ctx, 2, SpvOpLabel, id_label_cond); + spv_emit(ctx, 5, SpvOpINotEqual, tid_bool, id_cond, loop.id_counter, id_zero); + spv_emit(ctx, 4, SpvOpBranchConditional, id_cond, id_label_body, loop.id_label_merge); + + // emit start of loop body block + spv_emit(ctx, 2, SpvOpLabel, id_label_body); + + spv_loop_push(ctx, &loop); +} // emit_SPIRV_REP + +void emit_SPIRV_ENDREP(Context *ctx) +{ + uint32 id_one = spv_getscalari(ctx, 1); + SpirvLoopInfo loop; + spv_loop_pop(ctx, &loop); + + // emit end of loop body block + spv_emit(ctx, 2, SpvOpBranch, loop.id_label_continue); + + // emit loop continue block + spv_emit(ctx, 2, SpvOpLabel, loop.id_label_continue); + spv_emit(ctx, 5, SpvOpISub, loop.tid_counter, loop.id_counter_next, loop.id_counter, id_one); + spv_emit(ctx, 2, SpvOpBranch, loop.id_label_header); + + // emit start of next block + spv_emit(ctx, 2, SpvOpLabel, loop.id_label_merge); +} // emit_SPIRV_ENDREP + +void emit_SPIRV_LOOP(Context *ctx) +{ + SpirvLoopInfo loop = {0}; + uint32 id_label_init = spv_bumpid(ctx); + loop.id_label_header = spv_bumpid(ctx); + uint32 id_label_cond = spv_bumpid(ctx); + uint32 id_label_body = spv_bumpid(ctx); + loop.id_label_continue = spv_bumpid(ctx); + loop.id_label_merge = spv_bumpid(ctx); + + /* + i#.x = iteration count; every round we decrement it and terminate on 0. + i#.y = aL initial value; every round we subtract aL step from it. + i#.z = aL step value; + + We use copy of i# as iteration variable. Compared to rep loop, we only + need to add single instruction for extracting current aL value as single + int. + + rep i0 + for (int i = i0.x; i; i--) + + loop aL, i0 + for (int3 i = i0, int aL = i.y; i.x; i.x--, aL += i.z) + */ + + // emit end of previous block + spv_emit(ctx, 2, SpvOpBranch, id_label_init); + + // emit loop init block + spv_emit(ctx, 2, SpvOpLabel, id_label_init); + // This block only exists to allow use of SpvOpPhi in loop header block. + // SpvOpPhi needs to refer to predecessor by it's label ID, so insert dummy block just so we + // know what the ID is. + + // src0 has aL register. Does it hold any interesting information? + SpirvResult src1 = spv_load_srcarg(ctx, 1, 0x7); + uint32 tid_int = spv_get_type(ctx, STI_INT); + uint32 tid_bool = spv_get_type(ctx, STI_BOOL); + + loop.tid_counter = src1.tid; + loop.id_counter = spv_bumpid(ctx); + loop.id_counter_next = spv_bumpid(ctx); + loop.id_aL = spv_bumpid(ctx); + uint32 id_counter_x = spv_bumpid(ctx); + + uint32 id_cond = spv_bumpid(ctx); + uint32 id_zero = spv_getscalari(ctx, 0); + spv_emit(ctx, 2, SpvOpBranch, loop.id_label_header); + + // emit loop header block + spv_emit(ctx, 2, SpvOpLabel, loop.id_label_header); + spv_emit(ctx, 7, SpvOpPhi, loop.tid_counter, loop.id_counter, + src1.id, id_label_init, + loop.id_counter_next, loop.id_label_continue + ); + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_int, loop.id_aL, loop.id_counter, 1); + spv_emit(ctx, 4, SpvOpLoopMerge, loop.id_label_merge, loop.id_label_continue, 0); + spv_emit(ctx, 2, SpvOpBranch, id_label_cond); + + // emit loop condition block + spv_emit(ctx, 2, SpvOpLabel, id_label_cond); + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_int, id_counter_x, loop.id_counter, 0); + spv_emit(ctx, 5, SpvOpINotEqual, tid_bool, id_cond, id_counter_x, id_zero); + spv_emit(ctx, 4, SpvOpBranchConditional, id_cond, id_label_body, loop.id_label_merge); + + // emit start of loop body block + spv_emit(ctx, 2, SpvOpLabel, id_label_body); + + spv_loop_push(ctx, &loop); +} // emit_SPIRV_LOOP + +void emit_SPIRV_ENDLOOP(Context *ctx) +{ + uint32 tid_int = spv_get_type(ctx, STI_INT); + uint32 tid_ivec2 = spv_get_type(ctx, STI_IVEC2); + + uint32 id_minus_one = spv_getscalari(ctx, -1); + uint32 id_counter_z = spv_bumpid(ctx); + uint32 id_inc = spv_bumpid(ctx); + uint32 id_counter_xy = spv_bumpid(ctx); + uint32 id_counter_next_xy = spv_bumpid(ctx); + + SpirvLoopInfo loop; + spv_loop_pop(ctx, &loop); + + // emit end of loop body block + spv_emit(ctx, 2, SpvOpBranch, loop.id_label_continue); + + // emit loop continue block + spv_emit(ctx, 2, SpvOpLabel, loop.id_label_continue); + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_int, id_counter_z, loop.id_counter, 2); + spv_emit(ctx, 5, SpvOpCompositeConstruct, tid_ivec2, id_inc, id_minus_one, id_counter_z); + spv_emit(ctx, 7, SpvOpVectorShuffle, tid_ivec2, id_counter_xy, loop.id_counter, loop.id_counter, 0, 1); + spv_emit(ctx, 5, SpvOpIAdd, tid_ivec2, id_counter_next_xy, id_counter_xy, id_inc); + spv_emit(ctx, 5, SpvOpCompositeConstruct, loop.tid_counter, loop.id_counter_next, id_counter_next_xy, id_counter_z); + spv_emit(ctx, 2, SpvOpBranch, loop.id_label_header); + + // emit start of next block + spv_emit(ctx, 2, SpvOpLabel, loop.id_label_merge); +} // emit_SPIRV_ENDLOOP + +void emit_SPIRV_BREAKC(Context *ctx) +{ + SpirvLoopInfo loop; + spv_loop_get(ctx, &loop); + + SpvOp cmp_op = spv_get_comparison(ctx); + SpirvResult src0 = spv_load_srcarg(ctx, 0, 0x1); + SpirvResult src1 = spv_load_srcarg(ctx, 1, 0x1); + uint32 tid_bool = spv_get_type(ctx, STI_BOOL); + uint32 id_cond = spv_bumpid(ctx); + uint32 id_label_merge = spv_bumpid(ctx); + + // emit branch to merge target + spv_emit(ctx, 5, cmp_op, tid_bool, id_cond, src0.id, src1.id); + spv_emit(ctx, 3, SpvOpSelectionMerge, id_label_merge, 0); + spv_emit(ctx, 4, SpvOpBranchConditional, id_cond, loop.id_label_merge, id_label_merge); + spv_emit(ctx, 2, SpvOpLabel, id_label_merge); +} // emit_SPIRV_BREAKC + +void emit_SPIRV_BREAKP(Context *ctx) +{ + SpirvLoopInfo loop; + spv_loop_get(ctx, &loop); + + SpirvResult src0 = spv_load_srcarg(ctx, 0, 0x1); + + uint32 id_label_merge = spv_bumpid(ctx); + + spv_emit(ctx, 3, SpvOpSelectionMerge, id_label_merge, 0); + spv_emit(ctx, 4, SpvOpBranchConditional, src0.id, loop.id_label_merge, id_label_merge); + spv_emit(ctx, 2, SpvOpLabel, id_label_merge); +} // emit_SPIRV_BREAKP + +void emit_SPIRV_LABEL(Context *ctx) +{ + const SourceArgInfo* arg = &ctx->source_args[0]; + RegisterList *reg = spv_getreg(ctx, arg->regtype, arg->regnum); + spv_check_read_reg_id(ctx, reg); + + uint32 tid_void = spv_get_type(ctx, STI_VOID); + uint32 tid_func = spv_get_type(ctx, STI_FUNC_VOID); + uint32 id_func = reg->spirv.iddecl; + uint32 id_label = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 5, SpvOpFunction, tid_void, id_func, 0, tid_func); + spv_emit(ctx, 2, SpvOpLabel, id_label); + pop_output(ctx); +} // emit_SPIRV_LABEL + +void emit_SPIRV_RET(Context *ctx) +{ + spv_emit_func_end(ctx); +} // emit_SPIRV_RET + +void emit_SPIRV_CALL(Context *ctx) +{ + const SourceArgInfo* arg = &ctx->source_args[0]; + RegisterList *reg = spv_getreg(ctx, arg->regtype, arg->regnum); + spv_check_read_reg_id(ctx, reg); + + uint32 tid_void = spv_get_type(ctx, STI_VOID); + uint32 id_res = spv_bumpid(ctx); + uint32 id_func = reg->spirv.iddecl; + + push_output(ctx, &ctx->mainline); + if (ctx->loops > 0) + failf(ctx, "Function calls referencing aL not implemented."); + else + spv_emit(ctx, 4, SpvOpFunctionCall, tid_void, id_res, id_func); + + pop_output(ctx); +} // emit_SPIRV_CALL + +void emit_SPIRV_CALLNZ(Context *ctx) +{ + const SourceArgInfo* arg = &ctx->source_args[0]; + RegisterList *reg = spv_getreg(ctx, arg->regtype, arg->regnum); + spv_check_read_reg_id(ctx, reg); + + SpirvResult src1 = spv_load_srcarg(ctx, 1, 0x1); + + uint32 tid_void = spv_get_type(ctx, STI_VOID); + uint32 id_label_then = spv_bumpid(ctx); + uint32 id_func = reg->spirv.iddecl; + uint32 id_call_res = spv_bumpid(ctx); + uint32 id_label_merge = spv_bumpid(ctx); + + spv_emit(ctx, 3, SpvOpSelectionMerge, id_label_merge, 0); + spv_emit(ctx, 4, SpvOpBranchConditional, src1.id, id_label_then, id_label_merge); + + spv_emit(ctx, 2, SpvOpLabel, id_label_then); + if (ctx->loops > 0) + failf(ctx, "Function calls referencing aL not implemented."); + else + spv_emit(ctx, 4, SpvOpFunctionCall, tid_void, id_call_res, id_func); + spv_emit(ctx, 2, SpvOpBranch, id_label_merge); + + spv_emit(ctx, 2, SpvOpLabel, id_label_merge); +} // emit_SPIRV_CALLNZ + +void emit_SPIRV_TEXLDD(Context *ctx) +{ + const SourceArgInfo *samp_arg = &ctx->source_args[1]; + if (!reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, samp_arg->regnum)) + { + fail(ctx, "TEXLDD using undeclared sampler"); + return; + } // if + + // Prep the result + SpirvResult result; + result.tid = spv_get_type(ctx, STI_VEC4); + result.id = spv_bumpid(ctx); + + SpirvResult texcoord = spv_load_srcarg_full(ctx, 0); + SpirvResult sampler = spv_load_srcarg_full(ctx, 1); + SpirvResult grad_x = spv_load_srcarg_full(ctx, 2); + SpirvResult grad_y = spv_load_srcarg_full(ctx, 3); + + // Generate the instruction. + // SpvOpImageSampleExplicitLod should ignore the components of the + // texcoord that it doesn't need, so we don't need to mask it. + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 8, SpvOpImageSampleExplicitLod, result.tid, result.id, sampler.id, + texcoord.id, SpvImageOperandsGradMask, grad_x.id, grad_y.id); + pop_output(ctx); + + // Emit the result, finally. + assert(!isscalar(ctx, ctx->shader_type, samp_arg->regtype, samp_arg->regnum)); + spv_assign_destarg(ctx, result); +} // emit_SPIRV_TEXLDD + +void emit_SPIRV_SETP(Context *ctx) +{ + SpirvResult src0 = spv_load_srcarg_full(ctx, 0); + SpirvResult src1 = spv_load_srcarg_full(ctx, 1); + + SpirvResult dst; + dst.tid = spv_get_type(ctx, STI_BVEC4); + dst.id = spv_bumpid(ctx); + + SpvOp cmp_op = spv_get_comparison(ctx); + + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 5, cmp_op, dst.tid, dst.id, src0.id, src1.id); + pop_output(ctx); + + spv_assign_destarg(ctx, dst); +} // emit_SPIRV_SETP + +void emit_SPIRV_TEXLDL(Context *ctx) +{ + const SourceArgInfo *samp_arg = &ctx->source_args[1]; + RegisterList *sampler_reg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, samp_arg->regnum); + if (sampler_reg == NULL) + { + fail(ctx, "TEXLDL using undeclared sampler"); + return; + } // if + assert(!isscalar(ctx, ctx->shader_type, samp_arg->regtype, samp_arg->regnum)); + + // Prep the result + SpirvResult result; + result.tid = spv_get_type(ctx, STI_VEC4); + result.id = spv_bumpid(ctx); + + SpirvResult sampler = spv_load_srcarg_full(ctx, 1); + SpirvResult texcoord = spv_load_srcarg_full(ctx, 0); + + // The w component of texcoord_reg specifies the LOD. Extract it from texcoord_reg + uint32 tid_float = spv_get_type(ctx, STI_FLOAT); + uint32 id_lod = spv_bumpid(ctx); + + // Generate the instruction. + // SpvOpImageSampleExplicitLod should ignore the components of the + // texcoord that it doesn't need, so we don't need to mask it. + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 4 + 1, SpvOpCompositeExtract, tid_float, id_lod, texcoord.id, 3); + spv_emit(ctx, 7, SpvOpImageSampleExplicitLod, result.tid, result.id, sampler.id, + texcoord.id, SpvImageOperandsLodMask, id_lod); + pop_output(ctx); + + // Emit the result, finally. + spv_assign_destarg(ctx, result); +} // emit_SPIRV_TEXLDL + +void emit_SPIRV_BREAK(Context *ctx) +{ + uint32 id_label_merge = spv_bumpid(ctx); + spv_emit(ctx, 3, SpvOpSelectionMerge, id_label_merge, 0); + spv_emit(ctx, 2, SpvOpBranch, id_label_merge); + spv_emit(ctx, 2, SpvOpLabel, id_label_merge); +} // emit_SPIRV_BREAK + +void emit_SPIRV_TEXM3X2PAD(Context *ctx) +{ + // no-op ... work happens in emit_SPIRV_TEXM3X2TEX(). +} // emit_SPIRV_TEXM3X2PAD + +void emit_SPIRV_TEXM3X2TEX(Context *ctx) +{ + if (ctx->texm3x2pad_src0 == -1) + return; + + DestArgInfo *pDstInfo = &ctx->dest_arg; + + RegisterList *pSReg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, pDstInfo->regnum); + RegisterList *pSrc0 = spv_getreg(ctx, REG_TYPE_TEXTURE, ctx->texm3x2pad_src0); + RegisterList *pSrc1 = spv_getreg(ctx, REG_TYPE_TEXTURE, ctx->texm3x2pad_dst0); + RegisterList *pSrc2 = spv_getreg(ctx, REG_TYPE_TEXTURE, ctx->source_args[0].regnum); + RegisterList *pDst = spv_getreg(ctx, pDstInfo->regtype, pDstInfo->regnum); + + SpirvResult sampler = spv_loadreg(ctx, pSReg); + SpirvResult src0 = spv_loadreg(ctx, pSrc0); + SpirvResult src1 = spv_loadreg(ctx, pSrc1); + SpirvResult src2 = spv_loadreg(ctx, pSrc2); + SpirvResult src3 = spv_loadreg(ctx, pDst); + + src0 = spv_swizzle(ctx, src0, SPV_NO_SWIZZLE, 0x7); + src1 = spv_swizzle(ctx, src1, SPV_NO_SWIZZLE, 0x7); + src2 = spv_swizzle(ctx, src2, SPV_NO_SWIZZLE, 0x7); + src3 = spv_swizzle(ctx, src3, SPV_NO_SWIZZLE, 0x7); + + SpirvResult result; + uint32 tid_float = spv_get_type(ctx, STI_FLOAT); + uint32 tid_vec2 = spv_get_type(ctx, STI_VEC2); + result.tid = spv_get_type(ctx, STI_VEC4); + uint32 id_x = spv_bumpid(ctx); + uint32 id_y = spv_bumpid(ctx); + uint32 id_texcoord = spv_bumpid(ctx); + result.id = spv_bumpid(ctx); + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 5, SpvOpDot, tid_float, id_x, src0.id, src1.id); + spv_emit(ctx, 5, SpvOpDot, tid_float, id_y, src2.id, src3.id); + spv_emit(ctx, 3+2, SpvOpCompositeConstruct, tid_vec2, id_texcoord, id_x, id_y); + spv_emit(ctx, 5, SpvOpImageSampleImplicitLod, result.tid, result.id, sampler.id, id_texcoord); + pop_output(ctx); + spv_assign_destarg(ctx, result); +} // emit_SPIRV_TEXM3X2TEX + +void emit_SPIRV_TEXM3X3PAD(Context *ctx) +{ + // no-op ... work happens in emit_SPIRV_TEXM3X3*(). +} // emit_SPIRV_TEXM3X3PAD + +void emit_SPIRV_TEXM3X3(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + // vec4( + // dot({src0}.xyz, {src1}.xyz), + // dot({src2}.xyz, {src3}.xyz), + // dot({dst}.xyz, {src4}.xyz), + // 1 + // ) + + uint32 id_1 = spv_getscalarf(ctx, 1.0f); + + SpirvTexm3x3SetupResult setup = spv_texm3x3_setup(ctx); + + SpirvResult result; + result.tid = spv_get_type(ctx, STI_VEC4); + result.id = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 3 + 4, SpvOpCompositeConstruct, result.tid, result.id, + setup.id_res_x, setup.id_res_y, setup.id_res_z, id_1 + ); + pop_output(ctx); + + spv_assign_destarg(ctx, result); +} // emit_SPIRV_TEXM3X3 + +void emit_SPIRV_TEXM3X3TEX(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + RegisterList *pSReg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, ctx->dest_arg.regnum); + + // texture{ttypestr}({sampler}, + // vec3( + // dot({src0}.xyz, {src1}.xyz), + // dot({src2}.xyz, {src3}.xyz), + // dot({dst}.xyz, {src4}.xyz) + // ), + // ) + + SpirvResult sampler = spv_loadreg(ctx, pSReg); + + SpirvTexm3x3SetupResult setup = spv_texm3x3_setup(ctx); + + uint32 tid_vec3 = spv_get_type(ctx, STI_VEC3); + uint32 tid_vec4 = spv_get_type(ctx, STI_VEC4); + uint32 id_tc = spv_bumpid(ctx); + + SpirvResult result; + result.tid = tid_vec4; + result.id = spv_bumpid(ctx); + + push_output(ctx, &ctx->mainline); + spv_emit(ctx, 3 + 3, SpvOpCompositeConstruct, tid_vec3, id_tc, + setup.id_res_x, setup.id_res_y, setup.id_res_z + ); + spv_emit(ctx, 5, SpvOpImageSampleImplicitLod, result.tid, result.id, sampler.id, id_tc); + pop_output(ctx); + + spv_assign_destarg(ctx, result); +} // emit_SPIRV_TEXM3X3TEX + +void emit_SPIRV_TEXM3X3SPEC(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + RegisterList *pSReg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, ctx->dest_arg.regnum); + RegisterList *pSrc5 = spv_getreg(ctx, ctx->source_args[1].regtype, ctx->source_args[1].regnum); + + SpirvTexm3x3SetupResult setup = spv_texm3x3_setup(ctx); + + uint32 tid_vec3 = spv_get_type(ctx, STI_VEC3); + + push_output(ctx, &ctx->mainline); + + uint32 id_normal = spv_bumpid(ctx); + spv_emit(ctx, 3 + 3, SpvOpCompositeConstruct, tid_vec3, id_normal, + setup.id_res_x, setup.id_res_y, setup.id_res_z + ); + + SpirvResult src5 = spv_loadreg(ctx, pSrc5); + + uint32 id_eyeray = spv_bumpid(ctx); + spv_emit(ctx, 5 + 3, SpvOpVectorShuffle, tid_vec3, id_eyeray, src5.id, src5.id, 0, 1, 2); + + uint32 id_reflected = spv_reflect(ctx, id_normal, id_eyeray); + + SpirvResult sampler = spv_loadreg(ctx, pSReg); + + SpirvResult result; + result.tid = spv_get_type(ctx, STI_VEC4); + result.id = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpImageSampleImplicitLod, result.tid, result.id, sampler.id, id_reflected); + + pop_output(ctx); + + spv_assign_destarg(ctx, result); +} // emit_SPIRV_TEXM3X3SPEC + +void emit_SPIRV_TEXM3X3VSPEC(Context *ctx) +{ + if (ctx->texm3x3pad_src1 == -1) + return; + + RegisterList *pSReg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER, ctx->dest_arg.regnum); + + SpirvTexm3x3SetupResult setup = spv_texm3x3_setup(ctx); + + uint32 tid_float = spv_get_type(ctx, STI_FLOAT); + uint32 tid_vec3 = spv_get_type(ctx, STI_VEC3); + + push_output(ctx, &ctx->mainline); + + uint32 id_normal = spv_bumpid(ctx); + spv_emit(ctx, 3 + 3, SpvOpCompositeConstruct, tid_vec3, id_normal, + setup.id_res_x, setup.id_res_y, setup.id_res_z + ); + + uint32 id_eyeray_x = spv_bumpid(ctx); + uint32 id_eyeray_y = spv_bumpid(ctx); + uint32 id_eyeray_z = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_float, id_eyeray_x, setup.id_dst_pad0, 3); + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_float, id_eyeray_y, setup.id_dst_pad1, 3); + spv_emit(ctx, 5, SpvOpCompositeExtract, tid_float, id_eyeray_z, setup.id_dst, 3); + + uint32 id_eyeray = spv_bumpid(ctx); + spv_emit(ctx, 3 + 3, SpvOpCompositeConstruct, tid_vec3, id_eyeray, + id_eyeray_x, id_eyeray_y, id_eyeray_z + ); + + uint32 id_reflected = spv_reflect(ctx, id_normal, id_eyeray); + + SpirvResult sampler = spv_loadreg(ctx, pSReg); + + SpirvResult result; + result.tid = spv_get_type(ctx, STI_VEC4); + result.id = spv_bumpid(ctx); + spv_emit(ctx, 5, SpvOpImageSampleImplicitLod, result.tid, result.id, sampler.id, id_reflected); + + pop_output(ctx); + + spv_assign_destarg(ctx, result); +} // emit_SPIRV_TEXM3X3VSPEC + +void emit_SPIRV_TEXBEM(Context *ctx) +{ + spv_texbem(ctx, 0); +} // emit_SPIRV_TEXBEM + +void emit_SPIRV_TEXBEML(Context *ctx) +{ + spv_texbem(ctx, 1); +} // emit_SPIRV_TEXBEML + +void emit_SPIRV_EXPP(Context *ctx) +{ + // !!! FIXME: msdn's asm docs don't list this opcode, I'll have to check the driver documentation. + emit_SPIRV_EXP(ctx); // I guess this is just partial precision EXP? +} // emit_SPIRV_EXPP + +void emit_SPIRV_LOGP(Context *ctx) +{ + // LOGP is just low-precision LOG, but we'll take the higher precision. + emit_SPIRV_LOG(ctx); +} // emit_SPIRV_LOGP + +void emit_SPIRV_DSX(Context *ctx) +{ + SpirvResult dst, src; + spv_emit_begin_ds(ctx, &dst, &src); + spv_emit(ctx, 4, SpvOpDPdx, dst.tid, dst.id, src.id); + spv_emit_end(ctx, dst); +} // emit_SPIRV_DSX + +void emit_SPIRV_DSY(Context *ctx) +{ + SpirvResult dst, src; + spv_emit_begin_ds(ctx, &dst, &src); + spv_emit(ctx, 4, SpvOpDPdy, dst.tid, dst.id, src.id); + spv_emit_end(ctx, dst); +} // emit_SPIRV_DSY + +void emit_SPIRV_RESERVED(Context *ctx) +{ + // do nothing; fails in the state machine. +} // emit_SPIRV_RESERVED + +// !!! FIXME: The following are unimplemented even in the GLSL emitter. +EMIT_SPIRV_OPCODE_UNIMPLEMENTED_FUNC(TEXCRD) +EMIT_SPIRV_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2AR) +EMIT_SPIRV_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2GB) +EMIT_SPIRV_OPCODE_UNIMPLEMENTED_FUNC(TEXREG2RGB) +EMIT_SPIRV_OPCODE_UNIMPLEMENTED_FUNC(TEXDP3TEX) +EMIT_SPIRV_OPCODE_UNIMPLEMENTED_FUNC(TEXM3X2DEPTH) +EMIT_SPIRV_OPCODE_UNIMPLEMENTED_FUNC(TEXDP3) +EMIT_SPIRV_OPCODE_UNIMPLEMENTED_FUNC(TEXDEPTH) +EMIT_SPIRV_OPCODE_UNIMPLEMENTED_FUNC(BEM) + +#endif // SUPPORT_PROFILE_SPIRV + +#pragma GCC visibility pop diff --git a/mojoshader/profiles/mojoshader_profile_spirv.h b/mojoshader/profiles/mojoshader_profile_spirv.h new file mode 100644 index 0000000..e131f65 --- /dev/null +++ b/mojoshader/profiles/mojoshader_profile_spirv.h @@ -0,0 +1,229 @@ +/** + * MojoShader; generate shader programs from bytecode of compiled + * Direct3D shaders. + * + * Please see the file LICENSE.txt in the source's root directory. + * + * This file written by Ryan C. Gordon. + */ + +#ifndef MOJOSHADER_PROFILE_SPIRV_H +#define MOJOSHADER_PROFILE_SPIRV_H + +#if SUPPORT_PROFILE_SPIRV + +#define MOJOSHADER_SPIRV_VS_SAMPLER_SET 0 +#define MOJOSHADER_SPIRV_VS_UNIFORM_SET 1 +#define MOJOSHADER_SPIRV_PS_SAMPLER_SET 2 +#define MOJOSHADER_SPIRV_PS_UNIFORM_SET 3 + +// For baked-in constants in SPIR-V we want to store scalar values that we can +// use in composites, since OpConstantComposite uses result ids constituates +// rather than value literals. +// We'll store these lists grouped by type and have the lists themselves +// ordered by value in the ctx.spirv struct. +typedef struct ComponentList +{ + // result id from OpConstant + uint32 id; + union { + float f; + int i; + uint32 u; + } v; + struct ComponentList *next; +} ComponentList; + +typedef struct SpirvLoopInfo +{ + uint32 tid_counter; + uint32 id_counter; + uint32 id_counter_next; + uint32 id_aL; + uint32 id_label_header; + uint32 id_label_continue; + uint32 id_label_merge; +} SpirvLoopInfo; + +typedef enum SpirvType +{ + ST_FLOAT = 0, + ST_SINT = 1, + ST_UINT = 2, + ST_BOOL = 3, +} SpirvType; + +typedef enum SpirvStorageClass +{ + SC_INPUT = 0, + SC_OUTPUT = 1, + SC_PRIVATE = 2, + SC_UNIFORM_CONSTANT = 3, +} SpirvStorageClass; + +/* Not all type parameter combinations are actually used, but it's all rounded up to 64 so + * it's easier to work with. + */ +typedef enum SpirvTypeIdx +{ + STI_VOID = 0, + STI_FUNC_VOID = 1, + STI_FUNC_LIT = 2, + STI_IMAGE2D = 3, + STI_IMAGE3D = 4, + STI_IMAGECUBE = 5, + STI_PTR_IMAGE2D = 6, + STI_PTR_IMAGE3D = 7, + STI_PTR_IMAGECUBE = 8, + STI_PTR_VEC2_I = 9, // special case, needed only for point coord input. + + // 6 unused entries + + // 4 base types * 4 vector sizes = 16 entries + STI_FLOAT = (0 << 5) | (1 << 4) | (ST_FLOAT << 2) | 0, + STI_VEC2 = (0 << 5) | (1 << 4) | (ST_FLOAT << 2) | 1, + STI_VEC3 = (0 << 5) | (1 << 4) | (ST_FLOAT << 2) | 2, + STI_VEC4 = (0 << 5) | (1 << 4) | (ST_FLOAT << 2) | 3, + STI_INT = (0 << 5) | (1 << 4) | (ST_SINT << 2) | 0, + STI_IVEC2 = (0 << 5) | (1 << 4) | (ST_SINT << 2) | 1, + STI_IVEC3 = (0 << 5) | (1 << 4) | (ST_SINT << 2) | 2, + STI_IVEC4 = (0 << 5) | (1 << 4) | (ST_SINT << 2) | 3, + STI_UINT = (0 << 5) | (1 << 4) | (ST_UINT << 2) | 0, + STI_UVEC2 = (0 << 5) | (1 << 4) | (ST_UINT << 2) | 1, + STI_UVEC3 = (0 << 5) | (1 << 4) | (ST_UINT << 2) | 2, + STI_UVEC4 = (0 << 5) | (1 << 4) | (ST_UINT << 2) | 3, + STI_BOOL = (0 << 5) | (1 << 4) | (ST_BOOL << 2) | 0, + STI_BVEC2 = (0 << 5) | (1 << 4) | (ST_BOOL << 2) | 1, + STI_BVEC3 = (0 << 5) | (1 << 4) | (ST_BOOL << 2) | 2, + STI_BVEC4 = (0 << 5) | (1 << 4) | (ST_BOOL << 2) | 3, + + // 2 dims (vec4 + scalar) * 4 base types * 4 storage classes + STI_PTR_FLOAT_I = (1 << 5) | (0 << 4) | (ST_FLOAT << 2) | SC_INPUT, + STI_PTR_FLOAT_O = (1 << 5) | (0 << 4) | (ST_FLOAT << 2) | SC_OUTPUT, + STI_PTR_FLOAT_P = (1 << 5) | (0 << 4) | (ST_FLOAT << 2) | SC_PRIVATE, + STI_PTR_FLOAT_U = (1 << 5) | (0 << 4) | (ST_FLOAT << 2) | SC_UNIFORM_CONSTANT, + STI_PTR_INT_I = (1 << 5) | (0 << 4) | (ST_SINT << 2) | SC_INPUT, + STI_PTR_INT_O = (1 << 5) | (0 << 4) | (ST_SINT << 2) | SC_OUTPUT, + STI_PTR_INT_P = (1 << 5) | (0 << 4) | (ST_SINT << 2) | SC_PRIVATE, + STI_PTR_INT_U = (1 << 5) | (0 << 4) | (ST_SINT << 2) | SC_UNIFORM_CONSTANT, + STI_PTR_UINT_I = (1 << 5) | (0 << 4) | (ST_UINT << 2) | SC_INPUT, + STI_PTR_UINT_O = (1 << 5) | (0 << 4) | (ST_UINT << 2) | SC_OUTPUT, + STI_PTR_UINT_P = (1 << 5) | (0 << 4) | (ST_UINT << 2) | SC_PRIVATE, + STI_PTR_UINT_U = (1 << 5) | (0 << 4) | (ST_UINT << 2) | SC_UNIFORM_CONSTANT, + STI_PTR_BOOL_I = (1 << 5) | (0 << 4) | (ST_BOOL << 2) | SC_INPUT, + STI_PTR_BOOL_O = (1 << 5) | (0 << 4) | (ST_BOOL << 2) | SC_OUTPUT, + STI_PTR_BOOL_P = (1 << 5) | (0 << 4) | (ST_BOOL << 2) | SC_PRIVATE, + STI_PTR_BOOL_U = (1 << 5) | (0 << 4) | (ST_BOOL << 2) | SC_UNIFORM_CONSTANT, + STI_PTR_VEC4_I = (1 << 5) | (1 << 4) | (ST_FLOAT << 2) | SC_INPUT, + STI_PTR_VEC4_O = (1 << 5) | (1 << 4) | (ST_FLOAT << 2) | SC_OUTPUT, + STI_PTR_VEC4_P = (1 << 5) | (1 << 4) | (ST_FLOAT << 2) | SC_PRIVATE, + STI_PTR_VEC4_U = (1 << 5) | (1 << 4) | (ST_FLOAT << 2) | SC_UNIFORM_CONSTANT, + STI_PTR_IVEC4_I = (1 << 5) | (1 << 4) | (ST_SINT << 2) | SC_INPUT, + STI_PTR_IVEC4_O = (1 << 5) | (1 << 4) | (ST_SINT << 2) | SC_OUTPUT, + STI_PTR_IVEC4_P = (1 << 5) | (1 << 4) | (ST_SINT << 2) | SC_PRIVATE, + STI_PTR_IVEC4_U = (1 << 5) | (1 << 4) | (ST_SINT << 2) | SC_UNIFORM_CONSTANT, + STI_PTR_UVEC4_I = (1 << 5) | (1 << 4) | (ST_UINT << 2) | SC_INPUT, + STI_PTR_UVEC4_O = (1 << 5) | (1 << 4) | (ST_UINT << 2) | SC_OUTPUT, + STI_PTR_UVEC4_P = (1 << 5) | (1 << 4) | (ST_UINT << 2) | SC_PRIVATE, + STI_PTR_UVEC4_U = (1 << 5) | (1 << 4) | (ST_UINT << 2) | SC_UNIFORM_CONSTANT, + STI_PTR_BVEC4_I = (1 << 5) | (1 << 4) | (ST_BOOL << 2) | SC_INPUT, + STI_PTR_BVEC4_O = (1 << 5) | (1 << 4) | (ST_BOOL << 2) | SC_OUTPUT, + STI_PTR_BVEC4_P = (1 << 5) | (1 << 4) | (ST_BOOL << 2) | SC_PRIVATE, + STI_PTR_BVEC4_U = (1 << 5) | (1 << 4) | (ST_BOOL << 2) | SC_UNIFORM_CONSTANT, + + // 2 + 6 + 16 + 32 = 56 entries (+ 8 unused) + + // Helpers + STI_LENGTH_, + + STI_MISC_START_ = 0, + STI_MISC_END_ = 8, + STI_CORE_START_ = (0 << 5) | (1 << 4), + STI_PTR_START_ = (1 << 5) | (0 << 4), + STI_CORE_END_ = STI_PTR_START_, + STI_PTR_END_ = STI_LENGTH_, +} SpirvTypeIdx; + +// In addition to result ID we also need type ID (can't assume everything is vec4). +typedef struct SpirvResult +{ + uint32 tid; + uint32 id; +} SpirvResult; + +// This doesn't 100% correspond to glslangValidator semantics. It just says which mode to use at +// runtime (different from compile-time support being enabled). Technically, we could generate the +// same for both, but that would require GL code to use UBOs. +typedef enum SpirvMode +{ + SPIRV_MODE_GL, + SPIRV_MODE_VK, +} SpirvMode; + +typedef struct SpirvContext +{ +#if SUPPORT_PROFILE_GLSPIRV + uint32 id_vs_main_end; +#endif // SUPPORT_PROFILE_GLSPIRV + SpirvMode mode; + uint32 hasdepth; + // ext. glsl instructions have been imported + uint32 idext; + uint32 idmax; + uint32 idmain; + uint32 id_func_lit; + uint32 inoutcount; + uint32 id_var_fragcoord; + uint32 id_var_vpos; + uint32 id_var_frontfacing; + uint32 id_var_vface; + uint32 id_var_texcoord0_input; + uint32 id_var_texcoord0_private; + // ids for types so we can reuse them after they're declared + uint32 tid[STI_LENGTH_]; + uint32 idtrue; + uint32 idfalse; + uint32 id_0_0[4]; + uint32 id_0_125[4]; + uint32 id_0_25[4]; + uint32 id_0_5[4]; + uint32 id_1_0[4]; + uint32 id_2_0[4]; + uint32 id_4_0[4]; + uint32 id_8_0[4]; + uint32 id_flt_max[4]; + struct { + uint32 idvec4; + uint32 idivec4; + uint32 idbool; + } uniform_arrays; + uint32 id_uniform_block; + struct { + uint32 idvec4; + } constant_arrays; + struct { + ComponentList f; + ComponentList i; + ComponentList u; + } cl; + + SpirvPatchTable patch_table; + + // Required only on ps_1_3 and below, which only has 4 registers for this purpose. + struct { + uint32 idtexbem; + uint32 idtexbeml; + } sampler_extras[4]; + + // TEX opcode in ps_1_3 and below has one implicit texcoord input attribute for each texture + // register. We use this array to hold SSA id of this input attribute (see emit_SPIRV_global + // for details). + uint32 id_implicit_input[4]; + + int loop_stack_idx; + SpirvLoopInfo loop_stack[32]; +} SpirvContext; + +#endif // if SUPPORT_PROFILE_SPIRV + +#endif diff --git a/mojoshader/spirv/GLSL.std.450.h b/mojoshader/spirv/GLSL.std.450.h new file mode 100644 index 0000000..df31092 --- /dev/null +++ b/mojoshader/spirv/GLSL.std.450.h @@ -0,0 +1,131 @@ +/* +** Copyright (c) 2014-2016 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. +** +** MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS +** STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND +** HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/ +** +** 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. +*/ + +#ifndef GLSLstd450_H +#define GLSLstd450_H + +static const int GLSLstd450Version = 100; +static const int GLSLstd450Revision = 1; + +enum GLSLstd450 { + GLSLstd450Bad = 0, // Don't use + + GLSLstd450Round = 1, + GLSLstd450RoundEven = 2, + GLSLstd450Trunc = 3, + GLSLstd450FAbs = 4, + GLSLstd450SAbs = 5, + GLSLstd450FSign = 6, + GLSLstd450SSign = 7, + GLSLstd450Floor = 8, + GLSLstd450Ceil = 9, + GLSLstd450Fract = 10, + + GLSLstd450Radians = 11, + GLSLstd450Degrees = 12, + GLSLstd450Sin = 13, + GLSLstd450Cos = 14, + GLSLstd450Tan = 15, + GLSLstd450Asin = 16, + GLSLstd450Acos = 17, + GLSLstd450Atan = 18, + GLSLstd450Sinh = 19, + GLSLstd450Cosh = 20, + GLSLstd450Tanh = 21, + GLSLstd450Asinh = 22, + GLSLstd450Acosh = 23, + GLSLstd450Atanh = 24, + GLSLstd450Atan2 = 25, + + GLSLstd450Pow = 26, + GLSLstd450Exp = 27, + GLSLstd450Log = 28, + GLSLstd450Exp2 = 29, + GLSLstd450Log2 = 30, + GLSLstd450Sqrt = 31, + GLSLstd450InverseSqrt = 32, + + GLSLstd450Determinant = 33, + GLSLstd450MatrixInverse = 34, + + GLSLstd450Modf = 35, // second operand needs an OpVariable to write to + GLSLstd450ModfStruct = 36, // no OpVariable operand + GLSLstd450FMin = 37, + GLSLstd450UMin = 38, + GLSLstd450SMin = 39, + GLSLstd450FMax = 40, + GLSLstd450UMax = 41, + GLSLstd450SMax = 42, + GLSLstd450FClamp = 43, + GLSLstd450UClamp = 44, + GLSLstd450SClamp = 45, + GLSLstd450FMix = 46, + GLSLstd450IMix = 47, // Reserved + GLSLstd450Step = 48, + GLSLstd450SmoothStep = 49, + + GLSLstd450Fma = 50, + GLSLstd450Frexp = 51, // second operand needs an OpVariable to write to + GLSLstd450FrexpStruct = 52, // no OpVariable operand + GLSLstd450Ldexp = 53, + + GLSLstd450PackSnorm4x8 = 54, + GLSLstd450PackUnorm4x8 = 55, + GLSLstd450PackSnorm2x16 = 56, + GLSLstd450PackUnorm2x16 = 57, + GLSLstd450PackHalf2x16 = 58, + GLSLstd450PackDouble2x32 = 59, + GLSLstd450UnpackSnorm2x16 = 60, + GLSLstd450UnpackUnorm2x16 = 61, + GLSLstd450UnpackHalf2x16 = 62, + GLSLstd450UnpackSnorm4x8 = 63, + GLSLstd450UnpackUnorm4x8 = 64, + GLSLstd450UnpackDouble2x32 = 65, + + GLSLstd450Length = 66, + GLSLstd450Distance = 67, + GLSLstd450Cross = 68, + GLSLstd450Normalize = 69, + GLSLstd450FaceForward = 70, + GLSLstd450Reflect = 71, + GLSLstd450Refract = 72, + + GLSLstd450FindILsb = 73, + GLSLstd450FindSMsb = 74, + GLSLstd450FindUMsb = 75, + + GLSLstd450InterpolateAtCentroid = 76, + GLSLstd450InterpolateAtSample = 77, + GLSLstd450InterpolateAtOffset = 78, + + GLSLstd450NMin = 79, + GLSLstd450NMax = 80, + GLSLstd450NClamp = 81, + + GLSLstd450Count +}; + +#endif // #ifndef GLSLstd450_H diff --git a/mojoshader/spirv/spirv.h b/mojoshader/spirv/spirv.h new file mode 100644 index 0000000..d48488e --- /dev/null +++ b/mojoshader/spirv/spirv.h @@ -0,0 +1,871 @@ +/* +** Copyright (c) 2014-2016 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. +** +** MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS +** STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND +** HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/ +** +** 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 automatically generated by the same tool that creates +** the Binary Section of the SPIR-V specification. +*/ + +/* +** Enumeration tokens for SPIR-V, in various styles: +** C, C++, C++11, JSON, Lua, Python +** +** - C will have tokens with a "Spv" prefix, e.g.: SpvSourceLanguageGLSL +** - C++ will have tokens in the "spv" name space, e.g.: spv::SourceLanguageGLSL +** - C++11 will use enum classes in the spv namespace, e.g.: spv::SourceLanguage::GLSL +** - Lua will use tables, e.g.: spv.SourceLanguage.GLSL +** - Python will use dictionaries, e.g.: spv['SourceLanguage']['GLSL'] +** +** Some tokens act like mask values, which can be OR'd together, +** while others are mutually exclusive. The mask-like ones have +** "Mask" in their name, and a parallel enum that has the shift +** amount (1 << x) for each corresponding enumerant. +*/ + +#ifndef spirv_H +#define spirv_H + +typedef unsigned int SpvId; + +#define SPV_VERSION 0x10000 +#define SPV_REVISION 3 + +static const unsigned int SpvMagicNumber = 0x07230203; +static const unsigned int SpvVersion = 0x00010000; +static const unsigned int SpvRevision = 3; +static const unsigned int SpvOpCodeMask = 0xffff; +static const unsigned int SpvWordCountShift = 16; + +typedef enum SpvSourceLanguage_ { + SpvSourceLanguageUnknown = 0, + SpvSourceLanguageESSL = 1, + SpvSourceLanguageGLSL = 2, + SpvSourceLanguageOpenCL_C = 3, + SpvSourceLanguageOpenCL_CPP = 4, +} SpvSourceLanguage; + +typedef enum SpvExecutionModel_ { + SpvExecutionModelVertex = 0, + SpvExecutionModelTessellationControl = 1, + SpvExecutionModelTessellationEvaluation = 2, + SpvExecutionModelGeometry = 3, + SpvExecutionModelFragment = 4, + SpvExecutionModelGLCompute = 5, + SpvExecutionModelKernel = 6, +} SpvExecutionModel; + +typedef enum SpvAddressingModel_ { + SpvAddressingModelLogical = 0, + SpvAddressingModelPhysical32 = 1, + SpvAddressingModelPhysical64 = 2, +} SpvAddressingModel; + +typedef enum SpvMemoryModel_ { + SpvMemoryModelSimple = 0, + SpvMemoryModelGLSL450 = 1, + SpvMemoryModelOpenCL = 2, +} SpvMemoryModel; + +typedef enum SpvExecutionMode_ { + SpvExecutionModeInvocations = 0, + SpvExecutionModeSpacingEqual = 1, + SpvExecutionModeSpacingFractionalEven = 2, + SpvExecutionModeSpacingFractionalOdd = 3, + SpvExecutionModeVertexOrderCw = 4, + SpvExecutionModeVertexOrderCcw = 5, + SpvExecutionModePixelCenterInteger = 6, + SpvExecutionModeOriginUpperLeft = 7, + SpvExecutionModeOriginLowerLeft = 8, + SpvExecutionModeEarlyFragmentTests = 9, + SpvExecutionModePointMode = 10, + SpvExecutionModeXfb = 11, + SpvExecutionModeDepthReplacing = 12, + SpvExecutionModeDepthGreater = 14, + SpvExecutionModeDepthLess = 15, + SpvExecutionModeDepthUnchanged = 16, + SpvExecutionModeLocalSize = 17, + SpvExecutionModeLocalSizeHint = 18, + SpvExecutionModeInputPoints = 19, + SpvExecutionModeInputLines = 20, + SpvExecutionModeInputLinesAdjacency = 21, + SpvExecutionModeTriangles = 22, + SpvExecutionModeInputTrianglesAdjacency = 23, + SpvExecutionModeQuads = 24, + SpvExecutionModeIsolines = 25, + SpvExecutionModeOutputVertices = 26, + SpvExecutionModeOutputPoints = 27, + SpvExecutionModeOutputLineStrip = 28, + SpvExecutionModeOutputTriangleStrip = 29, + SpvExecutionModeVecTypeHint = 30, + SpvExecutionModeContractionOff = 31, +} SpvExecutionMode; + +typedef enum SpvStorageClass_ { + SpvStorageClassUniformConstant = 0, + SpvStorageClassInput = 1, + SpvStorageClassUniform = 2, + SpvStorageClassOutput = 3, + SpvStorageClassWorkgroup = 4, + SpvStorageClassCrossWorkgroup = 5, + SpvStorageClassPrivate = 6, + SpvStorageClassFunction = 7, + SpvStorageClassGeneric = 8, + SpvStorageClassPushConstant = 9, + SpvStorageClassAtomicCounter = 10, + SpvStorageClassImage = 11, +} SpvStorageClass; + +typedef enum SpvDim_ { + SpvDim1D = 0, + SpvDim2D = 1, + SpvDim3D = 2, + SpvDimCube = 3, + SpvDimRect = 4, + SpvDimBuffer = 5, + SpvDimSubpassData = 6, +} SpvDim; + +typedef enum SpvSamplerAddressingMode_ { + SpvSamplerAddressingModeNone = 0, + SpvSamplerAddressingModeClampToEdge = 1, + SpvSamplerAddressingModeClamp = 2, + SpvSamplerAddressingModeRepeat = 3, + SpvSamplerAddressingModeRepeatMirrored = 4, +} SpvSamplerAddressingMode; + +typedef enum SpvSamplerFilterMode_ { + SpvSamplerFilterModeNearest = 0, + SpvSamplerFilterModeLinear = 1, +} SpvSamplerFilterMode; + +typedef enum SpvImageFormat_ { + SpvImageFormatUnknown = 0, + SpvImageFormatRgba32f = 1, + SpvImageFormatRgba16f = 2, + SpvImageFormatR32f = 3, + SpvImageFormatRgba8 = 4, + SpvImageFormatRgba8Snorm = 5, + SpvImageFormatRg32f = 6, + SpvImageFormatRg16f = 7, + SpvImageFormatR11fG11fB10f = 8, + SpvImageFormatR16f = 9, + SpvImageFormatRgba16 = 10, + SpvImageFormatRgb10A2 = 11, + SpvImageFormatRg16 = 12, + SpvImageFormatRg8 = 13, + SpvImageFormatR16 = 14, + SpvImageFormatR8 = 15, + SpvImageFormatRgba16Snorm = 16, + SpvImageFormatRg16Snorm = 17, + SpvImageFormatRg8Snorm = 18, + SpvImageFormatR16Snorm = 19, + SpvImageFormatR8Snorm = 20, + SpvImageFormatRgba32i = 21, + SpvImageFormatRgba16i = 22, + SpvImageFormatRgba8i = 23, + SpvImageFormatR32i = 24, + SpvImageFormatRg32i = 25, + SpvImageFormatRg16i = 26, + SpvImageFormatRg8i = 27, + SpvImageFormatR16i = 28, + SpvImageFormatR8i = 29, + SpvImageFormatRgba32ui = 30, + SpvImageFormatRgba16ui = 31, + SpvImageFormatRgba8ui = 32, + SpvImageFormatR32ui = 33, + SpvImageFormatRgb10a2ui = 34, + SpvImageFormatRg32ui = 35, + SpvImageFormatRg16ui = 36, + SpvImageFormatRg8ui = 37, + SpvImageFormatR16ui = 38, + SpvImageFormatR8ui = 39, +} SpvImageFormat; + +typedef enum SpvImageChannelOrder_ { + SpvImageChannelOrderR = 0, + SpvImageChannelOrderA = 1, + SpvImageChannelOrderRG = 2, + SpvImageChannelOrderRA = 3, + SpvImageChannelOrderRGB = 4, + SpvImageChannelOrderRGBA = 5, + SpvImageChannelOrderBGRA = 6, + SpvImageChannelOrderARGB = 7, + SpvImageChannelOrderIntensity = 8, + SpvImageChannelOrderLuminance = 9, + SpvImageChannelOrderRx = 10, + SpvImageChannelOrderRGx = 11, + SpvImageChannelOrderRGBx = 12, + SpvImageChannelOrderDepth = 13, + SpvImageChannelOrderDepthStencil = 14, + SpvImageChannelOrdersRGB = 15, + SpvImageChannelOrdersRGBx = 16, + SpvImageChannelOrdersRGBA = 17, + SpvImageChannelOrdersBGRA = 18, +} SpvImageChannelOrder; + +typedef enum SpvImageChannelDataType_ { + SpvImageChannelDataTypeSnormInt8 = 0, + SpvImageChannelDataTypeSnormInt16 = 1, + SpvImageChannelDataTypeUnormInt8 = 2, + SpvImageChannelDataTypeUnormInt16 = 3, + SpvImageChannelDataTypeUnormShort565 = 4, + SpvImageChannelDataTypeUnormShort555 = 5, + SpvImageChannelDataTypeUnormInt101010 = 6, + SpvImageChannelDataTypeSignedInt8 = 7, + SpvImageChannelDataTypeSignedInt16 = 8, + SpvImageChannelDataTypeSignedInt32 = 9, + SpvImageChannelDataTypeUnsignedInt8 = 10, + SpvImageChannelDataTypeUnsignedInt16 = 11, + SpvImageChannelDataTypeUnsignedInt32 = 12, + SpvImageChannelDataTypeHalfFloat = 13, + SpvImageChannelDataTypeFloat = 14, + SpvImageChannelDataTypeUnormInt24 = 15, + SpvImageChannelDataTypeUnormInt101010_2 = 16, +} SpvImageChannelDataType; + +typedef enum SpvImageOperandsShift_ { + SpvImageOperandsBiasShift = 0, + SpvImageOperandsLodShift = 1, + SpvImageOperandsGradShift = 2, + SpvImageOperandsConstOffsetShift = 3, + SpvImageOperandsOffsetShift = 4, + SpvImageOperandsConstOffsetsShift = 5, + SpvImageOperandsSampleShift = 6, + SpvImageOperandsMinLodShift = 7, +} SpvImageOperandsShift; + +typedef enum SpvImageOperandsMask_ { + SpvImageOperandsMaskNone = 0, + SpvImageOperandsBiasMask = 0x00000001, + SpvImageOperandsLodMask = 0x00000002, + SpvImageOperandsGradMask = 0x00000004, + SpvImageOperandsConstOffsetMask = 0x00000008, + SpvImageOperandsOffsetMask = 0x00000010, + SpvImageOperandsConstOffsetsMask = 0x00000020, + SpvImageOperandsSampleMask = 0x00000040, + SpvImageOperandsMinLodMask = 0x00000080, +} SpvImageOperandsMask; + +typedef enum SpvFPFastMathModeShift_ { + SpvFPFastMathModeNotNaNShift = 0, + SpvFPFastMathModeNotInfShift = 1, + SpvFPFastMathModeNSZShift = 2, + SpvFPFastMathModeAllowRecipShift = 3, + SpvFPFastMathModeFastShift = 4, +} SpvFPFastMathModeShift; + +typedef enum SpvFPFastMathModeMask_ { + SpvFPFastMathModeMaskNone = 0, + SpvFPFastMathModeNotNaNMask = 0x00000001, + SpvFPFastMathModeNotInfMask = 0x00000002, + SpvFPFastMathModeNSZMask = 0x00000004, + SpvFPFastMathModeAllowRecipMask = 0x00000008, + SpvFPFastMathModeFastMask = 0x00000010, +} SpvFPFastMathModeMask; + +typedef enum SpvFPRoundingMode_ { + SpvFPRoundingModeRTE = 0, + SpvFPRoundingModeRTZ = 1, + SpvFPRoundingModeRTP = 2, + SpvFPRoundingModeRTN = 3, +} SpvFPRoundingMode; + +typedef enum SpvLinkageType_ { + SpvLinkageTypeExport = 0, + SpvLinkageTypeImport = 1, +} SpvLinkageType; + +typedef enum SpvAccessQualifier_ { + SpvAccessQualifierReadOnly = 0, + SpvAccessQualifierWriteOnly = 1, + SpvAccessQualifierReadWrite = 2, +} SpvAccessQualifier; + +typedef enum SpvFunctionParameterAttribute_ { + SpvFunctionParameterAttributeZext = 0, + SpvFunctionParameterAttributeSext = 1, + SpvFunctionParameterAttributeByVal = 2, + SpvFunctionParameterAttributeSret = 3, + SpvFunctionParameterAttributeNoAlias = 4, + SpvFunctionParameterAttributeNoCapture = 5, + SpvFunctionParameterAttributeNoWrite = 6, + SpvFunctionParameterAttributeNoReadWrite = 7, +} SpvFunctionParameterAttribute; + +typedef enum SpvDecoration_ { + SpvDecorationRelaxedPrecision = 0, + SpvDecorationSpecId = 1, + SpvDecorationBlock = 2, + SpvDecorationBufferBlock = 3, + SpvDecorationRowMajor = 4, + SpvDecorationColMajor = 5, + SpvDecorationArrayStride = 6, + SpvDecorationMatrixStride = 7, + SpvDecorationGLSLShared = 8, + SpvDecorationGLSLPacked = 9, + SpvDecorationCPacked = 10, + SpvDecorationBuiltIn = 11, + SpvDecorationNoPerspective = 13, + SpvDecorationFlat = 14, + SpvDecorationPatch = 15, + SpvDecorationCentroid = 16, + SpvDecorationSample = 17, + SpvDecorationInvariant = 18, + SpvDecorationRestrict = 19, + SpvDecorationAliased = 20, + SpvDecorationVolatile = 21, + SpvDecorationConstant = 22, + SpvDecorationCoherent = 23, + SpvDecorationNonWritable = 24, + SpvDecorationNonReadable = 25, + SpvDecorationUniform = 26, + SpvDecorationSaturatedConversion = 28, + SpvDecorationStream = 29, + SpvDecorationLocation = 30, + SpvDecorationComponent = 31, + SpvDecorationIndex = 32, + SpvDecorationBinding = 33, + SpvDecorationDescriptorSet = 34, + SpvDecorationOffset = 35, + SpvDecorationXfbBuffer = 36, + SpvDecorationXfbStride = 37, + SpvDecorationFuncParamAttr = 38, + SpvDecorationFPRoundingMode = 39, + SpvDecorationFPFastMathMode = 40, + SpvDecorationLinkageAttributes = 41, + SpvDecorationNoContraction = 42, + SpvDecorationInputAttachmentIndex = 43, + SpvDecorationAlignment = 44, +} SpvDecoration; + +typedef enum SpvBuiltIn_ { + SpvBuiltInPosition = 0, + SpvBuiltInPointSize = 1, + SpvBuiltInClipDistance = 3, + SpvBuiltInCullDistance = 4, + SpvBuiltInVertexId = 5, + SpvBuiltInInstanceId = 6, + SpvBuiltInPrimitiveId = 7, + SpvBuiltInInvocationId = 8, + SpvBuiltInLayer = 9, + SpvBuiltInViewportIndex = 10, + SpvBuiltInTessLevelOuter = 11, + SpvBuiltInTessLevelInner = 12, + SpvBuiltInTessCoord = 13, + SpvBuiltInPatchVertices = 14, + SpvBuiltInFragCoord = 15, + SpvBuiltInPointCoord = 16, + SpvBuiltInFrontFacing = 17, + SpvBuiltInSampleId = 18, + SpvBuiltInSamplePosition = 19, + SpvBuiltInSampleMask = 20, + SpvBuiltInFragDepth = 22, + SpvBuiltInHelperInvocation = 23, + SpvBuiltInNumWorkgroups = 24, + SpvBuiltInWorkgroupSize = 25, + SpvBuiltInWorkgroupId = 26, + SpvBuiltInLocalInvocationId = 27, + SpvBuiltInGlobalInvocationId = 28, + SpvBuiltInLocalInvocationIndex = 29, + SpvBuiltInWorkDim = 30, + SpvBuiltInGlobalSize = 31, + SpvBuiltInEnqueuedWorkgroupSize = 32, + SpvBuiltInGlobalOffset = 33, + SpvBuiltInGlobalLinearId = 34, + SpvBuiltInSubgroupSize = 36, + SpvBuiltInSubgroupMaxSize = 37, + SpvBuiltInNumSubgroups = 38, + SpvBuiltInNumEnqueuedSubgroups = 39, + SpvBuiltInSubgroupId = 40, + SpvBuiltInSubgroupLocalInvocationId = 41, + SpvBuiltInVertexIndex = 42, + SpvBuiltInInstanceIndex = 43, +} SpvBuiltIn; + +typedef enum SpvSelectionControlShift_ { + SpvSelectionControlFlattenShift = 0, + SpvSelectionControlDontFlattenShift = 1, +} SpvSelectionControlShift; + +typedef enum SpvSelectionControlMask_ { + SpvSelectionControlMaskNone = 0, + SpvSelectionControlFlattenMask = 0x00000001, + SpvSelectionControlDontFlattenMask = 0x00000002, +} SpvSelectionControlMask; + +typedef enum SpvLoopControlShift_ { + SpvLoopControlUnrollShift = 0, + SpvLoopControlDontUnrollShift = 1, +} SpvLoopControlShift; + +typedef enum SpvLoopControlMask_ { + SpvLoopControlMaskNone = 0, + SpvLoopControlUnrollMask = 0x00000001, + SpvLoopControlDontUnrollMask = 0x00000002, +} SpvLoopControlMask; + +typedef enum SpvFunctionControlShift_ { + SpvFunctionControlInlineShift = 0, + SpvFunctionControlDontInlineShift = 1, + SpvFunctionControlPureShift = 2, + SpvFunctionControlConstShift = 3, +} SpvFunctionControlShift; + +typedef enum SpvFunctionControlMask_ { + SpvFunctionControlMaskNone = 0, + SpvFunctionControlInlineMask = 0x00000001, + SpvFunctionControlDontInlineMask = 0x00000002, + SpvFunctionControlPureMask = 0x00000004, + SpvFunctionControlConstMask = 0x00000008, +} SpvFunctionControlMask; + +typedef enum SpvMemorySemanticsShift_ { + SpvMemorySemanticsAcquireShift = 1, + SpvMemorySemanticsReleaseShift = 2, + SpvMemorySemanticsAcquireReleaseShift = 3, + SpvMemorySemanticsSequentiallyConsistentShift = 4, + SpvMemorySemanticsUniformMemoryShift = 6, + SpvMemorySemanticsSubgroupMemoryShift = 7, + SpvMemorySemanticsWorkgroupMemoryShift = 8, + SpvMemorySemanticsCrossWorkgroupMemoryShift = 9, + SpvMemorySemanticsAtomicCounterMemoryShift = 10, + SpvMemorySemanticsImageMemoryShift = 11, +} SpvMemorySemanticsShift; + +typedef enum SpvMemorySemanticsMask_ { + SpvMemorySemanticsMaskNone = 0, + SpvMemorySemanticsAcquireMask = 0x00000002, + SpvMemorySemanticsReleaseMask = 0x00000004, + SpvMemorySemanticsAcquireReleaseMask = 0x00000008, + SpvMemorySemanticsSequentiallyConsistentMask = 0x00000010, + SpvMemorySemanticsUniformMemoryMask = 0x00000040, + SpvMemorySemanticsSubgroupMemoryMask = 0x00000080, + SpvMemorySemanticsWorkgroupMemoryMask = 0x00000100, + SpvMemorySemanticsCrossWorkgroupMemoryMask = 0x00000200, + SpvMemorySemanticsAtomicCounterMemoryMask = 0x00000400, + SpvMemorySemanticsImageMemoryMask = 0x00000800, +} SpvMemorySemanticsMask; + +typedef enum SpvMemoryAccessShift_ { + SpvMemoryAccessVolatileShift = 0, + SpvMemoryAccessAlignedShift = 1, + SpvMemoryAccessNontemporalShift = 2, +} SpvMemoryAccessShift; + +typedef enum SpvMemoryAccessMask_ { + SpvMemoryAccessMaskNone = 0, + SpvMemoryAccessVolatileMask = 0x00000001, + SpvMemoryAccessAlignedMask = 0x00000002, + SpvMemoryAccessNontemporalMask = 0x00000004, +} SpvMemoryAccessMask; + +typedef enum SpvScope_ { + SpvScopeCrossDevice = 0, + SpvScopeDevice = 1, + SpvScopeWorkgroup = 2, + SpvScopeSubgroup = 3, + SpvScopeInvocation = 4, +} SpvScope; + +typedef enum SpvGroupOperation_ { + SpvGroupOperationReduce = 0, + SpvGroupOperationInclusiveScan = 1, + SpvGroupOperationExclusiveScan = 2, +} SpvGroupOperation; + +typedef enum SpvKernelEnqueueFlags_ { + SpvKernelEnqueueFlagsNoWait = 0, + SpvKernelEnqueueFlagsWaitKernel = 1, + SpvKernelEnqueueFlagsWaitWorkGroup = 2, +} SpvKernelEnqueueFlags; + +typedef enum SpvKernelProfilingInfoShift_ { + SpvKernelProfilingInfoCmdExecTimeShift = 0, +} SpvKernelProfilingInfoShift; + +typedef enum SpvKernelProfilingInfoMask_ { + SpvKernelProfilingInfoMaskNone = 0, + SpvKernelProfilingInfoCmdExecTimeMask = 0x00000001, +} SpvKernelProfilingInfoMask; + +typedef enum SpvCapability_ { + SpvCapabilityMatrix = 0, + SpvCapabilityShader = 1, + SpvCapabilityGeometry = 2, + SpvCapabilityTessellation = 3, + SpvCapabilityAddresses = 4, + SpvCapabilityLinkage = 5, + SpvCapabilityKernel = 6, + SpvCapabilityVector16 = 7, + SpvCapabilityFloat16Buffer = 8, + SpvCapabilityFloat16 = 9, + SpvCapabilityFloat64 = 10, + SpvCapabilityInt64 = 11, + SpvCapabilityInt64Atomics = 12, + SpvCapabilityImageBasic = 13, + SpvCapabilityImageReadWrite = 14, + SpvCapabilityImageMipmap = 15, + SpvCapabilityPipes = 17, + SpvCapabilityGroups = 18, + SpvCapabilityDeviceEnqueue = 19, + SpvCapabilityLiteralSampler = 20, + SpvCapabilityAtomicStorage = 21, + SpvCapabilityInt16 = 22, + SpvCapabilityTessellationPointSize = 23, + SpvCapabilityGeometryPointSize = 24, + SpvCapabilityImageGatherExtended = 25, + SpvCapabilityStorageImageMultisample = 27, + SpvCapabilityUniformBufferArrayDynamicIndexing = 28, + SpvCapabilitySampledImageArrayDynamicIndexing = 29, + SpvCapabilityStorageBufferArrayDynamicIndexing = 30, + SpvCapabilityStorageImageArrayDynamicIndexing = 31, + SpvCapabilityClipDistance = 32, + SpvCapabilityCullDistance = 33, + SpvCapabilityImageCubeArray = 34, + SpvCapabilitySampleRateShading = 35, + SpvCapabilityImageRect = 36, + SpvCapabilitySampledRect = 37, + SpvCapabilityGenericPointer = 38, + SpvCapabilityInt8 = 39, + SpvCapabilityInputAttachment = 40, + SpvCapabilitySparseResidency = 41, + SpvCapabilityMinLod = 42, + SpvCapabilitySampled1D = 43, + SpvCapabilityImage1D = 44, + SpvCapabilitySampledCubeArray = 45, + SpvCapabilitySampledBuffer = 46, + SpvCapabilityImageBuffer = 47, + SpvCapabilityImageMSArray = 48, + SpvCapabilityStorageImageExtendedFormats = 49, + SpvCapabilityImageQuery = 50, + SpvCapabilityDerivativeControl = 51, + SpvCapabilityInterpolationFunction = 52, + SpvCapabilityTransformFeedback = 53, + SpvCapabilityGeometryStreams = 54, + SpvCapabilityStorageImageReadWithoutFormat = 55, + SpvCapabilityStorageImageWriteWithoutFormat = 56, + SpvCapabilityMultiViewport = 57, +} SpvCapability; + +typedef enum SpvOp_ { + SpvOpNop = 0, + SpvOpUndef = 1, + SpvOpSourceContinued = 2, + SpvOpSource = 3, + SpvOpSourceExtension = 4, + SpvOpName = 5, + SpvOpMemberName = 6, + SpvOpString = 7, + SpvOpLine = 8, + SpvOpExtension = 10, + SpvOpExtInstImport = 11, + SpvOpExtInst = 12, + SpvOpMemoryModel = 14, + SpvOpEntryPoint = 15, + SpvOpExecutionMode = 16, + SpvOpCapability = 17, + SpvOpTypeVoid = 19, + SpvOpTypeBool = 20, + SpvOpTypeInt = 21, + SpvOpTypeFloat = 22, + SpvOpTypeVector = 23, + SpvOpTypeMatrix = 24, + SpvOpTypeImage = 25, + SpvOpTypeSampler = 26, + SpvOpTypeSampledImage = 27, + SpvOpTypeArray = 28, + SpvOpTypeRuntimeArray = 29, + SpvOpTypeStruct = 30, + SpvOpTypeOpaque = 31, + SpvOpTypePointer = 32, + SpvOpTypeFunction = 33, + SpvOpTypeEvent = 34, + SpvOpTypeDeviceEvent = 35, + SpvOpTypeReserveId = 36, + SpvOpTypeQueue = 37, + SpvOpTypePipe = 38, + SpvOpTypeForwardPointer = 39, + SpvOpConstantTrue = 41, + SpvOpConstantFalse = 42, + SpvOpConstant = 43, + SpvOpConstantComposite = 44, + SpvOpConstantSampler = 45, + SpvOpConstantNull = 46, + SpvOpSpecConstantTrue = 48, + SpvOpSpecConstantFalse = 49, + SpvOpSpecConstant = 50, + SpvOpSpecConstantComposite = 51, + SpvOpSpecConstantOp = 52, + SpvOpFunction = 54, + SpvOpFunctionParameter = 55, + SpvOpFunctionEnd = 56, + SpvOpFunctionCall = 57, + SpvOpVariable = 59, + SpvOpImageTexelPointer = 60, + SpvOpLoad = 61, + SpvOpStore = 62, + SpvOpCopyMemory = 63, + SpvOpCopyMemorySized = 64, + SpvOpAccessChain = 65, + SpvOpInBoundsAccessChain = 66, + SpvOpPtrAccessChain = 67, + SpvOpArrayLength = 68, + SpvOpGenericPtrMemSemantics = 69, + SpvOpInBoundsPtrAccessChain = 70, + SpvOpDecorate = 71, + SpvOpMemberDecorate = 72, + SpvOpDecorationGroup = 73, + SpvOpGroupDecorate = 74, + SpvOpGroupMemberDecorate = 75, + SpvOpVectorExtractDynamic = 77, + SpvOpVectorInsertDynamic = 78, + SpvOpVectorShuffle = 79, + SpvOpCompositeConstruct = 80, + SpvOpCompositeExtract = 81, + SpvOpCompositeInsert = 82, + SpvOpCopyObject = 83, + SpvOpTranspose = 84, + SpvOpSampledImage = 86, + SpvOpImageSampleImplicitLod = 87, + SpvOpImageSampleExplicitLod = 88, + SpvOpImageSampleDrefImplicitLod = 89, + SpvOpImageSampleDrefExplicitLod = 90, + SpvOpImageSampleProjImplicitLod = 91, + SpvOpImageSampleProjExplicitLod = 92, + SpvOpImageSampleProjDrefImplicitLod = 93, + SpvOpImageSampleProjDrefExplicitLod = 94, + SpvOpImageFetch = 95, + SpvOpImageGather = 96, + SpvOpImageDrefGather = 97, + SpvOpImageRead = 98, + SpvOpImageWrite = 99, + SpvOpImage = 100, + SpvOpImageQueryFormat = 101, + SpvOpImageQueryOrder = 102, + SpvOpImageQuerySizeLod = 103, + SpvOpImageQuerySize = 104, + SpvOpImageQueryLod = 105, + SpvOpImageQueryLevels = 106, + SpvOpImageQuerySamples = 107, + SpvOpConvertFToU = 109, + SpvOpConvertFToS = 110, + SpvOpConvertSToF = 111, + SpvOpConvertUToF = 112, + SpvOpUConvert = 113, + SpvOpSConvert = 114, + SpvOpFConvert = 115, + SpvOpQuantizeToF16 = 116, + SpvOpConvertPtrToU = 117, + SpvOpSatConvertSToU = 118, + SpvOpSatConvertUToS = 119, + SpvOpConvertUToPtr = 120, + SpvOpPtrCastToGeneric = 121, + SpvOpGenericCastToPtr = 122, + SpvOpGenericCastToPtrExplicit = 123, + SpvOpBitcast = 124, + SpvOpSNegate = 126, + SpvOpFNegate = 127, + SpvOpIAdd = 128, + SpvOpFAdd = 129, + SpvOpISub = 130, + SpvOpFSub = 131, + SpvOpIMul = 132, + SpvOpFMul = 133, + SpvOpUDiv = 134, + SpvOpSDiv = 135, + SpvOpFDiv = 136, + SpvOpUMod = 137, + SpvOpSRem = 138, + SpvOpSMod = 139, + SpvOpFRem = 140, + SpvOpFMod = 141, + SpvOpVectorTimesScalar = 142, + SpvOpMatrixTimesScalar = 143, + SpvOpVectorTimesMatrix = 144, + SpvOpMatrixTimesVector = 145, + SpvOpMatrixTimesMatrix = 146, + SpvOpOuterProduct = 147, + SpvOpDot = 148, + SpvOpIAddCarry = 149, + SpvOpISubBorrow = 150, + SpvOpUMulExtended = 151, + SpvOpSMulExtended = 152, + SpvOpAny = 154, + SpvOpAll = 155, + SpvOpIsNan = 156, + SpvOpIsInf = 157, + SpvOpIsFinite = 158, + SpvOpIsNormal = 159, + SpvOpSignBitSet = 160, + SpvOpLessOrGreater = 161, + SpvOpOrdered = 162, + SpvOpUnordered = 163, + SpvOpLogicalEqual = 164, + SpvOpLogicalNotEqual = 165, + SpvOpLogicalOr = 166, + SpvOpLogicalAnd = 167, + SpvOpLogicalNot = 168, + SpvOpSelect = 169, + SpvOpIEqual = 170, + SpvOpINotEqual = 171, + SpvOpUGreaterThan = 172, + SpvOpSGreaterThan = 173, + SpvOpUGreaterThanEqual = 174, + SpvOpSGreaterThanEqual = 175, + SpvOpULessThan = 176, + SpvOpSLessThan = 177, + SpvOpULessThanEqual = 178, + SpvOpSLessThanEqual = 179, + SpvOpFOrdEqual = 180, + SpvOpFUnordEqual = 181, + SpvOpFOrdNotEqual = 182, + SpvOpFUnordNotEqual = 183, + SpvOpFOrdLessThan = 184, + SpvOpFUnordLessThan = 185, + SpvOpFOrdGreaterThan = 186, + SpvOpFUnordGreaterThan = 187, + SpvOpFOrdLessThanEqual = 188, + SpvOpFUnordLessThanEqual = 189, + SpvOpFOrdGreaterThanEqual = 190, + SpvOpFUnordGreaterThanEqual = 191, + SpvOpShiftRightLogical = 194, + SpvOpShiftRightArithmetic = 195, + SpvOpShiftLeftLogical = 196, + SpvOpBitwiseOr = 197, + SpvOpBitwiseXor = 198, + SpvOpBitwiseAnd = 199, + SpvOpNot = 200, + SpvOpBitFieldInsert = 201, + SpvOpBitFieldSExtract = 202, + SpvOpBitFieldUExtract = 203, + SpvOpBitReverse = 204, + SpvOpBitCount = 205, + SpvOpDPdx = 207, + SpvOpDPdy = 208, + SpvOpFwidth = 209, + SpvOpDPdxFine = 210, + SpvOpDPdyFine = 211, + SpvOpFwidthFine = 212, + SpvOpDPdxCoarse = 213, + SpvOpDPdyCoarse = 214, + SpvOpFwidthCoarse = 215, + SpvOpEmitVertex = 218, + SpvOpEndPrimitive = 219, + SpvOpEmitStreamVertex = 220, + SpvOpEndStreamPrimitive = 221, + SpvOpControlBarrier = 224, + SpvOpMemoryBarrier = 225, + SpvOpAtomicLoad = 227, + SpvOpAtomicStore = 228, + SpvOpAtomicExchange = 229, + SpvOpAtomicCompareExchange = 230, + SpvOpAtomicCompareExchangeWeak = 231, + SpvOpAtomicIIncrement = 232, + SpvOpAtomicIDecrement = 233, + SpvOpAtomicIAdd = 234, + SpvOpAtomicISub = 235, + SpvOpAtomicSMin = 236, + SpvOpAtomicUMin = 237, + SpvOpAtomicSMax = 238, + SpvOpAtomicUMax = 239, + SpvOpAtomicAnd = 240, + SpvOpAtomicOr = 241, + SpvOpAtomicXor = 242, + SpvOpPhi = 245, + SpvOpLoopMerge = 246, + SpvOpSelectionMerge = 247, + SpvOpLabel = 248, + SpvOpBranch = 249, + SpvOpBranchConditional = 250, + SpvOpSwitch = 251, + SpvOpKill = 252, + SpvOpReturn = 253, + SpvOpReturnValue = 254, + SpvOpUnreachable = 255, + SpvOpLifetimeStart = 256, + SpvOpLifetimeStop = 257, + SpvOpGroupAsyncCopy = 259, + SpvOpGroupWaitEvents = 260, + SpvOpGroupAll = 261, + SpvOpGroupAny = 262, + SpvOpGroupBroadcast = 263, + SpvOpGroupIAdd = 264, + SpvOpGroupFAdd = 265, + SpvOpGroupFMin = 266, + SpvOpGroupUMin = 267, + SpvOpGroupSMin = 268, + SpvOpGroupFMax = 269, + SpvOpGroupUMax = 270, + SpvOpGroupSMax = 271, + SpvOpReadPipe = 274, + SpvOpWritePipe = 275, + SpvOpReservedReadPipe = 276, + SpvOpReservedWritePipe = 277, + SpvOpReserveReadPipePackets = 278, + SpvOpReserveWritePipePackets = 279, + SpvOpCommitReadPipe = 280, + SpvOpCommitWritePipe = 281, + SpvOpIsValidReserveId = 282, + SpvOpGetNumPipePackets = 283, + SpvOpGetMaxPipePackets = 284, + SpvOpGroupReserveReadPipePackets = 285, + SpvOpGroupReserveWritePipePackets = 286, + SpvOpGroupCommitReadPipe = 287, + SpvOpGroupCommitWritePipe = 288, + SpvOpEnqueueMarker = 291, + SpvOpEnqueueKernel = 292, + SpvOpGetKernelNDrangeSubGroupCount = 293, + SpvOpGetKernelNDrangeMaxSubGroupSize = 294, + SpvOpGetKernelWorkGroupSize = 295, + SpvOpGetKernelPreferredWorkGroupSizeMultiple = 296, + SpvOpRetainEvent = 297, + SpvOpReleaseEvent = 298, + SpvOpCreateUserEvent = 299, + SpvOpIsValidEvent = 300, + SpvOpSetUserEventStatus = 301, + SpvOpCaptureEventProfilingInfo = 302, + SpvOpGetDefaultQueue = 303, + SpvOpBuildNDRange = 304, + SpvOpImageSparseSampleImplicitLod = 305, + SpvOpImageSparseSampleExplicitLod = 306, + SpvOpImageSparseSampleDrefImplicitLod = 307, + SpvOpImageSparseSampleDrefExplicitLod = 308, + SpvOpImageSparseSampleProjImplicitLod = 309, + SpvOpImageSparseSampleProjExplicitLod = 310, + SpvOpImageSparseSampleProjDrefImplicitLod = 311, + SpvOpImageSparseSampleProjDrefExplicitLod = 312, + SpvOpImageSparseFetch = 313, + SpvOpImageSparseGather = 314, + SpvOpImageSparseDrefGather = 315, + SpvOpImageSparseTexelsResident = 316, + SpvOpNoLine = 317, + SpvOpAtomicFlagTestAndSet = 318, + SpvOpAtomicFlagClear = 319, + SpvOpImageSparseRead = 320, +} SpvOp; + +#endif // #ifndef spirv_H + diff --git a/mojoshader/spirv/spirv_cross_c.h b/mojoshader/spirv/spirv_cross_c.h new file mode 100644 index 0000000..4736996 --- /dev/null +++ b/mojoshader/spirv/spirv_cross_c.h @@ -0,0 +1,1101 @@ +/* + * Copyright 2019-2021 Hans-Kristian Arntzen + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * At your option, you may choose to accept this material under either: + * 1. The Apache License, Version 2.0, found at , or + * 2. The MIT License, found at . + */ + +#ifndef SPIRV_CROSS_C_API_H +#define SPIRV_CROSS_C_API_H + +#include +#include "spirv.h" + +/* + * C89-compatible wrapper for SPIRV-Cross' API. + * Documentation here is sparse unless the behavior does not map 1:1 with C++ API. + * It is recommended to look at the canonical C++ API for more detailed information. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* Bumped if ABI or API breaks backwards compatibility. */ +#define SPVC_C_API_VERSION_MAJOR 0 +/* Bumped if APIs or enumerations are added in a backwards compatible way. */ +#define SPVC_C_API_VERSION_MINOR 59 +/* Bumped if internal implementation details change. */ +#define SPVC_C_API_VERSION_PATCH 0 + +#if !defined(SPVC_PUBLIC_API) +#if defined(SPVC_EXPORT_SYMBOLS) +/* Exports symbols. Standard C calling convention is used. */ +#if defined(__GNUC__) +#define SPVC_PUBLIC_API __attribute__((visibility("default"))) +#elif defined(_MSC_VER) +#define SPVC_PUBLIC_API __declspec(dllexport) +#else +#define SPVC_PUBLIC_API +#endif +#else +#define SPVC_PUBLIC_API +#endif +#endif + +/* + * Gets the SPVC_C_API_VERSION_* used to build this library. + * Can be used to check for ABI mismatch if so-versioning did not catch it. + */ +SPVC_PUBLIC_API void spvc_get_version(unsigned *major, unsigned *minor, unsigned *patch); + +/* Gets a human readable version string to identify which commit a particular binary was created from. */ +SPVC_PUBLIC_API const char *spvc_get_commit_revision_and_timestamp(void); + +/* These types are opaque to the user. */ +typedef struct spvc_context_s *spvc_context; +typedef struct spvc_parsed_ir_s *spvc_parsed_ir; +typedef struct spvc_compiler_s *spvc_compiler; +typedef struct spvc_compiler_options_s *spvc_compiler_options; +typedef struct spvc_resources_s *spvc_resources; +struct spvc_type_s; +typedef const struct spvc_type_s *spvc_type; +typedef struct spvc_constant_s *spvc_constant; +struct spvc_set_s; +typedef const struct spvc_set_s *spvc_set; + +/* + * Shallow typedefs. All SPIR-V IDs are plain 32-bit numbers, but this helps communicate which data is used. + * Maps to a SPIRType. + */ +typedef SpvId spvc_type_id; +/* Maps to a SPIRVariable. */ +typedef SpvId spvc_variable_id; +/* Maps to a SPIRConstant. */ +typedef SpvId spvc_constant_id; + +/* See C++ API. */ +typedef struct spvc_reflected_resource +{ + spvc_variable_id id; + spvc_type_id base_type_id; + spvc_type_id type_id; + const char *name; +} spvc_reflected_resource; + +typedef struct spvc_reflected_builtin_resource +{ + SpvBuiltIn builtin; + spvc_type_id value_type_id; + spvc_reflected_resource resource; +} spvc_reflected_builtin_resource; + +/* See C++ API. */ +typedef struct spvc_entry_point +{ + SpvExecutionModel execution_model; + const char *name; +} spvc_entry_point; + +/* See C++ API. */ +typedef struct spvc_combined_image_sampler +{ + spvc_variable_id combined_id; + spvc_variable_id image_id; + spvc_variable_id sampler_id; +} spvc_combined_image_sampler; + +/* See C++ API. */ +typedef struct spvc_specialization_constant +{ + spvc_constant_id id; + unsigned constant_id; +} spvc_specialization_constant; + +/* See C++ API. */ +typedef struct spvc_buffer_range +{ + unsigned index; + size_t offset; + size_t range; +} spvc_buffer_range; + +/* See C++ API. */ +typedef struct spvc_hlsl_root_constants +{ + unsigned start; + unsigned end; + unsigned binding; + unsigned space; +} spvc_hlsl_root_constants; + +/* See C++ API. */ +typedef struct spvc_hlsl_vertex_attribute_remap +{ + unsigned location; + const char *semantic; +} spvc_hlsl_vertex_attribute_remap; + +/* + * Be compatible with non-C99 compilers, which do not have stdbool. + * Only recent MSVC compilers supports this for example, and ideally SPIRV-Cross should be linkable + * from a wide range of compilers in its C wrapper. + */ +typedef unsigned char spvc_bool; +#define SPVC_TRUE ((spvc_bool)1) +#define SPVC_FALSE ((spvc_bool)0) + +typedef enum spvc_result +{ + /* Success. */ + SPVC_SUCCESS = 0, + + /* The SPIR-V is invalid. Should have been caught by validation ideally. */ + SPVC_ERROR_INVALID_SPIRV = -1, + + /* The SPIR-V might be valid or invalid, but SPIRV-Cross currently cannot correctly translate this to your target language. */ + SPVC_ERROR_UNSUPPORTED_SPIRV = -2, + + /* If for some reason we hit this, new or malloc failed. */ + SPVC_ERROR_OUT_OF_MEMORY = -3, + + /* Invalid API argument. */ + SPVC_ERROR_INVALID_ARGUMENT = -4, + + SPVC_ERROR_INT_MAX = 0x7fffffff +} spvc_result; + +typedef enum spvc_capture_mode +{ + /* The Parsed IR payload will be copied, and the handle can be reused to create other compiler instances. */ + SPVC_CAPTURE_MODE_COPY = 0, + + /* + * The payload will now be owned by the compiler. + * parsed_ir should now be considered a dead blob and must not be used further. + * This is optimal for performance and should be the go-to option. + */ + SPVC_CAPTURE_MODE_TAKE_OWNERSHIP = 1, + + SPVC_CAPTURE_MODE_INT_MAX = 0x7fffffff +} spvc_capture_mode; + +typedef enum spvc_backend +{ + /* This backend can only perform reflection, no compiler options are supported. Maps to spirv_cross::Compiler. */ + SPVC_BACKEND_NONE = 0, + SPVC_BACKEND_GLSL = 1, /* spirv_cross::CompilerGLSL */ + SPVC_BACKEND_HLSL = 2, /* CompilerHLSL */ + SPVC_BACKEND_MSL = 3, /* CompilerMSL */ + SPVC_BACKEND_CPP = 4, /* CompilerCPP */ + SPVC_BACKEND_JSON = 5, /* CompilerReflection w/ JSON backend */ + SPVC_BACKEND_INT_MAX = 0x7fffffff +} spvc_backend; + +/* Maps to C++ API. */ +typedef enum spvc_resource_type +{ + SPVC_RESOURCE_TYPE_UNKNOWN = 0, + SPVC_RESOURCE_TYPE_UNIFORM_BUFFER = 1, + SPVC_RESOURCE_TYPE_STORAGE_BUFFER = 2, + SPVC_RESOURCE_TYPE_STAGE_INPUT = 3, + SPVC_RESOURCE_TYPE_STAGE_OUTPUT = 4, + SPVC_RESOURCE_TYPE_SUBPASS_INPUT = 5, + SPVC_RESOURCE_TYPE_STORAGE_IMAGE = 6, + SPVC_RESOURCE_TYPE_SAMPLED_IMAGE = 7, + SPVC_RESOURCE_TYPE_ATOMIC_COUNTER = 8, + SPVC_RESOURCE_TYPE_PUSH_CONSTANT = 9, + SPVC_RESOURCE_TYPE_SEPARATE_IMAGE = 10, + SPVC_RESOURCE_TYPE_SEPARATE_SAMPLERS = 11, + SPVC_RESOURCE_TYPE_ACCELERATION_STRUCTURE = 12, + SPVC_RESOURCE_TYPE_RAY_QUERY = 13, + SPVC_RESOURCE_TYPE_SHADER_RECORD_BUFFER = 14, + SPVC_RESOURCE_TYPE_INT_MAX = 0x7fffffff +} spvc_resource_type; + +typedef enum spvc_builtin_resource_type +{ + SPVC_BUILTIN_RESOURCE_TYPE_UNKNOWN = 0, + SPVC_BUILTIN_RESOURCE_TYPE_STAGE_INPUT = 1, + SPVC_BUILTIN_RESOURCE_TYPE_STAGE_OUTPUT = 2, + SPVC_BUILTIN_RESOURCE_TYPE_INT_MAX = 0x7fffffff +} spvc_builtin_resource_type; + +/* Maps to spirv_cross::SPIRType::BaseType. */ +typedef enum spvc_basetype +{ + SPVC_BASETYPE_UNKNOWN = 0, + SPVC_BASETYPE_VOID = 1, + SPVC_BASETYPE_BOOLEAN = 2, + SPVC_BASETYPE_INT8 = 3, + SPVC_BASETYPE_UINT8 = 4, + SPVC_BASETYPE_INT16 = 5, + SPVC_BASETYPE_UINT16 = 6, + SPVC_BASETYPE_INT32 = 7, + SPVC_BASETYPE_UINT32 = 8, + SPVC_BASETYPE_INT64 = 9, + SPVC_BASETYPE_UINT64 = 10, + SPVC_BASETYPE_ATOMIC_COUNTER = 11, + SPVC_BASETYPE_FP16 = 12, + SPVC_BASETYPE_FP32 = 13, + SPVC_BASETYPE_FP64 = 14, + SPVC_BASETYPE_STRUCT = 15, + SPVC_BASETYPE_IMAGE = 16, + SPVC_BASETYPE_SAMPLED_IMAGE = 17, + SPVC_BASETYPE_SAMPLER = 18, + SPVC_BASETYPE_ACCELERATION_STRUCTURE = 19, + + SPVC_BASETYPE_INT_MAX = 0x7fffffff +} spvc_basetype; + +#define SPVC_COMPILER_OPTION_COMMON_BIT 0x1000000 +#define SPVC_COMPILER_OPTION_GLSL_BIT 0x2000000 +#define SPVC_COMPILER_OPTION_HLSL_BIT 0x4000000 +#define SPVC_COMPILER_OPTION_MSL_BIT 0x8000000 +#define SPVC_COMPILER_OPTION_LANG_BITS 0x0f000000 +#define SPVC_COMPILER_OPTION_ENUM_BITS 0xffffff + +#define SPVC_MAKE_MSL_VERSION(major, minor, patch) ((major) * 10000 + (minor) * 100 + (patch)) + +/* Maps to C++ API. */ +typedef enum spvc_msl_platform +{ + SPVC_MSL_PLATFORM_IOS = 0, + SPVC_MSL_PLATFORM_MACOS = 1, + SPVC_MSL_PLATFORM_MAX_INT = 0x7fffffff +} spvc_msl_platform; + +/* Maps to C++ API. */ +typedef enum spvc_msl_index_type +{ + SPVC_MSL_INDEX_TYPE_NONE = 0, + SPVC_MSL_INDEX_TYPE_UINT16 = 1, + SPVC_MSL_INDEX_TYPE_UINT32 = 2, + SPVC_MSL_INDEX_TYPE_MAX_INT = 0x7fffffff +} spvc_msl_index_type; + +/* Maps to C++ API. */ +typedef enum spvc_msl_shader_variable_format +{ + SPVC_MSL_SHADER_VARIABLE_FORMAT_OTHER = 0, + SPVC_MSL_SHADER_VARIABLE_FORMAT_UINT8 = 1, + SPVC_MSL_SHADER_VARIABLE_FORMAT_UINT16 = 2, + SPVC_MSL_SHADER_VARIABLE_FORMAT_ANY16 = 3, + SPVC_MSL_SHADER_VARIABLE_FORMAT_ANY32 = 4, + + /* Deprecated names. */ + SPVC_MSL_VERTEX_FORMAT_OTHER = SPVC_MSL_SHADER_VARIABLE_FORMAT_OTHER, + SPVC_MSL_VERTEX_FORMAT_UINT8 = SPVC_MSL_SHADER_VARIABLE_FORMAT_UINT8, + SPVC_MSL_VERTEX_FORMAT_UINT16 = SPVC_MSL_SHADER_VARIABLE_FORMAT_UINT16, + SPVC_MSL_SHADER_INPUT_FORMAT_OTHER = SPVC_MSL_SHADER_VARIABLE_FORMAT_OTHER, + SPVC_MSL_SHADER_INPUT_FORMAT_UINT8 = SPVC_MSL_SHADER_VARIABLE_FORMAT_UINT8, + SPVC_MSL_SHADER_INPUT_FORMAT_UINT16 = SPVC_MSL_SHADER_VARIABLE_FORMAT_UINT16, + SPVC_MSL_SHADER_INPUT_FORMAT_ANY16 = SPVC_MSL_SHADER_VARIABLE_FORMAT_ANY16, + SPVC_MSL_SHADER_INPUT_FORMAT_ANY32 = SPVC_MSL_SHADER_VARIABLE_FORMAT_ANY32, + + + SPVC_MSL_SHADER_INPUT_FORMAT_INT_MAX = 0x7fffffff +} spvc_msl_shader_variable_format, spvc_msl_shader_input_format, spvc_msl_vertex_format; + +/* Maps to C++ API. Deprecated; use spvc_msl_shader_interface_var. */ +typedef struct spvc_msl_vertex_attribute +{ + unsigned location; + + /* Obsolete, do not use. Only lingers on for ABI compatibility. */ + unsigned msl_buffer; + /* Obsolete, do not use. Only lingers on for ABI compatibility. */ + unsigned msl_offset; + /* Obsolete, do not use. Only lingers on for ABI compatibility. */ + unsigned msl_stride; + /* Obsolete, do not use. Only lingers on for ABI compatibility. */ + spvc_bool per_instance; + + spvc_msl_vertex_format format; + SpvBuiltIn builtin; +} spvc_msl_vertex_attribute; + +/* + * Initializes the vertex attribute struct. + */ +SPVC_PUBLIC_API void spvc_msl_vertex_attribute_init(spvc_msl_vertex_attribute *attr); + +/* Maps to C++ API. Deprecated; use spvc_msl_shader_interface_var_2. */ +typedef struct spvc_msl_shader_interface_var +{ + unsigned location; + spvc_msl_vertex_format format; + SpvBuiltIn builtin; + unsigned vecsize; +} spvc_msl_shader_interface_var, spvc_msl_shader_input; + +/* + * Initializes the shader input struct. + * Deprecated. Use spvc_msl_shader_interface_var_init_2(). + */ +SPVC_PUBLIC_API void spvc_msl_shader_interface_var_init(spvc_msl_shader_interface_var *var); +/* + * Deprecated. Use spvc_msl_shader_interface_var_init_2(). + */ +SPVC_PUBLIC_API void spvc_msl_shader_input_init(spvc_msl_shader_input *input); + +/* Maps to C++ API. */ +typedef enum spvc_msl_shader_variable_rate +{ + SPVC_MSL_SHADER_VARIABLE_RATE_PER_VERTEX = 0, + SPVC_MSL_SHADER_VARIABLE_RATE_PER_PRIMITIVE = 1, + SPVC_MSL_SHADER_VARIABLE_RATE_PER_PATCH = 2, + + SPVC_MSL_SHADER_VARIABLE_RATE_INT_MAX = 0x7fffffff, +} spvc_msl_shader_variable_rate; + +/* Maps to C++ API. */ +typedef struct spvc_msl_shader_interface_var_2 +{ + unsigned location; + spvc_msl_shader_variable_format format; + SpvBuiltIn builtin; + unsigned vecsize; + spvc_msl_shader_variable_rate rate; +} spvc_msl_shader_interface_var_2; + +/* + * Initializes the shader interface variable struct. + */ +SPVC_PUBLIC_API void spvc_msl_shader_interface_var_init_2(spvc_msl_shader_interface_var_2 *var); + +/* Maps to C++ API. */ +typedef struct spvc_msl_resource_binding +{ + SpvExecutionModel stage; + unsigned desc_set; + unsigned binding; + unsigned msl_buffer; + unsigned msl_texture; + unsigned msl_sampler; +} spvc_msl_resource_binding; + +/* + * Initializes the resource binding struct. + * The defaults are non-zero. + */ +SPVC_PUBLIC_API void spvc_msl_resource_binding_init(spvc_msl_resource_binding *binding); + +#define SPVC_MSL_PUSH_CONSTANT_DESC_SET (~(0u)) +#define SPVC_MSL_PUSH_CONSTANT_BINDING (0) +#define SPVC_MSL_SWIZZLE_BUFFER_BINDING (~(1u)) +#define SPVC_MSL_BUFFER_SIZE_BUFFER_BINDING (~(2u)) +#define SPVC_MSL_ARGUMENT_BUFFER_BINDING (~(3u)) + +/* Obsolete. Sticks around for backwards compatibility. */ +#define SPVC_MSL_AUX_BUFFER_STRUCT_VERSION 1 + +/* Runtime check for incompatibility. Obsolete. */ +SPVC_PUBLIC_API unsigned spvc_msl_get_aux_buffer_struct_version(void); + +/* Maps to C++ API. */ +typedef enum spvc_msl_sampler_coord +{ + SPVC_MSL_SAMPLER_COORD_NORMALIZED = 0, + SPVC_MSL_SAMPLER_COORD_PIXEL = 1, + SPVC_MSL_SAMPLER_INT_MAX = 0x7fffffff +} spvc_msl_sampler_coord; + +/* Maps to C++ API. */ +typedef enum spvc_msl_sampler_filter +{ + SPVC_MSL_SAMPLER_FILTER_NEAREST = 0, + SPVC_MSL_SAMPLER_FILTER_LINEAR = 1, + SPVC_MSL_SAMPLER_FILTER_INT_MAX = 0x7fffffff +} spvc_msl_sampler_filter; + +/* Maps to C++ API. */ +typedef enum spvc_msl_sampler_mip_filter +{ + SPVC_MSL_SAMPLER_MIP_FILTER_NONE = 0, + SPVC_MSL_SAMPLER_MIP_FILTER_NEAREST = 1, + SPVC_MSL_SAMPLER_MIP_FILTER_LINEAR = 2, + SPVC_MSL_SAMPLER_MIP_FILTER_INT_MAX = 0x7fffffff +} spvc_msl_sampler_mip_filter; + +/* Maps to C++ API. */ +typedef enum spvc_msl_sampler_address +{ + SPVC_MSL_SAMPLER_ADDRESS_CLAMP_TO_ZERO = 0, + SPVC_MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE = 1, + SPVC_MSL_SAMPLER_ADDRESS_CLAMP_TO_BORDER = 2, + SPVC_MSL_SAMPLER_ADDRESS_REPEAT = 3, + SPVC_MSL_SAMPLER_ADDRESS_MIRRORED_REPEAT = 4, + SPVC_MSL_SAMPLER_ADDRESS_INT_MAX = 0x7fffffff +} spvc_msl_sampler_address; + +/* Maps to C++ API. */ +typedef enum spvc_msl_sampler_compare_func +{ + SPVC_MSL_SAMPLER_COMPARE_FUNC_NEVER = 0, + SPVC_MSL_SAMPLER_COMPARE_FUNC_LESS = 1, + SPVC_MSL_SAMPLER_COMPARE_FUNC_LESS_EQUAL = 2, + SPVC_MSL_SAMPLER_COMPARE_FUNC_GREATER = 3, + SPVC_MSL_SAMPLER_COMPARE_FUNC_GREATER_EQUAL = 4, + SPVC_MSL_SAMPLER_COMPARE_FUNC_EQUAL = 5, + SPVC_MSL_SAMPLER_COMPARE_FUNC_NOT_EQUAL = 6, + SPVC_MSL_SAMPLER_COMPARE_FUNC_ALWAYS = 7, + SPVC_MSL_SAMPLER_COMPARE_FUNC_INT_MAX = 0x7fffffff +} spvc_msl_sampler_compare_func; + +/* Maps to C++ API. */ +typedef enum spvc_msl_sampler_border_color +{ + SPVC_MSL_SAMPLER_BORDER_COLOR_TRANSPARENT_BLACK = 0, + SPVC_MSL_SAMPLER_BORDER_COLOR_OPAQUE_BLACK = 1, + SPVC_MSL_SAMPLER_BORDER_COLOR_OPAQUE_WHITE = 2, + SPVC_MSL_SAMPLER_BORDER_COLOR_INT_MAX = 0x7fffffff +} spvc_msl_sampler_border_color; + +/* Maps to C++ API. */ +typedef enum spvc_msl_format_resolution +{ + SPVC_MSL_FORMAT_RESOLUTION_444 = 0, + SPVC_MSL_FORMAT_RESOLUTION_422, + SPVC_MSL_FORMAT_RESOLUTION_420, + SPVC_MSL_FORMAT_RESOLUTION_INT_MAX = 0x7fffffff +} spvc_msl_format_resolution; + +/* Maps to C++ API. */ +typedef enum spvc_msl_chroma_location +{ + SPVC_MSL_CHROMA_LOCATION_COSITED_EVEN = 0, + SPVC_MSL_CHROMA_LOCATION_MIDPOINT, + SPVC_MSL_CHROMA_LOCATION_INT_MAX = 0x7fffffff +} spvc_msl_chroma_location; + +/* Maps to C++ API. */ +typedef enum spvc_msl_component_swizzle +{ + SPVC_MSL_COMPONENT_SWIZZLE_IDENTITY = 0, + SPVC_MSL_COMPONENT_SWIZZLE_ZERO, + SPVC_MSL_COMPONENT_SWIZZLE_ONE, + SPVC_MSL_COMPONENT_SWIZZLE_R, + SPVC_MSL_COMPONENT_SWIZZLE_G, + SPVC_MSL_COMPONENT_SWIZZLE_B, + SPVC_MSL_COMPONENT_SWIZZLE_A, + SPVC_MSL_COMPONENT_SWIZZLE_INT_MAX = 0x7fffffff +} spvc_msl_component_swizzle; + +/* Maps to C++ API. */ +typedef enum spvc_msl_sampler_ycbcr_model_conversion +{ + SPVC_MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY = 0, + SPVC_MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY, + SPVC_MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_709, + SPVC_MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_601, + SPVC_MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_2020, + SPVC_MSL_SAMPLER_YCBCR_MODEL_CONVERSION_INT_MAX = 0x7fffffff +} spvc_msl_sampler_ycbcr_model_conversion; + +/* Maps to C+ API. */ +typedef enum spvc_msl_sampler_ycbcr_range +{ + SPVC_MSL_SAMPLER_YCBCR_RANGE_ITU_FULL = 0, + SPVC_MSL_SAMPLER_YCBCR_RANGE_ITU_NARROW, + SPVC_MSL_SAMPLER_YCBCR_RANGE_INT_MAX = 0x7fffffff +} spvc_msl_sampler_ycbcr_range; + +/* Maps to C++ API. */ +typedef struct spvc_msl_constexpr_sampler +{ + spvc_msl_sampler_coord coord; + spvc_msl_sampler_filter min_filter; + spvc_msl_sampler_filter mag_filter; + spvc_msl_sampler_mip_filter mip_filter; + spvc_msl_sampler_address s_address; + spvc_msl_sampler_address t_address; + spvc_msl_sampler_address r_address; + spvc_msl_sampler_compare_func compare_func; + spvc_msl_sampler_border_color border_color; + float lod_clamp_min; + float lod_clamp_max; + int max_anisotropy; + + spvc_bool compare_enable; + spvc_bool lod_clamp_enable; + spvc_bool anisotropy_enable; +} spvc_msl_constexpr_sampler; + +/* + * Initializes the constexpr sampler struct. + * The defaults are non-zero. + */ +SPVC_PUBLIC_API void spvc_msl_constexpr_sampler_init(spvc_msl_constexpr_sampler *sampler); + +/* Maps to the sampler Y'CbCr conversion-related portions of MSLConstexprSampler. See C++ API for defaults and details. */ +typedef struct spvc_msl_sampler_ycbcr_conversion +{ + unsigned planes; + spvc_msl_format_resolution resolution; + spvc_msl_sampler_filter chroma_filter; + spvc_msl_chroma_location x_chroma_offset; + spvc_msl_chroma_location y_chroma_offset; + spvc_msl_component_swizzle swizzle[4]; + spvc_msl_sampler_ycbcr_model_conversion ycbcr_model; + spvc_msl_sampler_ycbcr_range ycbcr_range; + unsigned bpc; +} spvc_msl_sampler_ycbcr_conversion; + +/* + * Initializes the constexpr sampler struct. + * The defaults are non-zero. + */ +SPVC_PUBLIC_API void spvc_msl_sampler_ycbcr_conversion_init(spvc_msl_sampler_ycbcr_conversion *conv); + +/* Maps to C++ API. */ +typedef enum spvc_hlsl_binding_flag_bits +{ + SPVC_HLSL_BINDING_AUTO_NONE_BIT = 0, + SPVC_HLSL_BINDING_AUTO_PUSH_CONSTANT_BIT = 1 << 0, + SPVC_HLSL_BINDING_AUTO_CBV_BIT = 1 << 1, + SPVC_HLSL_BINDING_AUTO_SRV_BIT = 1 << 2, + SPVC_HLSL_BINDING_AUTO_UAV_BIT = 1 << 3, + SPVC_HLSL_BINDING_AUTO_SAMPLER_BIT = 1 << 4, + SPVC_HLSL_BINDING_AUTO_ALL = 0x7fffffff +} spvc_hlsl_binding_flag_bits; +typedef unsigned spvc_hlsl_binding_flags; + +#define SPVC_HLSL_PUSH_CONSTANT_DESC_SET (~(0u)) +#define SPVC_HLSL_PUSH_CONSTANT_BINDING (0) + +/* Maps to C++ API. */ +typedef struct spvc_hlsl_resource_binding_mapping +{ + unsigned register_space; + unsigned register_binding; +} spvc_hlsl_resource_binding_mapping; + +typedef struct spvc_hlsl_resource_binding +{ + SpvExecutionModel stage; + unsigned desc_set; + unsigned binding; + + spvc_hlsl_resource_binding_mapping cbv, uav, srv, sampler; +} spvc_hlsl_resource_binding; + +/* + * Initializes the resource binding struct. + * The defaults are non-zero. + */ +SPVC_PUBLIC_API void spvc_hlsl_resource_binding_init(spvc_hlsl_resource_binding *binding); + +/* Maps to the various spirv_cross::Compiler*::Option structures. See C++ API for defaults and details. */ +typedef enum spvc_compiler_option +{ + SPVC_COMPILER_OPTION_UNKNOWN = 0, + + SPVC_COMPILER_OPTION_FORCE_TEMPORARY = 1 | SPVC_COMPILER_OPTION_COMMON_BIT, + SPVC_COMPILER_OPTION_FLATTEN_MULTIDIMENSIONAL_ARRAYS = 2 | SPVC_COMPILER_OPTION_COMMON_BIT, + SPVC_COMPILER_OPTION_FIXUP_DEPTH_CONVENTION = 3 | SPVC_COMPILER_OPTION_COMMON_BIT, + SPVC_COMPILER_OPTION_FLIP_VERTEX_Y = 4 | SPVC_COMPILER_OPTION_COMMON_BIT, + + SPVC_COMPILER_OPTION_GLSL_SUPPORT_NONZERO_BASE_INSTANCE = 5 | SPVC_COMPILER_OPTION_GLSL_BIT, + SPVC_COMPILER_OPTION_GLSL_SEPARATE_SHADER_OBJECTS = 6 | SPVC_COMPILER_OPTION_GLSL_BIT, + SPVC_COMPILER_OPTION_GLSL_ENABLE_420PACK_EXTENSION = 7 | SPVC_COMPILER_OPTION_GLSL_BIT, + SPVC_COMPILER_OPTION_GLSL_VERSION = 8 | SPVC_COMPILER_OPTION_GLSL_BIT, + SPVC_COMPILER_OPTION_GLSL_ES = 9 | SPVC_COMPILER_OPTION_GLSL_BIT, + SPVC_COMPILER_OPTION_GLSL_VULKAN_SEMANTICS = 10 | SPVC_COMPILER_OPTION_GLSL_BIT, + SPVC_COMPILER_OPTION_GLSL_ES_DEFAULT_FLOAT_PRECISION_HIGHP = 11 | SPVC_COMPILER_OPTION_GLSL_BIT, + SPVC_COMPILER_OPTION_GLSL_ES_DEFAULT_INT_PRECISION_HIGHP = 12 | SPVC_COMPILER_OPTION_GLSL_BIT, + + SPVC_COMPILER_OPTION_HLSL_SHADER_MODEL = 13 | SPVC_COMPILER_OPTION_HLSL_BIT, + SPVC_COMPILER_OPTION_HLSL_POINT_SIZE_COMPAT = 14 | SPVC_COMPILER_OPTION_HLSL_BIT, + SPVC_COMPILER_OPTION_HLSL_POINT_COORD_COMPAT = 15 | SPVC_COMPILER_OPTION_HLSL_BIT, + SPVC_COMPILER_OPTION_HLSL_SUPPORT_NONZERO_BASE_VERTEX_BASE_INSTANCE = 16 | SPVC_COMPILER_OPTION_HLSL_BIT, + + SPVC_COMPILER_OPTION_MSL_VERSION = 17 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_TEXEL_BUFFER_TEXTURE_WIDTH = 18 | SPVC_COMPILER_OPTION_MSL_BIT, + + /* Obsolete, use SWIZZLE_BUFFER_INDEX instead. */ + SPVC_COMPILER_OPTION_MSL_AUX_BUFFER_INDEX = 19 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_SWIZZLE_BUFFER_INDEX = 19 | SPVC_COMPILER_OPTION_MSL_BIT, + + SPVC_COMPILER_OPTION_MSL_INDIRECT_PARAMS_BUFFER_INDEX = 20 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_SHADER_OUTPUT_BUFFER_INDEX = 21 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_SHADER_PATCH_OUTPUT_BUFFER_INDEX = 22 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_SHADER_TESS_FACTOR_OUTPUT_BUFFER_INDEX = 23 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_SHADER_INPUT_WORKGROUP_INDEX = 24 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_ENABLE_POINT_SIZE_BUILTIN = 25 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_DISABLE_RASTERIZATION = 26 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_CAPTURE_OUTPUT_TO_BUFFER = 27 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_SWIZZLE_TEXTURE_SAMPLES = 28 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_PAD_FRAGMENT_OUTPUT_COMPONENTS = 29 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_TESS_DOMAIN_ORIGIN_LOWER_LEFT = 30 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_PLATFORM = 31 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_ARGUMENT_BUFFERS = 32 | SPVC_COMPILER_OPTION_MSL_BIT, + + SPVC_COMPILER_OPTION_GLSL_EMIT_PUSH_CONSTANT_AS_UNIFORM_BUFFER = 33 | SPVC_COMPILER_OPTION_GLSL_BIT, + + SPVC_COMPILER_OPTION_MSL_TEXTURE_BUFFER_NATIVE = 34 | SPVC_COMPILER_OPTION_MSL_BIT, + + SPVC_COMPILER_OPTION_GLSL_EMIT_UNIFORM_BUFFER_AS_PLAIN_UNIFORMS = 35 | SPVC_COMPILER_OPTION_GLSL_BIT, + + SPVC_COMPILER_OPTION_MSL_BUFFER_SIZE_BUFFER_INDEX = 36 | SPVC_COMPILER_OPTION_MSL_BIT, + + SPVC_COMPILER_OPTION_EMIT_LINE_DIRECTIVES = 37 | SPVC_COMPILER_OPTION_COMMON_BIT, + + SPVC_COMPILER_OPTION_MSL_MULTIVIEW = 38 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_VIEW_MASK_BUFFER_INDEX = 39 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_DEVICE_INDEX = 40 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_VIEW_INDEX_FROM_DEVICE_INDEX = 41 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_DISPATCH_BASE = 42 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_DYNAMIC_OFFSETS_BUFFER_INDEX = 43 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_TEXTURE_1D_AS_2D = 44 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_ENABLE_BASE_INDEX_ZERO = 45 | SPVC_COMPILER_OPTION_MSL_BIT, + + /* Obsolete. Use MSL_FRAMEBUFFER_FETCH_SUBPASS instead. */ + SPVC_COMPILER_OPTION_MSL_IOS_FRAMEBUFFER_FETCH_SUBPASS = 46 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_FRAMEBUFFER_FETCH_SUBPASS = 46 | SPVC_COMPILER_OPTION_MSL_BIT, + + SPVC_COMPILER_OPTION_MSL_INVARIANT_FP_MATH = 47 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_EMULATE_CUBEMAP_ARRAY = 48 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_ENABLE_DECORATION_BINDING = 49 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_FORCE_ACTIVE_ARGUMENT_BUFFER_RESOURCES = 50 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_FORCE_NATIVE_ARRAYS = 51 | SPVC_COMPILER_OPTION_MSL_BIT, + + SPVC_COMPILER_OPTION_ENABLE_STORAGE_IMAGE_QUALIFIER_DEDUCTION = 52 | SPVC_COMPILER_OPTION_COMMON_BIT, + + SPVC_COMPILER_OPTION_HLSL_FORCE_STORAGE_BUFFER_AS_UAV = 53 | SPVC_COMPILER_OPTION_HLSL_BIT, + + SPVC_COMPILER_OPTION_FORCE_ZERO_INITIALIZED_VARIABLES = 54 | SPVC_COMPILER_OPTION_COMMON_BIT, + + SPVC_COMPILER_OPTION_HLSL_NONWRITABLE_UAV_TEXTURE_AS_SRV = 55 | SPVC_COMPILER_OPTION_HLSL_BIT, + + SPVC_COMPILER_OPTION_MSL_ENABLE_FRAG_OUTPUT_MASK = 56 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_ENABLE_FRAG_DEPTH_BUILTIN = 57 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_ENABLE_FRAG_STENCIL_REF_BUILTIN = 58 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_ENABLE_CLIP_DISTANCE_USER_VARYING = 59 | SPVC_COMPILER_OPTION_MSL_BIT, + + SPVC_COMPILER_OPTION_HLSL_ENABLE_16BIT_TYPES = 60 | SPVC_COMPILER_OPTION_HLSL_BIT, + + SPVC_COMPILER_OPTION_MSL_MULTI_PATCH_WORKGROUP = 61 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_SHADER_INPUT_BUFFER_INDEX = 62 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_SHADER_INDEX_BUFFER_INDEX = 63 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_VERTEX_FOR_TESSELLATION = 64 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_VERTEX_INDEX_TYPE = 65 | SPVC_COMPILER_OPTION_MSL_BIT, + + SPVC_COMPILER_OPTION_GLSL_FORCE_FLATTENED_IO_BLOCKS = 66 | SPVC_COMPILER_OPTION_GLSL_BIT, + + SPVC_COMPILER_OPTION_MSL_MULTIVIEW_LAYERED_RENDERING = 67 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_ARRAYED_SUBPASS_INPUT = 68 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_R32UI_LINEAR_TEXTURE_ALIGNMENT = 69 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_R32UI_ALIGNMENT_CONSTANT_ID = 70 | SPVC_COMPILER_OPTION_MSL_BIT, + + SPVC_COMPILER_OPTION_HLSL_FLATTEN_MATRIX_VERTEX_INPUT_SEMANTICS = 71 | SPVC_COMPILER_OPTION_HLSL_BIT, + + SPVC_COMPILER_OPTION_MSL_IOS_USE_SIMDGROUP_FUNCTIONS = 72 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_EMULATE_SUBGROUPS = 73 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_FIXED_SUBGROUP_SIZE = 74 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_FORCE_SAMPLE_RATE_SHADING = 75 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_IOS_SUPPORT_BASE_VERTEX_INSTANCE = 76 | SPVC_COMPILER_OPTION_MSL_BIT, + + SPVC_COMPILER_OPTION_GLSL_OVR_MULTIVIEW_VIEW_COUNT = 77 | SPVC_COMPILER_OPTION_GLSL_BIT, + + SPVC_COMPILER_OPTION_RELAX_NAN_CHECKS = 78 | SPVC_COMPILER_OPTION_COMMON_BIT, + + SPVC_COMPILER_OPTION_MSL_RAW_BUFFER_TESE_INPUT = 79 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_SHADER_PATCH_INPUT_BUFFER_INDEX = 80 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_MANUAL_HELPER_INVOCATION_UPDATES = 81 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_CHECK_DISCARDED_FRAG_STORES = 82 | SPVC_COMPILER_OPTION_MSL_BIT, + + SPVC_COMPILER_OPTION_GLSL_ENABLE_ROW_MAJOR_LOAD_WORKAROUND = 83 | SPVC_COMPILER_OPTION_GLSL_BIT, + + SPVC_COMPILER_OPTION_MSL_ARGUMENT_BUFFERS_TIER = 84 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_SAMPLE_DREF_LOD_ARRAY_AS_GRAD = 85 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_READWRITE_TEXTURE_FENCES = 86 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_REPLACE_RECURSIVE_INPUTS = 87 | SPVC_COMPILER_OPTION_MSL_BIT, + SPVC_COMPILER_OPTION_MSL_AGX_MANUAL_CUBE_GRAD_FIXUP = 88 | SPVC_COMPILER_OPTION_MSL_BIT, + + SPVC_COMPILER_OPTION_INT_MAX = 0x7fffffff +} spvc_compiler_option; + +/* + * Context is the highest-level API construct. + * The context owns all memory allocations made by its child object hierarchy, including various non-opaque structs and strings. + * This means that the API user only has to care about one "destroy" call ever when using the C API. + * All pointers handed out by the APIs are only valid as long as the context + * is alive and spvc_context_release_allocations has not been called. + */ +SPVC_PUBLIC_API spvc_result spvc_context_create(spvc_context *context); + +/* Frees all memory allocations and objects associated with the context and its child objects. */ +SPVC_PUBLIC_API void spvc_context_destroy(spvc_context context); + +/* Frees all memory allocations and objects associated with the context and its child objects, but keeps the context alive. */ +SPVC_PUBLIC_API void spvc_context_release_allocations(spvc_context context); + +/* Get the string for the last error which was logged. */ +SPVC_PUBLIC_API const char *spvc_context_get_last_error_string(spvc_context context); + +/* Get notified in a callback when an error triggers. Useful for debugging. */ +typedef void (*spvc_error_callback)(void *userdata, const char *error); +SPVC_PUBLIC_API void spvc_context_set_error_callback(spvc_context context, spvc_error_callback cb, void *userdata); + +/* SPIR-V parsing interface. Maps to Parser which then creates a ParsedIR, and that IR is extracted into the handle. */ +SPVC_PUBLIC_API spvc_result spvc_context_parse_spirv(spvc_context context, const SpvId *spirv, size_t word_count, + spvc_parsed_ir *parsed_ir); + +/* + * Create a compiler backend. Capture mode controls if we construct by copy or move semantics. + * It is always recommended to use SPVC_CAPTURE_MODE_TAKE_OWNERSHIP if you only intend to cross-compile the IR once. + */ +SPVC_PUBLIC_API spvc_result spvc_context_create_compiler(spvc_context context, spvc_backend backend, + spvc_parsed_ir parsed_ir, spvc_capture_mode mode, + spvc_compiler *compiler); + +/* Maps directly to C++ API. */ +SPVC_PUBLIC_API unsigned spvc_compiler_get_current_id_bound(spvc_compiler compiler); + +/* Create compiler options, which will initialize defaults. */ +SPVC_PUBLIC_API spvc_result spvc_compiler_create_compiler_options(spvc_compiler compiler, + spvc_compiler_options *options); +/* Override options. Will return error if e.g. MSL options are used for the HLSL backend, etc. */ +SPVC_PUBLIC_API spvc_result spvc_compiler_options_set_bool(spvc_compiler_options options, + spvc_compiler_option option, spvc_bool value); +SPVC_PUBLIC_API spvc_result spvc_compiler_options_set_uint(spvc_compiler_options options, + spvc_compiler_option option, unsigned value); +/* Set compiler options. */ +SPVC_PUBLIC_API spvc_result spvc_compiler_install_compiler_options(spvc_compiler compiler, + spvc_compiler_options options); + +/* Compile IR into a string. *source is owned by the context, and caller must not free it themselves. */ +SPVC_PUBLIC_API spvc_result spvc_compiler_compile(spvc_compiler compiler, const char **source); + +/* Maps to C++ API. */ +SPVC_PUBLIC_API spvc_result spvc_compiler_add_header_line(spvc_compiler compiler, const char *line); +SPVC_PUBLIC_API spvc_result spvc_compiler_require_extension(spvc_compiler compiler, const char *ext); +SPVC_PUBLIC_API size_t spvc_compiler_get_num_required_extensions(spvc_compiler compiler); +SPVC_PUBLIC_API const char *spvc_compiler_get_required_extension(spvc_compiler compiler, size_t index); +SPVC_PUBLIC_API spvc_result spvc_compiler_flatten_buffer_block(spvc_compiler compiler, spvc_variable_id id); + +SPVC_PUBLIC_API spvc_bool spvc_compiler_variable_is_depth_or_compare(spvc_compiler compiler, spvc_variable_id id); + +SPVC_PUBLIC_API spvc_result spvc_compiler_mask_stage_output_by_location(spvc_compiler compiler, + unsigned location, unsigned component); +SPVC_PUBLIC_API spvc_result spvc_compiler_mask_stage_output_by_builtin(spvc_compiler compiler, SpvBuiltIn builtin); + +/* + * HLSL specifics. + * Maps to C++ API. + */ +SPVC_PUBLIC_API spvc_result spvc_compiler_hlsl_set_root_constants_layout(spvc_compiler compiler, + const spvc_hlsl_root_constants *constant_info, + size_t count); +SPVC_PUBLIC_API spvc_result spvc_compiler_hlsl_add_vertex_attribute_remap(spvc_compiler compiler, + const spvc_hlsl_vertex_attribute_remap *remap, + size_t remaps); +SPVC_PUBLIC_API spvc_variable_id spvc_compiler_hlsl_remap_num_workgroups_builtin(spvc_compiler compiler); + +SPVC_PUBLIC_API spvc_result spvc_compiler_hlsl_set_resource_binding_flags(spvc_compiler compiler, + spvc_hlsl_binding_flags flags); + +SPVC_PUBLIC_API spvc_result spvc_compiler_hlsl_add_resource_binding(spvc_compiler compiler, + const spvc_hlsl_resource_binding *binding); +SPVC_PUBLIC_API spvc_bool spvc_compiler_hlsl_is_resource_used(spvc_compiler compiler, + SpvExecutionModel model, + unsigned set, + unsigned binding); + +/* + * MSL specifics. + * Maps to C++ API. + */ +SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_is_rasterization_disabled(spvc_compiler compiler); + +/* Obsolete. Renamed to needs_swizzle_buffer. */ +SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_needs_aux_buffer(spvc_compiler compiler); +SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_needs_swizzle_buffer(spvc_compiler compiler); +SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_needs_buffer_size_buffer(spvc_compiler compiler); + +SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_needs_output_buffer(spvc_compiler compiler); +SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_needs_patch_output_buffer(spvc_compiler compiler); +SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_needs_input_threadgroup_mem(spvc_compiler compiler); +SPVC_PUBLIC_API spvc_result spvc_compiler_msl_add_vertex_attribute(spvc_compiler compiler, + const spvc_msl_vertex_attribute *attrs); +SPVC_PUBLIC_API spvc_result spvc_compiler_msl_add_resource_binding(spvc_compiler compiler, + const spvc_msl_resource_binding *binding); +/* Deprecated; use spvc_compiler_msl_add_shader_input_2(). */ +SPVC_PUBLIC_API spvc_result spvc_compiler_msl_add_shader_input(spvc_compiler compiler, + const spvc_msl_shader_interface_var *input); +SPVC_PUBLIC_API spvc_result spvc_compiler_msl_add_shader_input_2(spvc_compiler compiler, + const spvc_msl_shader_interface_var_2 *input); +/* Deprecated; use spvc_compiler_msl_add_shader_output_2(). */ +SPVC_PUBLIC_API spvc_result spvc_compiler_msl_add_shader_output(spvc_compiler compiler, + const spvc_msl_shader_interface_var *output); +SPVC_PUBLIC_API spvc_result spvc_compiler_msl_add_shader_output_2(spvc_compiler compiler, + const spvc_msl_shader_interface_var_2 *output); +SPVC_PUBLIC_API spvc_result spvc_compiler_msl_add_discrete_descriptor_set(spvc_compiler compiler, unsigned desc_set); +SPVC_PUBLIC_API spvc_result spvc_compiler_msl_set_argument_buffer_device_address_space(spvc_compiler compiler, unsigned desc_set, spvc_bool device_address); + +/* Obsolete, use is_shader_input_used. */ +SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_is_vertex_attribute_used(spvc_compiler compiler, unsigned location); +SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_is_shader_input_used(spvc_compiler compiler, unsigned location); +SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_is_shader_output_used(spvc_compiler compiler, unsigned location); + +SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_is_resource_used(spvc_compiler compiler, + SpvExecutionModel model, + unsigned set, + unsigned binding); +SPVC_PUBLIC_API spvc_result spvc_compiler_msl_remap_constexpr_sampler(spvc_compiler compiler, spvc_variable_id id, const spvc_msl_constexpr_sampler *sampler); +SPVC_PUBLIC_API spvc_result spvc_compiler_msl_remap_constexpr_sampler_by_binding(spvc_compiler compiler, unsigned desc_set, unsigned binding, const spvc_msl_constexpr_sampler *sampler); +SPVC_PUBLIC_API spvc_result spvc_compiler_msl_remap_constexpr_sampler_ycbcr(spvc_compiler compiler, spvc_variable_id id, const spvc_msl_constexpr_sampler *sampler, const spvc_msl_sampler_ycbcr_conversion *conv); +SPVC_PUBLIC_API spvc_result spvc_compiler_msl_remap_constexpr_sampler_by_binding_ycbcr(spvc_compiler compiler, unsigned desc_set, unsigned binding, const spvc_msl_constexpr_sampler *sampler, const spvc_msl_sampler_ycbcr_conversion *conv); +SPVC_PUBLIC_API spvc_result spvc_compiler_msl_set_fragment_output_components(spvc_compiler compiler, unsigned location, unsigned components); + +SPVC_PUBLIC_API unsigned spvc_compiler_msl_get_automatic_resource_binding(spvc_compiler compiler, spvc_variable_id id); +SPVC_PUBLIC_API unsigned spvc_compiler_msl_get_automatic_resource_binding_secondary(spvc_compiler compiler, spvc_variable_id id); + +SPVC_PUBLIC_API spvc_result spvc_compiler_msl_add_dynamic_buffer(spvc_compiler compiler, unsigned desc_set, unsigned binding, unsigned index); + +SPVC_PUBLIC_API spvc_result spvc_compiler_msl_add_inline_uniform_block(spvc_compiler compiler, unsigned desc_set, unsigned binding); + +SPVC_PUBLIC_API spvc_result spvc_compiler_msl_set_combined_sampler_suffix(spvc_compiler compiler, const char *suffix); +SPVC_PUBLIC_API const char *spvc_compiler_msl_get_combined_sampler_suffix(spvc_compiler compiler); + +/* + * Reflect resources. + * Maps almost 1:1 to C++ API. + */ +SPVC_PUBLIC_API spvc_result spvc_compiler_get_active_interface_variables(spvc_compiler compiler, spvc_set *set); +SPVC_PUBLIC_API spvc_result spvc_compiler_set_enabled_interface_variables(spvc_compiler compiler, spvc_set set); +SPVC_PUBLIC_API spvc_result spvc_compiler_create_shader_resources(spvc_compiler compiler, spvc_resources *resources); +SPVC_PUBLIC_API spvc_result spvc_compiler_create_shader_resources_for_active_variables(spvc_compiler compiler, + spvc_resources *resources, + spvc_set active); +SPVC_PUBLIC_API spvc_result spvc_resources_get_resource_list_for_type(spvc_resources resources, spvc_resource_type type, + const spvc_reflected_resource **resource_list, + size_t *resource_size); + +SPVC_PUBLIC_API spvc_result spvc_resources_get_builtin_resource_list_for_type( + spvc_resources resources, spvc_builtin_resource_type type, + const spvc_reflected_builtin_resource **resource_list, + size_t *resource_size); + +/* + * Decorations. + * Maps to C++ API. + */ +SPVC_PUBLIC_API void spvc_compiler_set_decoration(spvc_compiler compiler, SpvId id, SpvDecoration decoration, + unsigned argument); +SPVC_PUBLIC_API void spvc_compiler_set_decoration_string(spvc_compiler compiler, SpvId id, SpvDecoration decoration, + const char *argument); +SPVC_PUBLIC_API void spvc_compiler_set_name(spvc_compiler compiler, SpvId id, const char *argument); +SPVC_PUBLIC_API void spvc_compiler_set_member_decoration(spvc_compiler compiler, spvc_type_id id, unsigned member_index, + SpvDecoration decoration, unsigned argument); +SPVC_PUBLIC_API void spvc_compiler_set_member_decoration_string(spvc_compiler compiler, spvc_type_id id, + unsigned member_index, SpvDecoration decoration, + const char *argument); +SPVC_PUBLIC_API void spvc_compiler_set_member_name(spvc_compiler compiler, spvc_type_id id, unsigned member_index, + const char *argument); +SPVC_PUBLIC_API void spvc_compiler_unset_decoration(spvc_compiler compiler, SpvId id, SpvDecoration decoration); +SPVC_PUBLIC_API void spvc_compiler_unset_member_decoration(spvc_compiler compiler, spvc_type_id id, + unsigned member_index, SpvDecoration decoration); + +SPVC_PUBLIC_API spvc_bool spvc_compiler_has_decoration(spvc_compiler compiler, SpvId id, SpvDecoration decoration); +SPVC_PUBLIC_API spvc_bool spvc_compiler_has_member_decoration(spvc_compiler compiler, spvc_type_id id, + unsigned member_index, SpvDecoration decoration); +SPVC_PUBLIC_API const char *spvc_compiler_get_name(spvc_compiler compiler, SpvId id); +SPVC_PUBLIC_API unsigned spvc_compiler_get_decoration(spvc_compiler compiler, SpvId id, SpvDecoration decoration); +SPVC_PUBLIC_API const char *spvc_compiler_get_decoration_string(spvc_compiler compiler, SpvId id, + SpvDecoration decoration); +SPVC_PUBLIC_API unsigned spvc_compiler_get_member_decoration(spvc_compiler compiler, spvc_type_id id, + unsigned member_index, SpvDecoration decoration); +SPVC_PUBLIC_API const char *spvc_compiler_get_member_decoration_string(spvc_compiler compiler, spvc_type_id id, + unsigned member_index, SpvDecoration decoration); +SPVC_PUBLIC_API const char *spvc_compiler_get_member_name(spvc_compiler compiler, spvc_type_id id, unsigned member_index); + +/* + * Entry points. + * Maps to C++ API. + */ +SPVC_PUBLIC_API spvc_result spvc_compiler_get_entry_points(spvc_compiler compiler, + const spvc_entry_point **entry_points, + size_t *num_entry_points); +SPVC_PUBLIC_API spvc_result spvc_compiler_set_entry_point(spvc_compiler compiler, const char *name, + SpvExecutionModel model); +SPVC_PUBLIC_API spvc_result spvc_compiler_rename_entry_point(spvc_compiler compiler, const char *old_name, + const char *new_name, SpvExecutionModel model); +SPVC_PUBLIC_API const char *spvc_compiler_get_cleansed_entry_point_name(spvc_compiler compiler, const char *name, + SpvExecutionModel model); +SPVC_PUBLIC_API void spvc_compiler_set_execution_mode(spvc_compiler compiler, SpvExecutionMode mode); +SPVC_PUBLIC_API void spvc_compiler_unset_execution_mode(spvc_compiler compiler, SpvExecutionMode mode); +SPVC_PUBLIC_API void spvc_compiler_set_execution_mode_with_arguments(spvc_compiler compiler, SpvExecutionMode mode, + unsigned arg0, unsigned arg1, unsigned arg2); +SPVC_PUBLIC_API spvc_result spvc_compiler_get_execution_modes(spvc_compiler compiler, const SpvExecutionMode **modes, + size_t *num_modes); +SPVC_PUBLIC_API unsigned spvc_compiler_get_execution_mode_argument(spvc_compiler compiler, SpvExecutionMode mode); +SPVC_PUBLIC_API unsigned spvc_compiler_get_execution_mode_argument_by_index(spvc_compiler compiler, + SpvExecutionMode mode, unsigned index); +SPVC_PUBLIC_API SpvExecutionModel spvc_compiler_get_execution_model(spvc_compiler compiler); +SPVC_PUBLIC_API void spvc_compiler_update_active_builtins(spvc_compiler compiler); +SPVC_PUBLIC_API spvc_bool spvc_compiler_has_active_builtin(spvc_compiler compiler, SpvBuiltIn builtin, SpvStorageClass storage); + +/* + * Type query interface. + * Maps to C++ API, except it's read-only. + */ +SPVC_PUBLIC_API spvc_type spvc_compiler_get_type_handle(spvc_compiler compiler, spvc_type_id id); + +/* Pulls out SPIRType::self. This effectively gives the type ID without array or pointer qualifiers. + * This is necessary when reflecting decoration/name information on members of a struct, + * which are placed in the base type, not the qualified type. + * This is similar to spvc_reflected_resource::base_type_id. */ +SPVC_PUBLIC_API spvc_type_id spvc_type_get_base_type_id(spvc_type type); + +SPVC_PUBLIC_API spvc_basetype spvc_type_get_basetype(spvc_type type); +SPVC_PUBLIC_API unsigned spvc_type_get_bit_width(spvc_type type); +SPVC_PUBLIC_API unsigned spvc_type_get_vector_size(spvc_type type); +SPVC_PUBLIC_API unsigned spvc_type_get_columns(spvc_type type); +SPVC_PUBLIC_API unsigned spvc_type_get_num_array_dimensions(spvc_type type); +SPVC_PUBLIC_API spvc_bool spvc_type_array_dimension_is_literal(spvc_type type, unsigned dimension); +SPVC_PUBLIC_API SpvId spvc_type_get_array_dimension(spvc_type type, unsigned dimension); +SPVC_PUBLIC_API unsigned spvc_type_get_num_member_types(spvc_type type); +SPVC_PUBLIC_API spvc_type_id spvc_type_get_member_type(spvc_type type, unsigned index); +SPVC_PUBLIC_API SpvStorageClass spvc_type_get_storage_class(spvc_type type); + +/* Image type query. */ +SPVC_PUBLIC_API spvc_type_id spvc_type_get_image_sampled_type(spvc_type type); +SPVC_PUBLIC_API SpvDim spvc_type_get_image_dimension(spvc_type type); +SPVC_PUBLIC_API spvc_bool spvc_type_get_image_is_depth(spvc_type type); +SPVC_PUBLIC_API spvc_bool spvc_type_get_image_arrayed(spvc_type type); +SPVC_PUBLIC_API spvc_bool spvc_type_get_image_multisampled(spvc_type type); +SPVC_PUBLIC_API spvc_bool spvc_type_get_image_is_storage(spvc_type type); +SPVC_PUBLIC_API SpvImageFormat spvc_type_get_image_storage_format(spvc_type type); +SPVC_PUBLIC_API SpvAccessQualifier spvc_type_get_image_access_qualifier(spvc_type type); + +/* + * Buffer layout query. + * Maps to C++ API. + */ +SPVC_PUBLIC_API spvc_result spvc_compiler_get_declared_struct_size(spvc_compiler compiler, spvc_type struct_type, size_t *size); +SPVC_PUBLIC_API spvc_result spvc_compiler_get_declared_struct_size_runtime_array(spvc_compiler compiler, + spvc_type struct_type, size_t array_size, size_t *size); +SPVC_PUBLIC_API spvc_result spvc_compiler_get_declared_struct_member_size(spvc_compiler compiler, spvc_type type, unsigned index, size_t *size); + +SPVC_PUBLIC_API spvc_result spvc_compiler_type_struct_member_offset(spvc_compiler compiler, + spvc_type type, unsigned index, unsigned *offset); +SPVC_PUBLIC_API spvc_result spvc_compiler_type_struct_member_array_stride(spvc_compiler compiler, + spvc_type type, unsigned index, unsigned *stride); +SPVC_PUBLIC_API spvc_result spvc_compiler_type_struct_member_matrix_stride(spvc_compiler compiler, + spvc_type type, unsigned index, unsigned *stride); + +/* + * Workaround helper functions. + * Maps to C++ API. + */ +SPVC_PUBLIC_API spvc_result spvc_compiler_build_dummy_sampler_for_combined_images(spvc_compiler compiler, spvc_variable_id *id); +SPVC_PUBLIC_API spvc_result spvc_compiler_build_combined_image_samplers(spvc_compiler compiler); +SPVC_PUBLIC_API spvc_result spvc_compiler_get_combined_image_samplers(spvc_compiler compiler, + const spvc_combined_image_sampler **samplers, + size_t *num_samplers); + +/* + * Constants + * Maps to C++ API. + */ +SPVC_PUBLIC_API spvc_result spvc_compiler_get_specialization_constants(spvc_compiler compiler, + const spvc_specialization_constant **constants, + size_t *num_constants); +SPVC_PUBLIC_API spvc_constant spvc_compiler_get_constant_handle(spvc_compiler compiler, + spvc_constant_id id); + +SPVC_PUBLIC_API spvc_constant_id spvc_compiler_get_work_group_size_specialization_constants(spvc_compiler compiler, + spvc_specialization_constant *x, + spvc_specialization_constant *y, + spvc_specialization_constant *z); + +/* + * Buffer ranges + * Maps to C++ API. + */ +SPVC_PUBLIC_API spvc_result spvc_compiler_get_active_buffer_ranges(spvc_compiler compiler, + spvc_variable_id id, + const spvc_buffer_range **ranges, + size_t *num_ranges); + +/* + * No stdint.h until C99, sigh :( + * For smaller types, the result is sign or zero-extended as appropriate. + * Maps to C++ API. + * TODO: The SPIRConstant query interface and modification interface is not quite complete. + */ +SPVC_PUBLIC_API float spvc_constant_get_scalar_fp16(spvc_constant constant, unsigned column, unsigned row); +SPVC_PUBLIC_API float spvc_constant_get_scalar_fp32(spvc_constant constant, unsigned column, unsigned row); +SPVC_PUBLIC_API double spvc_constant_get_scalar_fp64(spvc_constant constant, unsigned column, unsigned row); +SPVC_PUBLIC_API unsigned spvc_constant_get_scalar_u32(spvc_constant constant, unsigned column, unsigned row); +SPVC_PUBLIC_API int spvc_constant_get_scalar_i32(spvc_constant constant, unsigned column, unsigned row); +SPVC_PUBLIC_API unsigned spvc_constant_get_scalar_u16(spvc_constant constant, unsigned column, unsigned row); +SPVC_PUBLIC_API int spvc_constant_get_scalar_i16(spvc_constant constant, unsigned column, unsigned row); +SPVC_PUBLIC_API unsigned spvc_constant_get_scalar_u8(spvc_constant constant, unsigned column, unsigned row); +SPVC_PUBLIC_API int spvc_constant_get_scalar_i8(spvc_constant constant, unsigned column, unsigned row); +SPVC_PUBLIC_API void spvc_constant_get_subconstants(spvc_constant constant, const spvc_constant_id **constituents, size_t *count); +SPVC_PUBLIC_API unsigned long long spvc_constant_get_scalar_u64(spvc_constant constant, unsigned column, unsigned row); +SPVC_PUBLIC_API long long spvc_constant_get_scalar_i64(spvc_constant constant, unsigned column, unsigned row); +SPVC_PUBLIC_API spvc_type_id spvc_constant_get_type(spvc_constant constant); + +/* + * C implementation of the C++ api. + */ +SPVC_PUBLIC_API void spvc_constant_set_scalar_fp16(spvc_constant constant, unsigned column, unsigned row, unsigned short value); +SPVC_PUBLIC_API void spvc_constant_set_scalar_fp32(spvc_constant constant, unsigned column, unsigned row, float value); +SPVC_PUBLIC_API void spvc_constant_set_scalar_fp64(spvc_constant constant, unsigned column, unsigned row, double value); +SPVC_PUBLIC_API void spvc_constant_set_scalar_u32(spvc_constant constant, unsigned column, unsigned row, unsigned value); +SPVC_PUBLIC_API void spvc_constant_set_scalar_i32(spvc_constant constant, unsigned column, unsigned row, int value); +SPVC_PUBLIC_API void spvc_constant_set_scalar_u64(spvc_constant constant, unsigned column, unsigned row, unsigned long long value); +SPVC_PUBLIC_API void spvc_constant_set_scalar_i64(spvc_constant constant, unsigned column, unsigned row, long long value); +SPVC_PUBLIC_API void spvc_constant_set_scalar_u16(spvc_constant constant, unsigned column, unsigned row, unsigned short value); +SPVC_PUBLIC_API void spvc_constant_set_scalar_i16(spvc_constant constant, unsigned column, unsigned row, signed short value); +SPVC_PUBLIC_API void spvc_constant_set_scalar_u8(spvc_constant constant, unsigned column, unsigned row, unsigned char value); +SPVC_PUBLIC_API void spvc_constant_set_scalar_i8(spvc_constant constant, unsigned column, unsigned row, signed char value); + +/* + * Misc reflection + * Maps to C++ API. + */ +SPVC_PUBLIC_API spvc_bool spvc_compiler_get_binary_offset_for_decoration(spvc_compiler compiler, + spvc_variable_id id, + SpvDecoration decoration, + unsigned *word_offset); + +SPVC_PUBLIC_API spvc_bool spvc_compiler_buffer_is_hlsl_counter_buffer(spvc_compiler compiler, spvc_variable_id id); +SPVC_PUBLIC_API spvc_bool spvc_compiler_buffer_get_hlsl_counter_buffer(spvc_compiler compiler, spvc_variable_id id, + spvc_variable_id *counter_id); + +SPVC_PUBLIC_API spvc_result spvc_compiler_get_declared_capabilities(spvc_compiler compiler, + const SpvCapability **capabilities, + size_t *num_capabilities); +SPVC_PUBLIC_API spvc_result spvc_compiler_get_declared_extensions(spvc_compiler compiler, const char ***extensions, + size_t *num_extensions); + +SPVC_PUBLIC_API const char *spvc_compiler_get_remapped_declared_block_name(spvc_compiler compiler, spvc_variable_id id); +SPVC_PUBLIC_API spvc_result spvc_compiler_get_buffer_block_decorations(spvc_compiler compiler, spvc_variable_id id, + const SpvDecoration **decorations, + size_t *num_decorations); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/mojoshader/unit_tests/preprocessor/errors/redefinition b/mojoshader/unit_tests/preprocessor/errors/redefinition deleted file mode 100644 index ad55947..0000000 --- a/mojoshader/unit_tests/preprocessor/errors/redefinition +++ /dev/null @@ -1,2 +0,0 @@ -#define x 1 -#define x 2 diff --git a/mojoshader/unit_tests/preprocessor/errors/redefinition-file b/mojoshader/unit_tests/preprocessor/errors/redefinition-file deleted file mode 100644 index cd7c712..0000000 --- a/mojoshader/unit_tests/preprocessor/errors/redefinition-file +++ /dev/null @@ -1 +0,0 @@ -#define __FILE__ 3 diff --git a/mojoshader/unit_tests/preprocessor/errors/redefinition-file.correct b/mojoshader/unit_tests/preprocessor/errors/redefinition-file.correct deleted file mode 100644 index 7140553..0000000 --- a/mojoshader/unit_tests/preprocessor/errors/redefinition-file.correct +++ /dev/null @@ -1 +0,0 @@ -preprocessor/errors/redefinition-file:2: ERROR: '__FILE__' already defined diff --git a/mojoshader/unit_tests/preprocessor/errors/redefinition-line b/mojoshader/unit_tests/preprocessor/errors/redefinition-line deleted file mode 100644 index 3319ef1..0000000 --- a/mojoshader/unit_tests/preprocessor/errors/redefinition-line +++ /dev/null @@ -1,3 +0,0 @@ -#define __LINE__ "wrong" - - diff --git a/mojoshader/unit_tests/preprocessor/errors/redefinition-line.correct b/mojoshader/unit_tests/preprocessor/errors/redefinition-line.correct deleted file mode 100644 index dd4ce82..0000000 --- a/mojoshader/unit_tests/preprocessor/errors/redefinition-line.correct +++ /dev/null @@ -1 +0,0 @@ -preprocessor/errors/redefinition-line:2: ERROR: '__LINE__' already defined diff --git a/mojoshader/unit_tests/preprocessor/errors/redefinition.correct b/mojoshader/unit_tests/preprocessor/errors/redefinition.correct deleted file mode 100644 index 450b442..0000000 --- a/mojoshader/unit_tests/preprocessor/errors/redefinition.correct +++ /dev/null @@ -1 +0,0 @@ -preprocessor/errors/redefinition:3: ERROR: 'x' already defined diff --git a/mojoshader/unit_tests/preprocessor/errors/too-many-macro-args b/mojoshader/unit_tests/preprocessor/errors/too-many-macro-args deleted file mode 100644 index fb76ea1..0000000 --- a/mojoshader/unit_tests/preprocessor/errors/too-many-macro-args +++ /dev/null @@ -1,3 +0,0 @@ -// This should produce an error, not anything like "WRONG 7 )" -#define x(a) a -x(WRONG, 7) diff --git a/mojoshader/unit_tests/preprocessor/errors/too-many-macro-args.correct b/mojoshader/unit_tests/preprocessor/errors/too-many-macro-args.correct deleted file mode 100644 index 903aebe..0000000 --- a/mojoshader/unit_tests/preprocessor/errors/too-many-macro-args.correct +++ /dev/null @@ -1 +0,0 @@ -preprocessor/errors/too-many-macro-args:3: ERROR: macro 'x' passed 2 arguments, but requires 1 diff --git a/mojoshader/unit_tests/preprocessor/errors/undef-file b/mojoshader/unit_tests/preprocessor/errors/undef-file deleted file mode 100644 index 38cce27..0000000 --- a/mojoshader/unit_tests/preprocessor/errors/undef-file +++ /dev/null @@ -1 +0,0 @@ -#undef __FILE__ \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/errors/undef-file-twice b/mojoshader/unit_tests/preprocessor/errors/undef-file-twice deleted file mode 100644 index ba3c464..0000000 --- a/mojoshader/unit_tests/preprocessor/errors/undef-file-twice +++ /dev/null @@ -1,4 +0,0 @@ -// this should only produce one warning. -#undef __FILE__ -#undef __FILE__ - diff --git a/mojoshader/unit_tests/preprocessor/errors/undef-file-twice.correct b/mojoshader/unit_tests/preprocessor/errors/undef-file-twice.correct deleted file mode 100644 index b4eaae6..0000000 --- a/mojoshader/unit_tests/preprocessor/errors/undef-file-twice.correct +++ /dev/null @@ -1 +0,0 @@ -preprocessor/errors/undef-file-twice:3: ERROR: undefining "__FILE__" diff --git a/mojoshader/unit_tests/preprocessor/errors/undef-file.correct b/mojoshader/unit_tests/preprocessor/errors/undef-file.correct deleted file mode 100644 index c17f64b..0000000 --- a/mojoshader/unit_tests/preprocessor/errors/undef-file.correct +++ /dev/null @@ -1 +0,0 @@ -preprocessor/errors/undef-file:1: ERROR: undefining "__FILE__" diff --git a/mojoshader/unit_tests/preprocessor/errors/undef-line b/mojoshader/unit_tests/preprocessor/errors/undef-line deleted file mode 100644 index de7c25a..0000000 --- a/mojoshader/unit_tests/preprocessor/errors/undef-line +++ /dev/null @@ -1,2 +0,0 @@ -#undef __LINE__ - diff --git a/mojoshader/unit_tests/preprocessor/errors/undef-line-twice b/mojoshader/unit_tests/preprocessor/errors/undef-line-twice deleted file mode 100644 index 7aede43..0000000 --- a/mojoshader/unit_tests/preprocessor/errors/undef-line-twice +++ /dev/null @@ -1,4 +0,0 @@ -// this should only produce one warning. -#undef __LINE__ -#undef __LINE__ - diff --git a/mojoshader/unit_tests/preprocessor/errors/undef-line-twice.correct b/mojoshader/unit_tests/preprocessor/errors/undef-line-twice.correct deleted file mode 100644 index e019902..0000000 --- a/mojoshader/unit_tests/preprocessor/errors/undef-line-twice.correct +++ /dev/null @@ -1 +0,0 @@ -preprocessor/errors/undef-line-twice:3: ERROR: undefining "__LINE__" diff --git a/mojoshader/unit_tests/preprocessor/errors/undef-line.correct b/mojoshader/unit_tests/preprocessor/errors/undef-line.correct deleted file mode 100644 index 2bc34dc..0000000 --- a/mojoshader/unit_tests/preprocessor/errors/undef-line.correct +++ /dev/null @@ -1 +0,0 @@ -preprocessor/errors/undef-line:2: ERROR: undefining "__LINE__" diff --git a/mojoshader/unit_tests/preprocessor/output/basic-sanity b/mojoshader/unit_tests/preprocessor/output/basic-sanity deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/basic-sanity +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/basic-sanity.correct b/mojoshader/unit_tests/preprocessor/output/basic-sanity.correct deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/basic-sanity.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/concat-operator-basic b/mojoshader/unit_tests/preprocessor/output/concat-operator-basic deleted file mode 100644 index 4675fce..0000000 --- a/mojoshader/unit_tests/preprocessor/output/concat-operator-basic +++ /dev/null @@ -1,3 +0,0 @@ -#define a(b,c) b##c -a(RI, GHT) - diff --git a/mojoshader/unit_tests/preprocessor/output/concat-operator-basic.correct b/mojoshader/unit_tests/preprocessor/output/concat-operator-basic.correct deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/concat-operator-basic.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/concat-operator-define-override b/mojoshader/unit_tests/preprocessor/output/concat-operator-define-override deleted file mode 100644 index 016c645..0000000 --- a/mojoshader/unit_tests/preprocessor/output/concat-operator-define-override +++ /dev/null @@ -1,6 +0,0 @@ -// This should produce "RIGHT" and not "WRONG" -#define RI WR -#define GHT ONG -#define REPLACE(RI, GHT) RI##GHT -REPLACE(RI, GHT) - diff --git a/mojoshader/unit_tests/preprocessor/output/concat-operator-define-override.correct b/mojoshader/unit_tests/preprocessor/output/concat-operator-define-override.correct deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/concat-operator-define-override.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/concat-operator-ignore-non-args b/mojoshader/unit_tests/preprocessor/output/concat-operator-ignore-non-args deleted file mode 100644 index 32357e0..0000000 --- a/mojoshader/unit_tests/preprocessor/output/concat-operator-ignore-non-args +++ /dev/null @@ -1,6 +0,0 @@ -// Should produce RIGHT and not WRONG -#define RI WR -#define GHT ONG -#define z(a) RI##GHT -z(1) - diff --git a/mojoshader/unit_tests/preprocessor/output/concat-operator-ignore-non-args.correct b/mojoshader/unit_tests/preprocessor/output/concat-operator-ignore-non-args.correct deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/concat-operator-ignore-non-args.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/concat-operator-multiple b/mojoshader/unit_tests/preprocessor/output/concat-operator-multiple deleted file mode 100644 index a669cea..0000000 --- a/mojoshader/unit_tests/preprocessor/output/concat-operator-multiple +++ /dev/null @@ -1,4 +0,0 @@ -/* This should produce "RIGHT" instead of "RI ## G ## HT" */ -#define x(a,b) a##G##b -x(RI, HT) - diff --git a/mojoshader/unit_tests/preprocessor/output/concat-operator-multiple.correct b/mojoshader/unit_tests/preprocessor/output/concat-operator-multiple.correct deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/concat-operator-multiple.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/concat-operator-stacked-override b/mojoshader/unit_tests/preprocessor/output/concat-operator-stacked-override deleted file mode 100644 index 298b5aa..0000000 --- a/mojoshader/unit_tests/preprocessor/output/concat-operator-stacked-override +++ /dev/null @@ -1,7 +0,0 @@ -// This should produce "RIGHT" and not "WRONG" -#define WR RI -#define ONG GHT -#define REPLACE(WR, ONG) WR##ONG -#define REPLACE2(WR, ONG) REPLACE(WR, ONG) -REPLACE2(WR, ONG) - diff --git a/mojoshader/unit_tests/preprocessor/output/concat-operator-stacked-override.correct b/mojoshader/unit_tests/preprocessor/output/concat-operator-stacked-override.correct deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/concat-operator-stacked-override.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/concat-operator-two-macros-with-args b/mojoshader/unit_tests/preprocessor/output/concat-operator-two-macros-with-args deleted file mode 100644 index 4bc6a86..0000000 --- a/mojoshader/unit_tests/preprocessor/output/concat-operator-two-macros-with-args +++ /dev/null @@ -1,4 +0,0 @@ -#define y(a) a -#define x(a) y(a)##y(a) - -x(RIGHT) diff --git a/mojoshader/unit_tests/preprocessor/output/concat-operator-two-macros-with-args.correct b/mojoshader/unit_tests/preprocessor/output/concat-operator-two-macros-with-args.correct deleted file mode 100644 index c8e4705..0000000 --- a/mojoshader/unit_tests/preprocessor/output/concat-operator-two-macros-with-args.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/elif-after-macro b/mojoshader/unit_tests/preprocessor/output/elif-after-macro deleted file mode 100644 index 3e4f74b..0000000 --- a/mojoshader/unit_tests/preprocessor/output/elif-after-macro +++ /dev/null @@ -1,9 +0,0 @@ -// This triggered an error before, when the "== D0" would not pop_source(). -#define D0 0 -#if DA == D0 -RIGHT -#elif D5 >= D4 -WRONG -#else -ALSOWRONG -#endif diff --git a/mojoshader/unit_tests/preprocessor/output/elif-after-macro-with-args b/mojoshader/unit_tests/preprocessor/output/elif-after-macro-with-args deleted file mode 100644 index 5343390..0000000 --- a/mojoshader/unit_tests/preprocessor/output/elif-after-macro-with-args +++ /dev/null @@ -1,8 +0,0 @@ -#define D0(x) 0 -#if DA == D0(5) -RIGHT -#elif D5 >= D4 -WRONG -#else -ALSOWRONG -#endif diff --git a/mojoshader/unit_tests/preprocessor/output/elif-after-macro-with-args.correct b/mojoshader/unit_tests/preprocessor/output/elif-after-macro-with-args.correct deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/elif-after-macro-with-args.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/elif-after-macro.correct b/mojoshader/unit_tests/preprocessor/output/elif-after-macro.correct deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/elif-after-macro.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/empty-file b/mojoshader/unit_tests/preprocessor/output/empty-file deleted file mode 100644 index e69de29..0000000 diff --git a/mojoshader/unit_tests/preprocessor/output/empty-file.correct b/mojoshader/unit_tests/preprocessor/output/empty-file.correct deleted file mode 100644 index e69de29..0000000 diff --git a/mojoshader/unit_tests/preprocessor/output/empty-macro-with-arg b/mojoshader/unit_tests/preprocessor/output/empty-macro-with-arg deleted file mode 100644 index e8d7e83..0000000 --- a/mojoshader/unit_tests/preprocessor/output/empty-macro-with-arg +++ /dev/null @@ -1,3 +0,0 @@ -// This should not crash when using the empty macro. -#define COMPUTE_FOO(a) -COMPUTE_FOO(a) diff --git a/mojoshader/unit_tests/preprocessor/output/empty-macro-with-arg.correct b/mojoshader/unit_tests/preprocessor/output/empty-macro-with-arg.correct deleted file mode 100644 index e69de29..0000000 diff --git a/mojoshader/unit_tests/preprocessor/output/file-macro b/mojoshader/unit_tests/preprocessor/output/file-macro deleted file mode 100644 index 4815727..0000000 --- a/mojoshader/unit_tests/preprocessor/output/file-macro +++ /dev/null @@ -1 +0,0 @@ -__FILE__ diff --git a/mojoshader/unit_tests/preprocessor/output/file-macro.correct b/mojoshader/unit_tests/preprocessor/output/file-macro.correct deleted file mode 100644 index ad82002..0000000 --- a/mojoshader/unit_tests/preprocessor/output/file-macro.correct +++ /dev/null @@ -1 +0,0 @@ -"preprocessor/output/file-macro" diff --git a/mojoshader/unit_tests/preprocessor/output/float-half-suffix b/mojoshader/unit_tests/preprocessor/output/float-half-suffix deleted file mode 100644 index ffaba4c..0000000 --- a/mojoshader/unit_tests/preprocessor/output/float-half-suffix +++ /dev/null @@ -1,4 +0,0 @@ -// This should produce "10.05h" and not "10.05 h" -10.05h -// This should produce "10.05e10h" and not "10.05e10 h" -10.05e10h diff --git a/mojoshader/unit_tests/preprocessor/output/float-half-suffix.correct b/mojoshader/unit_tests/preprocessor/output/float-half-suffix.correct deleted file mode 100644 index cac9457..0000000 --- a/mojoshader/unit_tests/preprocessor/output/float-half-suffix.correct +++ /dev/null @@ -1 +0,0 @@ -10.05h 10.05e10h diff --git a/mojoshader/unit_tests/preprocessor/output/just-a-comment b/mojoshader/unit_tests/preprocessor/output/just-a-comment deleted file mode 100644 index 2bc73f8..0000000 --- a/mojoshader/unit_tests/preprocessor/output/just-a-comment +++ /dev/null @@ -1,3 +0,0 @@ -/* -This is just comments, and should produce an empty file. -*/ // This is just a comment, too. \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/just-a-comment.correct b/mojoshader/unit_tests/preprocessor/output/just-a-comment.correct deleted file mode 100644 index e69de29..0000000 diff --git a/mojoshader/unit_tests/preprocessor/output/line-directive-filename b/mojoshader/unit_tests/preprocessor/output/line-directive-filename deleted file mode 100644 index 1195e06..0000000 --- a/mojoshader/unit_tests/preprocessor/output/line-directive-filename +++ /dev/null @@ -1,3 +0,0 @@ -// This should NOT produce an error -#line 1337 "Some_other_source_file.txt" -RIGHT diff --git a/mojoshader/unit_tests/preprocessor/output/line-directive-filename.correct b/mojoshader/unit_tests/preprocessor/output/line-directive-filename.correct deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/line-directive-filename.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/line-directive-no-filename b/mojoshader/unit_tests/preprocessor/output/line-directive-no-filename deleted file mode 100644 index 42ea6f4..0000000 --- a/mojoshader/unit_tests/preprocessor/output/line-directive-no-filename +++ /dev/null @@ -1,3 +0,0 @@ -// This should NOT produce an error -#line 1337 -RIGHT diff --git a/mojoshader/unit_tests/preprocessor/output/line-directive-no-filename.correct b/mojoshader/unit_tests/preprocessor/output/line-directive-no-filename.correct deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/line-directive-no-filename.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/line-directive-whitespace-filename b/mojoshader/unit_tests/preprocessor/output/line-directive-whitespace-filename deleted file mode 100644 index 4abb34e..0000000 --- a/mojoshader/unit_tests/preprocessor/output/line-directive-whitespace-filename +++ /dev/null @@ -1,3 +0,0 @@ -// This should NOT produce an error -#line 1337 "Some filename with a spaces in it.txt" -RIGHT diff --git a/mojoshader/unit_tests/preprocessor/output/line-directive-whitespace-filename.correct b/mojoshader/unit_tests/preprocessor/output/line-directive-whitespace-filename.correct deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/line-directive-whitespace-filename.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/line-macro b/mojoshader/unit_tests/preprocessor/output/line-macro deleted file mode 100644 index 381351d..0000000 --- a/mojoshader/unit_tests/preprocessor/output/line-macro +++ /dev/null @@ -1,4 +0,0 @@ -Line one: __LINE__ - -Line three: __LINE__ - diff --git a/mojoshader/unit_tests/preprocessor/output/line-macro.correct b/mojoshader/unit_tests/preprocessor/output/line-macro.correct deleted file mode 100644 index dbcd5ad..0000000 --- a/mojoshader/unit_tests/preprocessor/output/line-macro.correct +++ /dev/null @@ -1 +0,0 @@ -Line one : 1 Line three : 3 \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/macro-1-arg-accepts-void b/mojoshader/unit_tests/preprocessor/output/macro-1-arg-accepts-void deleted file mode 100644 index 1b35ff3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-1-arg-accepts-void +++ /dev/null @@ -1,5 +0,0 @@ -// x() should be considered one (blank) argument when there is a macro which -// has one parameter. It should produce "RIGHT" and not "RIGHT()", and no -// errors. -#define x(a) RIGHT a -x() diff --git a/mojoshader/unit_tests/preprocessor/output/macro-1-arg-accepts-void.correct b/mojoshader/unit_tests/preprocessor/output/macro-1-arg-accepts-void.correct deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-1-arg-accepts-void.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/macro-arg b/mojoshader/unit_tests/preprocessor/output/macro-arg deleted file mode 100644 index c50db60..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-arg +++ /dev/null @@ -1,4 +0,0 @@ -/* This should produce "RIGHT" instead of "WRONG" */ -#define x(WRONG) WRONG -x(RIGHT) - diff --git a/mojoshader/unit_tests/preprocessor/output/macro-arg-overrides-define b/mojoshader/unit_tests/preprocessor/output/macro-arg-overrides-define deleted file mode 100644 index c88a8c7..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-arg-overrides-define +++ /dev/null @@ -1,5 +0,0 @@ -// This should produce THIS_IS_THE_MACRO_ARG and not THIS_IS_THE_DEFINE. -#define x THIS_IS_THE_DEFINE -#define b(x) x -#define z(x) b(x) -z(THIS_IS_THE_MACRO_ARG) diff --git a/mojoshader/unit_tests/preprocessor/output/macro-arg-overrides-define.correct b/mojoshader/unit_tests/preprocessor/output/macro-arg-overrides-define.correct deleted file mode 100644 index cf2305a..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-arg-overrides-define.correct +++ /dev/null @@ -1 +0,0 @@ -THIS_IS_THE_MACRO_ARG \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/macro-arg.correct b/mojoshader/unit_tests/preprocessor/output/macro-arg.correct deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-arg.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/macro-args b/mojoshader/unit_tests/preprocessor/output/macro-args deleted file mode 100644 index e0dfd05..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-args +++ /dev/null @@ -1,4 +0,0 @@ -/* This should produce "RIGHT ANDRIGHT" instead of "WRONG ANDWRONG" */ -#define x(WRONG, ANDWRONG) WRONG ANDWRONG -x(RIGHT, ANDRIGHT) - diff --git a/mojoshader/unit_tests/preprocessor/output/macro-args-with-whitespace b/mojoshader/unit_tests/preprocessor/output/macro-args-with-whitespace deleted file mode 100644 index 6cc6ab3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-args-with-whitespace +++ /dev/null @@ -1,3 +0,0 @@ -#define right( x ) x -right( RIGHT ) - diff --git a/mojoshader/unit_tests/preprocessor/output/macro-args-with-whitespace.correct b/mojoshader/unit_tests/preprocessor/output/macro-args-with-whitespace.correct deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-args-with-whitespace.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/macro-args.correct b/mojoshader/unit_tests/preprocessor/output/macro-args.correct deleted file mode 100644 index e23043b..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-args.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT ANDRIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/macro-blank-arg b/mojoshader/unit_tests/preprocessor/output/macro-blank-arg deleted file mode 100644 index 1d51222..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-blank-arg +++ /dev/null @@ -1,4 +0,0 @@ -// This shouldn't produce an error (the "()" should be treated as one -// blank argument. -#define x(y) y -x() diff --git a/mojoshader/unit_tests/preprocessor/output/macro-blank-arg.correct b/mojoshader/unit_tests/preprocessor/output/macro-blank-arg.correct deleted file mode 100644 index e69de29..0000000 diff --git a/mojoshader/unit_tests/preprocessor/output/macro-empty-arg b/mojoshader/unit_tests/preprocessor/output/macro-empty-arg deleted file mode 100644 index ceae203..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-empty-arg +++ /dev/null @@ -1,5 +0,0 @@ -/* This should produce "RIGHT RIGHT" instead of "WRONG WRONG" (etc) */ -#define x(WRONG,ANDWRONG) WRONG ANDWRONG -x(RIGHT,) -x(,RIGHT) -x(,) diff --git a/mojoshader/unit_tests/preprocessor/output/macro-empty-arg.correct b/mojoshader/unit_tests/preprocessor/output/macro-empty-arg.correct deleted file mode 100644 index c8e4705..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-empty-arg.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/macro-multi-args-with-whitespace b/mojoshader/unit_tests/preprocessor/output/macro-multi-args-with-whitespace deleted file mode 100644 index 2f3d20b..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-multi-args-with-whitespace +++ /dev/null @@ -1,3 +0,0 @@ -#define right( x , y ) x ## y -right( RI , GHT ) - diff --git a/mojoshader/unit_tests/preprocessor/output/macro-multi-args-with-whitespace.correct b/mojoshader/unit_tests/preprocessor/output/macro-multi-args-with-whitespace.correct deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-multi-args-with-whitespace.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/macro-paren-stacking b/mojoshader/unit_tests/preprocessor/output/macro-paren-stacking deleted file mode 100644 index 12ec552..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-paren-stacking +++ /dev/null @@ -1,3 +0,0 @@ -/* Should give you "RIGHT" instead of an error. */ -#define a(a,b) b -a((1+1), RIGHT) diff --git a/mojoshader/unit_tests/preprocessor/output/macro-paren-stacking.correct b/mojoshader/unit_tests/preprocessor/output/macro-paren-stacking.correct deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-paren-stacking.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/macro-void-arg b/mojoshader/unit_tests/preprocessor/output/macro-void-arg deleted file mode 100644 index 51fd9df..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-void-arg +++ /dev/null @@ -1,4 +0,0 @@ -// This should not trigger a preprocessor error. -// Nor should it produce "RIGHT()". -#define x() RIGHT -x() diff --git a/mojoshader/unit_tests/preprocessor/output/macro-void-arg.correct b/mojoshader/unit_tests/preprocessor/output/macro-void-arg.correct deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-void-arg.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/macro-with-arg-as-macro-arg b/mojoshader/unit_tests/preprocessor/output/macro-with-arg-as-macro-arg deleted file mode 100644 index 588637e..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-with-arg-as-macro-arg +++ /dev/null @@ -1,5 +0,0 @@ -// Should produce "RIGHT" and not "l(b)" or whatnot. -#define bb(l) l -#define zz(c) c -#define qq(b) zz(bb(b)) -qq(RIGHT) diff --git a/mojoshader/unit_tests/preprocessor/output/macro-with-arg-as-macro-arg.correct b/mojoshader/unit_tests/preprocessor/output/macro-with-arg-as-macro-arg.correct deleted file mode 100644 index db561ff..0000000 --- a/mojoshader/unit_tests/preprocessor/output/macro-with-arg-as-macro-arg.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT diff --git a/mojoshader/unit_tests/preprocessor/output/nested-macro-args b/mojoshader/unit_tests/preprocessor/output/nested-macro-args deleted file mode 100644 index e203ae5..0000000 --- a/mojoshader/unit_tests/preprocessor/output/nested-macro-args +++ /dev/null @@ -1,6 +0,0 @@ -/* This should produce "RIGHT" instead of "WRONG" */ -#define x(a) a -#define y(WRONG) x(WRONG) - -y(RIGHT) - diff --git a/mojoshader/unit_tests/preprocessor/output/nested-macro-args.correct b/mojoshader/unit_tests/preprocessor/output/nested-macro-args.correct deleted file mode 100644 index 459b9a3..0000000 --- a/mojoshader/unit_tests/preprocessor/output/nested-macro-args.correct +++ /dev/null @@ -1 +0,0 @@ -RIGHT \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/pragma-directive-line-break b/mojoshader/unit_tests/preprocessor/output/pragma-directive-line-break deleted file mode 100644 index 5ae8d35..0000000 --- a/mojoshader/unit_tests/preprocessor/output/pragma-directive-line-break +++ /dev/null @@ -1,3 +0,0 @@ -#pragma warning (disable:4507) -Should_remain_on_separate_line; - diff --git a/mojoshader/unit_tests/preprocessor/output/pragma-directive-line-break.correct b/mojoshader/unit_tests/preprocessor/output/pragma-directive-line-break.correct deleted file mode 100644 index 047bcfd..0000000 --- a/mojoshader/unit_tests/preprocessor/output/pragma-directive-line-break.correct +++ /dev/null @@ -1,2 +0,0 @@ -#pragma warning ( disable : 4507 ) -Should_remain_on_separate_line ; diff --git a/mojoshader/unit_tests/preprocessor/output/stringify-operator-basic b/mojoshader/unit_tests/preprocessor/output/stringify-operator-basic deleted file mode 100644 index 700a51f..0000000 --- a/mojoshader/unit_tests/preprocessor/output/stringify-operator-basic +++ /dev/null @@ -1,3 +0,0 @@ -// will output "RIGHT" -#define x(z) #z -x(RIGHT) \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/stringify-operator-basic.correct b/mojoshader/unit_tests/preprocessor/output/stringify-operator-basic.correct deleted file mode 100644 index 9523502..0000000 --- a/mojoshader/unit_tests/preprocessor/output/stringify-operator-basic.correct +++ /dev/null @@ -1 +0,0 @@ -"RIGHT" \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/stringify-operator-blank-arg b/mojoshader/unit_tests/preprocessor/output/stringify-operator-blank-arg deleted file mode 100644 index 00152fe..0000000 --- a/mojoshader/unit_tests/preprocessor/output/stringify-operator-blank-arg +++ /dev/null @@ -1,4 +0,0 @@ -// This shouldn't produce an error (the "()" should be treated as one -// blank argument, turned into a "" -#define x(y) #y -x() diff --git a/mojoshader/unit_tests/preprocessor/output/stringify-operator-blank-arg.correct b/mojoshader/unit_tests/preprocessor/output/stringify-operator-blank-arg.correct deleted file mode 100644 index 3cc762b..0000000 --- a/mojoshader/unit_tests/preprocessor/output/stringify-operator-blank-arg.correct +++ /dev/null @@ -1 +0,0 @@ -"" \ No newline at end of file diff --git a/mojoshader/unit_tests/preprocessor/output/stringify-operator-indirect b/mojoshader/unit_tests/preprocessor/output/stringify-operator-indirect deleted file mode 100644 index af79de8..0000000 --- a/mojoshader/unit_tests/preprocessor/output/stringify-operator-indirect +++ /dev/null @@ -1,7 +0,0 @@ -// Should produce RIGHT and not WRONG. -#define WRONG RIGHT -#define STRINGIFY2(x) #x -#define STRINGIFY(x) STRINGIFY2(x) - -STRINGIFY(WRONG) - diff --git a/mojoshader/unit_tests/preprocessor/output/stringify-operator-indirect-line-macro b/mojoshader/unit_tests/preprocessor/output/stringify-operator-indirect-line-macro deleted file mode 100644 index 341ea89..0000000 --- a/mojoshader/unit_tests/preprocessor/output/stringify-operator-indirect-line-macro +++ /dev/null @@ -1,5 +0,0 @@ -// Should produce a line number in quotes, and not "__LINE__" -#define STRINGIFY2(x) #x -#define STRINGIFY(x) STRINGIFY2(x) - -STRINGIFY(__LINE__) diff --git a/mojoshader/unit_tests/preprocessor/output/stringify-operator-indirect-line-macro.correct b/mojoshader/unit_tests/preprocessor/output/stringify-operator-indirect-line-macro.correct deleted file mode 100644 index 9910bae..0000000 --- a/mojoshader/unit_tests/preprocessor/output/stringify-operator-indirect-line-macro.correct +++ /dev/null @@ -1 +0,0 @@ -"5" diff --git a/mojoshader/unit_tests/preprocessor/output/stringify-operator-indirect.correct b/mojoshader/unit_tests/preprocessor/output/stringify-operator-indirect.correct deleted file mode 100644 index 9a3b91d..0000000 --- a/mojoshader/unit_tests/preprocessor/output/stringify-operator-indirect.correct +++ /dev/null @@ -1 +0,0 @@ -"RIGHT" diff --git a/mojoshader/unit_tests/run_tests.pl b/mojoshader/unit_tests/run_tests.pl deleted file mode 100755 index 968bdaf..0000000 --- a/mojoshader/unit_tests/run_tests.pl +++ /dev/null @@ -1,192 +0,0 @@ -#!/usr/bin/perl -w - -use warnings; -use strict; -use Digest::SHA1; -use Cwd; - -use FindBin qw($Bin); -my $testdir = $Bin; -undef $Bin; -#print("testdir is $testdir\n"); -my $binpath = getcwd(); -#print("binpath is $binpath\n"); - -my $GPrintCmds = 0; - -my @modules = qw( preprocessor assembler compiler parser ); - - -sub compare_files { - my ($a, $b, $endlines) = @_; - - if (not open(FILE1, '<', $a)) { - return (0, "Couldn't open '$a' for checksum"); - } - if (not open(FILE2, '<', $b)) { - close(FILE1); - return (0, "Couldn't open '$b' for checksum"); - } - - my $sha1 = Digest::SHA1->new; - my $sha2 = Digest::SHA1->new; - - if (not $endlines) { - $sha1->addfile(*FILE1); - $sha2->addfile(*FILE2); - } else { - while () { s/[\r\n]//g; $sha1->add($_); } - while () { s/[\r\n]//g; $sha2->add($_); } - } - - close(FILE1); - close(FILE2); - - if ($sha1->hexdigest ne $sha2->hexdigest) { - return (0, "Result doesn't match expectations"); - } - - return (1); -} - -my %tests = (); - -$tests{'output'} = sub { - my ($module, $fname) = @_; - my $output = 'unittest_tempoutput'; - my $desired = $fname . '.correct'; - my $cmd = undef; - my $endlines = 1; - - # !!! FIXME: this should go elsewhere. - if ($module eq 'preprocessor') { - $cmd = "$binpath/mojoshader-compiler -P '$fname' -o '$output'"; - } else { - return (0, "Don't know how to do this module type"); - } - $cmd .= ' 2>/dev/null 1>/dev/null'; - - print("$cmd\n") if ($GPrintCmds); - - if (system($cmd) != 0) { - unlink($output) if (-f $output); - return (0, "External program reported error"); - } - - if (not -f $output) { return (0, "Didn't get any output file"); } - - my @retval = compare_files($desired, $output, $endlines); - unlink($output); - return @retval; -}; - -$tests{'errors'} = sub { - my ($module, $fname) = @_; - my $error_output = 'unittest_temperroutput'; - my $output = 'unittest_tempoutput'; - my $desired = $fname . '.correct'; - my $cmd = undef; - my $endlines = 1; - - # !!! FIXME: this should go elsewhere. - if ($module eq 'preprocessor') { - $cmd = "$binpath/mojoshader-compiler -P '$fname' -o '$output'"; - } else { - return (0, "Don't know how to do this module type"); - } - $cmd .= " 2>$error_output 1>/dev/null"; - - print("$cmd\n") if ($GPrintCmds); - - system($cmd); - unlink($output) if (-f $output); - - if (not -f $error_output) { return (0, "Didn't get any error output"); } - - my @retval = compare_files($desired, $error_output, $endlines); - unlink($error_output); - return @retval; -}; - -my $totaltests = 0; -my $pass = 0; -my $fail = 0; -my $skip = 0; -my @fails = (); - -my $result = ''; -chdir($testdir) or die("Failed to chdir('$testdir'): $!\n"); -foreach (@modules) { - my $module = $_; - foreach (keys %tests) { - my $testtype = $_; - my $fn = $tests{$_}; - my $d = "$module/$testtype"; - next if (not -d $d); # no tests at the moment. - opendir(TESTDIR, $d) || die("Failed to open dir '$d': $!\n"); - my $subsection = " ... $module / $testtype ...\n"; - print($subsection); - my $addedsubsection = 0; - my $fname = readdir(TESTDIR); - while (defined $fname) { - my $isfail = 0; - my $origfname = $fname; - $fname = readdir(TESTDIR); # set for next iteration. - next if (-d $origfname); - next if ($origfname =~ /\.correct\Z/); - my $fullfname = "$d/$origfname"; - my ($rc, $reason) = &$fn($module, $fullfname); - if ($rc == 1) { - $result = 'PASS'; - $pass++; - } elsif ($rc == 0) { - $isfail = 1; - $result = 'FAIL'; - $fail++; - } elsif ($rc == -1) { - $result = 'SKIP'; - $skip++; - } - - if (defined $reason) { - $reason = " ($reason)"; - } else { - $reason = ''; - } - my $output = "$result ${origfname}${reason}\n"; - print($output); - - if ($isfail) { - if (!$addedsubsection) { - $addedsubsection = 1; - push(@fails, $subsection); - } - push(@fails, $output); - } - - $totaltests++; - } - closedir(TESTDIR); - } -} - -if (scalar(@fails)) { - print("\n\n"); - print("*************************************************************\n"); - print("*************************************************************\n"); - print("** SOME TESTS FAILED! PLEASE CORRECT THE FOLLOWING ISSUES. **\n"); - print("*************************************************************\n"); - print("*************************************************************\n"); - print("\n"); - foreach (@fails) { - print $_; - } - print("\n\n"); -} - -print("\n$totaltests tests, $pass passed, $fail failed, $skip skipped.\n\n"); - -exit(($fail > 0) ? 1 : 0); - -# end if run_tests.pl ... - diff --git a/mojoshader/utils/finderrors.c b/mojoshader/utils/finderrors.c deleted file mode 100644 index d90f34e..0000000 --- a/mojoshader/utils/finderrors.c +++ /dev/null @@ -1,234 +0,0 @@ -/** - * MojoShader; generate shader programs from bytecode of compiled - * Direct3D shaders. - * - * Please see the file LICENSE.txt in the source's root directory. - * - * This file written by Ryan C. Gordon. - */ - -#include -#include -#include -#include -#include -#include - -#include "mojoshader.h" - -#if FINDERRORS_COMPILE_SHADERS -#include "SDL.h" -static void *lookup(const char *fnname, void *unused) -{ - (void) unused; - return SDL_GL_GetProcAddress(fnname); -} // lookup -#endif - -#ifdef _MSC_VER -#define WIN32_LEAN_AND_MEAN 1 -#include -#include // for alloca(). -#define snprintf _snprintf -#else -#include -#endif - -#define report printf - -static int do_file(const char *profile, const char *dname, const char *fn, int *total) -{ - int do_quit = 0; - - #if FINDERRORS_COMPILE_SHADERS - SDL_Event e; // pump event queue to keep OS happy. - while (SDL_PollEvent(&e)) - { - if (e.type == SDL_QUIT) - do_quit = 1; - } // while - SDL_GL_SwapBuffers(); - #endif - - if (do_quit) - { - report("FAIL: user requested quit!\n"); - return 0; - } // if - - int assembly = 0; - if (strstr(fn, ".bytecode") != NULL) - assembly = 0; - else if (strstr(fn, ".disasm") != NULL) - assembly = 1; - else - return 1; - - (*total)++; - - char *fname = (char *) alloca(strlen(fn) + strlen(dname) + 1); - sprintf(fname, "%s/%s", dname, fn); - FILE *io = fopen(fname, "rb"); - if (io == NULL) - { - report("FAIL: %s fopen() failed.\n", fname); - return 1; - } // if - - static unsigned char buf[1024 * 256]; - int rc = fread(buf, 1, sizeof (buf), io); - fclose(io); - if (rc == -1) - { - report("FAIL: %s %s\n", fname, strerror(errno)); - return 1; - } // if - - if (assembly) - { - const MOJOSHADER_parseData *a; - - buf[rc] = '\0'; // make sure the source is null-terminated. - a = MOJOSHADER_assemble(fname, (char *) buf, rc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); - - if (a->error_count > 0) - { - report("FAIL: %s (line %d) %s\n", - a->errors[0].filename ? a->errors[0].filename : "???", - a->errors[0].error_position, - a->errors[0].error); - return 1; - } // if - - else if (a->output_len > sizeof (buf)) - { - report("FAIL: %s buffer overflow in finderrors.c\n", fname); - return 1; - } // if - - rc = a->output_len; - memcpy(buf, a->output, rc); - MOJOSHADER_freeParseData(a); - } // if - - #if FINDERRORS_COMPILE_SHADERS - MOJOSHADER_glShader *shader = MOJOSHADER_glCompileShader(buf, rc, NULL, 0, NULL, 0); - if (shader == NULL) - report("FAIL: %s %s\n", fname, MOJOSHADER_glGetError()); - else - { - const MOJOSHADER_parseData *pd = MOJOSHADER_glGetShaderParseData(shader); - MOJOSHADER_glShader *v = (pd->shader_type == MOJOSHADER_TYPE_VERTEX) ? shader : NULL; - MOJOSHADER_glShader *p = (pd->shader_type == MOJOSHADER_TYPE_PIXEL) ? shader : NULL; - MOJOSHADER_glProgram *program = MOJOSHADER_glLinkProgram(v, p); - if (program == NULL) - report("FAIL: %s %s\n", fname, MOJOSHADER_glGetError()); - else - { - report("PASS: %s\n", fname); - MOJOSHADER_glDeleteProgram(program); - } // else - MOJOSHADER_glDeleteShader(shader); - } - #else - const MOJOSHADER_parseData *pd = MOJOSHADER_parse(profile, buf, rc, NULL, 0, NULL, NULL, NULL); - if (pd->error_count == 0) - report("PASS: %s\n", fname); - else - { - int i; - for (i = 0; i < pd->error_count; i++) - { - report("FAIL: %s (position %d) %s\n", pd->errors[i].filename, - pd->errors[i].error_position, pd->errors[i].error); - } // for - } // else - MOJOSHADER_freeParseData(pd); - #endif - - return 1; -} // do_file - - -static int do_dir(const char *dname, const char *profile) -{ - int total = 0; - -#ifdef _MSC_VER - WIN32_FIND_DATA dent; - HANDLE dirp = INVALID_HANDLE_VALUE; - FindFirstFileA(dname, &dent); - if (dirp != INVALID_HANDLE_VALUE) - { - do - { - if (!do_file(profile, dname, dent.cFileName, &total)) - break; - } while (FindNextFileA(dirp, &dent) != 0); - CloseHandle(dirp); - } // if -#else - struct dirent *dent = NULL; - DIR *dirp = opendir(dname); - if (dirp != NULL) - { - while ((dent = readdir(dirp)) != NULL) - { - if (!do_file(profile, dname, dent->d_name, &total)) - break; - } // while - closedir(dirp); - } // if -#endif - - return total; -} // do_dir - - -int main(int argc, char **argv) -{ - //printf("MojoShader finderrors\n"); - //printf("Compiled against changeset %s\n", MOJOSHADER_CHANGESET); - //printf("Linked against changeset %s\n", MOJOSHADER_changeset()); - //printf("\n"); - - if (argc <= 2) - printf("\n\nUSAGE: %s [dir1] ... [dirN]\n\n", argv[0]); - else - { - int total = 0; - int i; - const char *profile = argv[1]; - - #if FINDERRORS_COMPILE_SHADERS - SDL_Init(SDL_INIT_VIDEO); - SDL_GL_LoadLibrary(NULL); - SDL_SetVideoMode(640, 480, 0, SDL_OPENGL); - printf("Best profile is '%s'\n", MOJOSHADER_glBestProfile(lookup, 0)); - MOJOSHADER_glContext *ctx; - ctx = MOJOSHADER_glCreateContext(profile, lookup, 0, 0, 0, 0); - if (ctx == NULL) - { - printf("MOJOSHADER_glCreateContext() fail: %s\n", MOJOSHADER_glGetError()); - SDL_Quit(); - return 1; - } // if - MOJOSHADER_glMakeContextCurrent(ctx); - #endif - - for (i = 2; i < argc; i++) - total += do_dir(argv[i], profile); - - printf("Saw %d files.\n", total); - - #if FINDERRORS_COMPILE_SHADERS - MOJOSHADER_glDestroyContext(ctx); - SDL_Quit(); - #endif - } // else - - return 0; -} // main - -// end of finderrors.c ... - diff --git a/mojoshader/utils/mojoshader-compiler.c b/mojoshader/utils/mojoshader-compiler.c deleted file mode 100644 index 4fc91de..0000000 --- a/mojoshader/utils/mojoshader-compiler.c +++ /dev/null @@ -1,1102 +0,0 @@ -/** - * MojoShader; generate shader programs from bytecode of compiled - * Direct3D shaders. - * - * Please see the file LICENSE.txt in the source's root directory. - * - * This file written by Ryan C. Gordon. - */ - -#include -#include -#include -#include - -#include "mojoshader.h" - -#ifdef _WIN32 -#define snprintf _snprintf // !!! FIXME: not a safe replacement! -#endif - -static const char **include_paths = NULL; -static unsigned int include_path_count = 0; - -#define MOJOSHADER_DEBUG_MALLOC 0 - -#if MOJOSHADER_DEBUG_MALLOC -static void *Malloc(int len, void *d) -{ - void *ptr = malloc(len + sizeof (int)); - int *store = (int *) ptr; - printf("malloc() %d bytes (%p)\n", len, ptr); - if (ptr == NULL) return NULL; - *store = len; - return (void *) (store + 1); -} // Malloc - - -static void Free(void *_ptr, void *d) -{ - int *ptr = (((int *) _ptr) - 1); - int len = *ptr; - printf("free() %d bytes (%p)\n", len, ptr); - free(ptr); -} // Free -#else -#define Malloc NULL -#define Free NULL -#endif - - -static void fail(const char *err) -{ - printf("%s.\n", err); - exit(1); -} // fail - -static void print_unroll_attr(FILE *io, const int unroll) -{ - // -1 means "unroll at compiler's discretion", - // -2 means user didn't specify the attribute. - switch (unroll) - { - case 0: - fprintf(io, "[loop] "); - break; - case -1: - fprintf(io, "[unroll] "); - break; - case -2: - /* no-op. */ - break; - default: - assert(unroll > 0); - fprintf(io, "[unroll(%d)] ", unroll); - break; - } // case -} // print_unroll_attr - -static void print_ast_datatype(FILE *io, const MOJOSHADER_astDataType *dt) -{ - int i; - - if (dt == NULL) - return; - - switch (dt->type) - { - case MOJOSHADER_AST_DATATYPE_BOOL: - fprintf(io, "bool"); - return; - case MOJOSHADER_AST_DATATYPE_INT: - fprintf(io, "int"); - return; - case MOJOSHADER_AST_DATATYPE_UINT: - fprintf(io, "uint"); - return; - case MOJOSHADER_AST_DATATYPE_FLOAT: - fprintf(io, "float"); - return; - case MOJOSHADER_AST_DATATYPE_FLOAT_SNORM: - fprintf(io, "snorm float"); - return; - case MOJOSHADER_AST_DATATYPE_FLOAT_UNORM: - fprintf(io, "unorm float"); - return; - case MOJOSHADER_AST_DATATYPE_HALF: - fprintf(io, "half"); - return; - case MOJOSHADER_AST_DATATYPE_DOUBLE: - fprintf(io, "double"); - return; - case MOJOSHADER_AST_DATATYPE_STRING: - fprintf(io, "string"); - return; - case MOJOSHADER_AST_DATATYPE_SAMPLER_1D: - fprintf(io, "sampler1D"); - return; - case MOJOSHADER_AST_DATATYPE_SAMPLER_2D: - fprintf(io, "sampler2D"); - return; - case MOJOSHADER_AST_DATATYPE_SAMPLER_3D: - fprintf(io, "sampler3D"); - return; - case MOJOSHADER_AST_DATATYPE_SAMPLER_CUBE: - fprintf(io, "samplerCUBE"); - return; - case MOJOSHADER_AST_DATATYPE_SAMPLER_STATE: - fprintf(io, "sampler_state"); - return; - case MOJOSHADER_AST_DATATYPE_SAMPLER_COMPARISON_STATE: - fprintf(io, "SamplerComparisonState"); - return; - - case MOJOSHADER_AST_DATATYPE_STRUCT: - fprintf(io, "struct { "); - for (i = 0; i < dt->structure.member_count; i++) - { - print_ast_datatype(io, dt->structure.members[i].datatype); - fprintf(io, " %s; ", dt->structure.members[i].identifier); - } // for - fprintf(io, "}"); - return; - - case MOJOSHADER_AST_DATATYPE_ARRAY: - print_ast_datatype(io, dt->array.base); - if (dt->array.elements < 0) - fprintf(io, "[]"); - else - fprintf(io, "[%d]", dt->array.elements); - return; - - case MOJOSHADER_AST_DATATYPE_VECTOR: - fprintf(io, "vector<"); - print_ast_datatype(io, dt->vector.base); - fprintf(io, ",%d>", dt->vector.elements); - return; - - case MOJOSHADER_AST_DATATYPE_MATRIX: - fprintf(io, "matrix<"); - print_ast_datatype(io, dt->matrix.base); - fprintf(io, ",%d,%d>", dt->matrix.rows, dt->matrix.columns); - return; - - case MOJOSHADER_AST_DATATYPE_BUFFER: - fprintf(io, "buffer<"); - print_ast_datatype(io, dt->buffer.base); - fprintf(io, ">"); - return; - - case MOJOSHADER_AST_DATATYPE_USER: - fprintf(io, "%s", dt->user.name); - return; - - // this should only appear if we did semantic analysis on the AST, - // so we only print the return value here. - case MOJOSHADER_AST_DATATYPE_FUNCTION: - if (!dt->function.retval) - fprintf(io, "void"); - else - print_ast_datatype(io, dt->function.retval); - return; - - //case MOJOSHADER_AST_DATATYPE_NONE: - default: - assert(0 && "Unexpected datatype."); - return; - } // switch -} // print_ast_datatype - -// !!! FIXME: this screws up on order of operations. -static void print_ast(FILE *io, const int substmt, const void *_ast) -{ - const MOJOSHADER_astNode *ast = (const MOJOSHADER_astNode *) _ast; - const char *nl = substmt ? "" : "\n"; - int typeint = 0; - static int indent = 0; - int isblock = 0; - int i; - - // These _HAVE_ to be in the same order as MOJOSHADER_astNodeType! - static const char *binary[] = - { - ",", "*", "/", "%", "+", "-", "<<", ">>", "<", ">", "<=", ">=", "==", - "!=", "&", "^", "|", "&&", "||", "=", "*=", "/=", "%=", "+=", "-=", - "<<=", ">>=", "&=", "^=", "|=" - }; - - static const char *pre_unary[] = { "++", "--", "-", "~", "!" }; - static const char *post_unary[] = { "++", "--" }; - static const char *simple_stmt[] = { "", "break", "continue", "discard" }; - static const char *inpmod[] = { "", "in ", "out ", "in out ", "uniform " }; - static const char *fnstorage[] = { "", "inline " }; - - static const char *interpmod[] = { - "", " linear", " centroid", " nointerpolation", - " noperspective", " sample" - }; - - if (!ast) return; - - typeint = (int) ast->ast.type; - - #define DO_INDENT do { \ - if (!substmt) { for (i = 0; i < indent; i++) fprintf(io, " "); } \ - } while (0) - - switch (ast->ast.type) - { - case MOJOSHADER_AST_OP_PREINCREMENT: - case MOJOSHADER_AST_OP_PREDECREMENT: - case MOJOSHADER_AST_OP_NEGATE: - case MOJOSHADER_AST_OP_COMPLEMENT: - case MOJOSHADER_AST_OP_NOT: - fprintf(io, "%s", pre_unary[(typeint-MOJOSHADER_AST_OP_START_RANGE_UNARY)-1]); - print_ast(io, 0, ast->unary.operand); - break; - - case MOJOSHADER_AST_OP_POSTINCREMENT: - case MOJOSHADER_AST_OP_POSTDECREMENT: - print_ast(io, 0, ast->unary.operand); - fprintf(io, "%s", post_unary[typeint-MOJOSHADER_AST_OP_POSTINCREMENT]); - break; - - case MOJOSHADER_AST_OP_MULTIPLY: - case MOJOSHADER_AST_OP_DIVIDE: - case MOJOSHADER_AST_OP_MODULO: - case MOJOSHADER_AST_OP_ADD: - case MOJOSHADER_AST_OP_SUBTRACT: - case MOJOSHADER_AST_OP_LSHIFT: - case MOJOSHADER_AST_OP_RSHIFT: - case MOJOSHADER_AST_OP_LESSTHAN: - case MOJOSHADER_AST_OP_GREATERTHAN: - case MOJOSHADER_AST_OP_LESSTHANOREQUAL: - case MOJOSHADER_AST_OP_GREATERTHANOREQUAL: - case MOJOSHADER_AST_OP_EQUAL: - case MOJOSHADER_AST_OP_NOTEQUAL: - case MOJOSHADER_AST_OP_BINARYAND: - case MOJOSHADER_AST_OP_BINARYXOR: - case MOJOSHADER_AST_OP_BINARYOR: - case MOJOSHADER_AST_OP_LOGICALAND: - case MOJOSHADER_AST_OP_LOGICALOR: - case MOJOSHADER_AST_OP_ASSIGN: - case MOJOSHADER_AST_OP_MULASSIGN: - case MOJOSHADER_AST_OP_DIVASSIGN: - case MOJOSHADER_AST_OP_MODASSIGN: - case MOJOSHADER_AST_OP_ADDASSIGN: - case MOJOSHADER_AST_OP_SUBASSIGN: - case MOJOSHADER_AST_OP_LSHIFTASSIGN: - case MOJOSHADER_AST_OP_RSHIFTASSIGN: - case MOJOSHADER_AST_OP_ANDASSIGN: - case MOJOSHADER_AST_OP_XORASSIGN: - case MOJOSHADER_AST_OP_ORASSIGN: - case MOJOSHADER_AST_OP_COMMA: - print_ast(io, 0, ast->binary.left); - if (ast->ast.type != MOJOSHADER_AST_OP_COMMA) - fprintf(io, " "); // no space before the comma. - fprintf(io, "%s ", binary[ - (typeint - MOJOSHADER_AST_OP_START_RANGE_BINARY) - 1]); - print_ast(io, 0, ast->binary.right); - break; - - case MOJOSHADER_AST_OP_DEREF_ARRAY: - print_ast(io, 0, ast->binary.left); - fprintf(io, "["); - print_ast(io, 0, ast->binary.right); - fprintf(io, "]"); - break; - - case MOJOSHADER_AST_OP_DEREF_STRUCT: - print_ast(io, 0, ast->derefstruct.identifier); - fprintf(io, "."); - fprintf(io, "%s", ast->derefstruct.member); - break; - - case MOJOSHADER_AST_OP_CONDITIONAL: - print_ast(io, 0, ast->ternary.left); - fprintf(io, " ? "); - print_ast(io, 0, ast->ternary.center); - fprintf(io, " : "); - print_ast(io, 0, ast->ternary.right); - break; - - case MOJOSHADER_AST_OP_IDENTIFIER: - fprintf(io, "%s", ast->identifier.identifier); - break; - - case MOJOSHADER_AST_OP_INT_LITERAL: - fprintf(io, "%d", ast->intliteral.value); - break; - - case MOJOSHADER_AST_OP_FLOAT_LITERAL: - { - const float f = ast->floatliteral.value; - const long long flr = (long long) f; - if (((float) flr) == f) - fprintf(io, "%lld.0", flr); - else - fprintf(io, "%.16g", f); - break; - } // case - - case MOJOSHADER_AST_OP_STRING_LITERAL: - fprintf(io, "\"%s\"", ast->stringliteral.string); - break; - - case MOJOSHADER_AST_OP_BOOLEAN_LITERAL: - fprintf(io, "%s", ast->boolliteral.value ? "true" : "false"); - break; - - case MOJOSHADER_AST_ARGUMENTS: - print_ast(io, 0, ast->arguments.argument); - if (ast->arguments.next != NULL) - { - fprintf(io, ", "); - print_ast(io, 0, ast->arguments.next); - } // if - break; - - case MOJOSHADER_AST_OP_CALLFUNC: - print_ast(io, 0, ast->callfunc.identifier); - fprintf(io, "("); - print_ast(io, 0, ast->callfunc.args); - fprintf(io, ")"); - break; - - case MOJOSHADER_AST_OP_CONSTRUCTOR: - print_ast_datatype(io, ast->constructor.datatype); - fprintf(io, "("); - print_ast(io, 0, ast->constructor.args); - fprintf(io, ")"); - break; - - case MOJOSHADER_AST_OP_CAST: - fprintf(io, "("); - print_ast_datatype(io, ast->cast.datatype); - fprintf(io, ") ("); - print_ast(io, 0, ast->cast.operand); - fprintf(io, ")"); - break; - - case MOJOSHADER_AST_STATEMENT_EXPRESSION: - DO_INDENT; - print_ast(io, 0, ast->exprstmt.expr); // !!! FIXME: This is named badly... - fprintf(io, ";%s", nl); - print_ast(io, 0, ast->exprstmt.next); - break; - - case MOJOSHADER_AST_STATEMENT_IF: - DO_INDENT; - fprintf(io, "if ("); - print_ast(io, 0, ast->ifstmt.expr); - fprintf(io, ")\n"); - isblock = ast->ifstmt.statement->ast.type == MOJOSHADER_AST_STATEMENT_BLOCK; - if (!isblock) indent++; - print_ast(io, 0, ast->ifstmt.statement); - if (!isblock) indent--; - print_ast(io, 0, ast->ifstmt.next); - break; - - case MOJOSHADER_AST_STATEMENT_TYPEDEF: - DO_INDENT; - print_ast(io, 1, ast->typedefstmt.type_info); - fprintf(io, "%s", nl); - print_ast(io, 0, ast->typedefstmt.next); - break; - - case MOJOSHADER_AST_STATEMENT_SWITCH: - DO_INDENT; - switch ( ast->switchstmt.attributes ) - { - case MOJOSHADER_AST_SWITCHATTR_NONE: break; - case MOJOSHADER_AST_SWITCHATTR_FLATTEN: fprintf(io, "[flatten] "); break; - case MOJOSHADER_AST_SWITCHATTR_BRANCH: fprintf(io, "[branch] "); break; - case MOJOSHADER_AST_SWITCHATTR_FORCECASE: fprintf(io, "[forcecase] "); break; - case MOJOSHADER_AST_SWITCHATTR_CALL: fprintf(io, "[call] "); break; - } // switch - - fprintf(io, "switch ("); - print_ast(io, 0, ast->switchstmt.expr); - fprintf(io, ")\n"); - DO_INDENT; - fprintf(io, "{\n"); - indent++; - print_ast(io, 0, ast->switchstmt.cases); - indent--; - fprintf(io, "\n"); - DO_INDENT; - fprintf(io, "}\n"); - print_ast(io, 0, ast->switchstmt.next); - break; - - case MOJOSHADER_AST_SWITCH_CASE: - DO_INDENT; - fprintf(io, "case "); - print_ast(io, 0, ast->cases.expr); - fprintf(io, ":\n"); - isblock = ast->cases.statement->ast.type == MOJOSHADER_AST_STATEMENT_BLOCK; - if (!isblock) indent++; - print_ast(io, 0, ast->cases.statement); - if (!isblock) indent--; - print_ast(io, 0, ast->cases.next); - break; - - case MOJOSHADER_AST_STATEMENT_STRUCT: - DO_INDENT; - print_ast(io, 0, ast->structstmt.struct_info); - fprintf(io, ";%s%s", nl, nl); // always space these out. - print_ast(io, 0, ast->structstmt.next); - break; - - case MOJOSHADER_AST_STATEMENT_VARDECL: - DO_INDENT; - print_ast(io, 1, ast->vardeclstmt.declaration); - fprintf(io, ";%s", nl); - print_ast(io, 0, ast->vardeclstmt.next); - break; - - case MOJOSHADER_AST_STATEMENT_BLOCK: - DO_INDENT; - fprintf(io, "{\n"); - indent++; - print_ast(io, 0, ast->blockstmt.statements); - indent--; - DO_INDENT; - fprintf(io, "}\n"); - print_ast(io, 0, ast->blockstmt.next); - break; - - case MOJOSHADER_AST_STATEMENT_FOR: - DO_INDENT; - print_unroll_attr(io, ast->forstmt.unroll); - fprintf(io, "for ("); - print_ast(io, 1, ast->forstmt.var_decl); - print_ast(io, 1, ast->forstmt.initializer); - fprintf(io, "; "); - print_ast(io, 1, ast->forstmt.looptest); - fprintf(io, "; "); - print_ast(io, 1, ast->forstmt.counter); - - fprintf(io, ")\n"); - isblock = ast->forstmt.statement->ast.type == MOJOSHADER_AST_STATEMENT_BLOCK; - if (!isblock) indent++; - print_ast(io, 0, ast->forstmt.statement); - if (!isblock) indent--; - - print_ast(io, 0, ast->forstmt.next); - break; - - case MOJOSHADER_AST_STATEMENT_DO: - DO_INDENT; - print_unroll_attr(io, ast->dostmt.unroll); - fprintf(io, "do\n"); - - isblock = ast->dostmt.statement->ast.type == MOJOSHADER_AST_STATEMENT_BLOCK; - if (!isblock) indent++; - print_ast(io, 0, ast->dostmt.statement); - if (!isblock) indent--; - - DO_INDENT; - fprintf(io, "while ("); - print_ast(io, 0, ast->dostmt.expr); - fprintf(io, ");\n"); - - print_ast(io, 0, ast->dostmt.next); - break; - - case MOJOSHADER_AST_STATEMENT_WHILE: - DO_INDENT; - print_unroll_attr(io, ast->whilestmt.unroll); - fprintf(io, "while ("); - print_ast(io, 0, ast->whilestmt.expr); - fprintf(io, ")\n"); - - isblock = ast->whilestmt.statement->ast.type == MOJOSHADER_AST_STATEMENT_BLOCK; - if (!isblock) indent++; - print_ast(io, 0, ast->whilestmt.statement); - if (!isblock) indent--; - - print_ast(io, 0, ast->whilestmt.next); - break; - - case MOJOSHADER_AST_STATEMENT_RETURN: - DO_INDENT; - fprintf(io, "return"); - if (ast->returnstmt.expr) - { - fprintf(io, " "); - print_ast(io, 0, ast->returnstmt.expr); - } // if - fprintf(io, ";%s", nl); - print_ast(io, 0, ast->returnstmt.next); - break; - - case MOJOSHADER_AST_STATEMENT_EMPTY: - case MOJOSHADER_AST_STATEMENT_BREAK: - case MOJOSHADER_AST_STATEMENT_CONTINUE: - case MOJOSHADER_AST_STATEMENT_DISCARD: - DO_INDENT; - fprintf(io, "%s;%s", - simple_stmt[(typeint-MOJOSHADER_AST_STATEMENT_START_RANGE)-1], - nl); - print_ast(io, 0, ast->stmt.next); - break; - - case MOJOSHADER_AST_COMPUNIT_FUNCTION: - DO_INDENT; - print_ast(io, 0, ast->funcunit.declaration); - if (ast->funcunit.definition == NULL) - fprintf(io, ";%s", nl); - else - { - fprintf(io, "%s", nl); - print_ast(io, 0, ast->funcunit.definition); - fprintf(io, "%s", nl); - } // else - print_ast(io, 0, ast->funcunit.next); - break; - - case MOJOSHADER_AST_COMPUNIT_TYPEDEF: - DO_INDENT; - print_ast(io, 0, ast->typedefunit.type_info); - fprintf(io, "%s", nl); - print_ast(io, 0, ast->typedefunit.next); - break; - - case MOJOSHADER_AST_COMPUNIT_STRUCT: - DO_INDENT; - print_ast(io, 0, ast->structunit.struct_info); - fprintf(io, ";%s%s", nl, nl); // always space these out. - print_ast(io, 0, ast->structunit.next); - break; - - case MOJOSHADER_AST_COMPUNIT_VARIABLE: - DO_INDENT; - print_ast(io, 1, ast->varunit.declaration); - fprintf(io, ";%s", nl); - if (ast->varunit.next && - ast->varunit.next->ast.type!=MOJOSHADER_AST_COMPUNIT_VARIABLE) - { - fprintf(io, "%s", nl); // group vars together, and space out other things. - } // if - print_ast(io, 0, ast->varunit.next); - break; - - case MOJOSHADER_AST_SCALAR_OR_ARRAY: - fprintf(io, "%s", ast->soa.identifier); - if (ast->soa.isarray) - { - fprintf(io, "["); - print_ast(io, 0, ast->soa.dimension); - fprintf(io, "]"); - } // if - break; - - case MOJOSHADER_AST_TYPEDEF: - DO_INDENT; - fprintf(io, "typedef %s", ast->typdef.isconst ? "const " : ""); - print_ast_datatype(io, ast->typdef.datatype); - fprintf(io, " "); - print_ast(io, 0, ast->typdef.details); - fprintf(io, ";%s", nl); - break; - - case MOJOSHADER_AST_FUNCTION_PARAMS: - fprintf(io, "%s", inpmod[(int) ast->params.input_modifier]); - print_ast_datatype(io, ast->params.datatype); - fprintf(io, " %s", ast->params.identifier); - if (ast->params.semantic) - fprintf(io, " : %s", ast->params.semantic); - fprintf(io, "%s", interpmod[(int) ast->params.interpolation_modifier]); - - if (ast->params.initializer) - { - fprintf(io, " = "); - print_ast(io, 0, ast->params.initializer); - } // if - - if (ast->params.next) - { - fprintf(io, ", "); - print_ast(io, 0, ast->params.next); - } // if - break; - - case MOJOSHADER_AST_FUNCTION_SIGNATURE: - fprintf(io, "%s", fnstorage[(int) ast->funcsig.storage_class]); - if (ast->funcsig.datatype) - print_ast_datatype(io, ast->funcsig.datatype); - else - fprintf(io, "void"); - fprintf(io, " %s(", ast->funcsig.identifier); - print_ast(io, 0, ast->funcsig.params); - fprintf(io, ")"); - if (ast->funcsig.semantic) - fprintf(io, " : %s", ast->funcsig.semantic); - break; - - case MOJOSHADER_AST_STRUCT_DECLARATION: - fprintf(io, "struct %s\n", ast->structdecl.name); - DO_INDENT; - fprintf(io, "{\n"); - indent++; - print_ast(io, 0, ast->structdecl.members); - indent--; - DO_INDENT; - fprintf(io, "}"); - break; - - case MOJOSHADER_AST_STRUCT_MEMBER: - DO_INDENT; - fprintf(io, "%s", interpmod[(int)ast->structmembers.interpolation_mod]); - print_ast_datatype(io, ast->structmembers.datatype); - fprintf(io, " "); - print_ast(io, 0, ast->structmembers.details); - if (ast->structmembers.semantic) - fprintf(io, " : %s", ast->structmembers.semantic); - fprintf(io, ";%s", nl); - print_ast(io, 0, ast->structmembers.next); - break; - - case MOJOSHADER_AST_VARIABLE_DECLARATION: - DO_INDENT; - if (ast->vardecl.attributes & MOJOSHADER_AST_VARATTR_EXTERN) - fprintf(io, "extern "); - if (ast->vardecl.attributes & MOJOSHADER_AST_VARATTR_NOINTERPOLATION) - fprintf(io, "nointerpolation "); - if (ast->vardecl.attributes & MOJOSHADER_AST_VARATTR_SHARED) - fprintf(io, "shared"); - if (ast->vardecl.attributes & MOJOSHADER_AST_VARATTR_STATIC) - fprintf(io, "static "); - if (ast->vardecl.attributes & MOJOSHADER_AST_VARATTR_UNIFORM) - fprintf(io, "uniform "); - if (ast->vardecl.attributes & MOJOSHADER_AST_VARATTR_VOLATILE) - fprintf(io, "nointerpolation "); - if (ast->vardecl.attributes & MOJOSHADER_AST_VARATTR_CONST) - fprintf(io, "const "); - if (ast->vardecl.attributes & MOJOSHADER_AST_VARATTR_ROWMAJOR) - fprintf(io, "rowmajor "); - if (ast->vardecl.attributes & MOJOSHADER_AST_VARATTR_COLUMNMAJOR) - fprintf(io, "columnmajor "); - - if (ast->vardecl.datatype) - print_ast_datatype(io, ast->vardecl.datatype); - else - print_ast(io, 0, ast->vardecl.anonymous_datatype); - fprintf(io, " "); - print_ast(io, 0, ast->vardecl.details); - if (ast->vardecl.semantic) - fprintf(io, " : %s", ast->vardecl.semantic); - if (ast->vardecl.annotations) - { - fprintf(io, " "); - print_ast(io, 0, ast->vardecl.annotations); - } // if - if (ast->vardecl.initializer != NULL) - { - fprintf(io, " = "); - print_ast(io, 0, ast->vardecl.initializer); - } // if - print_ast(io, 0, ast->vardecl.lowlevel); - - if (ast->vardecl.next == NULL) - fprintf(io, "%s", nl); - else - { - const int attr = ast->vardecl.next->attributes; - fprintf(io, ", "); - ast->vardecl.next->attributes = 0; - print_ast(io, 1, ast->vardecl.next); - ast->vardecl.next->attributes = attr; - } // if - break; - - case MOJOSHADER_AST_PACK_OFFSET: - fprintf(io, " : packoffset(%s%s%s)", ast->packoffset.ident1, - ast->packoffset.ident2 ? "." : "", - ast->packoffset.ident2 ? ast->packoffset.ident2 : ""); - break; - - case MOJOSHADER_AST_VARIABLE_LOWLEVEL: - print_ast(io, 0, ast->varlowlevel.packoffset); - if (ast->varlowlevel.register_name) - fprintf(io, " : register(%s)", ast->varlowlevel.register_name); - break; - - case MOJOSHADER_AST_ANNOTATION: - { - const MOJOSHADER_astAnnotations *a = &ast->annotations; - fprintf(io, "<"); - while (a) - { - fprintf(io, " "); - print_ast_datatype(io, a->datatype); - if (a->initializer != NULL) - { - fprintf(io, " = "); - print_ast(io, 0, a->initializer); - } // if - if (a->next) - fprintf(io, ","); - a = a->next; - } // while - fprintf(io, " >"); - break; - } // case - - default: - assert(0 && "unexpected type"); - break; - } // switch - - #undef DO_INDENT -} // print_ast - - -static int open_include(MOJOSHADER_includeType inctype, const char *fname, - const char *parent, const char **outdata, - unsigned int *outbytes, MOJOSHADER_malloc m, - MOJOSHADER_free f, void *d) -{ - int i; - for (i = 0; i < include_path_count; i++) - { - const char *path = include_paths[i]; - const size_t len = strlen(path) + strlen(fname) + 2; - char *buf = (char *) m(len, d); - if (buf == NULL) - return 0; - - snprintf(buf, len, "%s/%s", path, fname); - FILE *io = fopen(buf, "rb"); - f(buf, d); - if (io == NULL) - continue; - - if (fseek(io, 0, SEEK_END) != -1) - { - const long fsize = ftell(io); - if ((fsize == -1) || (fseek(io, 0, SEEK_SET) == -1)) - { - fclose(io); - return 0; - } // if - - char *data = (char *) m(fsize, d); - if (data == NULL) - { - fclose(io); - return 0; - } // if - - if (fread(data, fsize, 1, io) != 1) - { - f(data, d); - fclose(io); - return 0; - } // if - - fclose(io); - *outdata = data; - *outbytes = (unsigned int) fsize; - return 1; - } // if - } // for - - return 0; -} // open_include - - -static void close_include(const char *data, MOJOSHADER_malloc m, - MOJOSHADER_free f, void *d) -{ - f((void *) data, d); -} // close_include - - -static int preprocess(const char *fname, const char *buf, int len, - const char *outfile, - const MOJOSHADER_preprocessorDefine *defs, - unsigned int defcount, FILE *io) -{ - const MOJOSHADER_preprocessData *pd; - int retval = 0; - - pd = MOJOSHADER_preprocess(fname, buf, len, defs, defcount, open_include, - close_include, Malloc, Free, NULL); - - if (pd->error_count > 0) - { - int i; - for (i = 0; i < pd->error_count; i++) - { - fprintf(stderr, "%s:%d: ERROR: %s\n", - pd->errors[i].filename ? pd->errors[i].filename : "???", - pd->errors[i].error_position, - pd->errors[i].error); - } // for - } // if - else - { - if (pd->output != NULL) - { - const int len = pd->output_len; - if ((len) && (fwrite(pd->output, len, 1, io) != 1)) - printf(" ... fwrite('%s') failed.\n", outfile); - else if ((outfile != NULL) && (fclose(io) == EOF)) - printf(" ... fclose('%s') failed.\n", outfile); - else - retval = 1; - } // if - } // else - MOJOSHADER_freePreprocessData(pd); - - return retval; -} // preprocess - - -static int assemble(const char *fname, const char *buf, int len, - const char *outfile, - const MOJOSHADER_preprocessorDefine *defs, - unsigned int defcount, FILE *io) -{ - const MOJOSHADER_parseData *pd; - int retval = 0; - - pd = MOJOSHADER_assemble(fname, buf, len, NULL, 0, NULL, 0, - defs, defcount, open_include, close_include, - Malloc, Free, NULL); - - if (pd->error_count > 0) - { - int i; - for (i = 0; i < pd->error_count; i++) - { - fprintf(stderr, "%s:%d: ERROR: %s\n", - pd->errors[i].filename ? pd->errors[i].filename : "???", - pd->errors[i].error_position, - pd->errors[i].error); - } // for - } // if - else - { - if (pd->output != NULL) - { - const int len = pd->output_len; - if ((len) && (fwrite(pd->output, len, 1, io) != 1)) - printf(" ... fwrite('%s') failed.\n", outfile); - else if ((outfile != NULL) && (fclose(io) == EOF)) - printf(" ... fclose('%s') failed.\n", outfile); - else - retval = 1; - } // if - } // else - MOJOSHADER_freeParseData(pd); - - return retval; -} // assemble - -static int ast(const char *fname, const char *buf, int len, - const char *outfile, const MOJOSHADER_preprocessorDefine *defs, - unsigned int defcount, FILE *io) -{ - const MOJOSHADER_astData *ad; - int retval = 0; - - ad = MOJOSHADER_parseAst(MOJOSHADER_SRC_PROFILE_HLSL_PS_1_1, // !!! FIXME - fname, buf, len, defs, defcount, - open_include, close_include, Malloc, Free, NULL); - - if (ad->error_count > 0) - { - int i; - for (i = 0; i < ad->error_count; i++) - { - fprintf(stderr, "%s:%d: ERROR: %s\n", - ad->errors[i].filename ? ad->errors[i].filename : "???", - ad->errors[i].error_position, - ad->errors[i].error); - } // for - } // if - else - { - print_ast(io, 0, ad->ast); - if ((outfile != NULL) && (fclose(io) == EOF)) - printf(" ... fclose('%s') failed.\n", outfile); - else - retval = 1; - } // else - MOJOSHADER_freeAstData(ad); - - return retval; -} // ast - -static int compile(const char *fname, const char *buf, int len, - const char *outfile, - const MOJOSHADER_preprocessorDefine *defs, - unsigned int defcount, FILE *io) -{ - // !!! FIXME: write me. - //const MOJOSHADER_parseData *pd; - //int retval = 0; - - MOJOSHADER_compile(MOJOSHADER_SRC_PROFILE_HLSL_PS_1_1, // !!! FIXME - fname, buf, len, defs, defcount, - open_include, close_include, - Malloc, Free, NULL); - return 1; -} // compile - -typedef enum -{ - ACTION_UNKNOWN, - ACTION_VERSION, - ACTION_PREPROCESS, - ACTION_ASSEMBLE, - ACTION_AST, - ACTION_COMPILE, -} Action; - - -int main(int argc, char **argv) -{ - Action action = ACTION_UNKNOWN; - int retval = 1; - const char *infile = NULL; - const char *outfile = NULL; - int i; - - MOJOSHADER_preprocessorDefine *defs = NULL; - unsigned int defcount = 0; - - include_paths = (const char **) malloc(sizeof (char *)); - include_paths[0] = "."; - include_path_count = 1; - - // !!! FIXME: clean this up. - for (i = 1; i < argc; i++) - { - const char *arg = argv[i]; - - if (strcmp(arg, "-P") == 0) - { - if ((action != ACTION_UNKNOWN) && (action != ACTION_PREPROCESS)) - fail("Multiple actions specified"); - action = ACTION_PREPROCESS; - } // if - - else if (strcmp(arg, "-A") == 0) - { - if ((action != ACTION_UNKNOWN) && (action != ACTION_ASSEMBLE)) - fail("Multiple actions specified"); - action = ACTION_ASSEMBLE; - } // else if - - else if (strcmp(arg, "-T") == 0) - { - if ((action != ACTION_UNKNOWN) && (action != ACTION_AST)) - fail("Multiple actions specified"); - action = ACTION_AST; - } // else if - - else if (strcmp(arg, "-C") == 0) - { - if ((action != ACTION_UNKNOWN) && (action != ACTION_COMPILE)) - fail("Multiple actions specified"); - action = ACTION_COMPILE; - } // else if - - else if ((strcmp(arg, "-V") == 0) || (strcmp(arg, "--version") == 0)) - { - if ((action != ACTION_UNKNOWN) && (action != ACTION_VERSION)) - fail("Multiple actions specified"); - action = ACTION_VERSION; - } // else if - - else if (strcmp(arg, "-o") == 0) - { - if (outfile != NULL) - fail("multiple output files specified"); - - arg = argv[++i]; - if (arg == NULL) - fail("no filename after '-o'"); - outfile = arg; - } // if - - else if (strcmp(arg, "-I") == 0) - { - arg = argv[++i]; - if (arg == NULL) - fail("no path after '-I'"); - - include_paths = (const char **) realloc(include_paths, - (include_path_count+1) * sizeof (char *)); - include_paths[include_path_count] = arg; - include_path_count++; - } // if - - else if (strncmp(arg, "-D", 2) == 0) - { - arg += 2; - char *ident = strdup(arg); - char *ptr = strchr(ident, '='); - const char *val = ""; - if (ptr) - { - *ptr = '\0'; - val = ptr+1; - } // if - - defs = (MOJOSHADER_preprocessorDefine *) realloc(defs, - (defcount+1) * sizeof (MOJOSHADER_preprocessorDefine)); - defs[defcount].identifier = ident; - defs[defcount].definition = val; - defcount++; - } // else if - - else - { - if (infile != NULL) - fail("multiple input files specified"); - infile = arg; - } // else - } // for - - if (action == ACTION_UNKNOWN) - action = ACTION_ASSEMBLE; - - if (action == ACTION_VERSION) - { - printf("mojoshader-compiler, changeset %s\n", MOJOSHADER_CHANGESET); - return 0; - } // if - - if (infile == NULL) - fail("no input file specified"); - - FILE *io = fopen(infile, "rb"); - if (io == NULL) - fail("failed to open input file"); - - fseek(io, 0, SEEK_END); - long fsize = ftell(io); - fseek(io, 0, SEEK_SET); - if (fsize == -1) - fsize = 1000000; - char *buf = (char *) malloc(fsize); - const int rc = fread(buf, 1, fsize, io); - fclose(io); - if (rc == EOF) - fail("failed to read input file"); - - FILE *outio = outfile ? fopen(outfile, "wb") : stdout; - if (outio == NULL) - fail("failed to open output file"); - - - if (action == ACTION_PREPROCESS) - retval = (!preprocess(infile, buf, rc, outfile, defs, defcount, outio)); - else if (action == ACTION_ASSEMBLE) - retval = (!assemble(infile, buf, rc, outfile, defs, defcount, outio)); - else if (action == ACTION_AST) - retval = (!ast(infile, buf, rc, outfile, defs, defcount, outio)); - else if (action == ACTION_COMPILE) - retval = (!compile(infile, buf, rc, outfile, defs, defcount, outio)); - - if ((retval != 0) && (outfile != NULL)) - remove(outfile); - - free(buf); - - for (i = 0; i < defcount; i++) - free((void *) defs[i].identifier); - free(defs); - - free(include_paths); - - return retval; -} // main - -// end of mojoshader-compiler.c ... -