commit f07e3bd4c9553e7cd2af058fb6b8482721e4e486 Author: Corentin Wallez Date: Thu Apr 20 14:38:20 2017 -0400 Initial commit of all the NXT integration. More like squashed history, contributors were: - Kai Ninomiya - Corentin Wallez diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000000..55f2c0c990 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,27 @@ +[submodule "external/glfw"] + path = third_party/glfw + url = https://github.com/glfw/glfw.git +[submodule "external/googletest"] + path = third_party/googletest + url = https://github.com/google/googletest.git +[submodule "external/glslang"] + path = third_party/glslang + url = https://github.com/google/glslang.git +[submodule "external/shaderc"] + path = third_party/shaderc + url = https://github.com/google/shaderc.git +[submodule "external/spirv-tools"] + path = third_party/spirv-tools + url = https://github.com/KhronosGroup/SPIRV-Tools.git +[submodule "external/spirv-headers"] + path = third_party/spirv-headers + url = https://github.com/KhronosGroup/SPIRV-Headers.git +[submodule "external/spirv-cross"] + path = third_party/spirv-cross + url = https://github.com/KhronosGroup/SPIRV-Cross.git +[submodule "external/stb"] + path = third_party/stb + url = https://github.com/nothings/stb.git +[submodule "external/glm"] + path = third_party/glm + url = https://github.com/g-truc/glm.git diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000000..01176762f6 --- /dev/null +++ b/AUTHORS @@ -0,0 +1,6 @@ +# This is the list of NXT authors for copyright purposes. +# +# This does not necessarily list everyone who has contributed code, since in +# some cases, their employer may be the copyright holder. To see the full list +# of contributors, see the revision history in source control. +Google Inc. diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000000..4fc7352291 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,75 @@ +# Copyright 2017 The NXT Authors +# +# 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. + +cmake_minimum_required(VERSION 2.8) +project(nxt C CXX) + +function(SetCXX14 Target) + if(MSVC) + set_property(TARGET ${Target} APPEND PROPERTY COMPILE_OPTIONS "/std:c++14") + else() + set_property(TARGET ${Target} APPEND PROPERTY COMPILE_OPTIONS "-std=c++14") + endif() +endfunction() +function(SetPIC Target) + if(MSVC) + else() + set_property(TARGET ${Target} APPEND PROPERTY COMPILE_OPTIONS "-fPIC") + endif() +endfunction() + +add_subdirectory(third_party) +add_subdirectory(generator) + +set(INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src/include) + +Generate( + LIB_NAME nxt + LIB_TYPE SHARED + PRINT_NAME libNXT + COMMAND_LINE_ARGS + ${GENERATOR_COMMON_ARGS} + -T nxt +) +target_include_directories(nxt PUBLIC ${GENERATED_DIR}) + +Generate( + LIB_NAME nxtcpp + LIB_TYPE SHARED + PRINT_NAME libNXT++ + COMMAND_LINE_ARGS + ${GENERATOR_COMMON_ARGS} + -T nxtcpp +) +target_include_directories(nxtcpp PUBLIC ${GENERATED_DIR} PUBLIC ${INCLUDE_DIR}) +target_link_libraries(nxtcpp nxt) +SetCXX14(nxtcpp) + +Generate( + LIB_NAME mock_nxt + LIB_TYPE SHARED + PRINT_NAME libMockNXT + COMMAND_LINE_ARGS + ${GENERATOR_COMMON_ARGS} + -T mock_nxt +) +target_include_directories(mock_nxt PUBLIC ${GENERATED_DIR}) +target_link_libraries(mock_nxt nxt gtest) +SetCXX14(mock_nxt) + +add_subdirectory(src/backend) +add_subdirectory(src/wire) +add_subdirectory(src/tests) + +add_subdirectory(examples) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000..b0e3b1164a --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,24 @@ +# How to contribute + +We'd love to accept your patches and contributions to this project. There are +just a few small guidelines you need to follow. + +## Contributor License Agreement + +Contributions to this project must be accompanied by a Contributor License +Agreement. You (or your employer) retain the copyright to your contribution, +this simply gives us permission to use and redistribute your contributions as +part of the project. Head over to to see +your current agreements on file or to sign a new one. + +You generally only need to submit a CLA once, so if you've already submitted one +(even if it was for a different project), you probably don't need to do it +again. + +## Code reviews + +All submissions, including submissions by project members, require review. We +use GitHub pull requests for this purpose. Consult +[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more +information on using pull requests. + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000..3afb763d20 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/README.md b/README.md new file mode 100644 index 0000000000..f27d5e04db --- /dev/null +++ b/README.md @@ -0,0 +1,121 @@ +# NXT, standalone part + +NXT is an unoriginal name for Chromium’s investigation and prototyping of a NeXT generation graphics API for the Web. This repository contains a native library implementing NXT on multiple backends, as well as some code generators used for the integration in Chromium. NXT is not an official Google product. + +We focused on efforts on two axis: + +- An investigation of the constraints coming from the Web and in particular portability, for which we looked at the intersection of the designs of D3D12, Metal, Vulkan, OpenGL and D3D11. See links to some of our investigations below. +- A prototype API inspired by all of D3D12, Metal and Vulkan, but none in particular. The API works on two backends: OpenGL and Metal and is usable from native code (think WebAssembly) and from Javascript inside of Chrome. Our focus was not to have a complete API but to show the breadth of potential usage. + +We’re making our investigation and prototype public to provide another example for the upcoming discussion in the “GPU for the Web” W3C community group. + +NXT currently has the following features: + +- Command buffers, graphics and compute pipelines +- Textures, samplers, vertex / index / uniform / storage buffers. +- Descriptor sets (called bind groups) and push constants +- SPIRV for the shading language +- Validation + +NXT is missing a lot of things to be usable for anything else than prototyping: + +- Render-targets / render passes +- Most of the fixed function pipeline state +- Barriers / resource transitions and GPU - CPU synchronization +- Buffer mapping +- ... + +We chose to use SPIRV in our prototype because it was the only language that had translators to other shading languages, thanks to SPIRV-Cross which saved us a ton of work. [SPIRV-Cross](https://github.com/KhronosGroup/SPIRV-Cross) doesn’t have an HLSL backend so we didn’t attempt a D3D12 backend (and D3D11 was too limiting for our prototype API). Only the Metal and the OpenGL backends are functional at this time. The OpenGL backend let us integrate in Chromium very easily. + +## Links + +Some of the investigations we made on the design of potential backend APIs: + +- [Binding model investigation](https://drive.google.com/open?id=1_xeTnk6DlN7YmePQQAlnHndA043rgwBzUYtatk5y7kQ) +- [Data uploads investigation](https://drive.google.com/open?id=1Mi9l14zG8HzJ5Z6107SdPhON0mq4d-3SUI8iS631nek) +- [Resource creation investigation](https://drive.google.com/open?id=1hK1SkTFkXJXPjyla0EEl1fOIwJSc6T41AV2mGiovyFU) +- [Vertex setup investigation](https://drive.google.com/open?id=1SIUpdg-6Xm5FFF1ktdBfnR5oRKjyPAfXir7Drui4cYM) + +[Another presentation](https://drive.google.com/open?id=1mLQEM__twfivV7nJLDBIomS9pegOYkJQWyM6lTse4PQ) about our work with more details on the architecture of the prototype, and a [video](https://youtu.be/ThlZ5K4hJvo) of the demo we showed. + +TODO: add a link to the NXT-chromium repo once it is uploaded. + +## Key elements of the prototype’s architecture + +### Builder pattern for object creation + +In NXT, object creation is done through builder objects that gather initialization parameters with a fluent interface and return the initialized object when GetResult() is called. + +In addition to the improved type-safety and subjective prettiness compared to giant constructors, this style enables additional optimizations. For example this removes the need for any check for an object being built and allows backend to forget parameters it might not care about. + +Here’s an example of buffer creation: + +```cpp +nxt::Buffer buffer = device.CreateBufferBuilder() + .SetUsage(nxt::BufferUsageBit::Uniform | nxt::BufferUsageBit::Mapped) + .SetSize(42) + .GetResult(); +``` + +### The wire client-server and error handling +What we call the wire is an API command buffer for NXT. The name was chosen to avoid conflict with the “command buffer” concept in graphics APIs. + +Originally OpenGL was designed as a client-server architecture with asynchronous errors and objects that could be used by the client before they were created by server. Over time more client state-tracking was added but the core asynchronous structure remained. This enabled OpenGL ES 2 / WebGL to be implemented in Chromium in which the web page and the GPU driver live in different processes. In addition to security this separation helps with performance in CPU-bound WebGL apps. + +For this reason we built NXT as a network-transparent API so that it could integrate nicely in the Chromium architecture, and we believe any next-generation Web API would have to be network-transparent too. + +In NXT, as in OpenGL, API objects can be used immediately after they have been created on the client, even if the server hasn’t seen the creation command yet. If object creation succeeds, everything happens transparently otherwise the object is tagged as being an error. NXT calls with error-tagged objects use the following rules: + +- Functions result in a noop. +- Functions returning an object return an error value. +- Builder methods mark the builder as an error value. + +The idea is that a whole bunch of object creation can be done when the application loads, then all the objects checked once for any error. The concept presented above is similar to [promise pipelining](http://www.erights.org/elib/distrib/pipeline.html) and to the [Maybe monad](https://en.wikipedia.org/wiki/Monad_(functional_programming)#The_Maybe_monad). + +Currently the wire only has client to server communication and there is no way to know the error status of objects or read API data like the content of buffers. In our prototype the wire is responsible for object lifetime validation. + +### Code generation + +Our prototype heavily relies on code generation. It greatly improved iteration time on the API as the generators kept the Javascript bindings, IDL files, wire, C++ bindings and friends up to date. But it reduced flexibility in the API shape as adding as changing the shape required modifying all generators in non-trivial ways. + +For example, NXT can only return objects which prevents mapping buffers or even reading back single pixel values. There is currently no way to know the error status on the client side. These improvements, and more, are planned, and contributions are welcome. + +Other generators include: + +- A C-header with the definition of nxtProcTable that is the “real” underlying NXT API exposed by the backends. +- Glue code generating nxtProcTable for a backend with simple validation included (enum value checks etc.) +- A mock API for testing + +## Structure of the code + +Here are the main files and directories: + +``` +/next.json - the JSON file describing the API that is used by the code generators +/examples - example code that was also used for end2end testing (it is not possible to do automated testing without being able to read back data) +/generator - The code generator and its templates +/generator/templates - The code generator templates +/generator/templates/blink - Templates used in the integration with Chromium +/src - Non-generator code for the ANGLE-like library +/src/backend +/src/backend/common - Handles all the state tracking and validation +/src/backend/metal - the Metal backend +/src/backend/opengl - the OpenGL backend +/src/wire - Glue code and interfaces for the wire +/third_party - external dependencies +``` + +## Getting and building the code + +NXT standalone is a CMake project with git submodules. To download and build it, do the following: + +```sh +git clone --recursive +cd +mkdir build && cd build +cmake .. +make +# Run executables in examples/, --help will provide the options to choose the backend (compute only works on Metal on OSX) and the command buffer. +``` + +It is currently known to compile on Linux and OSX, and has some warnings on Windows when using MSVC (it doesn’t handle code reachability in enum class switches correctly). diff --git a/examples/Animometer.cpp b/examples/Animometer.cpp new file mode 100644 index 0000000000..bddb437af4 --- /dev/null +++ b/examples/Animometer.cpp @@ -0,0 +1,163 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "Utils.h" + +#include +#include +#include +#include + +nxt::Device device; +nxt::Queue queue; +nxt::Pipeline pipeline; + +float RandomFloat(float min, float max) { + float zeroOne = rand() / float(RAND_MAX); + return zeroOne * (max - min) + min; +} + +struct ShaderData { + float scale; + float time; + float offsetX; + float offsetY; + float scalar; + float scalarOffset; +}; + +static std::vector shaderData; + +void init() { + nxtProcTable procs; + GetProcTableAndDevice(&procs, &device); + nxtSetProcs(&procs); + + queue = device.CreateQueueBuilder().GetResult(); + + nxt::ShaderModule vsModule = CreateShaderModule(device, nxt::ShaderStage::Vertex, R"( + #version 450 + + layout(push_constant) uniform ConstantsBlock { + float scale; + float time; + float offsetX; + float offsetY; + float scalar; + float scalarOffset; + } c; + + out vec4 v_color; + + const vec4 positions[3] = vec4[3]( + vec4( 0.0f, 0.1f, 0.0f, 1.0f), + vec4(-0.1f, -0.1f, 0.0f, 1.0f), + vec4( 0.1f, -0.1f, 0.0f, 1.0f) + ); + + const vec4 colors[3] = vec4[3]( + vec4(1.0f, 0.0f, 0.0f, 1.0f), + vec4(0.0f, 1.0f, 0.0f, 1.0f), + vec4(0.0f, 0.0f, 1.0f, 1.0f) + ); + + void main() { + vec4 position = positions[gl_VertexIndex]; + vec4 color = colors[gl_VertexIndex]; + + float fade = mod(c.scalarOffset + c.time * c.scalar / 10.0, 1.0); + if (fade < 0.5) { + fade = fade * 2.0; + } else { + fade = (1.0 - fade) * 2.0; + } + float xpos = position.x * c.scale; + float ypos = position.y * c.scale; + float angle = 3.14159 * 2.0 * fade; + float xrot = xpos * cos(angle) - ypos * sin(angle); + float yrot = xpos * sin(angle) + ypos * cos(angle); + xpos = xrot + c.offsetX; + ypos = yrot + c.offsetY; + v_color = vec4(fade, 1.0 - fade, 0.0, 1.0) + color; + gl_Position = vec4(xpos, ypos, 0.0, 1.0); + })" + ); + + nxt::ShaderModule fsModule = CreateShaderModule(device, nxt::ShaderStage::Fragment, R"( + #version 450 + out vec4 fragColor; + in vec4 v_color; + void main() { + fragColor = v_color; + })" + ); + + pipeline = device.CreatePipelineBuilder() + .SetStage(nxt::ShaderStage::Vertex, vsModule, "main") + .SetStage(nxt::ShaderStage::Fragment, fsModule, "main") + .GetResult(); + + shaderData.resize(10000); + for (auto& data : shaderData) { + data.scale = RandomFloat(0.2, 0.4); + data.time = 0.0; + data.offsetX = RandomFloat(-0.9, 0.9); + data.offsetY = RandomFloat(-0.9, 0.9); + data.scalar = RandomFloat(0.5, 2.0); + data.scalarOffset = RandomFloat(0.0, 10.0); + } +} + +void frame() { + static int f = 0; + f++; + + size_t i = 0; + + std::vector commands(50); + for (int j = 0; j < 50; j++) { + + nxt::CommandBufferBuilder builder = device.CreateCommandBufferBuilder() + .SetPipeline(pipeline) + .Clone(); + + for (int k = 0; k < 200; k++) { + + shaderData[i].time = f / 60.0f; + builder.SetPushConstants(nxt::ShaderStageBit::Vertex, 0, 6, reinterpret_cast(&shaderData[i])) + .DrawArrays(3, 1, 0, 0); + i++; + } + + commands[j] = builder.GetResult(); + } + + queue.Submit(50, commands.data()); + SwapBuffers(); + fprintf(stderr, "frame %i\n", f); +} + +int main(int argc, const char* argv[]) { + if (!InitUtils(argc, argv)) { + return 1; + } + init(); + + while (!ShouldQuit()) { + frame(); + usleep(16000); + } + + // TODO release stuff +} diff --git a/examples/BackendBinding.h b/examples/BackendBinding.h new file mode 100644 index 0000000000..0f92fe4afc --- /dev/null +++ b/examples/BackendBinding.h @@ -0,0 +1,34 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef UTILS_BACKENDBINDING_H_ +#define UTILS_BACKENDBINDING_H_ + +#include + +struct GLFWwindow; + +class BackendBinding { + public: + virtual void SetupGLFWWindowHints() = 0; + virtual void GetProcAndDevice(nxtProcTable* procs, nxtDevice* device) = 0; + virtual void SwapBuffers() = 0; + + void SetWindow(GLFWwindow* window) {this->window = window;} + + protected: + GLFWwindow* window = nullptr; +}; + +#endif // UTILS_BACKENDBINDING_H_ diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt new file mode 100644 index 0000000000..d4f97a736b --- /dev/null +++ b/examples/CMakeLists.txt @@ -0,0 +1,71 @@ +# Copyright 2017 The NXT Authors +# +# 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. + +list(APPEND UTILS_SOURCES + Utils.h + Utils.cpp + BackendBinding.h +) + +if (APPLE) + list(APPEND UTILS_SOURCES + MetalBinding.mm + ) +endif() + +add_library(utils SHARED ${UTILS_SOURCES}) +target_link_libraries(utils nxt_backend nxt_wire shaderc nxtcpp nxt) +SetCXX14(utils) + +add_executable(CHelloTriangle HelloTriangle.c) +target_link_libraries(CHelloTriangle utils) + +add_executable(CppHelloTriangle HelloTriangle.cpp) +target_link_libraries(CppHelloTriangle utils) +SetCXX14(CppHelloTriangle) + +add_executable(ComputeBoids ComputeBoids.cpp) +target_link_libraries(ComputeBoids utils) +target_include_directories(ComputeBoids PUBLIC ../ ${GLM_INCLUDE_DIR}) +SetCXX14(ComputeBoids) + +add_executable(HelloVertices HelloVertices.cpp) +target_link_libraries(HelloVertices utils) +SetCXX14(HelloVertices) + +add_executable(HelloInstancing HelloInstancing.cpp) +target_link_libraries(HelloInstancing utils) +SetCXX14(HelloInstancing) + +add_executable(HelloIndices HelloIndices.cpp) +target_link_libraries(HelloIndices utils) +SetCXX14(HelloIndices) + +add_executable(HelloUBO HelloUBO.cpp) +target_link_libraries(HelloUBO utils) +SetCXX14(HelloUBO) + +add_executable(HelloCompute HelloCompute.cpp) +target_link_libraries(HelloCompute utils) +SetCXX14(HelloCompute) + +add_executable(Animometer Animometer.cpp) +target_link_libraries(Animometer utils) +SetCXX14(Animometer) + +add_executable(SpirvTest SpirvTest.cpp) +target_link_libraries(SpirvTest shaderc spirv-cross nxtcpp) +SetCXX14(SpirvTest) + +add_subdirectory(glTFViewer) diff --git a/examples/ComputeBoids.cpp b/examples/ComputeBoids.cpp new file mode 100644 index 0000000000..327821d688 --- /dev/null +++ b/examples/ComputeBoids.cpp @@ -0,0 +1,324 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "Utils.h" + +#include +#include +#include +#include + +#include + +nxt::Device device; +nxt::Queue queue; + +nxt::Buffer modelBuffer; +std::array particleBuffers; + +nxt::Pipeline renderPipeline; + +nxt::Buffer updateParams; +nxt::Pipeline updatePipeline; +std::array updateBGs; + +std::array commandBuffers; + +size_t pingpong = 0; + +static const uint32_t kNumParticles = 1000; + +struct Particle { + glm::vec2 pos; + glm::vec2 vel; +}; + +struct SimParams { + float deltaT; + float rule1Distance; + float rule2Distance; + float rule3Distance; + float rule1Scale; + float rule2Scale; + float rule3Scale; + int particleCount; +}; + +void initBuffers() { + glm::vec2 model[3] = { + {-0.01, -0.02}, + {0.01, -0.02}, + {0.00, 0.02}, + }; + modelBuffer = device.CreateBufferBuilder() + .SetAllowedUsage(nxt::BufferUsageBit::Mapped | nxt::BufferUsageBit::Vertex) + .SetInitialUsage(nxt::BufferUsageBit::Mapped) + .SetSize(sizeof(model)) + .GetResult(); + modelBuffer.SetSubData(0, sizeof(model) / sizeof(uint32_t), + reinterpret_cast(model)); + modelBuffer.FreezeUsage(nxt::BufferUsageBit::Vertex); + + SimParams params = { 0.04, 0.1, 0.025, 0.025, 0.02, 0.05, 0.005, kNumParticles }; + updateParams = device.CreateBufferBuilder() + .SetAllowedUsage(nxt::BufferUsageBit::Mapped | nxt::BufferUsageBit::Uniform) + .SetInitialUsage(nxt::BufferUsageBit::Mapped) + .SetSize(sizeof(SimParams)) + .GetResult(); + updateParams.SetSubData(0, sizeof(SimParams) / sizeof(uint32_t), + reinterpret_cast(¶ms)); + updateParams.FreezeUsage(nxt::BufferUsageBit::Uniform); + + std::vector initialParticles(kNumParticles); + { + std::mt19937 generator; + std::uniform_real_distribution dist(-1.0f, 1.0f); + for (auto& p : initialParticles) + { + p.pos = glm::vec2(dist(generator), dist(generator)); + p.vel = glm::vec2(dist(generator), dist(generator)) * 0.1f; + } + } + + for (int i = 0; i < 2; i++) { + particleBuffers[i] = device.CreateBufferBuilder() + .SetAllowedUsage(nxt::BufferUsageBit::Mapped | nxt::BufferUsageBit::Vertex | nxt::BufferUsageBit::Storage) + .SetInitialUsage(nxt::BufferUsageBit::Mapped) + .SetSize(sizeof(Particle) * kNumParticles) + .GetResult(); + + particleBuffers[i].SetSubData(0, + sizeof(Particle) * kNumParticles / sizeof(uint32_t), + reinterpret_cast(initialParticles.data())); + } +} + +void initRender() { + nxt::ShaderModule vsModule = CreateShaderModule(device, nxt::ShaderStage::Vertex, R"( + #version 450 + layout(location = 0) in vec2 a_particlePos; + layout(location = 1) in vec2 a_particleVel; + layout(location = 2) in vec2 a_pos; + void main() { + float angle = -atan(a_particleVel.x, a_particleVel.y); + vec2 pos = vec2(a_pos.x * cos(angle) - a_pos.y * sin(angle), + a_pos.x * sin(angle) + a_pos.y * cos(angle)); + gl_Position = vec4(pos + a_particlePos, 0, 1); + } + )"); + + nxt::ShaderModule fsModule = CreateShaderModule(device, nxt::ShaderStage::Fragment, R"( + #version 450 + out vec4 fragColor; + void main() { + fragColor = vec4(1.0); + } + )"); + + nxt::InputState inputState = device.CreateInputStateBuilder() + .SetAttribute(0, 0, nxt::VertexFormat::FloatR32G32, offsetof(Particle, pos)) + .SetAttribute(1, 0, nxt::VertexFormat::FloatR32G32, offsetof(Particle, vel)) + .SetInput(0, sizeof(Particle), nxt::InputStepMode::Instance) + .SetAttribute(2, 1, nxt::VertexFormat::FloatR32G32, 0) + .SetInput(1, sizeof(glm::vec2), nxt::InputStepMode::Vertex) + .GetResult(); + + renderPipeline = device.CreatePipelineBuilder() + .SetStage(nxt::ShaderStage::Vertex, vsModule, "main") + .SetStage(nxt::ShaderStage::Fragment, fsModule, "main") + .SetInputState(inputState) + .GetResult(); +} + +void initSim() { + nxt::ShaderModule module = CreateShaderModule(device, nxt::ShaderStage::Compute, R"( + #version 450 + + struct Particle { + vec2 pos; + vec2 vel; + }; + + layout(std140, set = 0, binding = 0) uniform SimParams { + float deltaT; + float rule1Distance; + float rule2Distance; + float rule3Distance; + float rule1Scale; + float rule2Scale; + float rule3Scale; + int particleCount; + } params; + + layout(std140, set = 0, binding = 1) buffer ParticlesA { + Particle particlesA[1000]; + }; + + layout(std140, set = 0, binding = 2) buffer ParticlesB { + Particle particlesB[1000]; + }; + + void main() { + // https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp + + uint index = gl_GlobalInvocationID.x; + if (index >= params.particleCount) { return; } + + vec2 vPos = particlesA[index].pos; + vec2 vVel = particlesA[index].vel; + + vec2 cMass = vec2(0.0, 0.0); + vec2 cVel = vec2(0.0, 0.0); + vec2 colVel = vec2(0.0, 0.0); + int cMassCount = 0; + int cVelCount = 0; + + vec2 pos; + vec2 vel; + for (int i = 0; i < params.particleCount; ++i) { + if (i == index) { continue; } + pos = particlesA[i].pos.xy; + vel = particlesA[i].vel.xy; + + if (distance(pos, vPos) < params.rule1Distance) { + cMass += pos; + cMassCount++; + } + if (distance(pos, vPos) < params.rule2Distance) { + colVel -= (pos - vPos); + } + if (distance(pos, vPos) < params.rule3Distance) { + cVel += vel; + cVelCount++; + } + } + if (cMassCount > 0) { + cMass = cMass / cMassCount - vPos; + } + if (cVelCount > 0) { + cVel = cVel / cVelCount; + } + + vVel += cMass * params.rule1Scale + colVel * params.rule2Scale + cVel * params.rule3Scale; + + // clamp velocity for a more pleasing simulation. + vVel = normalize(vVel) * clamp(length(vVel), 0.0, 0.1); + + // kinematic update + vPos += vVel * params.deltaT; + + // Wrap around boundary + if (vPos.x < -1.0) vPos.x = 1.0; + if (vPos.x > 1.0) vPos.x = -1.0; + if (vPos.y < -1.0) vPos.y = 1.0; + if (vPos.y > 1.0) vPos.y = -1.0; + + particlesB[index].pos = vPos; + + // Write back + particlesB[index].vel = vVel; + } + )"); + + nxt::BindGroupLayout bgl = device.CreateBindGroupLayoutBuilder() + .SetBindingsType(nxt::ShaderStageBit::Compute, nxt::BindingType::UniformBuffer, 0, 1) + .SetBindingsType(nxt::ShaderStageBit::Compute, nxt::BindingType::StorageBuffer, 1, 2) + .GetResult(); + + nxt::PipelineLayout pl = device.CreatePipelineLayoutBuilder() + .SetBindGroupLayout(0, bgl) + .GetResult(); + + updatePipeline = device.CreatePipelineBuilder() + .SetLayout(pl) + .SetStage(nxt::ShaderStage::Compute, module, "main") + .GetResult(); + + nxt::BufferView updateParamsView = updateParams.CreateBufferViewBuilder() + .SetExtent(0, sizeof(SimParams)) + .GetResult(); + + std::array views; + for (uint32_t i = 0; i < 2; ++i) { + views[i] = particleBuffers[i].CreateBufferViewBuilder() + .SetExtent(0, kNumParticles * sizeof(Particle)) + .GetResult(); + } + + for (uint32_t i = 0; i < 2; ++i) { + updateBGs[i] = device.CreateBindGroupBuilder() + .SetLayout(bgl) + .SetUsage(nxt::BindGroupUsage::Frozen) + .SetBufferViews(0, 1, &updateParamsView) + .SetBufferViews(1, 1, &views[i]) + .SetBufferViews(2, 1, &views[(i + 1) % 2]) + .GetResult(); + } +} + +void initCommandBuffers() { + static const uint32_t zeroOffsets[1] = {0}; + for (int i = 0; i < 2; ++i) { + auto& bufferSrc = particleBuffers[i]; + auto& bufferDst = particleBuffers[(i + 1) % 2]; + commandBuffers[i] = device.CreateCommandBufferBuilder() + .SetPipeline(updatePipeline) + .TransitionBufferUsage(bufferSrc, nxt::BufferUsageBit::Storage) + .TransitionBufferUsage(bufferDst, nxt::BufferUsageBit::Storage) + .SetBindGroup(0, updateBGs[i]) + .Dispatch(kNumParticles, 1, 1) + + .SetPipeline(renderPipeline) + .TransitionBufferUsage(bufferDst, nxt::BufferUsageBit::Vertex) + .SetVertexBuffers(0, 1, &bufferDst, zeroOffsets) + .SetVertexBuffers(1, 1, &modelBuffer, zeroOffsets) + .DrawArrays(3, kNumParticles, 0, 0) + + .GetResult(); + } +} + +void init() { + nxtProcTable procs; + GetProcTableAndDevice(&procs, &device); + nxtSetProcs(&procs); + + queue = device.CreateQueueBuilder().GetResult(); + + initBuffers(); + initRender(); + initSim(); + initCommandBuffers(); +} + +void frame() { + queue.Submit(1, &commandBuffers[pingpong]); + SwapBuffers(); + + pingpong = (pingpong + 1) % 2; +} + +int main(int argc, const char* argv[]) { + if (!InitUtils(argc, argv)) { + return 1; + } + init(); + + while (!ShouldQuit()) { + frame(); + usleep(16000); + } + + // TODO release stuff +} diff --git a/examples/HelloCompute.cpp b/examples/HelloCompute.cpp new file mode 100644 index 0000000000..ad4daf4a10 --- /dev/null +++ b/examples/HelloCompute.cpp @@ -0,0 +1,154 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "Utils.h" + +#include +#include + +nxt::Device device; +nxt::Queue queue; +nxt::Buffer buffer; +nxt::Pipeline renderPipeline; +nxt::BindGroup renderBindGroup; +nxt::Pipeline computePipeline; +nxt::BindGroup computeBindGroup; + +void init() { + nxtProcTable procs; + GetProcTableAndDevice(&procs, &device); + nxtSetProcs(&procs); + + queue = device.CreateQueueBuilder().GetResult(); + + struct {uint32_t a; float b;} s; + memset(&s, sizeof(s), 0); + buffer = device.CreateBufferBuilder() + .SetAllowedUsage(nxt::BufferUsageBit::Mapped | nxt::BufferUsageBit::Uniform | nxt::BufferUsageBit::Storage) + .SetInitialUsage(nxt::BufferUsageBit::Mapped) + .SetSize(sizeof(s)) + .GetResult(); + buffer.SetSubData(0, sizeof(s) / sizeof(uint32_t), reinterpret_cast(&s)); + + nxt::BufferView view = buffer.CreateBufferViewBuilder() + .SetExtent(0, sizeof(s)) + .GetResult(); + + { + nxt::ShaderModule module = CreateShaderModule(device, nxt::ShaderStage::Compute, R"( + #version 450 + layout(set = 0, binding = 0) buffer myBlock { + int a; + float b; + } myStorage; + void main() { + myStorage.a = (myStorage.a + 1) % 256; + myStorage.b = mod((myStorage.b + 0.02), 1.0); + })" + ); + + nxt::BindGroupLayout bgl = device.CreateBindGroupLayoutBuilder() + .SetBindingsType(nxt::ShaderStageBit::Compute, nxt::BindingType::StorageBuffer, 0, 1) + .GetResult(); + + nxt::PipelineLayout pl = device.CreatePipelineLayoutBuilder() + .SetBindGroupLayout(0, bgl) + .GetResult(); + + computePipeline = device.CreatePipelineBuilder() + .SetLayout(pl) + .SetStage(nxt::ShaderStage::Compute, module, "main") + .GetResult(); + + computeBindGroup = device.CreateBindGroupBuilder() + .SetLayout(bgl) + .SetUsage(nxt::BindGroupUsage::Frozen) + .SetBufferViews(0, 1, &view) + .GetResult(); + } + + { + nxt::ShaderModule vsModule = CreateShaderModule(device, nxt::ShaderStage::Vertex, R"( + #version 450 + const vec2 pos[3] = vec2[3](vec2(0.0f, 0.5f), vec2(-0.5f, -0.5f), vec2(0.5f, -0.5f)); + void main() { + gl_Position = vec4(pos[gl_VertexIndex], 0.5, 1.0); + })" + ); + + nxt::ShaderModule fsModule = CreateShaderModule(device, nxt::ShaderStage::Fragment, R"( + #version 450 + layout(set = 0, binding = 0) uniform myBlock { + int a; + float b; + } myUbo; + out vec4 fragColor; + void main() { + fragColor = vec4(1.0, myUbo.a / 255.0, myUbo.b, 1.0); + })" + ); + + nxt::BindGroupLayout bgl = device.CreateBindGroupLayoutBuilder() + .SetBindingsType(nxt::ShaderStageBit::Fragment, nxt::BindingType::UniformBuffer, 0, 1) + .GetResult(); + + nxt::PipelineLayout pl = device.CreatePipelineLayoutBuilder() + .SetBindGroupLayout(0, bgl) + .GetResult(); + + renderPipeline = device.CreatePipelineBuilder() + .SetLayout(pl) + .SetStage(nxt::ShaderStage::Vertex, vsModule, "main") + .SetStage(nxt::ShaderStage::Fragment, fsModule, "main") + .GetResult(); + + renderBindGroup = device.CreateBindGroupBuilder() + .SetLayout(bgl) + .SetUsage(nxt::BindGroupUsage::Frozen) + .SetBufferViews(0, 1, &view) + .GetResult(); + } +} + +void frame() { + nxt::CommandBuffer commands = device.CreateCommandBufferBuilder() + .SetPipeline(computePipeline) + .TransitionBufferUsage(buffer, nxt::BufferUsageBit::Storage) + .SetBindGroup(0, computeBindGroup) + .Dispatch(1, 1, 1) + + .SetPipeline(renderPipeline) + .TransitionBufferUsage(buffer, nxt::BufferUsageBit::Uniform) + .SetBindGroup(0, renderBindGroup) + .DrawArrays(3, 1, 0, 0) + + .GetResult(); + + queue.Submit(1, &commands); + SwapBuffers(); +} + +int main(int argc, const char* argv[]) { + if (!InitUtils(argc, argv)) { + return 1; + } + init(); + + while (!ShouldQuit()) { + frame(); + usleep(16000); + } + + // TODO release stuff +} diff --git a/examples/HelloIndices.cpp b/examples/HelloIndices.cpp new file mode 100644 index 0000000000..4ac138fa17 --- /dev/null +++ b/examples/HelloIndices.cpp @@ -0,0 +1,117 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "Utils.h" + +#include +#include + +nxt::Device device; + +nxt::Buffer indexBuffer; +nxt::Buffer vertexBuffer; + +nxt::Queue queue; +nxt::Pipeline pipeline; + +void initBuffers() { + static const uint32_t indexData[3] = { + 0, 1, 2, + }; + indexBuffer = device.CreateBufferBuilder() + .SetAllowedUsage(nxt::BufferUsageBit::Mapped | nxt::BufferUsageBit::Index) + .SetInitialUsage(nxt::BufferUsageBit::Mapped) + .SetSize(sizeof(indexData)) + .GetResult(); + indexBuffer.SetSubData(0, sizeof(indexData) / sizeof(uint32_t), indexData); + indexBuffer.FreezeUsage(nxt::BufferUsageBit::Index); + + static const float vertexData[12] = { + 0.0f, 0.5f, 0.0f, 1.0f, + -0.5f, -0.5f, 0.0f, 1.0f, + 0.5f, -0.5f, 0.0f, 1.0f, + }; + vertexBuffer = device.CreateBufferBuilder() + .SetAllowedUsage(nxt::BufferUsageBit::Mapped | nxt::BufferUsageBit::Vertex) + .SetInitialUsage(nxt::BufferUsageBit::Mapped) + .SetSize(sizeof(vertexData)) + .GetResult(); + vertexBuffer.SetSubData(0, sizeof(vertexData) / sizeof(uint32_t), + reinterpret_cast(vertexData)); + vertexBuffer.FreezeUsage(nxt::BufferUsageBit::Vertex); +} + +void init() { + nxtProcTable procs; + GetProcTableAndDevice(&procs, &device); + nxtSetProcs(&procs); + + queue = device.CreateQueueBuilder().GetResult(); + + initBuffers(); + + nxt::ShaderModule vsModule = CreateShaderModule(device, nxt::ShaderStage::Vertex, R"( + #version 450 + layout(location = 0) in vec4 pos; + void main() { + gl_Position = pos; + })" + ); + + nxt::ShaderModule fsModule = CreateShaderModule(device, nxt::ShaderStage::Fragment, R"( + #version 450 + out vec4 fragColor; + void main() { + fragColor = vec4(1.0, 0.0, 0.0, 1.0); + })" + ); + + auto inputState = device.CreateInputStateBuilder() + .SetAttribute(0, 0, nxt::VertexFormat::FloatR32G32B32A32, 0) + .SetInput(0, 4 * sizeof(float), nxt::InputStepMode::Vertex) + .GetResult(); + + pipeline = device.CreatePipelineBuilder() + .SetStage(nxt::ShaderStage::Vertex, vsModule, "main") + .SetStage(nxt::ShaderStage::Fragment, fsModule, "main") + .SetInputState(inputState) + .GetResult(); +} + +void frame() { + static const uint32_t vertexBufferOffsets[1] = {0}; + nxt::CommandBuffer commands = device.CreateCommandBufferBuilder() + .SetPipeline(pipeline) + .SetVertexBuffers(0, 1, &vertexBuffer, vertexBufferOffsets) + .SetIndexBuffer(indexBuffer, 0, nxt::IndexFormat::Uint32) + .DrawElements(3, 1, 0, 0) + .GetResult(); + + queue.Submit(1, &commands); + SwapBuffers(); +} + +int main(int argc, const char* argv[]) { + if (!InitUtils(argc, argv)) { + return 1; + } + init(); + + while (!ShouldQuit()) { + frame(); + usleep(16000); + } + + // TODO release stuff +} diff --git a/examples/HelloInstancing.cpp b/examples/HelloInstancing.cpp new file mode 100644 index 0000000000..a180f397c7 --- /dev/null +++ b/examples/HelloInstancing.cpp @@ -0,0 +1,124 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "Utils.h" + +#include +#include + +nxt::Device device; + +nxt::Buffer vertexBuffer; +nxt::Buffer instanceBuffer; + +nxt::Queue queue; +nxt::Pipeline pipeline; + +void initBuffers() { + static const float vertexData[12] = { + 0.0f, 0.1f, 0.0f, 1.0f, + -0.1f, -0.1f, 0.0f, 1.0f, + 0.1f, -0.1f, 0.0f, 1.0f, + }; + vertexBuffer = device.CreateBufferBuilder() + .SetAllowedUsage(nxt::BufferUsageBit::Mapped | nxt::BufferUsageBit::Vertex) + .SetInitialUsage(nxt::BufferUsageBit::Mapped) + .SetSize(sizeof(vertexData)) + .GetResult(); + vertexBuffer.SetSubData(0, sizeof(vertexData) / sizeof(uint32_t), + reinterpret_cast(vertexData)); + vertexBuffer.FreezeUsage(nxt::BufferUsageBit::Vertex); + + static const float instanceData[8] = { + -0.5f, -0.5f, + -0.5f, 0.5f, + 0.5f, -0.5f, + 0.5f, 0.5f, + }; + instanceBuffer = device.CreateBufferBuilder() + .SetAllowedUsage(nxt::BufferUsageBit::Mapped | nxt::BufferUsageBit::Vertex) + .SetInitialUsage(nxt::BufferUsageBit::Mapped) + .SetSize(sizeof(instanceData)) + .GetResult(); + instanceBuffer.SetSubData(0, sizeof(instanceData) / sizeof(uint32_t), + reinterpret_cast(instanceData)); + instanceBuffer.FreezeUsage(nxt::BufferUsageBit::Vertex); +} + +void init() { + nxtProcTable procs; + GetProcTableAndDevice(&procs, &device); + nxtSetProcs(&procs); + + queue = device.CreateQueueBuilder().GetResult(); + + initBuffers(); + + nxt::ShaderModule vsModule = CreateShaderModule(device, nxt::ShaderStage::Vertex, R"( + #version 450 + layout(location = 0) in vec4 pos; + layout(location = 1) in vec2 instance; + void main() { + gl_Position = vec4(pos.xy + instance, pos.zw); + })" + ); + + nxt::ShaderModule fsModule = CreateShaderModule(device, nxt::ShaderStage::Fragment, R"( + #version 450 + out vec4 fragColor; + void main() { + fragColor = vec4(1.0, 0.0, 0.0, 1.0); + })" + ); + + auto inputState = device.CreateInputStateBuilder() + .SetAttribute(0, 0, nxt::VertexFormat::FloatR32G32B32A32, 0) + .SetInput(0, 4 * sizeof(float), nxt::InputStepMode::Vertex) + .SetAttribute(1, 1, nxt::VertexFormat::FloatR32G32, 0) + .SetInput(1, 2 * sizeof(float), nxt::InputStepMode::Instance) + .GetResult(); + + pipeline = device.CreatePipelineBuilder() + .SetStage(nxt::ShaderStage::Vertex, vsModule, "main") + .SetStage(nxt::ShaderStage::Fragment, fsModule, "main") + .SetInputState(inputState) + .GetResult(); +} + +void frame() { + static const uint32_t vertexBufferOffsets[1] = {0}; + nxt::CommandBuffer commands = device.CreateCommandBufferBuilder() + .SetPipeline(pipeline) + .SetVertexBuffers(0, 1, &vertexBuffer, vertexBufferOffsets) + .SetVertexBuffers(1, 1, &instanceBuffer, vertexBufferOffsets) + .DrawArrays(3, 4, 0, 0) + .GetResult(); + + queue.Submit(1, &commands); + SwapBuffers(); +} + +int main(int argc, const char* argv[]) { + if (!InitUtils(argc, argv)) { + return 1; + } + init(); + + while (!ShouldQuit()) { + frame(); + usleep(16000); + } + + // TODO release stuff +} diff --git a/examples/HelloTriangle.c b/examples/HelloTriangle.c new file mode 100644 index 0000000000..93f0579136 --- /dev/null +++ b/examples/HelloTriangle.c @@ -0,0 +1,90 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "Utils.h" + +#include + +nxtDevice device; +nxtQueue queue; +nxtPipeline pipeline; + +void init() { + nxtProcTable procs; + GetProcTableAndDevice(&procs, &device); + nxtSetProcs(&procs); + + { + nxtQueueBuilder builder = nxtDeviceCreateQueueBuilder(device); + queue = nxtQueueBuilderGetResult(builder); + nxtQueueBuilderRelease(builder); + } + + const char* vs = + "#version 450\n" + "const vec2 pos[3] = vec2[3](vec2(0.0f, 0.5f), vec2(-0.5f, -0.5f), vec2(0.5f, -0.5f));\n" + "void main() {\n" + " gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n" + "}\n"; + nxtShaderModule vsModule = CreateShaderModule(device, NXT_SHADER_STAGE_VERTEX, vs); + + const char* fs = + "#version 450\n" + "out vec4 fragColor;" + "void main() {\n" + " fragColor = vec4(1.0, 0.0, 0.0, 1.0);\n" + "}\n"; + nxtShaderModule fsModule = CreateShaderModule(device, NXT_SHADER_STAGE_FRAGMENT, fs); + + { + nxtPipelineBuilder builder = nxtDeviceCreatePipelineBuilder(device); + nxtPipelineBuilderSetStage(builder, NXT_SHADER_STAGE_VERTEX, vsModule, "main"); + nxtPipelineBuilderSetStage(builder, NXT_SHADER_STAGE_FRAGMENT, fsModule, "main"); + pipeline = nxtPipelineBuilderGetResult(builder); + nxtPipelineBuilderRelease(builder); + } + + nxtShaderModuleRelease(vsModule); + nxtShaderModuleRelease(fsModule); +} + +void frame() { + nxtCommandBuffer commands; + { + nxtCommandBufferBuilder builder = nxtDeviceCreateCommandBufferBuilder(device); + nxtCommandBufferBuilderSetPipeline(builder, pipeline); + nxtCommandBufferBuilderDrawArrays(builder, 3, 1, 0, 0); + commands = nxtCommandBufferBuilderGetResult(builder); + nxtCommandBufferBuilderRelease(builder); + } + + nxtQueueSubmit(queue, 1, &commands); + nxtCommandBufferRelease(commands); + + SwapBuffers(); +} + +int main(int argc, const char* argv[]) { + if (!InitUtils(argc, argv)) { + return 1; + } + init(); + + while (!ShouldQuit()) { + frame(); + usleep(16000); + } + + // TODO release stuff +} diff --git a/examples/HelloTriangle.cpp b/examples/HelloTriangle.cpp new file mode 100644 index 0000000000..780d86fd77 --- /dev/null +++ b/examples/HelloTriangle.cpp @@ -0,0 +1,185 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "Utils.h" + +#include +#include + +nxt::Device device; + +nxt::Buffer indexBuffer; +nxt::Buffer vertexBuffer; + +nxt::Texture texture; +nxt::Sampler sampler; + +nxt::Queue queue; +nxt::Pipeline pipeline; +nxt::BindGroup bindGroup; + +void initBuffers() { + static const uint32_t indexData[3] = { + 0, 1, 2, + }; + indexBuffer = device.CreateBufferBuilder() + .SetAllowedUsage(nxt::BufferUsageBit::Mapped | nxt::BufferUsageBit::Index) + .SetInitialUsage(nxt::BufferUsageBit::Mapped) + .SetSize(sizeof(indexData)) + .GetResult(); + indexBuffer.SetSubData(0, sizeof(indexData) / sizeof(uint32_t), indexData); + indexBuffer.FreezeUsage(nxt::BufferUsageBit::Index); + + static const float vertexData[12] = { + 0.0f, 0.5f, 0.0f, 1.0f, + -0.5f, -0.5f, 0.0f, 1.0f, + 0.5f, -0.5f, 0.0f, 1.0f, + }; + vertexBuffer = device.CreateBufferBuilder() + .SetAllowedUsage(nxt::BufferUsageBit::Mapped | nxt::BufferUsageBit::Vertex) + .SetInitialUsage(nxt::BufferUsageBit::Mapped) + .SetSize(sizeof(vertexData)) + .GetResult(); + vertexBuffer.SetSubData(0, sizeof(vertexData) / sizeof(uint32_t), + reinterpret_cast(vertexData)); + vertexBuffer.FreezeUsage(nxt::BufferUsageBit::Vertex); +} + +void initTextures() { + texture = device.CreateTextureBuilder() + .SetDimension(nxt::TextureDimension::e2D) + .SetExtent(1024, 1024, 1) + .SetFormat(nxt::TextureFormat::R8G8B8A8Unorm) + .SetMipLevels(1) + .SetAllowedUsage(nxt::TextureUsageBit::TransferDst | nxt::TextureUsageBit::Sampled) + .GetResult(); + + sampler = device.CreateSamplerBuilder() + .SetFilterMode(nxt::FilterMode::Linear, nxt::FilterMode::Linear, nxt::FilterMode::Linear) + .GetResult(); + + // Initialize the texture with arbitrary data until we can load images + std::vector data(4 * 1024 * 1024, 0); + for (size_t i = 0; i < data.size(); ++i) { + data[i] = i % 253; + } + + nxt::Buffer stagingBuffer = device.CreateBufferBuilder() + .SetAllowedUsage(nxt::BufferUsageBit::Mapped | nxt::BufferUsageBit::TransferSrc) + .SetInitialUsage(nxt::BufferUsageBit::Mapped) + .SetSize(data.size()) + .GetResult(); + stagingBuffer.SetSubData(0, data.size() / sizeof(uint32_t), reinterpret_cast(data.data())); + stagingBuffer.FreezeUsage(nxt::BufferUsageBit::TransferSrc); + + nxt::CommandBuffer copy = device.CreateCommandBufferBuilder() + .TransitionTextureUsage(texture, nxt::TextureUsageBit::TransferDst) + .CopyBufferToTexture(stagingBuffer, texture, 0, 0, 0, 1024, 1024, 1, 0) + .GetResult(); + + queue.Submit(1, ©); + texture.FreezeUsage(nxt::TextureUsageBit::Sampled); +} + +void init() { + nxtProcTable procs; + GetProcTableAndDevice(&procs, &device); + nxtSetProcs(&procs); + + queue = device.CreateQueueBuilder().GetResult(); + + initBuffers(); + initTextures(); + + nxt::ShaderModule vsModule = CreateShaderModule(device, nxt::ShaderStage::Vertex, R"( + #version 450 + layout(location = 0) in vec4 pos; + void main() { + gl_Position = pos; + })" + ); + + nxt::ShaderModule fsModule = CreateShaderModule(device, nxt::ShaderStage::Fragment, R"( + #version 450 + layout(set = 0, binding = 0) uniform sampler mySampler; + layout(set = 0, binding = 1) uniform texture2D myTexture; + + out vec4 fragColor; + void main() { + fragColor = texture(sampler2D(myTexture, mySampler), gl_FragCoord.xy / vec2(640.0, 480.0)); + })" + ); + + auto inputState = device.CreateInputStateBuilder() + .SetAttribute(0, 0, nxt::VertexFormat::FloatR32G32B32A32, 0) + .SetInput(0, 4 * sizeof(float), nxt::InputStepMode::Vertex) + .GetResult(); + + nxt::BindGroupLayout bgl = device.CreateBindGroupLayoutBuilder() + .SetBindingsType(nxt::ShaderStageBit::Fragment, nxt::BindingType::Sampler, 0, 1) + .SetBindingsType(nxt::ShaderStageBit::Fragment, nxt::BindingType::SampledTexture, 1, 1) + .GetResult(); + + nxt::PipelineLayout pl = device.CreatePipelineLayoutBuilder() + .SetBindGroupLayout(0, bgl) + .GetResult(); + + pipeline = device.CreatePipelineBuilder() + .SetLayout(pl) + .SetStage(nxt::ShaderStage::Vertex, vsModule, "main") + .SetStage(nxt::ShaderStage::Fragment, fsModule, "main") + .SetInputState(inputState) + .GetResult(); + + nxt::TextureView view = texture.CreateTextureViewBuilder().GetResult(); + + bindGroup = device.CreateBindGroupBuilder() + .SetLayout(bgl) + .SetUsage(nxt::BindGroupUsage::Frozen) + .SetSamplers(0, 1, &sampler) + .SetTextureViews(1, 1, &view) + .GetResult(); +} + +struct {uint32_t a; float b;} s; +void frame() { + s.a = (s.a + 1) % 256; + s.b += 0.02; + if (s.b >= 1.0f) {s.b = 0.0f;} + static const uint32_t vertexBufferOffsets[1] = {0}; + nxt::CommandBuffer commands = device.CreateCommandBufferBuilder() + .SetPipeline(pipeline) + .SetBindGroup(0, bindGroup) + .SetVertexBuffers(0, 1, &vertexBuffer, vertexBufferOffsets) + .SetIndexBuffer(indexBuffer, 0, nxt::IndexFormat::Uint32) + .DrawElements(3, 1, 0, 0) + .GetResult(); + + queue.Submit(1, &commands); + SwapBuffers(); +} + +int main(int argc, const char* argv[]) { + if (!InitUtils(argc, argv)) { + return 1; + } + init(); + + while (!ShouldQuit()) { + frame(); + usleep(16000); + } + + // TODO release stuff +} diff --git a/examples/HelloUBO.cpp b/examples/HelloUBO.cpp new file mode 100644 index 0000000000..3ddc88dfff --- /dev/null +++ b/examples/HelloUBO.cpp @@ -0,0 +1,116 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "Utils.h" + +#include + +nxt::Device device; +nxt::Queue queue; +nxt::Pipeline pipeline; +nxt::Buffer buffer; +nxt::BindGroup bindGroup; + +struct {uint32_t a; float b;} s; + +void init() { + nxtProcTable procs; + GetProcTableAndDevice(&procs, &device); + nxtSetProcs(&procs); + + queue = device.CreateQueueBuilder().GetResult(); + + nxt::ShaderModule vsModule = CreateShaderModule(device, nxt::ShaderStage::Vertex, R"( + #version 450 + const vec2 pos[3] = vec2[3](vec2(0.0f, 0.5f), vec2(-0.5f, -0.5f), vec2(0.5f, -0.5f)); + void main() { + gl_Position = vec4(pos[gl_VertexIndex], 0.5, 1.0); + })" + ); + + nxt::ShaderModule fsModule = CreateShaderModule(device, nxt::ShaderStage::Fragment, R"( + #version 450 + layout(set = 0, binding = 0) uniform myBlock { + int a; + float b; + } myUbo; + out vec4 fragColor; + void main() { + fragColor = vec4(1.0, myUbo.a / 255.0, myUbo.b, 1.0); + })" + ); + + nxt::BindGroupLayout bgl = device.CreateBindGroupLayoutBuilder() + .SetBindingsType(nxt::ShaderStageBit::Fragment, nxt::BindingType::UniformBuffer, 0, 1) + .GetResult(); + + nxt::PipelineLayout pl = device.CreatePipelineLayoutBuilder() + .SetBindGroupLayout(0, bgl) + .GetResult(); + + pipeline = device.CreatePipelineBuilder() + .SetLayout(pl) + .SetStage(nxt::ShaderStage::Vertex, vsModule, "main") + .SetStage(nxt::ShaderStage::Fragment, fsModule, "main") + .GetResult(); + + buffer = device.CreateBufferBuilder() + .SetAllowedUsage(nxt::BufferUsageBit::Mapped | nxt::BufferUsageBit::Uniform) + .SetInitialUsage(nxt::BufferUsageBit::Mapped) + .SetSize(sizeof(s)) + .GetResult(); + + nxt::BufferView view = buffer.CreateBufferViewBuilder() + .SetExtent(0, sizeof(s)) + .GetResult(); + + bindGroup = device.CreateBindGroupBuilder() + .SetLayout(bgl) + .SetUsage(nxt::BindGroupUsage::Frozen) + .SetBufferViews(0, 1, &view) + .GetResult(); +} + +void frame() { + s.a = (s.a + 1) % 256; + s.b += 0.02; + if (s.b >= 1.0f) {s.b = 0.0f;} + + buffer.TransitionUsage(nxt::BufferUsageBit::Mapped); + buffer.SetSubData(0, sizeof(s) / sizeof(uint32_t), reinterpret_cast(&s)); + + nxt::CommandBuffer commands = device.CreateCommandBufferBuilder() + .SetPipeline(pipeline) + .TransitionBufferUsage(buffer, nxt::BufferUsageBit::Uniform) + .SetBindGroup(0, bindGroup) + .DrawArrays(3, 1, 0, 0) + .GetResult(); + + queue.Submit(1, &commands); + SwapBuffers(); +} + +int main(int argc, const char* argv[]) { + if (!InitUtils(argc, argv)) { + return 1; + } + init(); + + while (!ShouldQuit()) { + frame(); + usleep(16000); + } + + // TODO release stuff +} diff --git a/examples/HelloVertices.cpp b/examples/HelloVertices.cpp new file mode 100644 index 0000000000..117ef39ed2 --- /dev/null +++ b/examples/HelloVertices.cpp @@ -0,0 +1,104 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "Utils.h" + +#include +#include + +nxt::Device device; + +nxt::Buffer vertexBuffer; + +nxt::Queue queue; +nxt::Pipeline pipeline; + +void initBuffers() { + static const float vertexData[12] = { + 0.0f, 0.5f, 0.0f, 1.0f, + -0.5f, -0.5f, 0.0f, 1.0f, + 0.5f, -0.5f, 0.0f, 1.0f, + }; + vertexBuffer = device.CreateBufferBuilder() + .SetAllowedUsage(nxt::BufferUsageBit::Mapped | nxt::BufferUsageBit::Vertex) + .SetInitialUsage(nxt::BufferUsageBit::Mapped) + .SetSize(sizeof(vertexData)) + .GetResult(); + vertexBuffer.SetSubData(0, sizeof(vertexData) / sizeof(uint32_t), + reinterpret_cast(vertexData)); + vertexBuffer.FreezeUsage(nxt::BufferUsageBit::Vertex); +} + +void init() { + nxtProcTable procs; + GetProcTableAndDevice(&procs, &device); + nxtSetProcs(&procs); + + queue = device.CreateQueueBuilder().GetResult(); + + initBuffers(); + + nxt::ShaderModule vsModule = CreateShaderModule(device, nxt::ShaderStage::Vertex, R"( + #version 450 + layout(location = 0) in vec4 pos; + void main() { + gl_Position = pos; + })" + ); + + nxt::ShaderModule fsModule = CreateShaderModule(device, nxt::ShaderStage::Fragment, R"( + #version 450 + out vec4 fragColor; + void main() { + fragColor = vec4(1.0, 0.0, 0.0, 1.0); + })" + ); + + auto inputState = device.CreateInputStateBuilder() + .SetAttribute(0, 0, nxt::VertexFormat::FloatR32G32B32A32, 0) + .SetInput(0, 4 * sizeof(float), nxt::InputStepMode::Vertex) + .GetResult(); + + pipeline = device.CreatePipelineBuilder() + .SetStage(nxt::ShaderStage::Vertex, vsModule, "main") + .SetStage(nxt::ShaderStage::Fragment, fsModule, "main") + .SetInputState(inputState) + .GetResult(); +} + +void frame() { + static const uint32_t vertexBufferOffsets[1] = {0}; + nxt::CommandBuffer commands = device.CreateCommandBufferBuilder() + .SetPipeline(pipeline) + .SetVertexBuffers(0, 1, &vertexBuffer, vertexBufferOffsets) + .DrawArrays(3, 1, 0, 0) + .GetResult(); + + queue.Submit(1, &commands); + SwapBuffers(); +} + +int main(int argc, const char* argv[]) { + if (!InitUtils(argc, argv)) { + return 1; + } + init(); + + while (!ShouldQuit()) { + frame(); + usleep(16000); + } + + // TODO release stuff +} diff --git a/examples/MetalBinding.mm b/examples/MetalBinding.mm new file mode 100644 index 0000000000..1eda8090de --- /dev/null +++ b/examples/MetalBinding.mm @@ -0,0 +1,78 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "BackendBinding.h" + +#define GLFW_EXPOSE_NATIVE_COCOA +#include "GLFW/glfw3.h" +#include "GLFW/glfw3native.h" + +#import +#import + +namespace backend { +namespace metal { + void Init(id metalDevice, nxtProcTable* procs, nxtDevice* device); + void SetNextDrawable(nxtDevice device, id drawable); + void Present(nxtDevice device); +} +} + +class MetalBinding : public BackendBinding { + public: + void SetupGLFWWindowHints() override { + glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); + } + void GetProcAndDevice(nxtProcTable* procs, nxtDevice* device) override { + metalDevice = MTLCreateSystemDefaultDevice(); + + id nsWindow = glfwGetCocoaWindow(window); + NSView* contentView = [nsWindow contentView]; + [contentView setWantsLayer: YES]; + + layer = [CAMetalLayer layer]; + [layer setDevice: metalDevice]; + [layer setPixelFormat: MTLPixelFormatBGRA8Unorm]; + [layer setFramebufferOnly: YES]; + [layer setDrawableSize: [contentView bounds].size]; + + [contentView setLayer: layer]; + + backend::metal::Init(metalDevice, procs, device); + backendDevice = *device; + + backend::metal::SetNextDrawable(backendDevice, GetNextDrawable()); + } + void SwapBuffers() override { + backend::metal::Present(backendDevice); + backend::metal::SetNextDrawable(backendDevice, GetNextDrawable()); + } + + private: + id GetNextDrawable() { + lastDrawable = [layer nextDrawable]; + return lastDrawable; + } + + id metalDevice = nil; + CAMetalLayer* layer = nullptr; + + id lastDrawable = nil; + + nxtDevice backendDevice = nullptr; +}; + +BackendBinding* CreateMetalBinding() { + return new MetalBinding; +} diff --git a/examples/SpirvTest.cpp b/examples/SpirvTest.cpp new file mode 100644 index 0000000000..0e75d8b8c3 --- /dev/null +++ b/examples/SpirvTest.cpp @@ -0,0 +1,89 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include + +#include +#include +#include + +bool CompileToSpv(std::string source, nxt::ShaderStage stage, std::vector* spv) { + shaderc::Compiler compiler; + shaderc::CompileOptions options; + + shaderc_shader_kind kind; + switch (stage) { + case nxt::ShaderStage::Vertex: + kind = shaderc_glsl_vertex_shader; + break; + case nxt::ShaderStage::Fragment: + kind = shaderc_glsl_fragment_shader; + break; + default: + return false; + } + + { + auto result = compiler.CompileGlslToSpvAssembly(source.c_str(), source.size(), kind, "toto", options); + if (result.GetCompilationStatus() != shaderc_compilation_status_success) { + std::cerr << result.GetErrorMessage(); + return false; + } + + std::cout << "*** Begin spirv assembly" << std::endl; + std::cout << std::string(result.cbegin(), result.cend()) << std::endl; + std::cout << "*** End spirv assembly" << std::endl; + } + + auto result = compiler.CompileGlslToSpv(source.c_str(), source.size(), kind, "toto", options); + if (result.GetCompilationStatus() != shaderc_compilation_status_success) { + std::cerr << result.GetErrorMessage(); + return false; + } + + spv->assign(result.cbegin(), result.cend()); + + return true; +} + +void TestSpv(std::string source, nxt::ShaderStage stage) { + std::vector spv; + if (!CompileToSpv(source, stage, &spv)) { + return; + } + + spirv_cross::CompilerGLSL glsl(std::move(spv)); + + spirv_cross::CompilerGLSL::Options options; + options.version = 450; + options.es = false; + glsl.set_options(options); + + std::cout << "*** Begin glsl cross" << std::endl; + std::cout << glsl.compile() << std::endl; + std::cout << "*** End glsl cross" << std::endl; +} + +int main(int argc, char const* const* argv) { + const char* vs = + "#version 450\n" + "layout(push_constant) uniform toto {int foo;} tata;\n" + "const vec2 pos[3] = vec2[3](vec2(0.0f, 0.5f), vec2(-0.5f, -0.5f), vec2(0.5f, -0.5f));\n" + "void main() {\n" + " gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n" + "}\n"; + TestSpv(vs, nxt::ShaderStage::Vertex); + + return 0; +} diff --git a/examples/Utils.cpp b/examples/Utils.cpp new file mode 100644 index 0000000000..b557f768de --- /dev/null +++ b/examples/Utils.cpp @@ -0,0 +1,267 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include +#include +#include +#include "GLFW/glfw3.h" + +#include "BackendBinding.h" +#include "../src/wire/TerribleCommandBuffer.h" + +#include +#include +#include +#include + +BackendBinding* CreateMetalBinding(); + +namespace backend { + void RegisterSynchronousErrorCallback(nxtDevice device, void(*)(const char*, void*), void* userData); + + namespace opengl { + void Init(void* (*getProc)(const char*), nxtProcTable* procs, nxtDevice* device); + void HACKCLEAR(); + } +} + +class OpenGLBinding : public BackendBinding { + public: + void SetupGLFWWindowHints() override { + #ifdef __APPLE__ + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); + glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + #else + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5); + glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + #endif + } + void GetProcAndDevice(nxtProcTable* procs, nxtDevice* device) override { + glfwMakeContextCurrent(window); + backend::opengl::Init(reinterpret_cast(glfwGetProcAddress), procs, device); + } + void SwapBuffers() override { + glfwSwapBuffers(window); + backend::opengl::HACKCLEAR(); + } +}; + +enum class BackendType { + OpenGL, + Metal, +}; + +enum class CmdBufType { + None, + Terrible, +}; + +static BackendType backendType = BackendType::OpenGL; +static CmdBufType cmdBufType = CmdBufType::Terrible; +static BackendBinding* binding = nullptr; + +static GLFWwindow* window = nullptr; + +static nxt::wire::CommandHandler* wireServer = nullptr; +static nxt::wire::TerribleCommandBuffer* cmdBuf = nullptr; + +void HandleSynchronousError(const char* errorMessage, void* userData) { + std::cerr << errorMessage << std::endl; + + if (userData != nullptr) { + auto wireServer = reinterpret_cast(userData); + wireServer->OnSynchronousError(); + } +} + +void GetProcTableAndDevice(nxtProcTable* procs, nxt::Device* device) { + switch (backendType) { + case BackendType::OpenGL: + binding = new OpenGLBinding; + break; + case BackendType::Metal: + #if defined(__APPLE__) + binding = CreateMetalBinding(); + #else + fprintf(stderr, "Metal backend no present on this platform\n"); + #endif + break; + } + + if (!glfwInit()) { + return; + } + + binding->SetupGLFWWindowHints(); + window = glfwCreateWindow(640, 480, "NXT window", nullptr, nullptr); + if (!window) { + return; + } + + binding->SetWindow(window); + + nxtDevice backendDevice; + nxtProcTable backendProcs; + binding->GetProcAndDevice(&backendProcs, &backendDevice); + + switch (cmdBufType) { + case CmdBufType::None: + *procs = backendProcs; + *device = nxt::Device::Acquire(backendDevice); + break; + + case CmdBufType::Terrible: + { + wireServer = nxt::wire::CreateCommandHandler(backendDevice, backendProcs); + cmdBuf = new nxt::wire::TerribleCommandBuffer(wireServer); + + nxtDevice clientDevice; + nxtProcTable clientProcs; + nxt::wire::NewClientDevice(&clientProcs, &clientDevice, cmdBuf); + + *procs = clientProcs; + *device = nxt::Device::Acquire(clientDevice); + } + break; + } + + backend::RegisterSynchronousErrorCallback(backendDevice, HandleSynchronousError, wireServer); +} + +nxt::ShaderModule CreateShaderModule(const nxt::Device& device, nxt::ShaderStage stage, const char* source) { + shaderc::Compiler compiler; + shaderc::CompileOptions options; + + shaderc_shader_kind kind; + switch (stage) { + case nxt::ShaderStage::Vertex: + kind = shaderc_glsl_vertex_shader; + break; + case nxt::ShaderStage::Fragment: + kind = shaderc_glsl_fragment_shader; + break; + case nxt::ShaderStage::Compute: + kind = shaderc_glsl_compute_shader; + break; + } + + auto result = compiler.CompileGlslToSpv(source, strlen(source), kind, "myshader?", options); + if (result.GetCompilationStatus() != shaderc_compilation_status_success) { + std::cerr << result.GetErrorMessage(); + return {}; + } + + size_t size = (result.cend() - result.cbegin()); + +#ifdef DUMP_SPIRV_ASSEMBLY + { + auto resultAsm = compiler.CompileGlslToSpvAssembly(source, strlen(source), kind, "myshader?", options); + size_t sizeAsm = (resultAsm.cend() - resultAsm.cbegin()); + + char* buffer = reinterpret_cast(malloc(sizeAsm + 1)); + memcpy(buffer, resultAsm.cbegin(), sizeAsm); + buffer[sizeAsm] = '\0'; + printf("SPIRV ASSEMBLY DUMP START\n%s\nSPIRV ASSEMBLY DUMP END\n", buffer); + free(buffer); + } +#endif + +#ifdef DUMP_SPIRV_JS_ARRAY + printf("SPIRV JS ARRAY DUMP START\n"); + for (size_t i = 0; i < size; i++) { + printf("%#010x", result.cbegin()[i]); + if ((i + 1) % 4 == 0) { + printf(",\n"); + } else { + printf(", "); + } + } + printf("\n"); + printf("SPIRV JS ARRAY DUMP END\n"); +#endif + + return device.CreateShaderModuleBuilder() + .SetSource(size, result.cbegin()) + .GetResult(); +} + +extern "C" { + bool InitUtils(int argc, const char** argv) { + for (int i = 0; i < argc; i++) { + if (std::string("-b") == argv[i] || std::string("--backend") == argv[i]) { + i++; + if (i < argc && std::string("opengl") == argv[i]) { + backendType = BackendType::OpenGL; + continue; + } + if (i < argc && std::string("metal") == argv[i]) { + backendType = BackendType::Metal; + continue; + } + fprintf(stderr, "--backend expects a backend name (opengl, metal)\n"); + return false; + } + if (std::string("-c") == argv[i] || std::string("--comand-buffer") == argv[i]) { + i++; + if (i < argc && std::string("none") == argv[i]) { + cmdBufType = CmdBufType::None; + continue; + } + if (i < argc && std::string("terrible") == argv[i]) { + cmdBufType = CmdBufType::Terrible; + continue; + } + fprintf(stderr, "--command-buffer expects a command buffer name (none, terrible)\n"); + return false; + } + if (std::string("-h") == argv[i] || std::string("--help") == argv[i]) { + printf("Usage: %s [-b BACKEND] [-c COMMAND_BUFFER]\n", argv[0]); + printf(" BACKEND is one of: opengl, metal\n"); + printf(" COMMAND_BUFFER is one of: none, terrible\n"); + return false; + } + } + return true; + } + + void GetProcTableAndDevice(nxtProcTable* procs, nxtDevice* device) { + nxt::Device cppDevice; + GetProcTableAndDevice(procs, &cppDevice); + *device = cppDevice.Release(); + } + + nxtShaderModule CreateShaderModule(nxtDevice device, nxtShaderStage stage, const char* source) { + return CreateShaderModule(device, static_cast(stage), source).Release(); + } + + void SwapBuffers() { + if (cmdBuf) { + cmdBuf->Flush(); + } + glfwPollEvents(); + binding->SwapBuffers(); + } + + bool ShouldQuit() { + return glfwWindowShouldClose(window); + } + + GLFWwindow* GetWindow() { + return window; + } +} diff --git a/examples/Utils.h b/examples/Utils.h new file mode 100644 index 0000000000..3c1f84c706 --- /dev/null +++ b/examples/Utils.h @@ -0,0 +1,38 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include + +#if defined(__cplusplus) +extern "C" { +#endif + bool InitUtils(int argc, const char** argv); + void SwapBuffers(); + bool ShouldQuit(); + + struct GLFWwindow; + struct GLFWwindow* GetWindow(); +#if defined(__cplusplus) +} +#endif + +// Yuck +#if defined(__cplusplus) + #include + void GetProcTableAndDevice(nxtProcTable* procs, nxt::Device* device); + nxt::ShaderModule CreateShaderModule(const nxt::Device& device, nxt::ShaderStage stage, const char* source); +#else + void GetProcTableAndDevice(nxtProcTable* procs, nxtDevice* device); + nxtShaderModule CreateShaderModule(nxtDevice device, nxtShaderStage stage, const char* source); +#endif diff --git a/examples/glTFViewer/CMakeLists.txt b/examples/glTFViewer/CMakeLists.txt new file mode 100644 index 0000000000..f6e7ee0ec8 --- /dev/null +++ b/examples/glTFViewer/CMakeLists.txt @@ -0,0 +1,18 @@ +# Copyright 2017 The NXT Authors +# +# 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. + +add_executable(glTFViewer glTFViewer.cpp) +target_link_libraries(glTFViewer utils) +target_include_directories(glTFViewer PUBLIC ../ ${GLM_INCLUDE_DIR}) +SetCXX14(glTFViewer) diff --git a/examples/glTFViewer/Camera.inl b/examples/glTFViewer/Camera.inl new file mode 100644 index 0000000000..ace6e60eb7 --- /dev/null +++ b/examples/glTFViewer/Camera.inl @@ -0,0 +1,67 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +class Camera { + public: + Camera() + : _azimuth(glm::radians(45.f)), + _altitude(glm::radians(30.f)), + _radius(10.f), + _center(0, 0, 0), + _dirty(true) { + recalculate(); + } + + void rotate(float dAzimuth, float dAltitude) { + _dirty = true; + _azimuth = glm::mod(_azimuth + dAzimuth, glm::radians(360.f)); + _altitude = glm::clamp(_altitude + dAltitude, glm::radians(-89.f), glm::radians(89.f)); + } + + void pan(float dX, float dY) { + recalculate(); + glm::vec3 vX = glm::normalize(glm::cross(-_eyeDir, glm::vec3(0, 1, 0))); + glm::vec3 vY = glm::normalize(glm::cross(_eyeDir, vX)); + _center += vX * dX * _radius + vY * dY * _radius; + } + + void zoom(float factor) { + _dirty = true; + _radius = _radius * glm::exp(-factor); + } + + glm::mat4 view() { + if (_dirty) { + recalculate(); + } + return _view; + } + private: + void recalculate() { + glm::vec4 eye4 = glm::vec4(1, 0, 0, 1); + eye4 = glm::rotate(glm::mat4(), _altitude, glm::vec3(0, 0, 1)) * eye4; + eye4 = glm::rotate(glm::mat4(), _azimuth, glm::vec3(0, 1, 0)) * eye4; + _eyeDir = glm::vec3(eye4); + + _view = glm::lookAt(_center + _eyeDir * _radius, _center, glm::vec3(0, 1, 0)); + _dirty = false; + } + float _azimuth; + float _altitude; + float _radius; + glm::vec3 _center; + glm::vec3 _eyeDir; + bool _dirty; + glm::mat4 _view; +}; diff --git a/examples/glTFViewer/README.md b/examples/glTFViewer/README.md new file mode 100644 index 0000000000..0dafad35fe --- /dev/null +++ b/examples/glTFViewer/README.md @@ -0,0 +1,30 @@ +# NXT glTF Viewer + +This is a barebones glTF model viewer using the NXT API. It is intended as a +proof of concept for the API and is not a robust model viewer. It can load +basic mesh/texture data from a few +[glTF sample models](https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/1.0), +such as: + +* 2CylinderEngine +* BoxWithoutIndices +* Cesium Man +* Duck +* Monster +* VC (Virtual City) + +## Usage + +`build/examples/glTFViewer/glTFViewer path/to/Duck.gltf` + +`build/examples/glTFViewer/glTFViewer path/to/Duck.gltf --backend metal` + +## Screenshots + +Duck: + +![Duck](img/nxt-gltf-duck.jpg) + +VC (Virtual City): + +![Virtual City](img/nxt-gltf-vc.jpg) diff --git a/examples/glTFViewer/glTFViewer.cpp b/examples/glTFViewer/glTFViewer.cpp new file mode 100644 index 0000000000..2f88e9b803 --- /dev/null +++ b/examples/glTFViewer/glTFViewer.cpp @@ -0,0 +1,654 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "Utils.h" + +#include +#include +#define GLM_FORCE_DEPTH_ZERO_TO_ONE +#include +#include +#include +#include + +#include "GLFW/glfw3.h" +#define TINYGLTF_LOADER_IMPLEMENTATION +#define STB_IMAGE_IMPLEMENTATION +#include + +#include "Camera.inl" + +namespace gl { + enum { + Triangles = 0x0004, + UnsignedShort = 0x1403, + UnsignedInt = 0x1405, + Float = 0x1406, + RGBA = 0x1908, + Nearest = 0x2600, + Linear = 0x2601, + NearestMipmapNearest = 0x2700, + LinearMipmapNearest = 0x2701, + NearestMipmapLinear = 0x2702, + LinearMipmapLinear = 0x2703, + ArrayBuffer = 0x8892, + ElementArrayBuffer = 0x8893, + FragmentShader = 0x8B30, + VertexShader = 0x8B31, + FloatVec2 = 0x8B50, + FloatVec3 = 0x8B51, + FloatVec4 = 0x8B52, + }; +} + +struct MaterialInfo { + nxt::Buffer uniformBuffer; + nxt::Pipeline pipeline; + nxt::BindGroup bindGroup0; + std::map slotSemantics; +}; + +struct u_transform_block { + glm::mat4 modelViewProj; + glm::mat4 modelInvTr; +}; + +nxt::Device device; +nxt::Queue queue; + +nxt::Buffer defaultBuffer; +std::map buffers; +std::map commandBuffers; +std::map slotSemantics = {{0, "POSITION"}, {1, "NORMAL"}, {2, "TEXCOORD_0"}}; + +nxt::Sampler defaultSampler; +std::map samplers; +nxt::TextureView defaultTexture; +std::map textures; + +tinygltf::Scene scene; +glm::mat4 projection = glm::perspective(glm::radians(60.f), 640.f/480, 0.1f, 2000.f); +Camera camera; + +// Helpers +namespace { + std::string getFilePathExtension(const std::string &FileName) { + if (FileName.find_last_of(".") != std::string::npos) { + return FileName.substr(FileName.find_last_of(".") + 1); + } + return ""; + } + + bool techniqueParameterTypeToVertexFormat(int type, nxt::VertexFormat *format) { + switch (type) { + case gl::FloatVec2: + *format = nxt::VertexFormat::FloatR32G32; + return true; + case gl::FloatVec3: + *format = nxt::VertexFormat::FloatR32G32B32; + return true; + case gl::FloatVec4: + *format = nxt::VertexFormat::FloatR32G32B32A32; + return true; + default: + return false; + } + } +} + +// Initialization +namespace { + void initBuffers() { + defaultBuffer = device.CreateBufferBuilder() + .SetAllowedUsage(nxt::BufferUsageBit::Vertex | nxt::BufferUsageBit::Index) + .SetSize(256) + .GetResult(); + defaultBuffer.FreezeUsage(nxt::BufferUsageBit::Vertex | nxt::BufferUsageBit::Index); + + for (const auto& bv : scene.bufferViews) { + const auto& iBufferViewID = bv.first; + const auto& iBufferView = bv.second; + + nxt::BufferUsageBit usage = nxt::BufferUsageBit::None; + switch (iBufferView.target) { + case gl::ArrayBuffer: + usage |= nxt::BufferUsageBit::Vertex; + break; + case gl::ElementArrayBuffer: + usage |= nxt::BufferUsageBit::Index; + break; + case 0: + fprintf(stderr, "TODO: buffer view has no target; skipping\n"); + continue; + default: + fprintf(stderr, "unsupported buffer view target %d\n", iBufferView.target); + continue; + } + const auto& iBuffer = scene.buffers.at(iBufferView.buffer); + + uint32_t iBufferViewSize = + iBufferView.byteLength ? iBufferView.byteLength : + (iBuffer.data.size() - iBufferView.byteOffset); + auto oBuffer = device.CreateBufferBuilder() + .SetAllowedUsage(nxt::BufferUsageBit::Mapped | usage) + .SetInitialUsage(nxt::BufferUsageBit::Mapped) + .SetSize(iBufferViewSize) + .GetResult(); + oBuffer.SetSubData(0, iBufferViewSize / sizeof(uint32_t), + reinterpret_cast(&iBuffer.data.at(iBufferView.byteOffset))); + oBuffer.FreezeUsage(usage); + buffers[iBufferViewID] = std::move(oBuffer); + } + } + + const MaterialInfo& getMaterial(const std::string& iMaterialID, uint32_t stridePos, uint32_t strideNor, uint32_t strideTxc) { + static std::map, MaterialInfo> materials; + auto key = make_tuple(iMaterialID, stridePos, strideNor, strideTxc); + auto it = materials.find(key); + if (it != materials.end()) { + return it->second; + } + + const auto& iMaterial = scene.materials.at(iMaterialID); + const auto& iTechnique = scene.techniques.at(iMaterial.technique); + const auto& iProgram = scene.programs.at(iTechnique.program); + + auto oVSModule = CreateShaderModule(device, nxt::ShaderStage::Vertex, R"( + #version 450 + + layout(set = 0, binding = 0) uniform u_transform_block { + mat4 modelViewProj; + mat4 modelInvTr; + } u_transform; + + layout(location = 0) in vec4 a_position; + layout(location = 1) in vec3 a_normal; + layout(location = 2) in vec2 a_texcoord; + + layout(location = 0) out vec3 v_normal; + layout(location = 1) out vec2 v_texcoord; + + void main() { + v_normal = (u_transform.modelInvTr * vec4(normalize(a_normal), 0)).rgb; + v_texcoord = a_texcoord; + gl_Position = u_transform.modelViewProj * a_position; + })"); + + auto oFSModule = CreateShaderModule(device, nxt::ShaderStage::Fragment, R"( + #version 450 + + layout(set = 0, binding = 1) uniform sampler u_samp; + layout(set = 0, binding = 2) uniform texture2D u_tex; + + layout(location = 0) in vec3 v_normal; + layout(location = 1) in vec2 v_texcoord; + + out vec4 fragcolor; + + void main() { + const vec3 lightdir = normalize(vec3(-1, -2, 3)); + vec3 normal = normalize(v_normal); + float diffuse = abs(dot(lightdir, normal)); + float diffamb = diffuse * 0.85 + 0.15; + vec3 albedo = texture(sampler2D(u_tex, u_samp), v_texcoord).rgb; + fragcolor = vec4(diffamb * albedo, 1); + })"); + + nxt::InputStateBuilder builder = device.CreateInputStateBuilder(); + std::bitset<3> slotsSet; + for (const auto& a : iTechnique.attributes) { + const auto iAttributeName = a.first; + const auto iParameter = iTechnique.parameters.at(a.second); + nxt::VertexFormat format; + if (!techniqueParameterTypeToVertexFormat(iParameter.type, &format)) { + fprintf(stderr, "unsupported technique parameter type %d\n", iParameter.type); + continue; + } + if (iParameter.semantic == "POSITION") { + builder.SetAttribute(0, 0, format, 0); + builder.SetInput(0, stridePos, nxt::InputStepMode::Vertex); + slotsSet.set(0); + } else if (iParameter.semantic == "NORMAL") { + builder.SetAttribute(1, 1, format, 0); + builder.SetInput(1, strideNor, nxt::InputStepMode::Vertex); + slotsSet.set(1); + } else if (iParameter.semantic == "TEXCOORD_0") { + builder.SetAttribute(2, 2, format, 0); + builder.SetInput(2, strideTxc, nxt::InputStepMode::Vertex); + slotsSet.set(2); + } else { + fprintf(stderr, "unsupported technique attribute semantic %s\n", iParameter.semantic.c_str()); + } + // TODO: use iAttributeParameter.node? + } + for (size_t i = 0; i < slotsSet.size(); i++) { + if (slotsSet[i]) { + continue; + } + builder.SetAttribute(i, i, nxt::VertexFormat::FloatR32G32B32A32, 0); + builder.SetInput(i, 0, nxt::InputStepMode::Vertex); + } + auto inputState = builder.GetResult(); + + auto bindGroupLayout = device.CreateBindGroupLayoutBuilder() + .SetBindingsType(nxt::ShaderStageBit::Vertex, nxt::BindingType::UniformBuffer, 0, 1) + .SetBindingsType(nxt::ShaderStageBit::Fragment, nxt::BindingType::Sampler, 1, 1) + .SetBindingsType(nxt::ShaderStageBit::Fragment, nxt::BindingType::SampledTexture, 2, 1) + .GetResult(); + + auto pipelineLayout = device.CreatePipelineLayoutBuilder() + .SetBindGroupLayout(0, bindGroupLayout) + .GetResult(); + auto pipeline = device.CreatePipelineBuilder() + .SetLayout(pipelineLayout) + .SetStage(nxt::ShaderStage::Vertex, oVSModule, "main") + .SetStage(nxt::ShaderStage::Fragment, oFSModule, "main") + .SetInputState(inputState) + .GetResult(); + + auto uniformBuffer = device.CreateBufferBuilder() + .SetAllowedUsage(nxt::BufferUsageBit::Mapped | nxt::BufferUsageBit::Uniform) + .SetInitialUsage(nxt::BufferUsageBit::Mapped) + .SetSize(sizeof(u_transform_block)) + .GetResult(); + + auto uniformView = uniformBuffer.CreateBufferViewBuilder() + .SetExtent(0, sizeof(u_transform_block)) + .GetResult(); + + auto bindGroupBuilder = device.CreateBindGroupBuilder(); + bindGroupBuilder.SetLayout(bindGroupLayout) + .SetUsage(nxt::BindGroupUsage::Frozen) + .SetBufferViews(0, 1, &uniformView); + { + auto it = iMaterial.values.find("diffuse"); + if (it != iMaterial.values.end() && !it->second.string_value.empty()) { + const auto& iTextureID = it->second.string_value; + const auto& textureView = textures[iTextureID]; + const auto& iSamplerID = scene.textures[iTextureID].sampler; + bindGroupBuilder.SetSamplers(1, 1, &samplers[iSamplerID]); + bindGroupBuilder.SetTextureViews(2, 1, &textureView); + } else { + bindGroupBuilder.SetSamplers(1, 1, &defaultSampler); + bindGroupBuilder.SetTextureViews(2, 1, &defaultTexture); + } + } + + MaterialInfo material = { + uniformBuffer.Get(), + pipeline.Get(), + bindGroupBuilder.GetResult(), + std::map(), + }; + materials[key] = std::move(material); + return materials.at(key); + } + + void initSamplers() { + defaultSampler = device.CreateSamplerBuilder() + .SetFilterMode(nxt::FilterMode::Nearest, nxt::FilterMode::Nearest, nxt::FilterMode::Nearest) + // TODO: wrap modes + .GetResult(); + + for (const auto& s : scene.samplers) { + const auto& iSamplerID = s.first; + const auto& iSampler = s.second; + + auto magFilter = nxt::FilterMode::Nearest; + auto minFilter = nxt::FilterMode::Nearest; + auto mipmapFilter = nxt::FilterMode::Nearest; + switch (iSampler.magFilter) { + case gl::Nearest: + magFilter = nxt::FilterMode::Nearest; + break; + case gl::Linear: + magFilter = nxt::FilterMode::Linear; + break; + default: + fprintf(stderr, "unsupported magFilter %d\n", iSampler.magFilter); + break; + } + switch (iSampler.minFilter) { + case gl::Nearest: + case gl::NearestMipmapNearest: + case gl::NearestMipmapLinear: + minFilter = nxt::FilterMode::Nearest; + break; + case gl::Linear: + case gl::LinearMipmapNearest: + case gl::LinearMipmapLinear: + minFilter = nxt::FilterMode::Linear; + break; + default: + fprintf(stderr, "unsupported minFilter %d\n", iSampler.magFilter); + break; + } + switch (iSampler.minFilter) { + case gl::NearestMipmapNearest: + case gl::LinearMipmapNearest: + mipmapFilter = nxt::FilterMode::Nearest; + break; + case gl::NearestMipmapLinear: + case gl::LinearMipmapLinear: + mipmapFilter = nxt::FilterMode::Linear; + break; + } + + auto oSampler = device.CreateSamplerBuilder() + .SetFilterMode(magFilter, minFilter, mipmapFilter) + // TODO: wrap modes + .GetResult(); + + samplers[iSamplerID] = std::move(oSampler); + } + } + + void initTextures() { + { + auto oTexture = device.CreateTextureBuilder() + .SetDimension(nxt::TextureDimension::e2D) + .SetExtent(1, 1, 1) + .SetFormat(nxt::TextureFormat::R8G8B8A8Unorm) + .SetMipLevels(1) + .SetAllowedUsage(nxt::TextureUsageBit::TransferDst | nxt::TextureUsageBit::Sampled) + .GetResult(); + // TODO: release this texture + + nxt::Buffer staging = device.CreateBufferBuilder() + .SetAllowedUsage(nxt::BufferUsageBit::Mapped | nxt::BufferUsageBit::TransferSrc) + .SetInitialUsage(nxt::BufferUsageBit::Mapped) + .SetSize(4) + .GetResult(); + // TODO: release this buffer + + uint32_t white = 0xffffffff; + staging.SetSubData(0, 1, &white); + staging.FreezeUsage(nxt::BufferUsageBit::TransferSrc); + auto cmdbuf = device.CreateCommandBufferBuilder() + .TransitionTextureUsage(oTexture, nxt::TextureUsageBit::TransferDst) + .CopyBufferToTexture(staging, oTexture, 0, 0, 0, 1, 1, 1, 0) + .GetResult(); + queue.Submit(1, &cmdbuf); + oTexture.FreezeUsage(nxt::TextureUsageBit::Sampled); + + defaultTexture = oTexture.CreateTextureViewBuilder().GetResult(); + } + + for (const auto& t : scene.textures) { + const auto& iTextureID = t.first; + const auto& iTexture = t.second; + const auto& iImage = scene.images[iTexture.source]; + + nxt::TextureFormat format = nxt::TextureFormat::R8G8B8A8Unorm; + switch (iTexture.format) { + case gl::RGBA: + format = nxt::TextureFormat::R8G8B8A8Unorm; + break; + default: + fprintf(stderr, "unsupported texture format %d\n", iTexture.format); + continue; + } + + auto oTexture = device.CreateTextureBuilder() + .SetDimension(nxt::TextureDimension::e2D) + .SetExtent(iImage.width, iImage.height, 1) + .SetFormat(format) + .SetMipLevels(1) + .SetAllowedUsage(nxt::TextureUsageBit::TransferDst | nxt::TextureUsageBit::Sampled) + .GetResult(); + // TODO: release this texture + + uint32_t numPixels = iImage.width * iImage.height; + const uint8_t* origData = iImage.image.data(); + const uint8_t* data = nullptr; + std::vector newData; + if (iImage.component == 4) { + data = origData; + } else if (iImage.component == 3) { + newData.resize(numPixels * 4); + for (size_t i = 0; i < numPixels; ++i) { + newData[4 * i + 0] = origData[3 * i + 0]; + newData[4 * i + 1] = origData[3 * i + 1]; + newData[4 * i + 2] = origData[3 * i + 2]; + newData[4 * i + 3] = 255; + } + data = newData.data(); + } else { + fprintf(stderr, "unsupported image.component %d\n", iImage.component); + } + + nxt::Buffer staging = device.CreateBufferBuilder() + .SetAllowedUsage(nxt::BufferUsageBit::Mapped | nxt::BufferUsageBit::TransferSrc) + .SetInitialUsage(nxt::BufferUsageBit::Mapped) + .SetSize(numPixels * 4) + .GetResult(); + // TODO: release this buffer + + staging.SetSubData(0, numPixels, + reinterpret_cast(data)); + staging.FreezeUsage(nxt::BufferUsageBit::TransferSrc); + auto cmdbuf = device.CreateCommandBufferBuilder() + .TransitionTextureUsage(oTexture, nxt::TextureUsageBit::TransferDst) + .CopyBufferToTexture(staging, oTexture, 0, 0, 0, iImage.width, iImage.height, 1, 0) + .GetResult(); + queue.Submit(1, &cmdbuf); + oTexture.FreezeUsage(nxt::TextureUsageBit::Sampled); + + textures[iTextureID] = oTexture.CreateTextureViewBuilder().GetResult(); + } + } + + void init() { + nxtProcTable procs; + GetProcTableAndDevice(&procs, &device); + nxtSetProcs(&procs); + + queue = device.CreateQueueBuilder().GetResult(); + + initBuffers(); + initSamplers(); + initTextures(); + } +} + +// Drawing +namespace { + void drawMesh(const tinygltf::Mesh& iMesh, const glm::mat4& model) { + nxt::CommandBufferBuilder cmd = device.CreateCommandBufferBuilder(); + for (const auto& iPrim : iMesh.primitives) { + if (iPrim.mode != gl::Triangles) { + fprintf(stderr, "unsupported primitive mode %d\n", iPrim.mode); + continue; + } + + u_transform_block transforms = { + (projection * camera.view() * model), + glm::inverseTranspose(model), + }; + + uint32_t strides[3] = {0}; + for (const auto& s : slotSemantics) { + if (s.first < 3) { + auto it = iPrim.attributes.find(s.second); + if (it == iPrim.attributes.end()) { + continue; + } + const auto& iAccessorName = it->second; + strides[s.first] = scene.accessors.at(iAccessorName).byteStride; + } + } + const MaterialInfo& material = getMaterial(iPrim.material, strides[0], strides[1], strides[2]); + material.uniformBuffer.TransitionUsage(nxt::BufferUsageBit::Mapped); + material.uniformBuffer.SetSubData(0, + sizeof(u_transform_block) / sizeof(uint32_t), + reinterpret_cast(&transforms)); + cmd.SetPipeline(material.pipeline); + cmd.TransitionBufferUsage(material.uniformBuffer, nxt::BufferUsageBit::Uniform); + cmd.SetBindGroup(0, material.bindGroup0); + + uint32_t vertexCount = 0; + for (const auto& s : slotSemantics) { + uint32_t slot = s.first; + const auto& iSemantic = s.second; + auto it = iPrim.attributes.find(s.second); + if (it == iPrim.attributes.end()) { + uint32_t zero = 0; + cmd.SetVertexBuffers(slot, 1, &defaultBuffer, &zero); + continue; + } + const auto& iAccessor = scene.accessors.at(it->second); + if (iAccessor.componentType != gl::Float || + (iAccessor.type != TINYGLTF_TYPE_VEC4 && iAccessor.type != TINYGLTF_TYPE_VEC3 && iAccessor.type != TINYGLTF_TYPE_VEC2)) { + fprintf(stderr, "unsupported vertex accessor component type %d and type %d\n", iAccessor.componentType, iAccessor.type); + continue; + } + + if (!vertexCount) { + vertexCount = iAccessor.count; + } + const auto& oBuffer = buffers.at(iAccessor.bufferView); + uint32_t iBufferOffset = iAccessor.byteOffset; + cmd.SetVertexBuffers(slot, 1, &oBuffer, &iBufferOffset); + } + + if (!iPrim.indices.empty()) { + const auto& iIndices = scene.accessors.at(iPrim.indices); + // DrawElements + if (iIndices.componentType != gl::UnsignedShort || iIndices.type != TINYGLTF_TYPE_SCALAR) { + fprintf(stderr, "unsupported index accessor component type %d and type %d\n", iIndices.componentType, iIndices.type); + continue; + } + const auto& oIndicesBuffer = buffers.at(iIndices.bufferView); + cmd.SetIndexBuffer(oIndicesBuffer, iIndices.byteOffset, nxt::IndexFormat::Uint16); + cmd.DrawElements(iIndices.count, 1, 0, 0); + } else { + // DrawArrays + cmd.DrawArrays(vertexCount, 1, 0, 0); + } + } + auto commands = cmd.GetResult(); + queue.Submit(1, &commands); + } + + void drawNode(const tinygltf::Node& node, const glm::mat4& parent = glm::mat4()) { + glm::mat4 model; + if (node.matrix.size() == 16) { + model = glm::make_mat4(node.matrix.data()); + } else { + if (node.scale.size() == 3) { + glm::vec3 scale = glm::make_vec3(node.scale.data()); + model = glm::scale(model, scale); + } + if (node.rotation.size() == 4) { + glm::quat rotation = glm::make_quat(node.rotation.data()); + model = glm::mat4_cast(rotation) * model; + } + if (node.translation.size() == 3) { + glm::vec3 translation = glm::make_vec3(node.translation.data()); + model = glm::translate(model, translation); + } + } + model = parent * model; + + for (const auto& meshID : node.meshes) { + drawMesh(scene.meshes[meshID], model); + } + for (const auto& child : node.children) { + drawNode(scene.nodes.at(child), model); + } + } + + void frame() { + const auto& defaultSceneNodes = scene.scenes.at(scene.defaultScene); + for (const auto& n : defaultSceneNodes) { + const auto& node = scene.nodes.at(n); + drawNode(node); + } + SwapBuffers(); + } +} + +// Mouse camera control +namespace { + bool buttons[GLFW_MOUSE_BUTTON_LAST + 1] = {0}; + + void mouseButtonCallback(GLFWwindow *window, int button, int action, int mods) { + buttons[button] = (action == GLFW_PRESS); + } + + void cursorPosCallback(GLFWwindow *window, double mouseX, double mouseY) { + static float oldX, oldY; + float dX = mouseX - oldX; + float dY = mouseY - oldY; + oldX = mouseX; + oldY = mouseY; + + if (buttons[2] || (buttons[0] && buttons[1])) { + camera.pan(-dX * 0.002, dY * 0.002); + } else if (buttons[0]) { + camera.rotate(dX * -0.01, dY * 0.01); + } else if (buttons[1]) { + camera.zoom(dY * -0.005); + } + } + + void scrollCallback(GLFWwindow *window, double xoffset, double yoffset) { + camera.zoom(yoffset * 0.04); + } +} + +int main(int argc, const char* argv[]) { + if (!InitUtils(argc, argv)) { + return 1; + } + if (argc < 2) { + fprintf(stderr, "Usage: %s model.gltf [... NXT Options]\n", argv[0]); + return 1; + } + + tinygltf::TinyGLTFLoader loader; + std::string err; + std::string input_filename(argv[1]); + std::string ext = getFilePathExtension(input_filename); + + bool ret = false; + if (ext.compare("glb") == 0) { + // assume binary glTF. + ret = loader.LoadBinaryFromFile(&scene, &err, input_filename.c_str()); + } else { + // assume ascii glTF. + ret = loader.LoadASCIIFromFile(&scene, &err, input_filename.c_str()); + } + if (!err.empty()) { + fprintf(stderr, "ERR: %s\n", err.c_str()); + } + if (!ret) { + fprintf(stderr, "Failed to load .glTF : %s\n", argv[1]); + exit(-1); + } + + init(); + + GLFWwindow* window = GetWindow(); + glfwSetMouseButtonCallback(window, mouseButtonCallback); + glfwSetCursorPosCallback(window, cursorPosCallback); + glfwSetScrollCallback(window, scrollCallback); + + while (!ShouldQuit()) { + frame(); + usleep(16000); + } + + // TODO release stuff +} diff --git a/examples/glTFViewer/img/nxt-gltf-duck.jpg b/examples/glTFViewer/img/nxt-gltf-duck.jpg new file mode 100644 index 0000000000..da78162a75 Binary files /dev/null and b/examples/glTFViewer/img/nxt-gltf-duck.jpg differ diff --git a/examples/glTFViewer/img/nxt-gltf-vc.jpg b/examples/glTFViewer/img/nxt-gltf-vc.jpg new file mode 100644 index 0000000000..29f969497a Binary files /dev/null and b/examples/glTFViewer/img/nxt-gltf-vc.jpg differ diff --git a/generator/CMakeLists.txt b/generator/CMakeLists.txt new file mode 100644 index 0000000000..82723c1725 --- /dev/null +++ b/generator/CMakeLists.txt @@ -0,0 +1,74 @@ +# Copyright 2017 The NXT Authors +# +# 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. + +find_package(PythonInterp REQUIRED) +include(CMakeParseArguments) + +# Check for Jinja2 +message(STATUS "${PYTHON_EXECUTABLE}") +execute_process( + COMMAND ${PYTHON_EXECUTABLE} -c "import jinja2" + RESULT_VARIABLE RET +) +if (NOT RET EQUAL 0) + message(FATAL_ERROR "Missing dependencies for VkCPP generation, please ensure you have python-jinja2 installed.") +endif() + +function(Generate) + set(oneValueArgs LIB_NAME LIB_TYPE PRINT_NAME EXECUTABLE) + set(multiValueArgs COMMAND_LINE_ARGS EXTRA_DEPS SOURCE) + cmake_parse_arguments(G "" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) + + execute_process( + COMMAND ${G_COMMAND_LINE_ARGS} --print-dependencies + OUTPUT_VARIABLE DEPENDENCIES + RESULT_VARIABLE RET + ) + if (NOT RET EQUAL 0) + message(STATUS ${RET}) + message(FATAL_ERROR "Failed to get the dependencies for ${G_PRINT_NAME}.") + endif() + + execute_process( + COMMAND ${G_COMMAND_LINE_ARGS} --print-outputs + OUTPUT_VARIABLE OUTPUTS + RESULT_VARIABLE RET + ) + if (NOT RET EQUAL 0) + message(FATAL_ERROR "Failed to get the outputs for ${G_PRINT_NAME}.") + endif() + + add_custom_command( + COMMAND ${G_COMMAND_LINE_ARGS} + DEPENDS ${DEPENDENCIES} ${G_EXTRA_DEPS} + OUTPUT ${OUTPUTS} + COMMENT "Generating files for ${G_PRINT_NAME}." + ) + + add_library(${G_LIB_NAME} ${G_LIB_TYPE} + ${G_SOURCE} + ${OUTPUTS} + ) +endfunction() + +set(GENERATED_DIR ${CMAKE_CURRENT_BINARY_DIR} PARENT_SCOPE) + +set(GENERATOR_COMMON_ARGS + ${PYTHON_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/main.py + ${CMAKE_SOURCE_DIR}/next.json + -t ${CMAKE_CURRENT_SOURCE_DIR}/templates + -o ${CMAKE_CURRENT_BINARY_DIR} + PARENT_SCOPE +) diff --git a/generator/main.py b/generator/main.py new file mode 100644 index 0000000000..a2be335b77 --- /dev/null +++ b/generator/main.py @@ -0,0 +1,427 @@ +# Copyright 2017 The NXT Authors +# +# 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. + +############################################################ +# COMMON +############################################################ +from collections import namedtuple + +class Name: + def __init__(self, name, native=False): + self.native = native + if native: + self.chunks = [name] + else: + self.chunks = name.split(' ') + + def CamelChunk(self, chunk): + return chunk[0].upper() + chunk[1:] + + def canonical_case(self): + return (' '.join(self.chunks)).lower() + + def concatcase(self): + return ''.join(self.chunks) + + def camelCase(self): + return self.chunks[0] + ''.join([self.CamelChunk(chunk) for chunk in self.chunks[1:]]) + + def CamelCase(self): + return ''.join([self.CamelChunk(chunk) for chunk in self.chunks]) + + def SNAKE_CASE(self): + return '_'.join([chunk.upper() for chunk in self.chunks]) + + def snake_case(self): + return '_'.join(self.chunks) + +class Type: + def __init__(self, name, record, native=False): + self.record = record + self.dict_name = name + self.name = Name(name, native=native) + self.category = record['category'] + self.is_builder = self.name.canonical_case().endswith(" builder") + +EnumValue = namedtuple('EnumValue', ['name', 'value']) +class EnumType(Type): + def __init__(self, name, record): + Type.__init__(self, name, record) + self.values = [EnumValue(Name(m['name']), m['value']) for m in self.record['values']] + +BitmaskValue = namedtuple('BitmaskValue', ['name', 'value']) +class BitmaskType(Type): + def __init__(self, name, record): + Type.__init__(self, name, record) + self.values = [BitmaskValue(Name(m['name']), m['value']) for m in self.record['values']] + self.full_mask = 0 + for value in self.values: + self.full_mask = self.full_mask | value.value + +class NativeType(Type): + def __init__(self, name, record): + Type.__init__(self, name, record, native=True) + +class MethodArgument: + def __init__(self, name, typ, annotation): + self.name = name + self.type = typ + self.annotation = annotation + self.length = None + +Method = namedtuple('Method', ['name', 'return_type', 'arguments']) +class ObjectType(Type): + def __init__(self, name, record): + Type.__init__(self, name, record) + self.methods = [] + +############################################################ +# PARSE +############################################################ +import json +def link_object(obj, types): + def make_method(record): + arguments = [] + arguments_by_name = {} + for a in record.get('args', []): + arg = MethodArgument(Name(a['name']), types[a['type']], a.get('annotation', 'value')) + arguments.append(arg) + arguments_by_name[arg.name.canonical_case()] = arg + + for (arg, a) in zip(arguments, record.get('args', [])): + assert(arg.annotation == 'value' or 'length' in a) + if arg.annotation != 'value': + if a['length'] == 'strlen': + arg.length = 'strlen' + else: + arg.length = arguments_by_name[a['length']] + + return Method(Name(record['name']), types[record.get('returns', 'void')], arguments) + + obj.methods = [make_method(m) for m in obj.record.get('methods', [])] + +def parse_json(json): + category_to_parser = { + 'bitmask': BitmaskType, + 'enum': EnumType, + 'native': NativeType, + 'object': ObjectType, + } + + types = {} + + by_category = {} + for name in category_to_parser.keys(): + by_category[name] = [] + + for (name, record) in json.items(): + if name[0] == '_': + continue + category = record['category'] + parsed = category_to_parser[category](name, record) + by_category[category].append(parsed) + types[name] = parsed + + for obj in by_category['object']: + link_object(obj, types) + + for category in by_category.keys(): + by_category[category] = sorted(by_category[category], key=lambda typ: typ.name.canonical_case()) + + return { + 'types': types, + 'by_category': by_category + } + +############################################################# +# OUTPUT +############################################################# +import re, os, sys +from collections import OrderedDict + +try: + import jinja2 +except ImportError: + # Try using Chromium's Jinja2 + dir, _ = os.path.split(os.path.realpath(__file__)) + third_party_dir = os.path.normpath(dir + (os.path.sep + os.path.pardir) * 2) + sys.path.insert(1, third_party_dir) + import jinja2 + +# A custom Jinja2 template loader that removes the extra indentation +# of the template blocks so that the output is correctly indented +class PreprocessingLoader(jinja2.BaseLoader): + def __init__(self, path): + self.path = path + + def get_source(self, environment, template): + path = os.path.join(self.path, template) + if not os.path.exists(path): + raise jinja2.TemplateNotFound(template) + mtime = os.path.getmtime(path) + with open(path) as f: + source = self.preprocess(f.read()) + return source, path, lambda: mtime == os.path.getmtime(path) + + blockstart = re.compile('{%-?\s*(if|for|block)[^}]*%}') + blockend = re.compile('{%-?\s*end(if|for|block)[^}]*%}') + + def preprocess(self, source): + lines = source.split('\n') + + # Compute the current indentation level of the template blocks and remove their indentation + result = [] + indentation_level = 0 + + for line in lines: + # The capture in the regex adds one element per block start or end so we divide by two + # there is also an extra line chunk corresponding to the line end, so we substract it. + numends = (len(self.blockend.split(line)) - 1) / 2 + indentation_level -= numends + + result.append(self.remove_indentation(line, indentation_level)) + + numstarts = (len(self.blockstart.split(line)) - 1) / 2 + indentation_level += numstarts + + return '\n'.join(result) + + def remove_indentation(self, line, n): + for _ in range(n): + if line.startswith(' '): + line = line[4:] + elif line.startswith('\t'): + line = line[1:] + else: + assert(line.strip() == '') + return line + +FileRender = namedtuple('FileRender', ['template', 'output', 'params_dicts']) + +def do_renders(renders, template_dir, output_dir): + env = jinja2.Environment(loader=PreprocessingLoader(template_dir), trim_blocks=True, lstrip_blocks=True, line_comment_prefix='//*') + for render in renders: + params = {} + for param_dict in render.params_dicts: + params.update(param_dict) + output = env.get_template(render.template).render(**params) + + output_file = output_dir + os.path.sep + render.output + directory = os.path.dirname(output_file) + if not os.path.exists(directory): + os.makedirs(directory) + + content = "" + try: + with open(output_file, 'r') as outfile: + content = outfile.read() + except: + pass + + if output != content: + with open(output_file, 'w') as outfile: + outfile.write(output) + +############################################################# +# MAIN SOMETHING WHATEVER +############################################################# +import argparse, sys + +def as_varName(*names): + return names[0].camelCase() + ''.join([name.CamelCase() for name in names[1:]]) + +def as_cType(name): + if name.native: + return name.concatcase() + else: + return 'nxt' + name.CamelCase() + +def as_cppType(name): + if name.native: + return name.concatcase() + else: + return name.CamelCase() + +def decorate(name, typ, arg): + if arg.annotation == 'value': + return typ + ' ' + name + elif arg.annotation == '*': + return typ + '* ' + name + elif arg.annotation == 'const*': + return typ + ' const * ' + name + else: + assert(False) + +def annotated(typ, arg): + name = as_varName(arg.name) + return decorate(name, typ, arg) + +def as_cEnum(type_name, value_name): + assert(not type_name.native and not value_name.native) + return 'NXT' + '_' + type_name.SNAKE_CASE() + '_' + value_name.SNAKE_CASE() + +def as_cppEnum(value_name): + assert(not value_name.native) + if value_name.concatcase()[0].isdigit(): + return "e" + value_name.CamelCase() + return value_name.CamelCase() + +def as_cMethod(type_name, method_name): + assert(not type_name.native and not method_name.native) + return 'nxt' + type_name.CamelCase() + method_name.CamelCase() + +def as_MethodSuffix(type_name, method_name): + assert(not type_name.native and not method_name.native) + return type_name.CamelCase() + method_name.CamelCase() + +def as_cProc(type_name, method_name): + assert(not type_name.native and not method_name.native) + return 'nxt' + 'Proc' + type_name.CamelCase() + method_name.CamelCase() + +def as_backendType(typ): + if typ.category == 'object': + return typ.name.CamelCase() + '*' + else: + return as_cType(typ.name) + +def native_methods(types, typ): + return [ + Method(Name('reference'), types['void'], []), + Method(Name('release'), types['void'], []), + ] + typ.methods + +def debug(text): + print(text) + +def main(): + targets = ['nxt', 'nxtcpp', 'mock_nxt', 'opengl', 'metal', 'wire', 'blink'] + + parser = argparse.ArgumentParser( + description = 'Generates code for various target for NXT.', + formatter_class = argparse.ArgumentDefaultsHelpFormatter + ) + parser.add_argument('json', metavar='NXT_JSON', nargs=1, type=str, help ='The NXT JSON definition to use.') + parser.add_argument('-t', '--template-dir', default='templates', type=str, help='Directory with template files.') + parser.add_argument('-o', '--output-dir', default=None, type=str, help='Output directory for the generated source files.') + parser.add_argument('-T', '--targets', default=None, type=str, help='Comma-separated subset of targets to output. Available targets: ' + ', '.join(targets)) + parser.add_argument('--print-dependencies', action='store_true', help='Prints a space separated list of file dependencies, used for CMake integration') + parser.add_argument('--print-outputs', action='store_true', help='Prints a space separated list of file outputs, used for CMake integration') + parser.add_argument('--gn', action='store_true', help='Make the printing of dependencies by GN friendly') + + args = parser.parse_args() + + if args.targets != None: + targets = args.targets.split(',') + + with open(args.json[0]) as f: + loaded_json = json.loads(f.read()) + + api_params = parse_json(loaded_json) + + base_params = { + 'enumerate': enumerate, + 'format': format, + 'len': len, + 'debug': debug, + + 'Name': lambda name: Name(name), + + 'as_annotated_cType': lambda arg: annotated(as_cType(arg.type.name), arg), + 'as_annotated_cppType': lambda arg: annotated(as_cppType(arg.type.name), arg), + 'as_cEnum': as_cEnum, + 'as_cppEnum': as_cppEnum, + 'as_cMethod': as_cMethod, + 'as_MethodSuffix': as_MethodSuffix, + 'as_cProc': as_cProc, + 'as_cType': as_cType, + 'as_cppType': as_cppType, + 'as_varName': as_varName, + 'decorate': decorate, + 'native_methods': lambda typ: native_methods(api_params['types'], typ) + } + + renders = [] + + if 'nxt' in targets: + renders.append(FileRender('api.h', 'nxt/nxt.h', [base_params, api_params])) + renders.append(FileRender('api.c', 'nxt/nxt.c', [base_params, api_params])) + + if 'nxtcpp' in targets: + renders.append(FileRender('apicpp.h', 'nxt/nxtcpp.h', [base_params, api_params])) + renders.append(FileRender('apicpp.cpp', 'nxt/nxtcpp.cpp', [base_params, api_params])) + + if 'mock_nxt' in targets: + renders.append(FileRender('mock_api.h', 'mock/mock_nxt.h', [base_params, api_params])) + renders.append(FileRender('mock_api.cpp', 'mock/mock_nxt.cpp', [base_params, api_params])) + + base_backend_params = [ + base_params, + api_params, + { + 'as_backendType': lambda typ: as_backendType(typ), # TODO as_backendType and friends take a Type and not a Name :( + 'as_annotated_backendType': lambda arg: annotated(as_backendType(arg.type), arg) + } + ] + + if 'opengl' in targets: + opengl_params = { + 'namespace': 'opengl', + } + renders.append(FileRender('BackendProcTable.cpp', 'opengl/ProcTable.cpp', base_backend_params + [opengl_params])) + + if 'metal' in targets: + metal_params = { + 'namespace': 'metal', + } + renders.append(FileRender('BackendProcTable.cpp', 'metal/ProcTable.mm', base_backend_params + [metal_params])) + + if 'wire' in targets: + renders.append(FileRender('wire/WireCmd.h', 'wire/WireCmd_autogen.h', base_backend_params)) + renders.append(FileRender('wire/WireCmd.cpp', 'wire/WireCmd.cpp', base_backend_params)) + renders.append(FileRender('wire/WireClient.cpp', 'wire/WireClient.cpp', base_backend_params)) + renders.append(FileRender('wire/WireServer.cpp', 'wire/WireServer.cpp', base_backend_params)) + + if 'blink' in targets: + renders.append(FileRender('blink/autogen.gni', 'autogen.gni', [base_params, api_params])) + renders.append(FileRender('blink/Objects.cpp', 'NXT.cpp', [base_params, api_params])) + renders.append(FileRender('blink/Forward.h', 'Forward.h', [base_params, api_params])) + + for typ in api_params['by_category']['object']: + file_prefix = 'NXT' + typ.name.CamelCase() + params = [base_params, api_params, {'type': typ}] + + renders.append(FileRender('blink/Object.h', file_prefix + '.h', params)) + renders.append(FileRender('blink/Object.idl', file_prefix + '.idl', params)) + + output_separator = '\n' if args.gn else ';' + if args.print_dependencies: + dependencies = set( + [os.path.abspath(args.template_dir + os.path.sep + render.template) for render in renders] + + [os.path.abspath(args.json[0])] + + [os.path.realpath(__file__)] + ) + sys.stdout.write(output_separator.join(dependencies)) + return 0 + + if args.print_outputs: + outputs = set( + [os.path.abspath(args.output_dir + os.path.sep + render.output) for render in renders] + ) + sys.stdout.write(output_separator.join(outputs)) + return 0 + + do_renders(renders, args.template_dir, args.output_dir) + +if __name__ == '__main__': + sys.exit(main()) diff --git a/generator/templates/BackendProcTable.cpp b/generator/templates/BackendProcTable.cpp new file mode 100644 index 0000000000..b92503bd5e --- /dev/null +++ b/generator/templates/BackendProcTable.cpp @@ -0,0 +1,185 @@ +//* Copyright 2017 The NXT Authors +//* +//* 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. + +#include "nxt/nxt.h" +#include "nxt/nxtcpp.h" + +#include "{{namespace}}/GeneratedCodeIncludes.h" + +#include + +namespace backend { +namespace {{namespace}} { + + namespace { + + //* Helper functions to check the value of enums + {% for type in by_category["enum"] %} + {% set cType = as_cType(type.name) %} + bool CheckEnum{{cType}}({{cType}} value) { + switch (value) { + {% for value in type.values %} + case {{as_cEnum(type.name, value.name)}}: + return true; + {% endfor %} + default: + return false; + } + } + {% endfor %} + + {% for type in by_category["bitmask"] %} + {% set cType = as_cType(type.name) %} + bool CheckBitmask{{cType}}({{cType}} value) { + return (value & ~{{type.full_mask}}) == 0; + } + {% endfor %} + + {% set methodsWithExtraValidation = ( + "CommandBufferBuilderGetResult", + "QueueSubmit", + ) %} + + {% for type in by_category["object"] %} + {% for method in native_methods(type) %} + {% set suffix = as_MethodSuffix(type.name, method.name) %} + + //* Entry point without validation, forwards the arguments to the method directly + {{as_backendType(method.return_type)}} NonValidating{{suffix}}( + {{-as_backendType(type)}} self + {%- for arg in method.arguments -%} + , {{as_annotated_backendType(arg)}} + {%- endfor -%} + ) { + {% if method.return_type.name.canonical_case() != "void" %} + auto result = + {%- endif %} + self->{{method.name.CamelCase()}}( + {%- for arg in method.arguments -%} + {%- if not loop.first %}, {% endif -%} + {%- if arg.type.category in ["enum", "bitmask"] -%} + static_cast({{as_varName(arg.name)}}) + {%- else -%} + {{as_varName(arg.name)}} + {%- endif -%} + {%- endfor -%} + ); + {% if method.return_type.name.canonical_case() != "void" %} + return reinterpret_cast<{{as_backendType(method.return_type)}}>(result); + {% endif %} + } + + //* Autogenerated part of the entry point validation + //* - Check that enum and bitmaks are in the correct range + //* - Check that builders have not been consumed already + //* - Others TODO + bool ValidateBase{{suffix}}( + {{-as_backendType(type)}} self + {%- for arg in method.arguments -%} + , {{as_annotated_backendType(arg)}} + {%- endfor -%} + ) { + {% if type.is_builder and method.name.canonical_case() not in ("release", "reference") %} + if (self->WasConsumed()) return false; + {% else %} + (void) self; + {% endif %} + {% for arg in method.arguments %} + {% if arg.type.category == "enum" %} + if (!CheckEnum{{as_cType(arg.type.name)}}({{as_varName(arg.name)}})) return false; + {% elif arg.type.category == "bitmask" %} + if (!CheckBitmask{{as_cType(arg.type.name)}}({{as_varName(arg.name)}})) return false; + {% else %} + (void) {{as_varName(arg.name)}}; + {% endif %} + {% endfor %} + return true; + } + + //* Entry point with validation + {{as_backendType(method.return_type)}} Validating{{suffix}}( + {{-as_backendType(type)}} self + {%- for arg in method.arguments -%} + , {{as_annotated_backendType(arg)}} + {%- endfor -%} + ) { + //* Do the autogenerated checks + bool valid = ValidateBase{{suffix}}(self + {%- for arg in method.arguments -%} + , {{as_varName(arg.name)}} + {%- endfor -%} + ); + + {% if suffix in methodsWithExtraValidation %} + if (valid) { + valid = self->Validate{{method.name.CamelCase()}}( + {%- for arg in method.arguments -%} + {% if not loop.first %}, {% endif %}{{as_varName(arg.name)}} + {%- endfor -%} + ); + } + {% endif %} + //* TODO Do the hand-written checks if necessary + //* On success, forward the arguments to the method, else error out without calling it + if (!valid) { + // TODO get the device and give it the error? + std::cout << "Error in {{suffix}}" << std::endl; + } + {% if method.return_type.name.canonical_case() == "void" %} + if (!valid) return; + {% else %} + if (!valid) { + return {}; + } + auto result = + {%- endif %} + self->{{method.name.CamelCase()}}( + {%- for arg in method.arguments -%} + {%- if not loop.first %}, {% endif -%} + {%- if arg.type.category in ["enum", "bitmask"] -%} + static_cast({{as_varName(arg.name)}}) + {%- else -%} + {{as_varName(arg.name)}} + {%- endif -%} + {%- endfor -%} + ); + {% if method.return_type.name.canonical_case() != "void" %} + return reinterpret_cast<{{as_backendType(method.return_type)}}>(result); + {% endif %} + } + {% endfor %} + {% endfor %} + } + + nxtProcTable GetNonValidatingProcs() { + nxtProcTable table; + {% for type in by_category["object"] %} + {% for method in native_methods(type) %} + table.{{as_varName(type.name, method.name)}} = reinterpret_cast<{{as_cProc(type.name, method.name)}}>(NonValidating{{as_MethodSuffix(type.name, method.name)}}); + {% endfor %} + {% endfor %} + return table; + } + + nxtProcTable GetValidatingProcs() { + nxtProcTable table; + {% for type in by_category["object"] %} + {% for method in native_methods(type) %} + table.{{as_varName(type.name, method.name)}} = reinterpret_cast<{{as_cProc(type.name, method.name)}}>(Validating{{as_MethodSuffix(type.name, method.name)}}); + {% endfor %} + {% endfor %} + return table; + } +} +} diff --git a/generator/templates/api.c b/generator/templates/api.c new file mode 100644 index 0000000000..31d39341b1 --- /dev/null +++ b/generator/templates/api.c @@ -0,0 +1,46 @@ +//* Copyright 2017 The NXT Authors +//* +//* 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. + +#include "nxt/nxt.h" + +static nxtProcTable procs; + +static nxtProcTable nullProcs; + +void nxtSetProcs(const nxtProcTable* procs_) { + if (procs_) { + procs = *procs_; + } else { + procs = nullProcs; + } +} + +{% for type in by_category["object"] %} + {% for method in native_methods(type) %} + {{as_cType(method.return_type.name)}} {{as_cMethod(type.name, method.name)}}( + {{-as_cType(type.name)}} {{as_varName(type.name)}} + {%- for arg in method.arguments -%} + , {{as_annotated_cType(arg)}} + {%- endfor -%} + ) { + {% if method.return_type.name.canonical_case() != "void" %}return {% endif %} + procs.{{as_varName(type.name, method.name)}}({{as_varName(type.name)}} + {%- for arg in method.arguments -%} + , {{as_varName(arg.name)}} + {%- endfor -%} + ); + } + {% endfor %} + +{% endfor %} diff --git a/generator/templates/api.h b/generator/templates/api.h new file mode 100644 index 0000000000..fa937801a3 --- /dev/null +++ b/generator/templates/api.h @@ -0,0 +1,85 @@ +//* Copyright 2017 The NXT Authors +//* +//* 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. + +#ifndef NXT_H +#define NXT_H + +#include +#include +#include + +{% for type in by_category["object"] %} + typedef struct {{as_cType(type.name)}}Impl* {{as_cType(type.name)}}; +{% endfor %} + +{% for type in by_category["enum"] + by_category["bitmask"] %} + typedef enum { + {% for value in type.values %} + {{as_cEnum(type.name, value.name)}} = 0x{{format(value.value, "08X")}}, + {% endfor %} + {{as_cEnum(type.name, Name("force32"))}} = 0x7FFFFFFF + } {{as_cType(type.name)}}; + +{% endfor %} + +#ifdef __cplusplus +extern "C" { +#endif + +{% for type in by_category["object"] %} + // Procs of {{type.name.CamelCase()}} + {% for method in native_methods(type) %} + typedef {{as_cType(method.return_type.name)}} (*{{as_cProc(type.name, method.name)}})( + {{-as_cType(type.name)}} {{as_varName(type.name)}} + {%- for arg in method.arguments -%} + , {{as_annotated_cType(arg)}} + {%- endfor -%} + ); + {% endfor %} + +{% endfor %} + +struct nxtProcTable_s { + {% for type in by_category["object"] %} + {% for method in native_methods(type) %} + {{as_cProc(type.name, method.name)}} {{as_varName(type.name, method.name)}}; + {% endfor %} + + {% endfor %} +}; +typedef struct nxtProcTable_s nxtProcTable; + +// Stuff below is for convenience and will forward calls to a static nxtProcTable. + +// Set which nxtProcTable will be used +void nxtSetProcs(const nxtProcTable* procs); + +{% for type in by_category["object"] %} + // Methods of {{type.name.CamelCase()}} + {% for method in native_methods(type) %} + {{as_cType(method.return_type.name)}} {{as_cMethod(type.name, method.name)}}( + {{-as_cType(type.name)}} {{as_varName(type.name)}} + {%- for arg in method.arguments -%} + , {{as_annotated_cType(arg)}} + {%- endfor -%} + ); + {% endfor %} + +{% endfor %} + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // NXT_H diff --git a/generator/templates/apicpp.cpp b/generator/templates/apicpp.cpp new file mode 100644 index 0000000000..2130495e8e --- /dev/null +++ b/generator/templates/apicpp.cpp @@ -0,0 +1,109 @@ +//* Copyright 2017 The NXT Authors +//* +//* 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. + +#include "nxtcpp.h" + +namespace nxt { + + {% for type in by_category["enum"] + by_category["bitmask"] %} + {% set CppType = as_cppType(type.name) %} + {% set CType = as_cType(type.name) %} + + static_assert(sizeof({{CppType}}) == sizeof({{CType}}), "sizeof mismatch for {{CppType}}"); + static_assert(alignof({{CppType}}) == alignof({{CType}}), "alignof mismatch for {{CppType}}"); + + {% for value in type.values %} + static_assert(static_cast({{CppType}}::{{as_cppEnum(value.name)}}) == {{as_cEnum(type.name, value.name)}}, "value mismatch for {{CppType}}::{{as_cppEnum(value.name)}}"); + {% endfor %} + + {% endfor %} + + + {% for type in by_category["object"] %} + {% set CppType = as_cppType(type.name) %} + {% set CType = as_cType(type.name) %} + + static_assert(sizeof({{CppType}}) == sizeof({{CType}}), "sizeof mismatch for {{CppType}}"); + static_assert(alignof({{CppType}}) == alignof({{CType}}), "alignof mismatch for {{CppType}}"); + + {% macro render_cpp_method_declaration(type, method) %} + {% set CppType = as_cppType(type.name) %} + {% if method.return_type.name.concatcase() == "void" -%} + {{CppType}} const& + {%- else -%} + {{as_cppType(method.return_type.name)}} + {%- endif -%} + {{" "}}{{CppType}}::{{method.name.CamelCase()}}( + {%- for arg in method.arguments -%} + {%- if not loop.first %}, {% endif -%} + {%- if arg.type.category == "object" and arg.annotation == "value" -%} + {{as_cppType(arg.type.name)}} const& {{as_varName(arg.name)}} + {%- else -%} + {{as_annotated_cppType(arg)}} + {%- endif -%} + {%- endfor -%} + ) const + {%- endmacro %} + + {% macro render_cpp_to_c_method_call(type, method) -%} + {{as_cMethod(type.name, method.name)}}(Get() + {%- for arg in method.arguments -%},{{" "}} + {%- if arg.annotation == "value" -%} + {%- if arg.type.category == "object" -%} + {{as_varName(arg.name)}}.Get() + {%- elif arg.type.category == "enum" or arg.type.category == "bitmask" -%} + static_cast<{{as_cType(arg.type.name)}}>({{as_varName(arg.name)}}) + {%- elif arg.type.category == "native" -%} + {{as_varName(arg.name)}} + {%- else -%} + UNHANDLED + {%- endif -%} + {%- else -%} + reinterpret_cast<{{decorate("", as_cType(arg.type.name), arg)}}>({{as_varName(arg.name)}}) + {%- endif -%} + {%- endfor -%} + ) + {%- endmacro %} + + {% for method in type.methods %} + {{render_cpp_method_declaration(type, method)}} { + {% if method.return_type.name.concatcase() == "void" %} + {{render_cpp_to_c_method_call(type, method)}}; + return *this; + {% else %} + auto result = {{render_cpp_to_c_method_call(type, method)}}; + {% if method.return_type.category == "native" %} + return result; + {% elif method.return_type.category == "object" %} + return {{as_cppType(method.return_type.name)}}::Acquire(result); + {% else %} + return static_cast<{{as_cppType(method.return_type.name)}}>(result); + {% endif%} + {% endif %} + } + {% endfor %} + void {{CppType}}::NxtReference({{CType}} handle) { + if (handle != nullptr) { + {{as_cMethod(type.name, Name("reference"))}}(handle); + } + } + void {{CppType}}::NxtRelease({{CType}} handle) { + if (handle != nullptr) { + {{as_cMethod(type.name, Name("release"))}}(handle); + } + } + + {% endfor %} + +} diff --git a/generator/templates/apicpp.h b/generator/templates/apicpp.h new file mode 100644 index 0000000000..a66521df91 --- /dev/null +++ b/generator/templates/apicpp.h @@ -0,0 +1,149 @@ +//* Copyright 2017 The NXT Authors +//* +//* 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. + +#ifndef NXTCPP_H +#define NXTCPP_H + +#include "nxt.h" + +#include "nxt/EnumClassBitmasks.h" + +namespace nxt { + + {% for type in by_category["enum"] %} + enum class {{as_cppType(type.name)}} : uint32_t { + {% for value in type.values %} + {{as_cppEnum(value.name)}} = 0x{{format(value.value, "08X")}}, + {% endfor %} + }; + + {% endfor %} + + {% for type in by_category["bitmask"] %} + enum class {{as_cppType(type.name)}} : uint32_t { + {% for value in type.values %} + {{as_cppEnum(value.name)}} = 0x{{format(value.value, "08X")}}, + {% endfor %} + }; + + {% endfor %} + + {% for type in by_category["bitmask"] %} + template<> + struct IsNXTBitmask<{{as_cppType(type.name)}}> { + static constexpr bool enable = true; + }; + + {% endfor %} + + {% for type in by_category["object"] %} + class {{as_cppType(type.name)}}; + {% endfor %} + + template + class ObjectBase { + public: + ObjectBase(): handle(nullptr) { + } + ObjectBase(CType handle): handle(handle) { + if (handle) Derived::NxtReference(handle); + } + ~ObjectBase() { + if (handle) Derived::NxtRelease(handle); + } + + ObjectBase(ObjectBase const& other) = delete; + Derived& operator=(ObjectBase const& other) = delete; + + ObjectBase(ObjectBase&& other) { + Derived::NxtRelease(handle); + handle = other.handle; + other.handle = 0; + } + Derived& operator=(ObjectBase&& other) { + if (&other == this) return static_cast(*this); + + Derived::NxtRelease(handle); + handle = other.handle; + other.handle = 0; + + return static_cast(*this); + } + + explicit operator bool() const { + return handle != nullptr; + } + CType Get() const { + return handle; + } + CType Release() { + CType result = handle; + handle = 0; + return result; + } + Derived Clone() const { + return Derived(handle); + } + static Derived Acquire(CType handle) { + Derived result; + result.handle = handle; + return result; + } + + protected: + CType handle; + }; + + {% macro render_cpp_method_declaration(type, method) %} + {% set CppType = as_cppType(type.name) %} + {% if method.return_type.name.concatcase() == "void" -%} + {{CppType}} const& + {%- else -%} + {{as_cppType(method.return_type.name)}} + {%- endif -%} + {{" "}}{{method.name.CamelCase()}}( + {%- for arg in method.arguments -%} + {%- if not loop.first %}, {% endif -%} + {%- if arg.type.category == "object" and arg.annotation == "value" -%} + {{as_cppType(arg.type.name)}} const& {{as_varName(arg.name)}} + {%- else -%} + {{as_annotated_cppType(arg)}} + {%- endif -%} + {%- endfor -%} + ) const + {%- endmacro %} + + {% for type in by_category["object"] %} + {% set CppType = as_cppType(type.name) %} + {% set CType = as_cType(type.name) %} + class {{CppType}} : public ObjectBase<{{CppType}}, {{CType}}> { + public: + using ObjectBase::ObjectBase; + using ObjectBase::operator=; + + {% for method in type.methods %} + {{render_cpp_method_declaration(type, method)}}; + {% endfor %} + + private: + friend ObjectBase<{{CppType}}, {{CType}}>; + static void NxtReference({{CType}} handle); + static void NxtRelease({{CType}} handle); + }; + + {% endfor %} + +} // namespace nxt + +#endif // NXTCPP_H diff --git a/generator/templates/blink/Forward.h b/generator/templates/blink/Forward.h new file mode 100644 index 0000000000..8d9a291dee --- /dev/null +++ b/generator/templates/blink/Forward.h @@ -0,0 +1,33 @@ +//* Copyright 2017 The NXT Authors +//* +//* 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. + +#ifndef NXTForward_H +#define NXTForward_H + +namespace blink { + + {% for other_type in by_category["object"] %} + class NXT{{other_type.name.CamelCase()}}; + {% endfor %} + +} + +struct nxtProcTable_s; +typedef struct nxtProcTable_s nxtProcTable; + +{% for type in by_category["object"] %} + typedef struct {{as_cType(type.name)}}Impl* {{as_cType(type.name)}}; +{% endfor %} + +#endif //NXTForward_H diff --git a/generator/templates/blink/Object.h b/generator/templates/blink/Object.h new file mode 100644 index 0000000000..c4db588a9a --- /dev/null +++ b/generator/templates/blink/Object.h @@ -0,0 +1,99 @@ +//* Copyright 2017 The NXT Authors +//* +//* 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. + +{% macro blinkType(type) -%} + {%- if type.category == "object" -%} + NXT{{type.name.CamelCase()}}* + {%- elif type.category == "enum" or type.category == "bitmask" -%} + uint32_t + {%- else -%} + {{as_cType(type.name)}} + {%- endif -%} +{%- endmacro %} + +{% set Class = "NXT" + type.name.CamelCase() %} + +#ifndef {{Class}}_H +#define {{Class}}_H + +#include "bindings/core/v8/ScriptWrappable.h" +#include "platform/heap/GarbageCollected.h" +#include "wtf/text/WTFString.h" + +#include "../NXTState.h" +#include "Forward.h" + +namespace blink { + +class {{Class}} final : + public GarbageCollectedFinalized<{{Class}}>, + public ScriptWrappable { + + WTF_MAKE_NONCOPYABLE({{Class}}); + USING_PRE_FINALIZER({{Class}}, dispose); + public: + DEFINE_INLINE_TRACE() { + visitor->trace(m_state); + }; + + public: + DEFINE_WRAPPERTYPEINFO(); + + public: + {{Class}}({{as_cType(type.name)}} self, Member state); + void dispose(); + + {% for method in type.methods %} + {% if method.return_type.name.concatcase() == "void" %} + {{Class}}* + {%- else %} + {{blinkType(method.return_type)}} + {%- endif -%} + {{" "}}{{method.name.camelCase()}}( + {%- for arg in method.arguments -%} + {%- if not loop.first %}, {% endif -%} + {%- if arg.annotation == "value" -%} + {{blinkType(arg.type)}} {{as_varName(arg.name)}} + {%- elif arg.annotation == "const*" and arg.length == "strlen" -%} + String {{as_varName(arg.name)}} + {%- else -%} + {%- if arg.type.category == "object" -%} + const HeapVector>& {{as_varName(arg.name)}} + {%- else -%} + const Vector<{{blinkType(arg.type)}}>& {{as_varName(arg.name)}} + {%- endif -%} + {%- endif -%} + {%- endfor -%} + ); + {% endfor %} + + {{as_cType(type.name)}} GetNXT(); + + {% if type.name.canonical_case() == "device" %} + {% for type in by_category["enum"] + by_category["bitmask"] %} + {% for value in type.values %} + static constexpr uint32_t k{{type.name.CamelCase()}}{{value.name.CamelCase()}} = 0x{{format(value.value, "08X")}}; + {% endfor %} + {% endfor %} + {% endif %} + + private: + {{as_cType(type.name)}} m_self = nullptr; + Member m_state; +}; + +} + +#endif // {{Class}}_H + diff --git a/generator/templates/blink/Object.idl b/generator/templates/blink/Object.idl new file mode 100644 index 0000000000..717ae1683f --- /dev/null +++ b/generator/templates/blink/Object.idl @@ -0,0 +1,55 @@ +//* Copyright 2017 The NXT Authors +//* +//* 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. + +typedef unsigned long uint32_t; + +{% macro idlType(type) -%} + {%- if type.category == "object" -%} + NXT{{type.name.CamelCase()}} + {%- elif type.category == "enum" or type.category == "bitmask" -%} + uint32_t + {%- else -%} + {{as_cType(type.name)}} + {%- endif -%} +{%- endmacro %} + +interface {{idlType(type)}} { + {% if type.name.canonical_case() == "device" %} + {% for type in by_category["enum"] + by_category["bitmask"] %} + {% for value in type.values %} + const uint32_t {{type.name.SNAKE_CASE()}}_{{value.name.SNAKE_CASE()}} = 0x{{format(value.value, "08X")}}; + {% endfor %} + {% endfor %} + {% endif %} + + {% for method in type.methods %} + {% if method.return_type.name.concatcase() == "void" %} + {{idlType(type)}} + {%- else %} + {{idlType(method.return_type)}} + {%- endif -%} + {{" "}}{{method.name.camelCase()}}( + {%- for arg in method.arguments -%} + {%- if not loop.first %}, {% endif -%} + {%- if arg.annotation == "value" -%} + {{idlType(arg.type)}} {{as_varName(arg.name)}} + {%- elif arg.annotation == "const*" and arg.length == "strlen" -%} + DOMString {{as_varName(arg.name)}} + {%- else -%} + {{idlType(arg.type)}}[] {{as_varName(arg.name)}} + {%- endif -%} + {%- endfor -%} + ); + {% endfor %} +}; diff --git a/generator/templates/blink/Objects.cpp b/generator/templates/blink/Objects.cpp new file mode 100644 index 0000000000..963551a15a --- /dev/null +++ b/generator/templates/blink/Objects.cpp @@ -0,0 +1,117 @@ +//* Copyright 2017 The NXT Authors +//* +//* 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. + +{% macro blinkType(type) -%} + {%- if type.category == "object" -%} + NXT{{type.name.CamelCase()}}* + {%- elif type.category == "enum" or type.category == "bitmask" -%} + uint32_t + {%- else -%} + {{as_cType(type.name)}} + {%- endif -%} +{%- endmacro %} + +{% for other_type in by_category["object"] %} + #include "NXT{{other_type.name.CamelCase()}}.h" +{% endfor %} + +#include "nxt/nxt.h" +#include "wtf/text/StringUTF8Adaptor.h" + +namespace blink { + + {% for type in by_category["object"] %} + {% set Class = "NXT" + type.name.CamelCase() %} + {{Class}}::{{Class}}({{as_cType(type.name)}} self, Member state) + : m_self(self), m_state(state) { + } + void {{Class}}::dispose() { + {% if type.name.canonical_case() != "device" %} + m_state->getProcTable()->{{as_varName(type.name, Name("release"))}}(m_self); + {% endif %} + } + + {% for method in type.methods %} + {% if method.return_type.name.concatcase() == "void" %} + {{Class}}* + {%- else %} + {{blinkType(method.return_type)}} + {%- endif -%} + {{" "}}{{Class}}::{{method.name.camelCase()}}( + {%- for arg in method.arguments -%} + {%- if not loop.first %}, {% endif -%} + {%- if arg.annotation == "value" -%} + {{blinkType(arg.type)}} {{as_varName(arg.name)}}_ + {%- elif arg.annotation == "const*" and arg.length == "strlen" -%} + String {{as_varName(arg.name)}}_ + {%- else -%} + {%- if arg.type.category == "object" -%} + const HeapVector>& {{as_varName(arg.name)}}_ + {%- else -%} + const Vector<{{blinkType(arg.type)}}>& {{as_varName(arg.name)}}_ + {%- endif -%} + {%- endif -%} + {%- endfor -%} + ) { + {% for arg in method.arguments %} + {% set argName = as_varName(arg.name) %} + {% set cType = as_cType(arg.type.name) %} + {% if arg.annotation == "value" %} + {% if arg.type.category == "object" %} + {{cType}} {{argName}} = {{argName}}_->GetNXT(); + {% else %} + {{cType}} {{argName}} = static_cast<{{cType}}>({{argName}}_); + {% endif %} + {% elif arg.annotation == "const*" %} + {% if arg.length == "strlen" %} + WTF::StringUTF8Adaptor {{argName}}Adaptor({{argName}}_); + std::string {{argName}}String({{argName}}Adaptor.data(), {{argName}}Adaptor.length()); + const char* {{argName}} = {{argName}}String.c_str(); + {% elif arg.type.category == "object" %} + //* TODO error on bad length + auto {{argName}}Array = std::unique_ptr<{{cType}}[]>(new {{cType}}[{{argName}}_.size()]); + for (size_t i = 0; i < {{argName}}_.size(); i++) { + {{argName}}Array[i] = {{argName}}_[i]->GetNXT(); + } + const {{cType}}* {{argName}} = &{{argName}}Array[0]; + {% else %} + //* TODO error on bad length + const {{cType}}* {{argName}} = {{argName}}_.data(); + {% endif %} + {% endif %} + {% endfor %} + + {% if method.return_type.name.concatcase() != "void" %} + auto result = + {%- endif %} + m_state->getProcTable()->{{as_varName(type.name, method.name)}}(m_self + {%- for arg in method.arguments -%} + , {{as_varName(arg.name)}} + {%- endfor -%} + ); + + {% if method.return_type.name.concatcase() == "void" %} + return this; + {% else %} + // TODO actually return the object given by the call to the procs + return new NXT{{method.return_type.name.CamelCase()}}(result, m_state); + {% endif %} + } + {% endfor %} + + {{as_cType(type.name)}} {{Class}}::GetNXT() { + return m_self; + } + {% endfor %} +} diff --git a/generator/templates/blink/api.idl b/generator/templates/blink/api.idl new file mode 100644 index 0000000000..9ed081ce53 --- /dev/null +++ b/generator/templates/blink/api.idl @@ -0,0 +1,53 @@ +//* Copyright 2017 The NXT Authors +//* +//* 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. + +typedef unsigned long uint32_t; + +{% macro idlType(type) -%} + {%- if type.category == "object" -%} + NXT{{type.name.CamelCase()}} + {%- else -%} + {{as_cType(type.name)}} + {%- endif -%} +{%- endmacro %} + +interface {{as_idlType(type.name)}} { + {% if type.name.canonical_case() == "device" %} + {% for type in by_category["enum"] + by_category["bitmask"] %} + {% for value in type.values %} + const uint32_t {{type.name.SNAKE_CASE()}}_{{value.name.SNAKE_CASE()}} = 0x{{format(value.value, "08X")}}; + {% endfor %} + {% endfor %} + {% endif %} + + {% for method in type.methods %} + {% if method.return_type.name.concatcase() == "void" %} + {{as_idlType(type.name)}} + {%- else %} + {{as_idlType(method.return_type.name)}} + {%- endif -%} + {{" "}}{{method.name.camelCase()}}( + {%- for arg in method.arguments -%} + {%- if not loop.first %}, {% endif -%} + {%- if arg.annotation == "value" -%} + {{as_idlType(arg.type.name)}} {{as_varName(arg.name)}} + {%- elif arg.annotation == "const*" and arg.length == "strlen" -%} + String {{as_varName(arg.name)}} + {%- else -%} + {{as_idlType(arg.type.name)}}[] {{as_varName(arg.name)}} + {%- endif -%} + {%- endfor -%} + ); + {% endfor %} +}; diff --git a/generator/templates/blink/autogen.gni b/generator/templates/blink/autogen.gni new file mode 100644 index 0000000000..bbcf6555d9 --- /dev/null +++ b/generator/templates/blink/autogen.gni @@ -0,0 +1,27 @@ +//* Copyright 2017 The NXT Authors +//* +//* 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. + +autogen_nxt_sources = [ + "gen/NXT.cpp", + "gen/Forward.h", + {% for type in by_category["object"] %} + "gen/NXT{{type.name.CamelCase()}}.h", + {% endfor %} +] + +autogen_nxt_idl = [ + {% for type in by_category["object"] %} + "nxt/gen/NXT{{type.name.CamelCase()}}.idl", + {% endfor %} +] diff --git a/generator/templates/mock_api.cpp b/generator/templates/mock_api.cpp new file mode 100644 index 0000000000..df1bd3eb4f --- /dev/null +++ b/generator/templates/mock_api.cpp @@ -0,0 +1,60 @@ +//* Copyright 2017 The NXT Authors +//* +//* 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. + +#include "mock_nxt.h" + +namespace { + {% for type in by_category["object"] %} + {% for method in native_methods(type) %} + {{as_cType(method.return_type.name)}} Forward{{as_MethodSuffix(type.name, method.name)}}( + {{-as_cType(type.name)}} self + {%- for arg in method.arguments -%} + , {{as_annotated_cType(arg)}} + {%- endfor -%} + ) { + auto tablePtr = reinterpret_cast(self); + return (*tablePtr)->{{as_MethodSuffix(type.name, method.name)}}(self + {%- for arg in method.arguments -%} + , {{as_varName(arg.name)}} + {%- endfor -%} + ); + } + {% endfor %} + + {% endfor %} +} + +ProcTableAsClass::~ProcTableAsClass() { + for (auto ptr : selfPtrs) { + delete ptr; + } +} + +void ProcTableAsClass::GetProcTableAndDevice(nxtProcTable* table, nxtDevice* device) { + *device = GetNewDevice(); + + {% for type in by_category["object"] %} + {% for method in native_methods(type) %} + table->{{as_varName(type.name, method.name)}} = reinterpret_cast<{{as_cProc(type.name, method.name)}}>(Forward{{as_MethodSuffix(type.name, method.name)}}); + {% endfor %} + {% endfor %} +} + +{% for type in by_category["object"] %} + {{as_cType(type.name)}} ProcTableAsClass::GetNew{{type.name.CamelCase()}}() { + auto self = new ProcTableAsClass*(this); + selfPtrs.push_back(self); + return reinterpret_cast<{{as_cType(type.name)}}>(self); + } +{% endfor %} diff --git a/generator/templates/mock_api.h b/generator/templates/mock_api.h new file mode 100644 index 0000000000..79e66bd831 --- /dev/null +++ b/generator/templates/mock_api.h @@ -0,0 +1,64 @@ +//* Copyright 2017 The NXT Authors +//* +//* 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. + +#ifndef MOCK_NXT_H +#define MOCK_NXT_H + +#include +#include + +class ProcTableAsClass { + public: + virtual ~ProcTableAsClass(); + + void GetProcTableAndDevice(nxtProcTable* table, nxtDevice* device); + + {% for type in by_category["object"] %} + {{as_cType(type.name)}} GetNew{{type.name.CamelCase()}}(); + {% endfor %} + + {% for type in by_category["object"] %} + {% for method in native_methods(type) %} + virtual {{as_cType(method.return_type.name)}} {{as_MethodSuffix(type.name, method.name)}}( + {{-as_cType(type.name)}} {{as_varName(type.name)}} + {%- for arg in method.arguments -%} + , {{as_annotated_cType(arg)}} + {%- endfor -%} + ) = 0; + {% endfor %} + + {% endfor %} + + private: + std::vector selfPtrs; +}; + +class MockProcTable : public ProcTableAsClass { + public: + {% for type in by_category["object"] %} + {% for method in native_methods(type) %} + MOCK_METHOD{{len(method.arguments) + 1}}( + {{-as_MethodSuffix(type.name, method.name)}}, + {{as_cType(method.return_type.name)}}( + {{-as_cType(type.name)}} {{as_varName(type.name)}} + {%- for arg in method.arguments -%} + , {{as_annotated_cType(arg)}} + {%- endfor -%} + )); + {% endfor %} + + {% endfor %} +}; + +#endif // MOCK_NXT_H diff --git a/generator/templates/wire/WireClient.cpp b/generator/templates/wire/WireClient.cpp new file mode 100644 index 0000000000..dabda12c7b --- /dev/null +++ b/generator/templates/wire/WireClient.cpp @@ -0,0 +1,221 @@ +//* Copyright 2017 The NXT Authors +//* +//* 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. + +#include "Wire.h" +#include "WireCmd.h" + +#include +#include + +namespace nxt { +namespace wire { + + //* Client side implementation of the API, will serialize everything to memory to send to the server side. + namespace client { + + class Device; + + //* All non-Device objects of the client side have: + //* - A pointer to the device to get where to serialize commands + //* - The external reference count + //* - An ID that is used to refer to this object when talking with the server side + struct ObjectBase { + ObjectBase(Device* device, uint32_t refcount, uint32_t id) + :device(device), refcount(refcount), id(id) { + } + + Device* device; + uint32_t refcount; + uint32_t id; + }; + + {% for type in by_category["object"] if not type.name.canonical_case() == "device" %} + struct {{type.name.CamelCase()}} : ObjectBase { + using ObjectBase::ObjectBase; + }; + {% endfor %} + + //* TODO: Remember objects so they can all be destroyed at device destruction. + template + class ObjectAllocator { + public: + ObjectAllocator(Device* device) : device(device) { + } + + T* New() { + return new T(device, 1, GetNewId()); + } + void Free(T* obj) { + FreeId(obj->id); + delete obj; + } + + private: + uint32_t GetNewId() { + if (freeIds.empty()) { + return currentId ++; + } + uint32_t id = freeIds.back(); + freeIds.pop_back(); + return id; + } + void FreeId(uint32_t id) { + freeIds.push_back(id); + }; + + // 0 is an ID reserved to represent nullptr + uint32_t currentId = 1; + std::vector freeIds; + Device* device; + }; + + //* The client wire uses the global NXT device to store its global data such as the serializer + //* and the object id allocators. + class Device : public ObjectBase { + public: + Device(CommandSerializer* serializer) + : ObjectBase(this, 1, 1), + {% for type in by_category["object"] if not type.name.canonical_case() == "device" %} + {{type.name.camelCase()}}(this), + {% endfor %} + serializer(serializer) { + } + + void* GetCmdSpace(size_t size) { + return serializer->GetCmdSpace(size); + } + + {% for type in by_category["object"] if not type.name.canonical_case() == "device" %} + ObjectAllocator<{{type.name.CamelCase()}}> {{type.name.camelCase()}}; + {% endfor %} + + private: + CommandSerializer* serializer = nullptr; + }; + + //* Implementation of the client API functions. + {% for type in by_category["object"] %} + {% set Type = type.name.CamelCase() %} + + {% for method in type.methods %} + {% set Suffix = as_MethodSuffix(type.name, method.name) %} + + {{as_backendType(method.return_type)}} Client{{Suffix}}( + {{-as_backendType(type)}} self + {%- for arg in method.arguments -%} + , {{as_annotated_backendType(arg)}} + {%- endfor -%} + ) { + Device* device = self->device; + wire::{{Suffix}}Cmd cmd; + + //* Create the structure going on the wire on the stack and fill it with the value + //* arguments so it can compute its size. + { + //* Value objects are stored as IDs + {% for arg in method.arguments if arg.annotation == "value" %} + {% if arg.type.category == "object" %} + cmd.{{as_varName(arg.name)}} = {{as_varName(arg.name)}}->id; + {% else %} + cmd.{{as_varName(arg.name)}} = {{as_varName(arg.name)}}; + {% endif %} + {% endfor %} + + cmd.self = self->id; + + //* The length of const char* is considered a value argument. + {% for arg in method.arguments if arg.length == "strlen" %} + cmd.{{as_varName(arg.name)}}Strlen = strlen({{as_varName(arg.name)}}); + {% endfor %} + } + + //* Allocate space to send the command and copy the value args over. + size_t requiredSize = cmd.GetRequiredSize(); + auto allocCmd = reinterpret_cast(device->GetCmdSpace(requiredSize)); + *allocCmd = cmd; + + //* In the allocated space, write the non-value arguments. + {% for arg in method.arguments if arg.annotation != "value" %} + {% set argName = as_varName(arg.name) %} + {% if arg.length == "strlen" %} + memcpy(allocCmd->GetPtr_{{argName}}(), {{argName}}, allocCmd->{{argName}}Strlen + 1); + {% elif arg.type.category == "object" %} + auto {{argName}}Storage = reinterpret_cast(allocCmd->GetPtr_{{argName}}()); + for (size_t i = 0; i < {{as_varName(arg.length.name)}}; i++) { + {{argName}}Storage[i] = {{argName}}[i]->id; + } + {% else %} + memcpy(allocCmd->GetPtr_{{argName}}(), {{argName}}, {{as_varName(arg.length.name)}} * sizeof(*{{argName}})); + {% endif %} + {% endfor %} + + //* For object creation, store the object ID the client will use for the result. + {% if method.return_type.category == "object" %} + auto result = self->device->{{method.return_type.name.camelCase()}}.New(); + allocCmd->resultId = result->id; + return result; + {% endif %} + } + {% endfor %} + + {% if not type.name.canonical_case() == "device" %} + //* When an object's refcount reaches 0, notify the server side of it and delete it. + void Client{{as_MethodSuffix(type.name, Name("release"))}}({{Type}}* obj) { + obj->refcount --; + + if (obj->refcount > 0) { + return; + } + + wire::{{as_MethodSuffix(type.name, Name("destroy"))}}Cmd cmd; + cmd.objectId = obj->id; + + size_t requiredSize = cmd.GetRequiredSize(); + auto allocCmd = reinterpret_cast(obj->device->GetCmdSpace(requiredSize)); + *allocCmd = cmd; + + obj->device->{{type.name.camelCase()}}.Free(obj); + } + + void Client{{as_MethodSuffix(type.name, Name("reference"))}}({{Type}}* obj) { + obj->refcount ++; + } + {% endif %} + {% endfor %} + + void ClientDeviceReference(Device* self) { + } + + void ClientDeviceRelease(Device* self) { + } + + nxtProcTable GetProcs() { + nxtProcTable table; + {% for type in by_category["object"] %} + {% for method in native_methods(type) %} + table.{{as_varName(type.name, method.name)}} = reinterpret_cast<{{as_cProc(type.name, method.name)}}>(Client{{as_MethodSuffix(type.name, method.name)}}); + {% endfor %} + {% endfor %} + return table; + } + + } + + void NewClientDevice(nxtProcTable* procs, nxtDevice* device, CommandSerializer* serializer) { + *device = reinterpret_cast(new client::Device(serializer)); + *procs = client::GetProcs(); + } + +} +} diff --git a/generator/templates/wire/WireCmd.cpp b/generator/templates/wire/WireCmd.cpp new file mode 100644 index 0000000000..87b38f939f --- /dev/null +++ b/generator/templates/wire/WireCmd.cpp @@ -0,0 +1,75 @@ +//* Copyright 2017 The NXT Authors +//* +//* 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. + +#include "wire/WireCmd_autogen.h" + +namespace nxt { +namespace wire { + + {% for type in by_category["object"] %} + {% for method in type.methods %} + {% set Suffix = as_MethodSuffix(type.name, method.name) %} + + size_t {{Suffix}}Cmd::GetRequiredSize() const { + size_t result = sizeof(*this); + + {% for arg in method.arguments if arg.annotation != "value" %} + {% if arg.length == "strlen" %} + result += {{as_varName(arg.name)}}Strlen + 1; + {% elif arg.type.category == "object" %} + result += {{as_varName(arg.length.name)}} * sizeof(uint32_t); + {% else %} + result += {{as_varName(arg.length.name)}} * sizeof({{as_cType(arg.type.name)}}); + {% endif %} + {% endfor %} + + return result; + } + + {% for const in ["", "const"] %} + {% for get_arg in method.arguments if get_arg.annotation != "value" %} + + {{const}} uint8_t* {{Suffix}}Cmd::GetPtr_{{as_varName(get_arg.name)}}() {{const}} { + //* Start counting after the current structure + {{const}} uint8_t* ptr = reinterpret_cast<{{const}} uint8_t*>(this + 1); + + //* Increment the pointer until we find the 'arg' then return early. + //* This will mean some of the code will be unreachable but there is no + //* "break" in Jinja2. + {% for arg in method.arguments if arg.annotation != "value" %} + {% if get_arg == arg %} + return ptr; + {% endif %} + {% if arg.length == "strlen" %} + ptr += {{as_varName(arg.name)}}Strlen + 1; + {% elif arg.type.category == "object" %} + ptr += {{as_varName(arg.length.name)}} * sizeof(uint32_t); + {% else %} + ptr += {{as_varName(arg.length.name)}} * sizeof({{as_cType(arg.type.name)}}); + {% endif %} + {% endfor %} + } + + {% endfor %} + {% endfor %} + {% endfor %} + + {% set Suffix = as_MethodSuffix(type.name, Name("destroy")) %} + size_t {{Suffix}}Cmd::GetRequiredSize() const { + return sizeof(*this); + } + {% endfor %} + +} +} diff --git a/generator/templates/wire/WireCmd.h b/generator/templates/wire/WireCmd.h new file mode 100644 index 0000000000..a71e7e50e7 --- /dev/null +++ b/generator/templates/wire/WireCmd.h @@ -0,0 +1,96 @@ +//* Copyright 2017 The NXT Authors +//* +//* 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. + +#ifndef WIRE_WIRECMD_AUTOGEN_H_ +#define WIRE_WIRECMD_AUTOGEN_H_ + +#include + +namespace nxt { +namespace wire { + + //* Enum used as a prefix to each command on the wire format. + enum class WireCmd : uint32_t { + {% for type in by_category["object"] %} + {% for method in type.methods %} + {{as_MethodSuffix(type.name, method.name)}}, + {% endfor %} + {{as_MethodSuffix(type.name, Name("destroy"))}}, + {% endfor %} + }; + + {% for type in by_category["object"] %} + {% for method in type.methods %} + {% set Suffix = as_MethodSuffix(type.name, method.name) %} + + //* Structure for the wire format of each of the commands. Parameters passed by value + //* are embedded directly in the structure. Other parameters are assumed to be in the + //* memory directly following the structure in the buffer. With value parameters the + //* structure can compute how much buffer size it needs and where the start of non-value + //* parameters is in the buffer. + struct {{Suffix}}Cmd { + + //* Start the structure with the command ID, so that casting to WireCmd gives the ID. + wire::WireCmd commandId = wire::WireCmd::{{Suffix}}; + + uint32_t self; + + //* Commands creating objects say which ID the created object will be referred as. + {% if method.return_type.category == "object" %} + uint32_t resultId; + {% endif %} + + //* Value types are directly in the command, objects being replaced with their IDs. + {% for arg in method.arguments if arg.annotation == "value" %} + {% if arg.type.category == "object" %} + uint32_t {{as_varName(arg.name)}}; + {% else %} + {{as_cType(arg.type.name)}} {{as_varName(arg.name)}}; + {% endif %} + {% endfor %} + + //* const char* have their length embedded directly in the command. + {% for arg in method.arguments if arg.length == "strlen" %} + size_t {{as_varName(arg.name)}}Strlen; + {% endfor %} + + //* The following commands do computation, provided the members for value parameters + //* have been initialized. + + //* Compute how much buffer memory is required to hold the structure and all its arguments. + size_t GetRequiredSize() const; + + //* Gets the pointer to the start of the buffer containing a non-value parameter. + {% for get_arg in method.arguments if get_arg.annotation != "value" %} + {% set ArgName = as_varName(get_arg.name) %} + uint8_t* GetPtr_{{ArgName}}(); + const uint8_t* GetPtr_{{ArgName}}() const; + {% endfor %} + }; + {% endfor %} + + //* The command structure used when sending that an ID is destroyed. + {% set Suffix = as_MethodSuffix(type.name, Name("destroy")) %} + struct {{Suffix}}Cmd { + wire::WireCmd commandId = wire::WireCmd::{{Suffix}}; + uint32_t objectId; + + size_t GetRequiredSize() const; + }; + {% endfor %} + +} +} + +#endif // WIRE_WIRECMD_AUTOGEN_H_ diff --git a/generator/templates/wire/WireServer.cpp b/generator/templates/wire/WireServer.cpp new file mode 100644 index 0000000000..63eaa62a58 --- /dev/null +++ b/generator/templates/wire/WireServer.cpp @@ -0,0 +1,343 @@ +//* Copyright 2017 The NXT Authors +//* +//* 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. + +#include "Wire.h" +#include "WireCmd.h" + +#include +#include + +namespace nxt { +namespace wire { + + namespace server { + //* Stores what the backend knows about the type. + template + struct ObjectDataBase { + //* The backend-provided handle to this object. + T handle; + //* Used by the error-propagation mechanism to know if this object is an error. + //* TODO(cwallez@chromium.org): this is doubling the memory usae of + //* std::vector consider making it a special marker value in handle instead. + bool valid; + //* Whether this object has been allocated, used by the KnownObjects queries + //* TODO(cwallez@chromium.org): make this an internal bit vector in KnownObjects. + bool allocated; + }; + + //* Keeps track of the mapping between client IDs and backend objects. + template + class KnownObjects { + public: + using Data = ObjectDataBase; + + KnownObjects() { + //* Pre-allocate ID 0 to refer to the null handle. + Data nullObject; + nullObject.handle = nullptr; + nullObject.valid = true; + nullObject.allocated = true; + known.push_back(nullObject); + } + + //* Get a backend objects for a given client ID. + //* Returns nullptr if the ID hasn't previously been allocated. + Data* Get(uint32_t id) { + if (id >= known.size()) { + return nullptr; + } + + Data* data = &known[id]; + + if (!data->allocated) { + return nullptr; + } + + return data; + } + + //* Allocates the data for a given ID and returns it. + //* Returns nullptr if the ID is already allocated, or too far ahead. + //* Invalidates all the Data* + Data* Allocate(uint32_t id) { + if (id > known.size()) { + return nullptr; + } + + Data data; + data.allocated = true; + data.valid = false; + data.handle = nullptr; + + if (id >= known.size()) { + known.push_back(data); + return &known.back(); + } + + if (known[id].allocated) { + return nullptr; + } + + known[id] = data; + return &known[id]; + } + + //* Marks an ID as deallocated + void Free(uint32_t id) { + assert(id < known.size()); + known[id].allocated = false; + } + + private: + std::vector known; + }; + + class Server : public CommandHandler { + public: + Server(nxtDevice device, const nxtProcTable& procs) : procs(procs) { + //* The client-server knowledge is bootstrapped with device 1. + auto* deviceData = knownDevice.Allocate(1); + deviceData->handle = device; + deviceData->valid = true; + } + + const uint8_t* HandleCommands(const uint8_t* commands, size_t size) override { + while (size > sizeof(WireCmd)) { + WireCmd cmdId = *reinterpret_cast(commands); + + bool success = false; + switch (cmdId) { + {% for type in by_category["object"] %} + {% for method in type.methods %} + {% set Suffix = as_MethodSuffix(type.name, method.name) %} + case WireCmd::{{Suffix}}: + success = Handle{{Suffix}}(&commands, &size); + break; + {% endfor %} + {% set Suffix = as_MethodSuffix(type.name, Name("destroy")) %} + case WireCmd::{{Suffix}}: + success = Handle{{Suffix}}(&commands, &size); + break; + {% endfor %} + + default: + success = false; + } + + if (!success) { + return nullptr; + } + } + + if (size != 0) { + return nullptr; + } + + return commands; + } + + void OnSynchronousError() override { + gotError = true; + } + + private: + nxtProcTable procs; + bool gotError = false; + + //* The list of known IDs for each object type. + {% for type in by_category["object"] %} + KnownObjects<{{as_cType(type.name)}}> known{{type.name.CamelCase()}}; + {% endfor %} + + //* Helper function for the getting of the command data in command handlers. + //* Checks there is enough data left, updates the buffer / size and returns + //* the command (or nullptr for an error). + template + const T* GetCommand(const uint8_t** commands, size_t* size) { + if (*size < sizeof(T)) { + return nullptr; + } + + const T* cmd = reinterpret_cast(*commands); + + size_t cmdSize = cmd->GetRequiredSize(); + if (*size < cmdSize) { + return nullptr; + } + + *commands += cmdSize; + *size -= cmdSize; + + return cmd; + } + + //* Implementation of the command handlers + {% for type in by_category["object"] %} + {% for method in type.methods %} + {% set Suffix = as_MethodSuffix(type.name, method.name) %} + + //* The generic command handlers + + bool Handle{{Suffix}}(const uint8_t** commands, size_t* size) { + //* Get command ptr, and check it fits in the buffer. + const auto* cmd = GetCommand<{{Suffix}}Cmd>(commands, size); + if (cmd == nullptr) { + return false; + } + + //* While unpacking arguments, if any of them is an error, valid will be set to false. + bool valid = true; + + //* Unpack 'self' + {% set Type = type.name.CamelCase() %} + {{as_cType(type.name)}} self; + auto* selfData = known{{Type}}.Get(cmd->self); + { + if (selfData == nullptr) { + return false; + } + valid = valid && selfData->valid; + self = selfData->handle; + } + + //* Unpack value objects from IDs. + {% for arg in method.arguments if arg.annotation == "value" and arg.type.category == "object" %} + {% set Type = arg.type.name.CamelCase() %} + {{as_cType(arg.type.name)}} arg_{{as_varName(arg.name)}}; + { + auto* data = known{{Type}}.Get(cmd->{{as_varName(arg.name)}}); + if (data == nullptr) { + return false; + } + valid = valid && data->valid; + arg_{{as_varName(arg.name)}} = data->handle; + } + {% endfor %} + + //* Unpack pointer arguments + {% for arg in method.arguments if arg.annotation != "value" %} + {% set argName = as_varName(arg.name) %} + const {{as_cType(arg.type.name)}}* arg_{{argName}}; + {% if arg.length == "strlen" %} + //* Unpack strings, checking they are null-terminated. + arg_{{argName}} = reinterpret_cast(cmd->GetPtr_{{argName}}()); + if (arg_{{argName}}[cmd->{{argName}}Strlen] != 0) { + return false; + } + {% elif arg.type.category == "object" %} + //* Unpack arrays of objects. + //* TODO(cwallez@chromium.org) do not allocate when there are few objects. + std::vector<{{as_cType(arg.type.name)}}> {{argName}}Storage(cmd->{{as_varName(arg.length.name)}}); + auto {{argName}}Ids = reinterpret_cast(cmd->GetPtr_{{argName}}()); + for (size_t i = 0; i < cmd->{{as_varName(arg.length.name)}}; i++) { + {% set Type = arg.type.name.CamelCase() %} + auto* data = known{{Type}}.Get({{argName}}Ids[i]); + if (data == nullptr) { + return false; + } + {{argName}}Storage[i] = data->handle; + valid = valid && data->valid; + } + arg_{{argName}} = {{argName}}Storage.data(); + {% else %} + //* For anything else, just get the pointer. + arg_{{argName}} = reinterpret_cast(cmd->GetPtr_{{argName}}()); + {% endif %} + {% endfor %} + + //* At that point all the data has been upacked in cmd->* or arg_* + + //* In all cases allocate the object data as it will be refered-to by the client. + {% set returns = method.return_type.name.canonical_case() != "void" %} + {% if returns %} + {% set Type = method.return_type.name.CamelCase() %} + auto* resultData = known{{Type}}.Allocate(cmd->resultId); + if (resultData == nullptr) { + return false; + } + {% endif %} + + //* After the data is allocated, apply the argument error propagation mechanism + if (!valid) { + return true; + } + + {% if returns -%} + auto result = + {%- endif -%} + procs.{{as_varName(type.name, method.name)}}(self + {%- for arg in method.arguments -%} + {% if arg.annotation == "value" and arg.type.category != "object" %} + , cmd->{{as_varName(arg.name)}} + {% else %} + , arg_{{as_varName(arg.name)}} + {% endif %} + {%- endfor -%} + ); + + {% if returns %} + resultData->handle = result; + resultData->valid = result != nullptr; + {% endif %} + + if (gotError) { + {% if type.is_builder %} + //* Get the data again, has been invalidated by the call to + //* known.Allocate + known{{type.name.CamelCase()}}.Get(cmd->self)->valid = false; + {% endif %} + gotError = false; + } + + return true; + } + {% endfor %} + + //* Handlers for the destruction of objects: clients do the tracking of the + //* reference / release and only send destroy on refcount = 0. + {% set Suffix = as_MethodSuffix(type.name, Name("destroy")) %} + bool Handle{{Suffix}}(const uint8_t** commands, size_t* size) { + const auto* cmd = GetCommand<{{Suffix}}Cmd>(commands, size); + if (cmd == nullptr) { + return false; + } + + //* ID 0 are reserved for nullptr and cannot be destroyed. + if (cmd->objectId == 0) { + return false; + } + + auto* data = known{{type.name.CamelCase()}}.Get(cmd->objectId); + if (data == nullptr) { + return false; + } + + if (data->valid) { + procs.{{as_varName(type.name, Name("release"))}}(data->handle); + } + + known{{type.name.CamelCase()}}.Free(cmd->objectId); + return true; + } + {% endfor %} + }; + + } + + CommandHandler* CreateCommandHandler(nxtDevice device, const nxtProcTable& procs) { + return new server::Server(device, procs); + } + +} +} diff --git a/next.json b/next.json new file mode 100644 index 0000000000..75b15d0e27 --- /dev/null +++ b/next.json @@ -0,0 +1,670 @@ +{ + "_comment": [ + "Copyright 2017 The NXT Authors", + "", + "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." + ], + "bind group": { + "category": "object" + }, + "bind group builder": { + "category": "object", + "methods": [ + { + "name": "get result", + "returns": "bind group" + }, + { + "name": "set layout", + "args": [ + {"name": "layout", "type": "bind group layout"} + ] + }, + { + "name": "set usage", + "args": [ + {"name": "usage", "type": "bind group usage"} + ] + }, + { + "name": "set buffer views", + "args": [ + {"name": "start", "type": "uint32_t"}, + {"name": "count", "type": "uint32_t"}, + {"name": "buffer views", "type": "buffer view", "annotation": "const*", "length": "count"} + ] + }, + { + "name": "set samplers", + "args": [ + {"name": "start", "type": "uint32_t"}, + {"name": "count", "type": "uint32_t"}, + {"name": "samplers", "type": "sampler", "annotation": "const*", "length": "count"} + ] + }, + { + "name": "set texture views", + "args": [ + {"name": "start", "type": "uint32_t"}, + {"name": "count", "type": "uint32_t"}, + {"name": "texture views", "type": "texture view", "annotation": "const*", "length": "count"} + ] + } + ], + "TODO": [ + "When resource are added, add methods for setting the content of the bind group" + ] + }, + "bind group usage": { + "category": "enum", + "values": [ + {"value": 0, "name": "frozen"}, + {"value": 1, "name": "dynamic"} + ] + }, + "bind group layout": { + "category": "object" + }, + "bind group layout builder": { + "category": "object", + "methods": [ + { + "name": "get result", + "returns": "bind group layout" + }, + { + "name": "set bindings type", + "args": [ + {"name": "visibility", "type": "shader stage bit"}, + {"name": "binding type", "type": "binding type"}, + {"name": "start", "type": "uint32_t"}, + {"name": "count", "type": "uint32_t"} + ] + } + ] + }, + "binding type": { + "category": "enum", + "values": [ + {"value": 0, "name": "uniform buffer"}, + {"value": 1, "name": "sampler"}, + {"value": 2, "name": "sampled texture"}, + {"value": 3, "name": "storage buffer"} + ] + }, + "buffer": { + "category": "object", + "methods": [ + { + "name": "create buffer view builder", + "returns": "buffer view builder" + }, + { + "name": "set sub data", + "args": [ + {"name": "start", "type": "uint32_t"}, + {"name": "count", "type": "uint32_t"}, + {"name": "data", "type": "uint32_t", "annotation": "const*", "length": "count"} + ] + }, + { + "name": "transition usage", + "args": [ + {"name": "usage", "type": "buffer usage bit"} + ] + }, + { + "name": "freeze usage", + "args": [ + {"name": "usage", "type": "buffer usage bit"} + ] + } + ] + }, + "buffer builder": { + "category": "object", + "methods": [ + { + "name": "get result", + "returns": "buffer" + }, + { + "name": "set allowed usage", + "args": [ + {"name": "usage", "type": "buffer usage bit"} + ] + }, + { + "name": "set initial usage", + "args": [ + {"name": "usage", "type": "buffer usage bit"} + ] + }, + { + "name": "set size", + "args": [ + {"name": "size", "type": "uint32_t"} + ] + } + ] + }, + "buffer usage bit": { + "category": "bitmask", + "values": [ + {"value": 0, "name": "none"}, + {"value": 1, "name": "mapped"}, + {"value": 2, "name": "transfer src"}, + {"value": 4, "name": "transfer dst"}, + {"value": 8, "name": "index"}, + {"value": 16, "name": "vertex"}, + {"value": 32, "name": "uniform"}, + {"value": 64, "name": "storage"} + ] + }, + "buffer view": { + "category": "object" + }, + "buffer view builder": { + "category": "object", + "methods": [ + { + "name": "get result", + "returns": "buffer view" + }, + { + "name": "set extent", + "args": [ + {"name": "offset", "type": "uint32_t"}, + {"name": "size", "type": "uint32_t"} + ] + } + ] + }, + "char": { + "category": "native" + }, + "command buffer": { + "category": "object" + }, + "command buffer builder": { + "category": "object", + "methods": [ + { + "name": "get result", + "returns": "command buffer" + }, + { + "name": "copy buffer to texture", + "args": [ + {"name": "buffer", "type": "buffer"}, + {"name": "texture", "type": "texture"}, + {"name": "x", "type": "uint32_t"}, + {"name": "y", "type": "uint32_t"}, + {"name": "z", "type": "uint32_t"}, + {"name": "width", "type": "uint32_t"}, + {"name": "height", "type": "uint32_t"}, + {"name": "depth", "type": "uint32_t"}, + {"name": "level", "type": "uint32_t"} + ], + "TODO": [ + "Make pretty with Offset and Extents structures", + "Allow choosing the aspect (depth vs. stencil)?", + "The following where removed because gmock supports only 10 arguments", + "this means the buffer is assumed to be packed and starting at 0.", + {"name": "row length", "type": "uint32_t"}, + {"name": "image height", "type": "uint32_t"}, + {"name": "buffer offset", "type": "uint32_t"} + ] + }, + { + "name": "dispatch", + "args": [ + {"name": "x", "type": "uint32_t"}, + {"name": "y", "type": "uint32_t"}, + {"name": "z", "type": "uint32_t"} + ] + }, + { + "name": "draw arrays", + "args": [ + {"name": "vertex count", "type": "uint32_t"}, + {"name": "instance count", "type": "uint32_t"}, + {"name": "first vertex", "type": "uint32_t"}, + {"name": "first instance", "type": "uint32_t"} + ] + }, + { + "name": "draw elements", + "args": [ + {"name": "index count", "type": "uint32_t"}, + {"name": "instance count", "type": "uint32_t"}, + {"name": "first index", "type": "uint32_t"}, + {"name": "first instance", "type": "uint32_t"} + ] + }, + { + "name": "set bind group", + "args": [ + {"name": "group index", "type": "uint32_t"}, + {"name": "group", "type": "bind group"} + ] + }, + { + "name": "set index buffer", + "args": [ + {"name": "buffer", "type": "buffer"}, + {"name": "offset", "type": "uint32_t"}, + {"name": "format", "type": "index format"} + ] + }, + { + "name": "set push constants", + "TODO": [ + "data should be void*", + "TODO Vulkan has an additional stage mask" + ], + "args": [ + {"name": "stage", "type": "shader stage bit"}, + {"name": "offset", "type": "uint32_t"}, + {"name": "count", "type": "uint32_t"}, + {"name": "data", "type": "uint32_t", "annotation": "const*", "length": "count"} + ] + }, + { + "name": "set pipeline", + "args": [ + {"name": "pipeline", "type": "pipeline"} + ], + "notes": [ + "Not specifying graphics or compute because we know from render pass" + ] + }, + { + "name": "set vertex buffers", + "args": [ + {"name": "start slot", "type": "uint32_t"}, + {"name": "count", "type": "uint32_t"}, + {"name": "buffers", "type": "buffer", "annotation": "const*", "length": "count"}, + {"name": "offsets", "type": "uint32_t", "annotation": "const*", "length": "count"} + ] + }, + { + "name": "transition buffer usage", + "args": [ + {"name": "buffer", "type": "buffer"}, + {"name": "usage", "type": "buffer usage bit"} + ] + }, + { + "name": "transition texture usage", + "args": [ + {"name": "texture", "type": "texture"}, + {"name": "usage", "type": "texture usage bit"} + ] + } + ] + }, + "device": { + "category": "object", + "methods": [ + { + "name": "create bind group builder", + "returns": "bind group builder" + }, + { + "name": "create bind group layout builder", + "returns": "bind group layout builder" + }, + { + "name": "create buffer builder", + "returns": "buffer builder" + }, + { + "name": "create command buffer builder", + "returns": "command buffer builder" + }, + { + "name": "create input state builder", + "returns": "input state builder" + }, + { + "name": "create pipeline builder", + "returns": "pipeline builder" + }, + { + "name": "create pipeline layout builder", + "returns": "pipeline layout builder" + }, + { + "name": "create queue builder", + "returns": "queue builder" + }, + { + "name": "create sampler builder", + "returns": "sampler builder" + }, + { + "name": "create shader module builder", + "returns": "shader module builder" + }, + { + "name": "create texture builder", + "returns": "texture builder" + }, + { + "name": "copy bind groups", + "args": [ + {"name": "start", "type": "uint32_t"}, + {"name": "count", "type": "uint32_t"}, + {"name": "source", "type": "bind group"}, + {"name": "target", "type": "bind group"} + ] + } + ] + }, + "filter mode": { + "category": "enum", + "values": [ + {"value": 0, "name":"nearest"}, + {"value": 1, "name":"linear"} + ] + }, + "index format": { + "category": "enum", + "values": [ + {"value": 0, "name": "uint16"}, + {"value": 1, "name": "uint32"} + ] + }, + "input state": { + "category": "object" + }, + "input state builder": { + "category": "object", + "methods": [ + { + "name": "get result", + "returns": "input state" + }, + { + "name": "set attribute", + "args": [ + {"name": "shader location", "type": "uint32_t"}, + {"name": "binding slot", "type": "uint32_t"}, + {"name": "format", "type": "vertex format"}, + {"name": "offset", "type": "uint32_t"} + ] + }, + { + "name": "set input", + "args": [ + {"name": "binding slot", "type": "uint32_t"}, + {"name": "stride", "type": "uint32_t"}, + {"name": "step mode", "type": "input step mode"} + ] + } + ] + }, + "input step mode": { + "category": "enum", + "values": [ + {"value": 0, "name": "vertex"}, + {"value": 1, "name": "instance"} + ] + }, + "pipeline": { + "category": "object" + }, + "pipeline builder": { + "category": "object", + "methods": [ + { + "name": "get result", + "returns": "pipeline" + }, + { + "name": "set layout", + "args": [ + {"name": "layout", "type": "pipeline layout"} + ] + }, + { + "name": "set stage", + "args": [ + {"name": "stage", "type": "shader stage"}, + {"name": "module", "type": "shader module"}, + {"name": "entry point", "type": "char", "annotation": "const*", "length": "strlen"} + ] + }, + { + "name": "set input state", + "args": [ + {"name": "input", "type": "input state"} + ] + } + ] + }, + "pipeline layout": { + "category": "object" + }, + "pipeline layout builder": { + "category": "object", + "methods": [ + { + "name": "get result", + "returns": "pipeline layout" + }, + { + "name": "set bind group layout", + "args": [ + {"name": "group index", "type": "uint32_t"}, + {"name": "layout", "type": "bind group layout"} + ] + } + ] + }, + "queue": { + "category": "object", + "methods": [ + { + "name": "submit", + "args": [ + {"name": "num commands", "type": "uint32_t"}, + {"name": "commands", "type": "command buffer", "annotation": "const*", "length": "num commands"} + ] + } + ] + }, + "queue builder": { + "category": "object", + "methods": [ + { + "name": "get result", + "returns": "queue" + } + ] + }, + "sampler": { + "category": "object" + }, + "sampler builder": { + "category": "object", + "methods": [ + { + "name": "get result", + "returns": "sampler" + }, + { + "name": "set filter mode", + "args": [ + {"name": "mag filter", "type": "filter mode"}, + {"name": "min filter", "type": "filter mode"}, + {"name": "mipmap filter", "type": "filter mode"} + ] + } + ] + }, + "shader module": { + "category": "object" + }, + "shader module builder": { + "category": "object", + "methods": [ + { + "name": "get result", + "returns": "shader module" + }, + { + "name": "set source", + "args": [ + {"name": "code size", "type": "uint32_t"}, + {"name": "code", "type": "uint32_t", "annotation": "const*", "length": "code size"} + ] + } + ] + }, + "shader stage": { + "category": "enum", + "values": [ + {"value": 0, "name": "vertex"}, + {"value": 1, "name": "fragment"}, + {"value": 2, "name": "compute"} + ] + }, + "shader stage bit": { + "category": "bitmask", + "values": [ + {"value": 1, "name": "vertex"}, + {"value": 2, "name": "fragment"}, + {"value": 4, "name": "compute"} + ] + }, + "texture": { + "category": "object", + "methods": [ + { + "name": "create texture view builder", + "returns": "texture view builder" + }, + { + "name": "transition usage", + "args": [ + {"name": "usage", "type": "texture usage bit"} + ] + }, + { + "name": "freeze usage", + "args": [ + {"name": "usage", "type": "texture usage bit"} + ] + } + ] + }, + "texture builder": { + "category": "object", + "methods": [ + { + "name": "get result", + "returns": "texture" + }, + { + "name": "set dimension", + "args": [ + {"name": "dimension", "type": "texture dimension"} + ] + }, + { + "name": "set extent", + "args": [ + {"name": "width", "type": "uint32_t"}, + {"name": "height", "type": "uint32_t"}, + {"name": "depth", "type": "uint32_t"} + ] + }, + { + "name": "set format", + "args": [ + {"name": "format", "type": "texture format"} + ] + }, + { + "name": "set mip levels", + "args": [ + {"name": "num mip levels", "type": "uint32_t"} + ] + }, + { + "name": "set allowed usage", + "args": [ + {"name": "usage", "type": "texture usage bit"} + ] + }, + { + "name": "set initial usage", + "args": [ + {"name": "usage", "type": "texture usage bit"} + ] + } + ] + }, + "texture dimension": { + "category": "enum", + "values": [ + {"value": 0, "name": "2D"} + ] + }, + "texture usage bit": { + "category": "bitmask", + "values": [ + {"value": 0, "name": "none"}, + {"value": 1, "name": "transfer src"}, + {"value": 2, "name": "transfer dst"}, + {"value": 4, "name": "sampled"}, + {"value": 8, "name": "storage"}, + {"value": 16, "name": "color attachment"}, + {"value": 32, "name": "depth stencil attachment"} + ] + }, + "texture view": { + "category": "object" + }, + "texture view builder": { + "category": "object", + "methods": [ + { + "name": "get result", + "returns": "texture view" + } + ] + }, + "texture format": { + "category": "enum", + "values": [ + {"value": 0, "name": "r8 g8 b8 a8 unorm"} + ] + }, + "vertex format": { + "category": "enum", + "values": [ + {"value": 0, "name": "float r32 g32 b32 a32"}, + {"value": 1, "name": "float r32 g32 b32"}, + {"value": 2, "name": "float r32 g32"} + ] + }, + "void": { + "category": "native" + }, + "uint32_t": { + "category": "native" + } +} diff --git a/src/backend/CMakeLists.txt b/src/backend/CMakeLists.txt new file mode 100644 index 0000000000..cfb2a552b3 --- /dev/null +++ b/src/backend/CMakeLists.txt @@ -0,0 +1,133 @@ +# Copyright 2017 The NXT Authors +# +# 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. + +set(COMMON_DIR ${CMAKE_CURRENT_SOURCE_DIR}/common) +set(METAL_DIR ${CMAKE_CURRENT_SOURCE_DIR}/metal) +set(OPENGL_DIR ${CMAKE_CURRENT_SOURCE_DIR}/opengl) +set(TESTS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/tests) + +list(APPEND BACKEND_SOURCES + ${COMMON_DIR}/BindGroup.cpp + ${COMMON_DIR}/BindGroup.h + ${COMMON_DIR}/BindGroupLayout.cpp + ${COMMON_DIR}/BindGroupLayout.h + ${COMMON_DIR}/BitSetIterator.h + ${COMMON_DIR}/Buffer.cpp + ${COMMON_DIR}/Buffer.h + ${COMMON_DIR}/CommandAllocator.cpp + ${COMMON_DIR}/CommandAllocator.h + ${COMMON_DIR}/CommandBuffer.cpp + ${COMMON_DIR}/CommandBuffer.h + ${COMMON_DIR}/Device.cpp + ${COMMON_DIR}/Device.h + ${COMMON_DIR}/Forward.h + ${COMMON_DIR}/InputState.cpp + ${COMMON_DIR}/InputState.h + ${COMMON_DIR}/Math.cpp + ${COMMON_DIR}/Math.h + ${COMMON_DIR}/PerStage.cpp + ${COMMON_DIR}/PerStage.h + ${COMMON_DIR}/Pipeline.cpp + ${COMMON_DIR}/Pipeline.h + ${COMMON_DIR}/PipelineLayout.cpp + ${COMMON_DIR}/PipelineLayout.h + ${COMMON_DIR}/Queue.cpp + ${COMMON_DIR}/Queue.h + ${COMMON_DIR}/RefCounted.cpp + ${COMMON_DIR}/RefCounted.h + ${COMMON_DIR}/Sampler.cpp + ${COMMON_DIR}/Sampler.h + ${COMMON_DIR}/ShaderModule.cpp + ${COMMON_DIR}/ShaderModule.h + ${COMMON_DIR}/Texture.cpp + ${COMMON_DIR}/Texture.h + ${COMMON_DIR}/ToBackend.h +) + +# OpenGL Backend + +Generate( + LIB_NAME opengl_autogen + LIB_TYPE STATIC + PRINT_NAME "OpenGL backend autogenerated files" + COMMAND_LINE_ARGS + ${GENERATOR_COMMON_ARGS} + -T opengl +) +target_link_libraries(opengl_autogen glfw glad nxtcpp) +target_include_directories(opengl_autogen PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) +target_include_directories(opengl_autogen PUBLIC ${GENERATED_DIR}) +SetCXX14(opengl_autogen) +SetPIC(opengl_autogen) + +list(APPEND BACKEND_SOURCES + ${OPENGL_DIR}/CommandBufferGL.cpp + ${OPENGL_DIR}/CommandBufferGL.h + ${OPENGL_DIR}/OpenGLBackend.cpp + ${OPENGL_DIR}/OpenGLBackend.h + ${OPENGL_DIR}/PipelineGL.cpp + ${OPENGL_DIR}/PipelineGL.h + ${OPENGL_DIR}/PipelineLayoutGL.cpp + ${OPENGL_DIR}/PipelineLayoutGL.h + ${OPENGL_DIR}/SamplerGL.cpp + ${OPENGL_DIR}/SamplerGL.h + ${OPENGL_DIR}/ShaderModuleGL.cpp + ${OPENGL_DIR}/ShaderModuleGL.h + ${OPENGL_DIR}/TextureGL.cpp + ${OPENGL_DIR}/TextureGL.h +) + +# Metal Backend + +if (APPLE) + Generate( + LIB_NAME metal_autogen + LIB_TYPE STATIC + PRINT_NAME "Metal backend autogenerated files" + COMMAND_LINE_ARGS + ${GENERATOR_COMMON_ARGS} + -T metal + ) + target_link_libraries(metal_autogen glfw glad nxtcpp "-framework QuartzCore" "-framework Metal") + target_include_directories(metal_autogen PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) + target_include_directories(metal_autogen PUBLIC ${GENERATED_DIR}) + SetCXX14(metal_autogen) + SetPIC(metal_autogen) + + list(APPEND BACKEND_SOURCES + ${METAL_DIR}/MetalBackend.mm + ${METAL_DIR}/MetalBackend.h + ) +endif() + +add_library(nxt_backend SHARED ${BACKEND_SOURCES}) +target_link_libraries(nxt_backend opengl_autogen glfw glad spirv-cross) +if (APPLE) + target_link_libraries(nxt_backend metal_autogen) +endif() +target_include_directories(nxt_backend PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) +SetCXX14(nxt_backend) + +add_executable(backend_unittests + ${TESTS_DIR}/BitSetIteratorTests.cpp + ${TESTS_DIR}/CommandAllocatorTests.cpp + ${TESTS_DIR}/MathTests.cpp + ${TESTS_DIR}/PerStageTests.cpp + ${TESTS_DIR}/RefCountedTests.cpp + ${TESTS_DIR}/ToBackendTests.cpp + ${TESTS_DIR}/UnittestsMain.cpp +) +target_link_libraries(backend_unittests nxt_backend gtest) +target_include_directories(backend_unittests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) +SetCXX14(backend_unittests) diff --git a/src/backend/common/BindGroup.cpp b/src/backend/common/BindGroup.cpp new file mode 100644 index 0000000000..744325aabc --- /dev/null +++ b/src/backend/common/BindGroup.cpp @@ -0,0 +1,213 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "BindGroup.h" + +#include "BindGroupLayout.h" +#include "Buffer.h" +#include "Device.h" +#include "Texture.h" + +namespace backend { + + // BindGroup + + BindGroupBase::BindGroupBase(BindGroupBuilder* builder) + : layout(std::move(builder->layout)), usage(builder->usage), bindings(std::move(builder->bindings)) { + } + + const BindGroupLayoutBase* BindGroupBase::GetLayout() const { + return layout.Get(); + } + + nxt::BindGroupUsage BindGroupBase::GetUsage() const { + return usage; + } + + BufferViewBase* BindGroupBase::GetBindingAsBufferView(size_t binding) { + ASSERT(binding < kMaxBindingsPerGroup); + ASSERT(layout->GetBindingInfo().mask[binding]); + ASSERT(layout->GetBindingInfo().types[binding] == nxt::BindingType::UniformBuffer || + layout->GetBindingInfo().types[binding] == nxt::BindingType::StorageBuffer); + return reinterpret_cast(bindings[binding].Get()); + } + + SamplerBase* BindGroupBase::GetBindingAsSampler(size_t binding) { + ASSERT(binding < kMaxBindingsPerGroup); + ASSERT(layout->GetBindingInfo().mask[binding]); + ASSERT(layout->GetBindingInfo().types[binding] == nxt::BindingType::Sampler); + return reinterpret_cast(bindings[binding].Get()); + } + + TextureViewBase* BindGroupBase::GetBindingAsTextureView(size_t binding) { + ASSERT(binding < kMaxBindingsPerGroup); + ASSERT(layout->GetBindingInfo().mask[binding]); + ASSERT(layout->GetBindingInfo().types[binding] == nxt::BindingType::SampledTexture); + return reinterpret_cast(bindings[binding].Get()); + } + + // BindGroupBuilder + + enum BindGroupSetProperties { + BINDGROUP_PROPERTY_USAGE = 0x1, + BINDGROUP_PROPERTY_LAYOUT = 0x2, + }; + + BindGroupBuilder::BindGroupBuilder(DeviceBase* device) + : device(device) { + } + + bool BindGroupBuilder::WasConsumed() const { + return consumed; + } + + BindGroupBase* BindGroupBuilder::GetResult() { + constexpr int allProperties = BINDGROUP_PROPERTY_USAGE | BINDGROUP_PROPERTY_LAYOUT; + if ((propertiesSet & allProperties) != allProperties) { + device->HandleError("Bindgroup missing properties"); + return nullptr; + } + + if (setMask != layout->GetBindingInfo().mask) { + device->HandleError("Bindgroup missing bindings"); + return nullptr; + } + + consumed = true; + return device->CreateBindGroup(this); + } + + void BindGroupBuilder::SetLayout(BindGroupLayoutBase* layout) { + if ((propertiesSet & BINDGROUP_PROPERTY_LAYOUT) != 0) { + device->HandleError("Bindgroup layout property set multiple times"); + return; + } + + this->layout = layout; + propertiesSet |= BINDGROUP_PROPERTY_LAYOUT; + } + + void BindGroupBuilder::SetUsage(nxt::BindGroupUsage usage) { + if ((propertiesSet & BINDGROUP_PROPERTY_USAGE) != 0) { + device->HandleError("Bindgroup usage property set multiple times"); + return; + } + + this->usage = usage; + propertiesSet |= BINDGROUP_PROPERTY_USAGE; + } + + void BindGroupBuilder::SetBufferViews(uint32_t start, uint32_t count, BufferViewBase* const * bufferViews) { + if (!SetBindingsValidationBase(start, count)) { + return; + } + + const auto& layoutInfo = layout->GetBindingInfo(); + for (size_t i = start, j = 0; i < start + count; ++i, ++j) { + nxt::BufferUsageBit requiredBit; + switch (layoutInfo.types[i]) { + case nxt::BindingType::UniformBuffer: + requiredBit = nxt::BufferUsageBit::Uniform; + break; + + case nxt::BindingType::StorageBuffer: + requiredBit = nxt::BufferUsageBit::Storage; + break; + + case nxt::BindingType::Sampler: + case nxt::BindingType::SampledTexture: + device->HandleError("Setting buffer for a wrong binding type"); + return; + } + + if (!(bufferViews[j]->GetBuffer()->GetAllowedUsage() & requiredBit)) { + device->HandleError("Buffer needs to allow the correct usage bit"); + return; + } + } + + SetBindingsBase(start, count, reinterpret_cast(bufferViews)); + } + + void BindGroupBuilder::SetSamplers(uint32_t start, uint32_t count, SamplerBase* const * samplers) { + if (!SetBindingsValidationBase(start, count)) { + return; + } + + const auto& layoutInfo = layout->GetBindingInfo(); + for (size_t i = start, j = 0; i < start + count; ++i, ++j) { + if (layoutInfo.types[i] != nxt::BindingType::Sampler) { + device->HandleError("Setting binding for a wrong layout binding type"); + return; + } + } + + SetBindingsBase(start, count, reinterpret_cast(samplers)); + } + + void BindGroupBuilder::SetTextureViews(uint32_t start, uint32_t count, TextureViewBase* const * textureViews) { + if (!SetBindingsValidationBase(start, count)) { + return; + } + + const auto& layoutInfo = layout->GetBindingInfo(); + for (size_t i = start, j = 0; i < start + count; ++i, ++j) { + if (layoutInfo.types[i] != nxt::BindingType::SampledTexture) { + device->HandleError("Setting binding for a wrong layout binding type"); + return; + } + + if (!(textureViews[j]->GetTexture()->GetAllowedUsage() & nxt::TextureUsageBit::Sampled)) { + device->HandleError("Texture needs to allow the sampled usage bit"); + return; + } + } + + SetBindingsBase(start, count, reinterpret_cast(textureViews)); + } + + void BindGroupBuilder::SetBindingsBase(uint32_t start, uint32_t count, RefCounted* const * objects) { + for (size_t i = start, j = 0; i < start + count; ++i, ++j) { + setMask.set(i); + bindings[i] = objects[j]; + } + } + + bool BindGroupBuilder::SetBindingsValidationBase(uint32_t start, uint32_t count) { + if (start + count > kMaxBindingsPerGroup) { + device->HandleError("Setting bindings type over maximum number of bindings"); + return false; + } + + if ((propertiesSet & BINDGROUP_PROPERTY_LAYOUT) == 0) { + device->HandleError("Bindgroup layout must be set before views"); + return false; + } + + const auto& layoutInfo = layout->GetBindingInfo(); + for (size_t i = start, j = 0; i < start + count; ++i, ++j) { + if (setMask[i]) { + device->HandleError("Setting already set binding"); + return false; + } + + if (!layoutInfo.mask[i]) { + device->HandleError("Setting binding that isn't present in the layout"); + return false; + } + } + + return true; + } +} diff --git a/src/backend/common/BindGroup.h b/src/backend/common/BindGroup.h new file mode 100644 index 0000000000..4e6f9000b1 --- /dev/null +++ b/src/backend/common/BindGroup.h @@ -0,0 +1,95 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_BINDGROUP_H_ +#define BACKEND_COMMON_BINDGROUP_H_ + +#include "Forward.h" +#include "RefCounted.h" + +#include "nxt/nxtcpp.h" + +#include +#include +#include + +namespace backend { + + class BindGroupBase : public RefCounted { + public: + BindGroupBase(BindGroupBuilder* builder); + + const BindGroupLayoutBase* GetLayout() const; + nxt::BindGroupUsage GetUsage() const; + BufferViewBase* GetBindingAsBufferView(size_t binding); + SamplerBase* GetBindingAsSampler(size_t binding); + TextureViewBase* GetBindingAsTextureView(size_t binding); + + private: + Ref layout; + nxt::BindGroupUsage usage; + std::array, kMaxBindingsPerGroup> bindings; + }; + + class BindGroupBuilder : public RefCounted { + public: + BindGroupBuilder(DeviceBase* device); + + bool WasConsumed() const; + + // NXT API + BindGroupBase* GetResult(); + void SetLayout(BindGroupLayoutBase* layout); + void SetUsage(nxt::BindGroupUsage usage); + + template + void SetBufferViews(uint32_t start, uint32_t count, T* const* bufferViews) { + static_assert(std::is_base_of::value, ""); + SetBufferViews(start, count, reinterpret_cast(bufferViews)); + } + void SetBufferViews(uint32_t start, uint32_t count, BufferViewBase* const * bufferViews); + + template + void SetSamplers(uint32_t start, uint32_t count, T* const* samplers) { + static_assert(std::is_base_of::value, ""); + SetSamplers(start, count, reinterpret_cast(samplers)); + } + void SetSamplers(uint32_t start, uint32_t count, SamplerBase* const * samplers); + + template + void SetTextureViews(uint32_t start, uint32_t count, T* const* textureViews) { + static_assert(std::is_base_of::value, ""); + SetTextureViews(start, count, reinterpret_cast(textureViews)); + } + void SetTextureViews(uint32_t start, uint32_t count, TextureViewBase* const * textureViews); + + private: + friend class BindGroupBase; + + void SetBindingsBase(uint32_t start, uint32_t count, RefCounted* const * objects); + bool SetBindingsValidationBase(uint32_t start, uint32_t count); + + DeviceBase* device; + std::bitset setMask; + int propertiesSet = 0; + bool consumed = false; + + Ref layout; + nxt::BindGroupUsage usage; + std::array, kMaxBindingsPerGroup> bindings; + }; + +} + +#endif // BACKEND_COMMON_BINDGROUP_H_ diff --git a/src/backend/common/BindGroupLayout.cpp b/src/backend/common/BindGroupLayout.cpp new file mode 100644 index 0000000000..27c6d92824 --- /dev/null +++ b/src/backend/common/BindGroupLayout.cpp @@ -0,0 +1,144 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "BindGroupLayout.h" + +#include "Device.h" + +#include + +namespace backend { + + namespace { + + // Workaround for Chrome's stdlib having a broken std::hash for enums and bitsets + template + typename std::enable_if::value, size_t>::type Hash(T value) { + using Integral = typename nxt::UnderlyingType::type; + return std::hash()(static_cast(value)); + } + + template + size_t Hash(const std::bitset& value) { + static_assert(N <= sizeof(unsigned long long) * 8, ""); + return std::hash()(value.to_ullong()); + } + + + // TODO(cwallez@chromium.org): see if we can use boost's hash combined or some equivalent + // this currently assumes that size_t is 64 bits + void CombineHashes(size_t* h1, size_t h2) { + *h1 ^= (h2 << 7) + (h2 >> (64 - 7)) + 0x304975; + } + + size_t HashBindingInfo(const BindGroupLayoutBase::LayoutBindingInfo& info) { + size_t hash = Hash(info.mask); + + for (size_t binding = 0; binding < kMaxBindingsPerGroup; ++binding) { + if (info.mask[binding]) { + CombineHashes(&hash, Hash(info.visibilities[binding])); + CombineHashes(&hash, Hash(info.types[binding])); + } + } + + return hash; + } + + bool operator== (const BindGroupLayoutBase::LayoutBindingInfo& a, const BindGroupLayoutBase::LayoutBindingInfo& b) { + if (a.mask != b.mask) { + return false; + } + + for (size_t binding = 0; binding < kMaxBindingsPerGroup; ++binding) { + if (a.mask[binding]) { + if (a.visibilities[binding] != b.visibilities[binding]) { + return false; + } + if (a.types[binding] != b.types[binding]) { + return false; + } + } + } + + return true; + } + } + + // BindGroupLayoutBase + + BindGroupLayoutBase::BindGroupLayoutBase(BindGroupLayoutBuilder* builder, bool blueprint) + : device(builder->device), bindingInfo(builder->bindingInfo), blueprint(blueprint) { + } + + BindGroupLayoutBase::~BindGroupLayoutBase() { + // Do not register the actual cached object if we are a blueprint + if (!blueprint) { + device->UncacheBindGroupLayout(this); + } + } + + const BindGroupLayoutBase::LayoutBindingInfo& BindGroupLayoutBase::GetBindingInfo() const { + return bindingInfo; + } + + // BindGroupLayoutBuilder + + BindGroupLayoutBuilder::BindGroupLayoutBuilder(DeviceBase* device) : device(device) { + } + + bool BindGroupLayoutBuilder::WasConsumed() const { + return consumed; + } + + const BindGroupLayoutBase::LayoutBindingInfo& BindGroupLayoutBuilder::GetBindingInfo() const { + return bindingInfo; + } + + BindGroupLayoutBase* BindGroupLayoutBuilder::GetResult() { + consumed = true; + BindGroupLayoutBase blueprint(this, true); + + auto* result = device->GetOrCreateBindGroupLayout(&blueprint, this); + result->Reference(); + return result; + } + + void BindGroupLayoutBuilder::SetBindingsType(nxt::ShaderStageBit visibility, nxt::BindingType bindingType, uint32_t start, uint32_t count) { + if (start + count > kMaxBindingsPerGroup) { + device->HandleError("Setting bindings type over maximum number of bindings"); + return; + } + + for (size_t i = start; i < start + count; i++) { + if (bindingInfo.mask[i]) { + device->HandleError("Setting already set binding type"); + return; + } + bindingInfo.mask.set(i); + bindingInfo.visibilities[i] = visibility; + bindingInfo.types[i] = bindingType; + } + } + + // BindGroupLayoutCacheFuncs + + size_t BindGroupLayoutCacheFuncs::operator() (const BindGroupLayoutBase* bgl) const { + return HashBindingInfo(bgl->GetBindingInfo()); + } + + bool BindGroupLayoutCacheFuncs::operator() (const BindGroupLayoutBase* a, const BindGroupLayoutBase* b) const { + return a->GetBindingInfo() == b->GetBindingInfo(); + } + +} diff --git a/src/backend/common/BindGroupLayout.h b/src/backend/common/BindGroupLayout.h new file mode 100644 index 0000000000..91f6115057 --- /dev/null +++ b/src/backend/common/BindGroupLayout.h @@ -0,0 +1,76 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_BINDGROUPLAYOUT_H_ +#define BACKEND_COMMON_BINDGROUPLAYOUT_H_ + +#include "Forward.h" +#include "RefCounted.h" + +#include "nxt/nxtcpp.h" + +#include +#include + +namespace backend { + + class BindGroupLayoutBase : public RefCounted { + public: + BindGroupLayoutBase(BindGroupLayoutBuilder* builder, bool blueprint = false); + ~BindGroupLayoutBase() override; + + struct LayoutBindingInfo { + std::array visibilities; + std::array types; + std::bitset mask; + }; + const LayoutBindingInfo& GetBindingInfo() const; + + private: + DeviceBase* device; + LayoutBindingInfo bindingInfo; + bool blueprint = false; + }; + + class BindGroupLayoutBuilder : public RefCounted { + public: + BindGroupLayoutBuilder(DeviceBase* device); + + bool WasConsumed() const; + const BindGroupLayoutBase::LayoutBindingInfo& GetBindingInfo() const; + + // NXT API + BindGroupLayoutBase* GetResult(); + void SetBindingsType(nxt::ShaderStageBit visibility, nxt::BindingType bindingType, uint32_t start, uint32_t count); + + private: + friend class BindGroupLayoutBase; + + DeviceBase* device; + BindGroupLayoutBase::LayoutBindingInfo bindingInfo; + bool consumed = false; + }; + + // Implements the functors necessary for the unordered_set-based cache. + struct BindGroupLayoutCacheFuncs { + // The hash function + size_t operator() (const BindGroupLayoutBase* bgl) const; + + // The equality predicate + bool operator() (const BindGroupLayoutBase* a, const BindGroupLayoutBase* b) const; + }; + +} + +#endif // BACKEND_COMMON_BINDGROUPLAYOUT_H_ diff --git a/src/backend/common/BitSetIterator.h b/src/backend/common/BitSetIterator.h new file mode 100644 index 0000000000..baeb8625bc --- /dev/null +++ b/src/backend/common/BitSetIterator.h @@ -0,0 +1,135 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_BITSETITERATOR_H_ +#define BACKEND_COMMON_BITSETITERATOR_H_ + +#include "Forward.h" +#include "Math.h" + +#include +#include + +// This is ANGLE's BitSetIterator class with a customizable return type +// TODO(cwallez@chromium.org): it could be optimized, in particular when N <= 64 + +namespace backend { + + template + T roundUp(const T value, const T alignment) { + auto temp = value + alignment - static_cast(1); + return temp - temp % alignment; + } + + template + class BitSetIterator final { + public: + BitSetIterator(const std::bitset& bitset); + BitSetIterator(const BitSetIterator& other); + BitSetIterator &operator=(const BitSetIterator& other); + + class Iterator final { + public: + Iterator(const std::bitset& bits); + Iterator& operator++(); + + bool operator==(const Iterator& other) const; + bool operator!=(const Iterator& other) const; + T operator*() const { return static_cast(mCurrentBit); } + + private: + unsigned long getNextBit(); + + static const size_t BitsPerWord = sizeof(unsigned long) * 8; + std::bitset mBits; + unsigned long mCurrentBit; + unsigned long mOffset; + }; + + Iterator begin() const { return Iterator(mBits); } + Iterator end() const { return Iterator(std::bitset(0)); } + + private: + const std::bitset mBits; + }; + + template + BitSetIterator::BitSetIterator(const std::bitset& bitset) + : mBits(bitset) { + } + + template + BitSetIterator::BitSetIterator(const BitSetIterator& other) + : mBits(other.mBits) { + } + + template + BitSetIterator& BitSetIterator::operator=(const BitSetIterator& other) { + mBits = other.mBits; + return *this; + } + + template + BitSetIterator::Iterator::Iterator(const std::bitset& bits) + : mBits(bits), mCurrentBit(0), mOffset(0) { + if (bits.any()) { + mCurrentBit = getNextBit(); + } else { + mOffset = static_cast(roundUp(N, BitsPerWord)); + } + } + + template + typename BitSetIterator::Iterator& BitSetIterator::Iterator::operator++() { + ASSERT(mBits.any()); + mBits.set(mCurrentBit - mOffset, 0); + mCurrentBit = getNextBit(); + return *this; + } + + template + bool BitSetIterator::Iterator::operator==(const Iterator& other) const { + return mOffset == other.mOffset && mBits == other.mBits; + } + + template + bool BitSetIterator::Iterator::operator!=(const Iterator& other) const { + return !(*this == other); + } + + template + unsigned long BitSetIterator::Iterator::getNextBit() { + static std::bitset wordMask(std::numeric_limits::max()); + + while (mOffset < N) { + unsigned long wordBits = (mBits & wordMask).to_ulong(); + if (wordBits != 0ul) { + return ScanForward(wordBits) + mOffset; + } + + mBits >>= BitsPerWord; + mOffset += BitsPerWord; + } + return 0; + } + + // Helper to avoid needing to specify the template parameter size + template + BitSetIterator IterateBitSet(const std::bitset& bitset) { + return BitSetIterator(bitset); + } + +} + +#endif // BACKEND_COMMON_BITSETITERATOR_H_ diff --git a/src/backend/common/Buffer.cpp b/src/backend/common/Buffer.cpp new file mode 100644 index 0000000000..7592b041fe --- /dev/null +++ b/src/backend/common/Buffer.cpp @@ -0,0 +1,233 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "Buffer.h" + +#include "Device.h" + +#include +#include + +namespace backend { + + // Buffer + + BufferBase::BufferBase(BufferBuilder* builder) + : device(builder->device), + size(builder->size), + allowedUsage(builder->allowedUsage), + currentUsage(builder->currentUsage) { + } + + BufferViewBuilder* BufferBase::CreateBufferViewBuilder() { + return new BufferViewBuilder(device, this); + } + + uint32_t BufferBase::GetSize() const { + return size; + } + + nxt::BufferUsageBit BufferBase::GetAllowedUsage() const { + return allowedUsage; + } + + nxt::BufferUsageBit BufferBase::GetUsage() const { + return currentUsage; + } + + void BufferBase::SetSubData(uint32_t start, uint32_t count, const uint32_t* data) { + if ((start + count) * sizeof(uint32_t) > GetSize()) { + device->HandleError("Buffer subdata out of range"); + return; + } + + if (!(currentUsage & nxt::BufferUsageBit::Mapped)) { + device->HandleError("Buffer needs the mapped usage bit"); + return; + } + + SetSubDataImpl(start, count, data); + } + + bool BufferBase::IsFrozen() const { + return frozen; + } + + bool BufferBase::HasFrozenUsage(nxt::BufferUsageBit usage) const { + return frozen && (usage & allowedUsage); + } + + bool BufferBase::IsUsagePossible(nxt::BufferUsageBit allowedUsage, nxt::BufferUsageBit usage) { + const nxt::BufferUsageBit allReadBits = + nxt::BufferUsageBit::TransferSrc | + nxt::BufferUsageBit::Index | + nxt::BufferUsageBit::Vertex | + nxt::BufferUsageBit::Uniform; + bool allowed = (usage & allowedUsage) == usage; + bool readOnly = (usage & allReadBits) == usage; + bool singleUse = nxt::HasZeroOrOneBits(usage); + return allowed && (readOnly || singleUse); + } + + bool BufferBase::IsTransitionPossible(nxt::BufferUsageBit usage) const { + if (frozen) { + return false; + } + return IsUsagePossible(allowedUsage, usage); + } + + void BufferBase::TransitionUsageImpl(nxt::BufferUsageBit usage) { + assert(IsTransitionPossible(usage)); + currentUsage = usage; + } + + void BufferBase::TransitionUsage(nxt::BufferUsageBit usage) { + if (!IsTransitionPossible(usage)) { + device->HandleError("Buffer frozen or usage not allowed"); + return; + } + TransitionUsageImpl(usage); + } + + void BufferBase::FreezeUsage(nxt::BufferUsageBit usage) { + if (!IsTransitionPossible(usage)) { + device->HandleError("Buffer frozen or usage not allowed"); + return; + } + allowedUsage = usage; + currentUsage = usage; + frozen = true; + } + + // BufferBuilder + + enum BufferSetProperties { + BUFFER_PROPERTY_ALLOWED_USAGE = 0x1, + BUFFER_PROPERTY_INITIAL_USAGE = 0x2, + BUFFER_PROPERTY_SIZE = 0x4, + }; + + BufferBuilder::BufferBuilder(DeviceBase* device) : device(device) { + } + + bool BufferBuilder::WasConsumed() const { + return consumed; + } + + BufferBase* BufferBuilder::GetResult() { + constexpr int allProperties = BUFFER_PROPERTY_ALLOWED_USAGE | BUFFER_PROPERTY_SIZE; + if ((propertiesSet & allProperties) != allProperties) { + device->HandleError("Buffer missing properties"); + return nullptr; + } + + if (!BufferBase::IsUsagePossible(allowedUsage, currentUsage)) { + device->HandleError("Initial buffer usage is not allowed"); + return nullptr; + } + + consumed = true; + return device->CreateBuffer(this); + } + + void BufferBuilder::SetAllowedUsage(nxt::BufferUsageBit usage) { + if ((propertiesSet & BUFFER_PROPERTY_ALLOWED_USAGE) != 0) { + device->HandleError("Buffer allowedUsage property set multiple times"); + return; + } + + this->allowedUsage = usage; + propertiesSet |= BUFFER_PROPERTY_ALLOWED_USAGE; + } + + void BufferBuilder::SetInitialUsage(nxt::BufferUsageBit usage) { + if ((propertiesSet & BUFFER_PROPERTY_INITIAL_USAGE) != 0) { + device->HandleError("Buffer initialUsage property set multiple times"); + return; + } + + this->currentUsage = usage; + propertiesSet |= BUFFER_PROPERTY_INITIAL_USAGE; + } + + void BufferBuilder::SetSize(uint32_t size) { + if ((propertiesSet & BUFFER_PROPERTY_SIZE) != 0) { + device->HandleError("Buffer size property set multiple times"); + return; + } + + this->size = size; + propertiesSet |= BUFFER_PROPERTY_SIZE; + } + + // BufferViewBase + + BufferViewBase::BufferViewBase(BufferViewBuilder* builder) + : buffer(std::move(builder->buffer)), size(builder->size), offset(builder->offset) { + } + + BufferBase* BufferViewBase::GetBuffer() { + return buffer.Get(); + } + + uint32_t BufferViewBase::GetSize() const { + return size; + } + + uint32_t BufferViewBase::GetOffset() const { + return offset; + } + + // BufferViewBuilder + + enum BufferViewSetProperties { + BUFFER_VIEW_PROPERTY_EXTENT = 0x1, + }; + + BufferViewBuilder::BufferViewBuilder(DeviceBase* device, BufferBase* buffer) + : device(device), buffer(buffer) { + } + + bool BufferViewBuilder::WasConsumed() const { + return consumed; + } + + BufferViewBase* BufferViewBuilder::GetResult() { + constexpr int allProperties = BUFFER_VIEW_PROPERTY_EXTENT; + if ((propertiesSet & allProperties) != allProperties) { + device->HandleError("Buffer view missing properties"); + return nullptr; + } + + return device->CreateBufferView(this); + } + + void BufferViewBuilder::SetExtent(uint32_t offset, uint32_t size) { + if ((propertiesSet & BUFFER_VIEW_PROPERTY_EXTENT) != 0) { + device->HandleError("Buffer view extent property set multiple times"); + return; + } + + uint64_t viewEnd = static_cast(offset) + static_cast(size); + if (viewEnd > static_cast(buffer->GetSize())) { + device->HandleError("Buffer view end is OOB"); + return; + } + + this->offset = offset; + this->size = size; + propertiesSet |= BUFFER_VIEW_PROPERTY_EXTENT; + } + +} diff --git a/src/backend/common/Buffer.h b/src/backend/common/Buffer.h new file mode 100644 index 0000000000..d8216bcb95 --- /dev/null +++ b/src/backend/common/Buffer.h @@ -0,0 +1,114 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_BUFFER_H_ +#define BACKEND_COMMON_BUFFER_H_ + +#include "Forward.h" +#include "RefCounted.h" + +#include "nxt/nxtcpp.h" + +namespace backend { + + class BufferBase : public RefCounted { + public: + BufferBase(BufferBuilder* builder); + + uint32_t GetSize() const; + nxt::BufferUsageBit GetAllowedUsage() const; + nxt::BufferUsageBit GetUsage() const; + static bool IsUsagePossible(nxt::BufferUsageBit allowedUsage, nxt::BufferUsageBit usage); + bool IsTransitionPossible(nxt::BufferUsageBit usage) const; + bool IsFrozen() const; + bool HasFrozenUsage(nxt::BufferUsageBit usage) const; + void TransitionUsageImpl(nxt::BufferUsageBit usage); + + // NXT API + BufferViewBuilder* CreateBufferViewBuilder(); + void SetSubData(uint32_t start, uint32_t count, const uint32_t* data); + void TransitionUsage(nxt::BufferUsageBit usage); + void FreezeUsage(nxt::BufferUsageBit usage); + + private: + virtual void SetSubDataImpl(uint32_t start, uint32_t count, const uint32_t* data) = 0; + + DeviceBase* device; + uint32_t size; + nxt::BufferUsageBit allowedUsage = nxt::BufferUsageBit::None; + nxt::BufferUsageBit currentUsage = nxt::BufferUsageBit::None; + bool frozen = false; + }; + + class BufferBuilder : public RefCounted { + public: + BufferBuilder(DeviceBase* device); + + bool WasConsumed() const; + + // NXT API + BufferBase* GetResult(); + void SetAllowedUsage(nxt::BufferUsageBit usage); + void SetInitialUsage(nxt::BufferUsageBit usage); + void SetSize(uint32_t size); + + private: + friend class BufferBase; + + DeviceBase* device; + uint32_t size; + nxt::BufferUsageBit allowedUsage = nxt::BufferUsageBit::None; + nxt::BufferUsageBit currentUsage = nxt::BufferUsageBit::None; + int propertiesSet = 0; + bool consumed = false; + }; + + class BufferViewBase : public RefCounted { + public: + BufferViewBase(BufferViewBuilder* builder); + + BufferBase* GetBuffer(); + uint32_t GetSize() const; + uint32_t GetOffset() const; + + private: + Ref buffer; + uint32_t size; + uint32_t offset; + }; + + class BufferViewBuilder : public RefCounted { + public: + BufferViewBuilder(DeviceBase* device, BufferBase* buffer); + + bool WasConsumed() const; + + // NXT API + BufferViewBase* GetResult(); + void SetExtent(uint32_t offset, uint32_t size); + + private: + friend class BufferViewBase; + + DeviceBase* device; + Ref buffer; + uint32_t offset = 0; + uint32_t size = 0; + int propertiesSet = 0; + bool consumed = false; + }; + +} + +#endif // BACKEND_COMMON_BUFFER_H_ diff --git a/src/backend/common/CommandAllocator.cpp b/src/backend/common/CommandAllocator.cpp new file mode 100644 index 0000000000..0526e103ea --- /dev/null +++ b/src/backend/common/CommandAllocator.cpp @@ -0,0 +1,219 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "CommandAllocator.h" + +#include "Math.h" + +#include +#include +#include +#define ASSERT assert + +namespace backend { + + constexpr uint32_t EndOfBlock = UINT_MAX;//std::numeric_limits::max(); + constexpr uint32_t AdditionalData = UINT_MAX - 1;//std::numeric_limits::max(); + + // TODO(cwallez@chromium.org): figure out a way to have more type safety for the iterator + + CommandIterator::CommandIterator() + : endOfBlock(EndOfBlock) { + Reset(); + } + + CommandIterator::~CommandIterator() { + ASSERT(dataWasDestroyed); + + if (!IsEmpty()) { + for (auto& block : blocks) { + free(block.block); + } + } + } + + CommandIterator::CommandIterator(CommandIterator&& other) + : endOfBlock(EndOfBlock) { + if (!other.IsEmpty()) { + blocks = std::move(other.blocks); + other.Reset(); + } + other.DataWasDestroyed(); + Reset(); + } + + CommandIterator& CommandIterator::operator=(CommandIterator&& other) { + if (!other.IsEmpty()) { + blocks = std::move(other.blocks); + other.Reset(); + } else { + blocks.clear(); + } + other.DataWasDestroyed(); + Reset(); + return *this; + } + + CommandIterator::CommandIterator(CommandAllocator&& allocator) + : blocks(allocator.AcquireBlocks()), endOfBlock(EndOfBlock) { + Reset(); + } + + CommandIterator& CommandIterator::operator=(CommandAllocator&& allocator) { + blocks = allocator.AcquireBlocks(); + Reset(); + return *this; + } + + void CommandIterator::Reset() { + currentBlock = 0; + + if (blocks.empty()) { + // This will case the first NextCommandId call to try to move to the next + // block and stop the iteration immediately, without special casing the + // initialization. + currentPtr = reinterpret_cast(&endOfBlock); + blocks.emplace_back(); + blocks[0].size = sizeof(endOfBlock); + blocks[0].block = currentPtr; + } else { + currentPtr = Align(blocks[0].block, alignof(uint32_t)); + } + } + + void CommandIterator::DataWasDestroyed() { + dataWasDestroyed = true; + } + + bool CommandIterator::IsEmpty() const { + return blocks[0].block == reinterpret_cast(&endOfBlock); + } + + bool CommandIterator::NextCommandId(uint32_t* commandId) { + uint8_t* idPtr = Align(currentPtr, alignof(uint32_t)); + ASSERT(idPtr + sizeof(uint32_t) <= blocks[currentBlock].block + blocks[currentBlock].size); + + uint32_t id = *reinterpret_cast(idPtr); + + if (id == EndOfBlock) { + currentBlock++; + if (currentBlock >= blocks.size()) { + Reset(); + return false; + } + currentPtr = Align(blocks[currentBlock].block, alignof(uint32_t)); + return NextCommandId(commandId); + } + + currentPtr = idPtr + sizeof(uint32_t); + *commandId = id; + return true; + } + + void* CommandIterator::NextCommand(size_t commandSize, size_t commandAlignment) { + uint8_t* commandPtr = Align(currentPtr, commandAlignment); + ASSERT(commandPtr + sizeof(commandSize) <= blocks[currentBlock].block + blocks[currentBlock].size); + + currentPtr = commandPtr + commandSize; + return commandPtr; + } + + void* CommandIterator::NextData(size_t dataSize, size_t dataAlignment) { + uint32_t id; + bool hasId = NextCommandId(&id); + ASSERT(hasId); + ASSERT(id == AdditionalData); + + return NextCommand(dataSize, dataAlignment); + } + + // Potential TODO(cwallez@chromium.org): + // - Host the size and pointer to next block in the block itself to avoid having an allocation in the vector + // - Assume T's alignof is, say 64bits, static assert it, and make commandAlignment a constant in Allocate + // - Be able to optimize allocation to one block, for command buffers expected to live long to avoid cache misses + // - Better block allocation, maybe have NXT API to say command buffer is going to have size close to another + + CommandAllocator::CommandAllocator() + : currentPtr(reinterpret_cast(&dummyEnum[0])), endPtr(reinterpret_cast(&dummyEnum[1])) { + } + + CommandAllocator::~CommandAllocator() { + ASSERT(blocks.empty()); + } + + CommandBlocks&& CommandAllocator::AcquireBlocks() { + ASSERT(currentPtr != nullptr && endPtr != nullptr); + ASSERT(IsAligned(currentPtr, alignof(uint32_t))); + ASSERT(currentPtr + sizeof(uint32_t) <= endPtr); + *reinterpret_cast(currentPtr) = EndOfBlock; + + currentPtr = nullptr; + endPtr = nullptr; + return std::move(blocks); + } + + uint8_t* CommandAllocator::Allocate(uint32_t commandId, size_t commandSize, size_t commandAlignment) { + ASSERT(currentPtr != nullptr); + ASSERT(endPtr != nullptr); + ASSERT(commandId != EndOfBlock); + + // It should always be possible to allocate one id, for EndOfBlock tagging, + ASSERT(IsAligned(currentPtr, alignof(uint32_t))); + ASSERT(currentPtr + sizeof(uint32_t) <= endPtr); + uint32_t* idAlloc = reinterpret_cast(currentPtr); + + uint8_t* commandAlloc = Align(currentPtr + sizeof(uint32_t), commandAlignment); + uint8_t* nextPtr = Align(commandAlloc + commandSize, alignof(uint32_t)); + + // When there is not enough space, we signal the EndOfBlock, so that the iterator nows to + // move to the next one. EndOfBlock on the last block means the end of the commands. + if (nextPtr + sizeof(uint32_t) > endPtr) { + + // Even if we are not able to get another block, the list of commands will be well-formed + // and iterable as this block will be that last one. + *idAlloc = EndOfBlock; + + // Make sure we have space for current allocation, plus end of block and alignment padding + // for the first id. + if (!GetNewBlock(nextPtr - currentPtr + sizeof(uint32_t) + alignof(uint32_t))) { + return nullptr; + } + return Allocate(commandId, commandSize, commandAlignment); + } + + *idAlloc = commandId; + currentPtr = nextPtr; + return commandAlloc; + } + + uint8_t* CommandAllocator::AllocateData(size_t commandSize, size_t commandAlignment) { + return Allocate(AdditionalData, commandSize, commandAlignment); + } + + bool CommandAllocator::GetNewBlock(size_t minimumSize) { + // Allocate blocks doubling sizes each time, to a maximum of 16k (or at least minimumSize). + lastAllocationSize = std::max(minimumSize, std::min(lastAllocationSize * 2, size_t(16384))); + + uint8_t* block = reinterpret_cast(malloc(lastAllocationSize)); + if (block == nullptr) { + return false; + } + + blocks.push_back({lastAllocationSize, block}); + currentPtr = Align(block, alignof(uint32_t)); + endPtr = block + lastAllocationSize; + return true; + } + +} diff --git a/src/backend/common/CommandAllocator.h b/src/backend/common/CommandAllocator.h new file mode 100644 index 0000000000..3633d2e3fe --- /dev/null +++ b/src/backend/common/CommandAllocator.h @@ -0,0 +1,150 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_COMMAND_ALLOCATOR_H_ +#define BACKEND_COMMON_COMMAND_ALLOCATOR_H_ + +#include +#include +#include + +namespace backend { + + // Allocation for command buffers should be fast. To avoid doing an allocation per command + // or to avoid copying commands when reallocing, we use a linear allocator in a growing set + // of large memory blocks. We also use this to have the format to be (u32 commandId, command), + // so that iteration over the commands is easy. + + // Usage of the allocator and iterator: + // CommandAllocator allocator; + // DrawCommand* cmd = allocator.Allocate(CommandType::Draw); + // // Fill command + // // Repeat allocation and filling commands + // + // CommandIterator commands(allocator); + // CommandType type; + // void* command; + // while(commands.NextCommandId(&e)) { + // switch(e) { + // case CommandType::Draw: + // DrawCommand* draw = commands.NextCommand(); + // // Do the draw + // break; + // // other cases + // } + // } + + // Note that you need to extract the commands from the CommandAllocator before destroying it + // and must tell the CommandIterator when the allocated commands have been processed for + // deletion. + + // These are the lists of blocks, should not be used directly, only through CommandAllocator + // and CommandIterator + struct BlockDef { + size_t size; + uint8_t* block; + }; + using CommandBlocks = std::vector; + + class CommandAllocator; + + // TODO(cwallez@chromium.org): prevent copy for both iterator and allocator + class CommandIterator { + public: + CommandIterator(); + ~CommandIterator(); + + CommandIterator(CommandIterator&& other); + CommandIterator& operator=(CommandIterator&& other); + + CommandIterator(CommandAllocator&& allocator); + CommandIterator& operator=(CommandAllocator&& allocator); + + template + bool NextCommandId(E* commandId) { + return NextCommandId(reinterpret_cast(commandId)); + } + template + T* NextCommand() { + return reinterpret_cast(NextCommand(sizeof(T), alignof(T))); + } + template + T* NextData(size_t count) { + return reinterpret_cast(NextData(sizeof(T) * count, alignof(T))); + } + + // Needs to be called if iteration was stopped early. + void Reset(); + + void DataWasDestroyed(); + + private: + bool IsEmpty() const; + + bool NextCommandId(uint32_t* commandId); + void* NextCommand(size_t commandSize, size_t commandAlignment); + void* NextData(size_t dataSize, size_t dataAlignment); + + CommandBlocks blocks; + uint8_t* currentPtr = nullptr; + size_t currentBlock = 0; + // Used to avoid a special case for empty iterators. + uint32_t endOfBlock; + bool dataWasDestroyed = false; + }; + + class CommandAllocator { + public: + CommandAllocator(); + ~CommandAllocator(); + + template + T* Allocate(E commandId) { + static_assert(sizeof(E) == sizeof(uint32_t), ""); + static_assert(alignof(E) == alignof(uint32_t), ""); + return reinterpret_cast(Allocate(static_cast(commandId), sizeof(T), alignof(T))); + } + + template + T* AllocateData(size_t count) { + return reinterpret_cast(AllocateData(sizeof(T) * count, alignof(T))); + } + + private: + friend CommandIterator; + CommandBlocks&& AcquireBlocks(); + + uint8_t* Allocate(uint32_t commandId, size_t commandSize, size_t commandAlignment); + uint8_t* AllocateData(size_t dataSize, size_t dataAlignment); + bool GetNewBlock(size_t minimumSize); + + CommandBlocks blocks; + size_t lastAllocationSize = 2048; + + // Pointers to the current range of allocation in the block. Guaranteed to allow + // for at least one uint32_t is not nullptr, so that the special EndOfBlock command id + // can always be written. + // Nullptr iff the blocks were moved out. + uint8_t* currentPtr = nullptr; + uint8_t* endPtr = nullptr; + + // Data used for the block range at initialization so that the first call to Allocate + // sees there is not enough space and calls GetNewBlock. This avoids having to special + // case the initialization in Allocate. + uint32_t dummyEnum[1] = {0}; + }; + +} + +#endif // BACKEND_COMMON_COMMAND_ALLOCATOR_H_ diff --git a/src/backend/common/CommandBuffer.cpp b/src/backend/common/CommandBuffer.cpp new file mode 100644 index 0000000000..d118e64273 --- /dev/null +++ b/src/backend/common/CommandBuffer.cpp @@ -0,0 +1,623 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "CommandBuffer.h" + +#include "BindGroup.h" +#include "BindGroupLayout.h" +#include "Buffer.h" +#include "Commands.h" +#include "Device.h" +#include "InputState.h" +#include "Pipeline.h" +#include "PipelineLayout.h" +#include "Texture.h" + +#include +#include + +namespace backend { + + CommandBufferBase::CommandBufferBase(CommandBufferBuilder* builder) + : device(builder->device), + buffersTransitioned(std::move(builder->buffersTransitioned)), + texturesTransitioned(std::move(builder->texturesTransitioned)) { + } + + bool CommandBufferBase::ValidateResourceUsagesImmediate() { + for (auto buffer : buffersTransitioned) { + if (buffer->IsFrozen()) { + device->HandleError("Command buffer: cannot transition buffer with frozen usage"); + return false; + } + } + for (auto texture : texturesTransitioned) { + if (texture->IsFrozen()) { + device->HandleError("Command buffer: cannot transition texture with frozen usage"); + return false; + } + } + return true; + } + + void FreeCommands(CommandIterator* commands) { + Command type; + while(commands->NextCommandId(&type)) { + switch (type) { + case Command::CopyBufferToTexture: + { + CopyBufferToTextureCmd* copy = commands->NextCommand(); + copy->~CopyBufferToTextureCmd(); + } + break; + case Command::Dispatch: + { + DispatchCmd* dispatch = commands->NextCommand(); + dispatch->~DispatchCmd(); + } + break; + case Command::DrawArrays: + { + DrawArraysCmd* draw = commands->NextCommand(); + draw->~DrawArraysCmd(); + } + break; + case Command::DrawElements: + { + DrawElementsCmd* draw = commands->NextCommand(); + draw->~DrawElementsCmd(); + } + break; + case Command::SetPipeline: + { + SetPipelineCmd* cmd = commands->NextCommand(); + cmd->~SetPipelineCmd(); + } + break; + case Command::SetPushConstants: + { + SetPushConstantsCmd* cmd = commands->NextCommand(); + commands->NextData(cmd->count); + cmd->~SetPushConstantsCmd(); + } + break; + case Command::SetBindGroup: + { + SetBindGroupCmd* cmd = commands->NextCommand(); + cmd->~SetBindGroupCmd(); + } + break; + case Command::SetIndexBuffer: + { + SetIndexBufferCmd* cmd = commands->NextCommand(); + cmd->~SetIndexBufferCmd(); + } + break; + case Command::SetVertexBuffers: + { + SetVertexBuffersCmd* cmd = commands->NextCommand(); + auto buffers = commands->NextData>(cmd->count); + for (size_t i = 0; i < cmd->count; ++i) { + (&buffers[i])->~Ref(); + } + commands->NextData(cmd->count); + cmd->~SetVertexBuffersCmd(); + } + break; + case Command::TransitionBufferUsage: + { + TransitionBufferUsageCmd* cmd = commands->NextCommand(); + cmd->~TransitionBufferUsageCmd(); + } + break; + case Command::TransitionTextureUsage: + { + TransitionTextureUsageCmd* cmd = commands->NextCommand(); + cmd->~TransitionTextureUsageCmd(); + } + break; + } + } + commands->DataWasDestroyed(); + } + + CommandBufferBuilder::CommandBufferBuilder(DeviceBase* device) : device(device) { + } + + CommandBufferBuilder::~CommandBufferBuilder() { + if (!consumed) { + MoveToIterator(); + FreeCommands(&iterator); + } + } + + bool CommandBufferBuilder::WasConsumed() const { + return consumed; + } + + enum ValidationAspect { + VALIDATION_ASPECT_RENDER_PIPELINE, + VALIDATION_ASPECT_COMPUTE_PIPELINE, + VALIDATION_ASPECT_BINDGROUPS, + VALIDATION_ASPECT_VERTEX_BUFFERS, + VALIDATION_ASPECT_INDEX_BUFFER, + + VALIDATION_ASPECT_COUNT, + }; + + using ValidationAspects = std::bitset; + + bool CommandBufferBuilder::ValidateGetResult() { + MoveToIterator(); + + ValidationAspects aspects; + std::bitset bindgroupsSet; + std::bitset inputsSet; + PipelineBase* lastPipeline = nullptr; + + std::map mostRecentBufferUsages; + auto bufferHasGuaranteedUsageBit = [&](BufferBase* buffer, nxt::BufferUsageBit usage) -> bool { + assert(usage != nxt::BufferUsageBit::None && nxt::HasZeroOrOneBits(usage)); + if (buffer->HasFrozenUsage(usage)) { + return true; + } + auto it = mostRecentBufferUsages.find(buffer); + return it != mostRecentBufferUsages.end() && (it->second & usage); + }; + + std::map mostRecentTextureUsages; + auto textureHasGuaranteedUsageBit = [&](TextureBase* texture, nxt::TextureUsageBit usage) -> bool { + assert(usage != nxt::TextureUsageBit::None && nxt::HasZeroOrOneBits(usage)); + if (texture->HasFrozenUsage(usage)) { + return true; + } + auto it = mostRecentTextureUsages.find(texture); + return it != mostRecentTextureUsages.end() && (it->second & usage); + }; + + auto validateBindGroupUsages = [&](BindGroupBase* group) -> bool { + const auto& layoutInfo = group->GetLayout()->GetBindingInfo(); + for (size_t i = 0; i < kMaxBindingsPerGroup; ++i) { + if (!layoutInfo.mask[i]) { + continue; + } + + nxt::BindingType type = layoutInfo.types[i]; + switch (type) { + case nxt::BindingType::UniformBuffer: + case nxt::BindingType::StorageBuffer: + { + nxt::BufferUsageBit requiredUsage; + switch (type) { + case nxt::BindingType::UniformBuffer: + requiredUsage = nxt::BufferUsageBit::Uniform; + break; + + case nxt::BindingType::StorageBuffer: + requiredUsage = nxt::BufferUsageBit::Storage; + break; + + default: + assert(false); + return false; + } + + auto buffer = group->GetBindingAsBufferView(i)->GetBuffer(); + if (!bufferHasGuaranteedUsageBit(buffer, requiredUsage)) { + device->HandleError("Can't guarantee buffer usage needed by bind group"); + return false; + } + } + break; + case nxt::BindingType::SampledTexture: + { + auto requiredUsage = nxt::TextureUsageBit::Sampled; + + auto texture = group->GetBindingAsTextureView(i)->GetTexture(); + if (!textureHasGuaranteedUsageBit(texture, requiredUsage)) { + device->HandleError("Can't guarantee texture usage needed by bind group"); + return false; + } + } + break; + case nxt::BindingType::Sampler: + continue; + } + } + return true; + }; + + Command type; + while(iterator.NextCommandId(&type)) { + switch (type) { + case Command::CopyBufferToTexture: + { + CopyBufferToTextureCmd* copy = iterator.NextCommand(); + BufferBase* buffer = copy->buffer.Get(); + TextureBase* texture = copy->texture.Get(); + uint64_t width = copy->width; + uint64_t height = copy->height; + uint64_t depth = copy->depth; + uint64_t x = copy->x; + uint64_t y = copy->y; + uint64_t z = copy->z; + uint32_t level = copy->level; + + if (!bufferHasGuaranteedUsageBit(buffer, nxt::BufferUsageBit::TransferSrc)) { + device->HandleError("Buffer needs the transfer source usage bit"); + return false; + } + + if (!textureHasGuaranteedUsageBit(texture, nxt::TextureUsageBit::TransferDst)) { + device->HandleError("Texture needs the transfer destination usage bit"); + return false; + } + + if (width == 0 || height == 0 || depth == 0) { + device->HandleError("Empty copy"); + return false; + } + + // TODO(cwallez@chromium.org): check for overflows + uint64_t pixelSize = TextureFormatPixelSize(texture->GetFormat()); + uint64_t dataSize = width * height * depth * pixelSize; + + // TODO(cwallez@chromium.org): handle buffer offset when it is in the command. + if (dataSize > static_cast(buffer->GetSize())) { + device->HandleError("Copy would read after end of the buffer"); + return false; + } + + if (x + width > static_cast(texture->GetWidth()) || + y + height > static_cast(texture->GetHeight()) || + z + depth > static_cast(texture->GetDepth()) || + level > texture->GetNumMipLevels()) { + device->HandleError("Copy would write outside of the texture"); + return false; + } + } + break; + + case Command::Dispatch: + { + DispatchCmd* cmd = iterator.NextCommand(); + + constexpr ValidationAspects requiredDispatchAspects = + 1 << VALIDATION_ASPECT_COMPUTE_PIPELINE | + 1 << VALIDATION_ASPECT_BINDGROUPS | + 1 << VALIDATION_ASPECT_VERTEX_BUFFERS; + + if ((requiredDispatchAspects & ~aspects).any()) { + // Compute the lazily computed aspects + if (bindgroupsSet.all()) { + aspects.set(VALIDATION_ASPECT_BINDGROUPS); + } + + auto requiredInputs = lastPipeline->GetInputState()->GetInputsSetMask(); + if ((inputsSet & ~requiredInputs).none()) { + aspects.set(VALIDATION_ASPECT_VERTEX_BUFFERS); + } + + // Check again if anything is missing + if ((requiredDispatchAspects & ~aspects).any()) { + device->HandleError("Some dispatch state is missing"); + return false; + } + } + } + break; + + case Command::DrawArrays: + case Command::DrawElements: + { + constexpr ValidationAspects requiredDrawAspects = + 1 << VALIDATION_ASPECT_RENDER_PIPELINE | + 1 << VALIDATION_ASPECT_BINDGROUPS | + 1 << VALIDATION_ASPECT_VERTEX_BUFFERS; + + if ((requiredDrawAspects & ~aspects).any()) { + // Compute the lazily computed aspects + if (bindgroupsSet.all()) { + aspects.set(VALIDATION_ASPECT_BINDGROUPS); + } + + auto requiredInputs = lastPipeline->GetInputState()->GetInputsSetMask(); + if ((inputsSet & ~requiredInputs).none()) { + aspects.set(VALIDATION_ASPECT_VERTEX_BUFFERS); + } + + // Check again if anything is missing + if ((requiredDrawAspects & ~aspects).any()) { + device->HandleError("Some draw state is missing"); + return false; + } + } + + if (type == Command::DrawArrays) { + DrawArraysCmd* draw = iterator.NextCommand(); + } else { + ASSERT(type == Command::DrawElements); + DrawElementsCmd* draw = iterator.NextCommand(); + + if (!aspects[VALIDATION_ASPECT_INDEX_BUFFER]) { + device->HandleError("Draw elements requires an index buffer"); + return false; + } + } + } + break; + + case Command::SetPipeline: + { + SetPipelineCmd* cmd = iterator.NextCommand(); + PipelineBase* pipeline = cmd->pipeline.Get(); + PipelineLayoutBase* layout = pipeline->GetLayout(); + + if (pipeline->IsCompute()) { + aspects.set(VALIDATION_ASPECT_COMPUTE_PIPELINE); + aspects.reset(VALIDATION_ASPECT_RENDER_PIPELINE); + } else { + aspects.set(VALIDATION_ASPECT_RENDER_PIPELINE); + aspects.reset(VALIDATION_ASPECT_COMPUTE_PIPELINE); + } + aspects.reset(VALIDATION_ASPECT_BINDGROUPS); + aspects.reset(VALIDATION_ASPECT_VERTEX_BUFFERS); + bindgroupsSet = ~layout->GetBindGroupsLayoutMask(); + + // Only bindgroups that were not the same layout in the last pipeline need to be set again. + if (lastPipeline) { + PipelineLayoutBase* lastLayout = lastPipeline->GetLayout(); + for (uint32_t i = 0; i < kMaxBindGroups; ++i) { + if (lastLayout->GetBindGroupLayout(i) == layout->GetBindGroupLayout(i)) { + bindgroupsSet |= uint64_t(1) << i; + } + } + } + + lastPipeline = pipeline; + } + break; + + case Command::SetPushConstants: + { + SetPushConstantsCmd* cmd = iterator.NextCommand(); + iterator.NextData(cmd->count); + if (cmd->count + cmd->offset > kMaxPushConstants) { + device->HandleError("Setting pushconstants past the limit"); + return false; + } + } + break; + + case Command::SetBindGroup: + { + SetBindGroupCmd* cmd = iterator.NextCommand(); + uint32_t index = cmd->index; + + if (cmd->group->GetLayout() != lastPipeline->GetLayout()->GetBindGroupLayout(index)) { + device->HandleError("Bind group layout mismatch"); + return false; + } + if (!validateBindGroupUsages(cmd->group.Get())) { + return false; + } + bindgroupsSet |= uint64_t(1) << index; + } + break; + + case Command::SetIndexBuffer: + { + SetIndexBufferCmd* cmd = iterator.NextCommand(); + auto buffer = cmd->buffer; + auto usage = nxt::BufferUsageBit::Index; + if (!bufferHasGuaranteedUsageBit(buffer.Get(), usage)) { + device->HandleError("Buffer needs the index usage bit to be guaranteed"); + return false; + } + + aspects.set(VALIDATION_ASPECT_INDEX_BUFFER); + } + break; + + case Command::SetVertexBuffers: + { + SetVertexBuffersCmd* cmd = iterator.NextCommand(); + auto buffers = iterator.NextData>(cmd->count); + iterator.NextData(cmd->count); + + for (uint32_t i = 0; i < cmd->count; ++i) { + auto buffer = buffers[i]; + auto usage = nxt::BufferUsageBit::Vertex; + if (!bufferHasGuaranteedUsageBit(buffer.Get(), usage)) { + device->HandleError("Buffer needs vertex usage bit to be guaranteed"); + return false; + } + inputsSet.set(cmd->startSlot + i); + } + } + break; + + case Command::TransitionBufferUsage: + { + TransitionBufferUsageCmd* cmd = iterator.NextCommand(); + auto buffer = cmd->buffer.Get(); + auto usage = cmd->usage; + + if (!cmd->buffer->IsTransitionPossible(cmd->usage)) { + device->HandleError("Buffer frozen or usage not allowed"); + return false; + } + + mostRecentBufferUsages[buffer] = usage; + + buffersTransitioned.insert(buffer); + } + break; + + case Command::TransitionTextureUsage: + { + TransitionTextureUsageCmd* cmd = iterator.NextCommand(); + auto texture = cmd->texture.Get(); + auto usage = cmd->usage; + + if (!cmd->texture->IsTransitionPossible(cmd->usage)) { + device->HandleError("Texture frozen or usage not allowed"); + return false; + } + + mostRecentTextureUsages[texture] = usage; + + texturesTransitioned.insert(texture); + } + break; + } + } + + return true; + } + + CommandIterator CommandBufferBuilder::AcquireCommands() { + return std::move(iterator); + } + + CommandBufferBase* CommandBufferBuilder::GetResult() { + MoveToIterator(); + consumed = true; + return device->CreateCommandBuffer(this); + } + + void CommandBufferBuilder::CopyBufferToTexture(BufferBase* buffer, TextureBase* texture, uint32_t x, uint32_t y, uint32_t z, + uint32_t width, uint32_t height, uint32_t depth, uint32_t level) { + CopyBufferToTextureCmd* copy = allocator.Allocate(Command::CopyBufferToTexture); + new(copy) CopyBufferToTextureCmd; + copy->buffer = buffer; + copy->texture = texture; + copy->x = x; + copy->y = y; + copy->z = z; + copy->width = width; + copy->height = height; + copy->depth = depth; + copy->level = level; + } + + void CommandBufferBuilder::Dispatch(uint32_t x, uint32_t y, uint32_t z) { + DispatchCmd* dispatch = allocator.Allocate(Command::Dispatch); + new(dispatch) DispatchCmd; + dispatch->x = x; + dispatch->y = y; + dispatch->z = z; + } + + void CommandBufferBuilder::DrawArrays(uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t firstInstance) { + DrawArraysCmd* draw = allocator.Allocate(Command::DrawArrays); + new(draw) DrawArraysCmd; + draw->vertexCount = vertexCount; + draw->instanceCount = instanceCount; + draw->firstVertex = firstVertex; + draw->firstInstance = firstInstance; + } + + void CommandBufferBuilder::DrawElements(uint32_t indexCount, uint32_t instanceCount, uint32_t firstIndex, uint32_t firstInstance) { + DrawElementsCmd* draw = allocator.Allocate(Command::DrawElements); + new(draw) DrawElementsCmd; + draw->indexCount = indexCount; + draw->instanceCount = instanceCount; + draw->firstIndex = firstIndex; + draw->firstInstance = firstInstance; + } + + void CommandBufferBuilder::SetPipeline(PipelineBase* pipeline) { + SetPipelineCmd* cmd = allocator.Allocate(Command::SetPipeline); + new(cmd) SetPipelineCmd; + cmd->pipeline = pipeline; + } + + void CommandBufferBuilder::SetPushConstants(nxt::ShaderStageBit stage, uint32_t offset, uint32_t count, const void* data) { + if (offset + count > kMaxPushConstants) { + device->HandleError("Setting too many push constants"); + return; + } + + SetPushConstantsCmd* cmd = allocator.Allocate(Command::SetPushConstants); + new(cmd) SetPushConstantsCmd; + cmd->stage = stage; + cmd->offset = offset; + cmd->count = count; + + uint32_t* values = allocator.AllocateData(count); + memcpy(values, data, count * sizeof(uint32_t)); + } + + void CommandBufferBuilder::SetBindGroup(uint32_t groupIndex, BindGroupBase* group) { + if (groupIndex >= kMaxBindGroups) { + device->HandleError("Setting bind group over the max"); + return; + } + + SetBindGroupCmd* cmd = allocator.Allocate(Command::SetBindGroup); + new(cmd) SetBindGroupCmd; + cmd->index = groupIndex; + cmd->group = group; + } + + void CommandBufferBuilder::SetIndexBuffer(BufferBase* buffer, uint32_t offset, nxt::IndexFormat format) { + // TODO(kainino@chromium.org): validation + + SetIndexBufferCmd* cmd = allocator.Allocate(Command::SetIndexBuffer); + new(cmd) SetIndexBufferCmd; + cmd->buffer = buffer; + cmd->offset = offset; + cmd->format = format; + } + + void CommandBufferBuilder::SetVertexBuffers(uint32_t startSlot, uint32_t count, BufferBase* const* buffers, uint32_t const* offsets){ + // TODO(kainino@chromium.org): validation + + SetVertexBuffersCmd* cmd = allocator.Allocate(Command::SetVertexBuffers); + new(cmd) SetVertexBuffersCmd; + cmd->startSlot = startSlot; + cmd->count = count; + + Ref* cmdBuffers = allocator.AllocateData>(count); + for (size_t i = 0; i < count; ++i) { + new(&cmdBuffers[i]) Ref(buffers[i]); + } + + uint32_t* cmdOffsets = allocator.AllocateData(count); + memcpy(cmdOffsets, offsets, count * sizeof(uint32_t)); + } + + void CommandBufferBuilder::TransitionBufferUsage(BufferBase* buffer, nxt::BufferUsageBit usage) { + TransitionBufferUsageCmd* cmd = allocator.Allocate(Command::TransitionBufferUsage); + new(cmd) TransitionBufferUsageCmd; + cmd->buffer = buffer; + cmd->usage = usage; + } + + void CommandBufferBuilder::TransitionTextureUsage(TextureBase* texture, nxt::TextureUsageBit usage) { + TransitionTextureUsageCmd* cmd = allocator.Allocate(Command::TransitionTextureUsage); + new(cmd) TransitionTextureUsageCmd; + cmd->texture = texture; + cmd->usage = usage; + } + + void CommandBufferBuilder::MoveToIterator() { + if (!movedToIterator) { + iterator = std::move(allocator); + movedToIterator = true; + } + } + +} diff --git a/src/backend/common/CommandBuffer.h b/src/backend/common/CommandBuffer.h new file mode 100644 index 0000000000..1642d54dd1 --- /dev/null +++ b/src/backend/common/CommandBuffer.h @@ -0,0 +1,98 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_COMMANDBUFFERGL_H_ +#define BACKEND_COMMON_COMMANDBUFFERGL_H_ + +#include "nxt/nxtcpp.h" + +#include "CommandAllocator.h" +#include "RefCounted.h" + +#include +#include + +namespace backend { + + class BindGroupBase; + class BufferBase; + class DeviceBase; + class PipelineBase; + class TextureBase; + + class CommandBufferBuilder; + + class CommandBufferBase : public RefCounted { + public: + CommandBufferBase(CommandBufferBuilder* builder); + bool ValidateResourceUsagesImmediate(); + + private: + DeviceBase* device; + std::set buffersTransitioned; + std::set texturesTransitioned; + }; + + class CommandBufferBuilder : public RefCounted { + public: + CommandBufferBuilder(DeviceBase* device); + ~CommandBufferBuilder(); + + bool WasConsumed() const; + bool ValidateGetResult(); + + CommandIterator AcquireCommands(); + + // NXT API + CommandBufferBase* GetResult(); + + void CopyBufferToTexture(BufferBase* buffer, TextureBase* texture, uint32_t x, uint32_t y, uint32_t z, + uint32_t width, uint32_t height, uint32_t depth, uint32_t level); + void Dispatch(uint32_t x, uint32_t y, uint32_t z); + void DrawArrays(uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t firstInstance); + void DrawElements(uint32_t vertexCount, uint32_t instanceCount, uint32_t firstIndex, uint32_t firstInstance); + void SetPushConstants(nxt::ShaderStageBit stage, uint32_t offset, uint32_t count, const void* data); + void SetPipeline(PipelineBase* pipeline); + void SetBindGroup(uint32_t groupIndex, BindGroupBase* group); + void SetIndexBuffer(BufferBase* buffer, uint32_t offset, nxt::IndexFormat format); + + template + void SetVertexBuffers(uint32_t startSlot, uint32_t count, T* const* buffers, uint32_t const* offsets) { + static_assert(std::is_base_of::value, ""); + SetVertexBuffers(startSlot, count, reinterpret_cast(buffers), offsets); + } + void SetVertexBuffers(uint32_t startSlot, uint32_t count, BufferBase* const* buffers, uint32_t const* offsets); + + void TransitionBufferUsage(BufferBase* buffer, nxt::BufferUsageBit usage); + void TransitionTextureUsage(TextureBase* texture, nxt::TextureUsageBit usage); + + private: + friend class CommandBufferBase; + + void MoveToIterator(); + + DeviceBase* device; + CommandAllocator allocator; + CommandIterator iterator; + bool consumed = false; + bool movedToIterator = false; + // These pointers will remain valid since they are referenced by + // the bind groups which are referenced by this command buffer. + std::set buffersTransitioned; + std::set texturesTransitioned; + }; + +} + +#endif // BACKEND_COMMON_COMMANDBUFFERGL_H_ diff --git a/src/backend/common/Commands.h b/src/backend/common/Commands.h new file mode 100644 index 0000000000..f9eebd0222 --- /dev/null +++ b/src/backend/common/Commands.h @@ -0,0 +1,114 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_COMMANDS_H_ +#define BACKEND_COMMON_COMMANDS_H_ + +#include "Texture.h" + +#include "nxt/nxtcpp.h" + +namespace backend { + + // Definition of the commands that are present in the CommandIterator given by the + // CommandBufferBuilder. There are not defined in CommandBuffer.h to break some header + // dependencies: Ref needs Object to be defined. + + enum class Command { + CopyBufferToTexture, + Dispatch, + DrawArrays, + DrawElements, + SetPipeline, + SetPushConstants, + SetBindGroup, + SetIndexBuffer, + SetVertexBuffers, + TransitionBufferUsage, + TransitionTextureUsage, + }; + + struct CopyBufferToTextureCmd { + Ref buffer; + Ref texture; + uint32_t x, y, z; + uint32_t width, height, depth; + uint32_t level; + }; + + struct DispatchCmd { + uint32_t x; + uint32_t y; + uint32_t z; + }; + + struct DrawArraysCmd { + uint32_t vertexCount; + uint32_t instanceCount; + uint32_t firstVertex; + uint32_t firstInstance; + }; + + struct DrawElementsCmd { + uint32_t indexCount; + uint32_t instanceCount; + uint32_t firstIndex; + uint32_t firstInstance; + }; + + struct SetPipelineCmd { + Ref pipeline; + }; + + struct SetPushConstantsCmd { + nxt::ShaderStageBit stage; + uint32_t offset; + uint32_t count; + }; + + struct SetBindGroupCmd { + uint32_t index; + Ref group; + }; + + struct SetIndexBufferCmd { + Ref buffer; + uint32_t offset; + nxt::IndexFormat format; + }; + + struct SetVertexBuffersCmd { + uint32_t startSlot; + uint32_t count; + }; + + struct TransitionBufferUsageCmd { + Ref buffer; + nxt::BufferUsageBit usage; + }; + + struct TransitionTextureUsageCmd { + Ref texture; + uint32_t startLevel; + uint32_t levelCount; + nxt::TextureUsageBit usage; + }; + + // This needs to be called before the CommandIterator is freed so that the Ref<> present in + // the commands have a chance to run their destructor and remove internal references. + void FreeCommands(CommandIterator* commands); + +} + +#endif // BACKEND_COMMON_COMMANDS_H_ diff --git a/src/backend/common/Device.cpp b/src/backend/common/Device.cpp new file mode 100644 index 0000000000..9dea47d052 --- /dev/null +++ b/src/backend/common/Device.cpp @@ -0,0 +1,126 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "Device.h" + +#include "BindGroup.h" +#include "BindGroupLayout.h" +#include "Buffer.h" +#include "CommandBuffer.h" +#include "InputState.h" +#include "Pipeline.h" +#include "PipelineLayout.h" +#include "Queue.h" +#include "Sampler.h" +#include "ShaderModule.h" +#include "Texture.h" + +#include + +namespace backend { + + void RegisterSynchronousErrorCallback(nxtDevice device, ErrorCallback callback, void* userData) { + auto deviceBase = reinterpret_cast(device); + deviceBase->RegisterErrorCallback(callback, userData); + } + + // DeviceBase::Caches + + // The caches are unordered_sets of pointers with special hash and compare functions + // to compare the value of the objects, instead of the pointers. + using BindGroupLayoutCache = std::unordered_set; + + struct DeviceBase::Caches { + BindGroupLayoutCache bindGroupLayouts; + }; + + // DeviceBase + + DeviceBase::DeviceBase() { + caches = new DeviceBase::Caches(); + } + + DeviceBase::~DeviceBase() { + delete caches; + } + + void DeviceBase::HandleError(const char* message) { + if (errorCallback) { + errorCallback(message, errorUserData); + } + } + + void DeviceBase::RegisterErrorCallback(ErrorCallback callback, void* userData) { + this->errorCallback = callback; + this->errorUserData = userData; + } + + BindGroupLayoutBase* DeviceBase::GetOrCreateBindGroupLayout(const BindGroupLayoutBase* blueprint, BindGroupLayoutBuilder* builder) { + // The blueprint is only used to search in the cache and is not modified. However cached + // objects can be modified, and unordered_set cannot search for a const pointer in a non + // const pointer set. That's why we do a const_cast here, but the blueprint won't be + // modified. + auto iter = caches->bindGroupLayouts.find(const_cast(blueprint)); + if (iter != caches->bindGroupLayouts.end()) { + return *iter; + } + + BindGroupLayoutBase* backendObj = CreateBindGroupLayout(builder); + caches->bindGroupLayouts.insert(backendObj); + return backendObj; + } + + void DeviceBase::UncacheBindGroupLayout(BindGroupLayoutBase* obj) { + caches->bindGroupLayouts.erase(obj); + } + + BindGroupBuilder* DeviceBase::CreateBindGroupBuilder() { + return new BindGroupBuilder(this); + } + BindGroupLayoutBuilder* DeviceBase::CreateBindGroupLayoutBuilder() { + return new BindGroupLayoutBuilder(this); + } + BufferBuilder* DeviceBase::CreateBufferBuilder() { + return new BufferBuilder(this); + } + CommandBufferBuilder* DeviceBase::CreateCommandBufferBuilder() { + return new CommandBufferBuilder(this); + } + InputStateBuilder* DeviceBase::CreateInputStateBuilder() { + return new InputStateBuilder(this); + } + PipelineBuilder* DeviceBase::CreatePipelineBuilder() { + return new PipelineBuilder(this); + } + PipelineLayoutBuilder* DeviceBase::CreatePipelineLayoutBuilder() { + return new PipelineLayoutBuilder(this); + } + QueueBuilder* DeviceBase::CreateQueueBuilder() { + return new QueueBuilder(this); + } + SamplerBuilder* DeviceBase::CreateSamplerBuilder() { + return new SamplerBuilder(this); + } + ShaderModuleBuilder* DeviceBase::CreateShaderModuleBuilder() { + return new ShaderModuleBuilder(this); + } + TextureBuilder* DeviceBase::CreateTextureBuilder() { + return new TextureBuilder(this); + } + + void DeviceBase::CopyBindGroups(uint32_t start, uint32_t count, BindGroupBase* source, BindGroupBase* target) { + // TODO(cwallez@chromium.org): update state tracking then call the backend + } + +} diff --git a/src/backend/common/Device.h b/src/backend/common/Device.h new file mode 100644 index 0000000000..a7b8e4cd25 --- /dev/null +++ b/src/backend/common/Device.h @@ -0,0 +1,94 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_DEVICEBASE_H_ +#define BACKEND_COMMON_DEVICEBASE_H_ + +#include "common/Forward.h" +#include "common/RefCounted.h" + +#include "nxt/nxtcpp.h" + +namespace backend { + + using ErrorCallback = void (*)(const char* errorMessage, void* userData); + + class DeviceBase { + public: + DeviceBase(); + ~DeviceBase(); + + void HandleError(const char* message); + void RegisterErrorCallback(ErrorCallback callback, void* userData); + + virtual BindGroupBase* CreateBindGroup(BindGroupBuilder* builder) = 0; + virtual BindGroupLayoutBase* CreateBindGroupLayout(BindGroupLayoutBuilder* builder) = 0; + virtual BufferBase* CreateBuffer(BufferBuilder* builder) = 0; + virtual BufferViewBase* CreateBufferView(BufferViewBuilder* builder) = 0; + virtual CommandBufferBase* CreateCommandBuffer(CommandBufferBuilder* builder) = 0; + virtual InputStateBase* CreateInputState(InputStateBuilder* builder) = 0; + virtual PipelineBase* CreatePipeline(PipelineBuilder* builder) = 0; + virtual PipelineLayoutBase* CreatePipelineLayout(PipelineLayoutBuilder* builder) = 0; + virtual QueueBase* CreateQueue(QueueBuilder* builder) = 0; + virtual SamplerBase* CreateSampler(SamplerBuilder* builder) = 0; + virtual ShaderModuleBase* CreateShaderModule(ShaderModuleBuilder* builder) = 0; + virtual TextureBase* CreateTexture(TextureBuilder* builder) = 0; + virtual TextureViewBase* CreateTextureView(TextureViewBuilder* builder) = 0; + + // Many NXT objects are completely immutable once created which means that if two + // builders are given the same arguments, they can return the same object. Reusing + // objects will help make comparisons between objects by a single pointer comparison. + // + // Technically no object is immutable as they have a reference count, and an + // application with reference-counting issues could "see" that objects are reused. + // This is solved by automatic-reference counting, and also the fact that when using + // the client-server wire every creation will get a different proxy object, with a + // different reference count. + // + // When trying to create an object, we give both the builder and an example of what + // the built object will be, the "blueprint". The blueprint is just a FooBase object + // instead of a backend Foo object. If the blueprint doesn't match an object in the + // cache, then the builder is used to make a new object. + BindGroupLayoutBase* GetOrCreateBindGroupLayout(const BindGroupLayoutBase* blueprint, BindGroupLayoutBuilder* builder); + void UncacheBindGroupLayout(BindGroupLayoutBase* obj); + + // NXT API + BindGroupBuilder* CreateBindGroupBuilder(); + BindGroupLayoutBuilder* CreateBindGroupLayoutBuilder(); + BufferBuilder* CreateBufferBuilder(); + BufferViewBuilder* CreateBufferViewBuilder(); + CommandBufferBuilder* CreateCommandBufferBuilder(); + InputStateBuilder* CreateInputStateBuilder(); + PipelineBuilder* CreatePipelineBuilder(); + PipelineLayoutBuilder* CreatePipelineLayoutBuilder(); + QueueBuilder* CreateQueueBuilder(); + SamplerBuilder* CreateSamplerBuilder(); + ShaderModuleBuilder* CreateShaderModuleBuilder(); + TextureBuilder* CreateTextureBuilder(); + + void CopyBindGroups(uint32_t start, uint32_t count, BindGroupBase* source, BindGroupBase* target); + + private: + // The object caches aren't exposed in the header as they would require a lot of + // additional includes. + struct Caches; + Caches* caches = nullptr; + + ErrorCallback errorCallback = nullptr; + void* errorUserData = nullptr; + }; + +} + +#endif // BACKEND_COMMON_DEVICEBASE_H_ diff --git a/src/backend/common/Forward.h b/src/backend/common/Forward.h new file mode 100644 index 0000000000..94e64ce64b --- /dev/null +++ b/src/backend/common/Forward.h @@ -0,0 +1,71 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_FORWARD_H_ +#define BACKEND_COMMON_FORWARD_H_ + +#include +#include + +#define ASSERT assert + +namespace backend { + + class BindGroupBase; + class BindGroupBuilder; + class BindGroupLayoutBase; + class BindGroupLayoutBuilder; + class BufferBase; + class BufferBuilder; + class BufferViewBase; + class BufferViewBuilder; + class CommandBufferBase; + class CommandBufferBuilder; + class InputStateBase; + class InputStateBuilder; + class PipelineBase; + class PipelineBuilder; + class PipelineLayoutBase; + class PipelineLayoutBuilder; + class QueueBase; + class QueueBuilder; + class SamplerBase; + class SamplerBuilder; + class ShaderModuleBase; + class ShaderModuleBuilder; + class TextureBase; + class TextureBuilder; + class TextureViewBase; + class TextureViewBuilder; + + class DeviceBase; + + template + class Ref; + + template + class PerStage; + + // TODO(cwallez@chromium.org): where should constants live? + static constexpr uint32_t kMaxPushConstants = 32u; + static constexpr uint32_t kMaxBindGroups = 4u; + static constexpr uint32_t kMaxBindingsPerGroup = 16u; // TODO(cwallez@chromium.org): investigate bindgroup limits + static constexpr uint32_t kMaxVertexAttributes = 16u; + static constexpr uint32_t kMaxVertexInputs = 16u; + static constexpr uint32_t kNumStages = 3; + + enum PushConstantType : uint8_t; +} + +#endif // BACKEND_COMMON_FORWARD_H_ diff --git a/src/backend/common/InputState.cpp b/src/backend/common/InputState.cpp new file mode 100644 index 0000000000..2b2da0c117 --- /dev/null +++ b/src/backend/common/InputState.cpp @@ -0,0 +1,139 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "InputState.h" + +#include "Device.h" + +namespace backend { + + // InputState helpers + + size_t IndexFormatSize(nxt::IndexFormat format) { + switch (format) { + case nxt::IndexFormat::Uint16: + return sizeof(uint16_t); + case nxt::IndexFormat::Uint32: + return sizeof(uint32_t); + } + } + + uint32_t VertexFormatNumComponents(nxt::VertexFormat format) { + switch (format) { + case nxt::VertexFormat::FloatR32G32B32A32: + return 4; + case nxt::VertexFormat::FloatR32G32B32: + return 3; + case nxt::VertexFormat::FloatR32G32: + return 2; + } + } + + size_t VertexFormatSize(nxt::VertexFormat format) { + switch (format) { + case nxt::VertexFormat::FloatR32G32B32A32: + case nxt::VertexFormat::FloatR32G32B32: + case nxt::VertexFormat::FloatR32G32: + return VertexFormatNumComponents(format) * sizeof(float); + } + } + + // InputStateBase + + InputStateBase::InputStateBase(InputStateBuilder* builder) { + attributesSetMask = builder->attributesSetMask; + attributeInfos = builder->attributeInfos; + inputsSetMask = builder->inputsSetMask; + inputInfos = builder->inputInfos; + } + + const std::bitset& InputStateBase::GetAttributesSetMask() const { + return attributesSetMask; + } + + const InputStateBase::AttributeInfo& InputStateBase::GetAttribute(uint32_t location) const { + ASSERT(attributesSetMask[location]); + return attributeInfos[location]; + } + + const std::bitset& InputStateBase::GetInputsSetMask() const { + return inputsSetMask; + } + + const InputStateBase::InputInfo& InputStateBase::GetInput(uint32_t slot) const { + ASSERT(inputsSetMask[slot]); + return inputInfos[slot]; + } + + // InputStateBuilder + + InputStateBuilder::InputStateBuilder(DeviceBase* device) : device(device) { + } + + bool InputStateBuilder::WasConsumed() const { + return consumed; + } + + InputStateBase* InputStateBuilder::GetResult() { + for (uint32_t location = 0; location < kMaxVertexAttributes; ++location) { + if (attributesSetMask[location] && + !inputsSetMask[attributeInfos[location].bindingSlot]) { + device->HandleError("Attribute uses unset input"); + return nullptr; + } + } + consumed = true; + return device->CreateInputState(this); + } + + void InputStateBuilder::SetAttribute(uint32_t shaderLocation, + uint32_t bindingSlot, nxt::VertexFormat format, uint32_t offset) { + if (shaderLocation >= kMaxVertexAttributes) { + device->HandleError("Setting attribute out of bounds"); + return; + } + if (bindingSlot >= kMaxVertexInputs) { + device->HandleError("Binding slot out of bounds"); + return; + } + if (attributesSetMask[shaderLocation]) { + device->HandleError("Setting already set attribute"); + return; + } + + attributesSetMask.set(shaderLocation); + auto& info = attributeInfos[shaderLocation]; + info.bindingSlot = bindingSlot; + info.format = format; + info.offset = offset; + } + + void InputStateBuilder::SetInput(uint32_t bindingSlot, uint32_t stride, + nxt::InputStepMode stepMode) { + if (bindingSlot >= kMaxVertexInputs) { + device->HandleError("Setting input out of bounds"); + return; + } + if (inputsSetMask[bindingSlot]) { + device->HandleError("Setting already set input"); + return; + } + + inputsSetMask.set(bindingSlot); + auto& info = inputInfos[bindingSlot]; + info.stride = stride; + info.stepMode = stepMode; + } + +} diff --git a/src/backend/common/InputState.h b/src/backend/common/InputState.h new file mode 100644 index 0000000000..3cf29c2814 --- /dev/null +++ b/src/backend/common/InputState.h @@ -0,0 +1,85 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_INPUTSTATE_H_ +#define BACKEND_COMMON_INPUTSTATE_H_ + +#include "Forward.h" +#include "RefCounted.h" + +#include "nxt/nxtcpp.h" + +#include +#include + +namespace backend { + + size_t IndexFormatSize(nxt::IndexFormat format); + uint32_t VertexFormatNumComponents(nxt::VertexFormat format); + size_t VertexFormatSize(nxt::VertexFormat format); + + class InputStateBase : public RefCounted { + public: + InputStateBase(InputStateBuilder* builder); + + struct AttributeInfo { + uint32_t bindingSlot; + nxt::VertexFormat format; + uint32_t offset; + }; + + struct InputInfo { + uint32_t stride; + nxt::InputStepMode stepMode; + }; + + const std::bitset& GetAttributesSetMask() const; + const AttributeInfo& GetAttribute(uint32_t location) const; + const std::bitset& GetInputsSetMask() const; + const InputInfo& GetInput(uint32_t slot) const; + + private: + std::bitset attributesSetMask; + std::array attributeInfos; + std::bitset inputsSetMask; + std::array inputInfos; + }; + + class InputStateBuilder : public RefCounted { + public: + InputStateBuilder(DeviceBase* device); + + bool WasConsumed() const; + + // NXT API + InputStateBase* GetResult(); + void SetAttribute(uint32_t shaderLocation, uint32_t bindingSlot, + nxt::VertexFormat format, uint32_t offset); + void SetInput(uint32_t bindingSlot, uint32_t stride, + nxt::InputStepMode stepMode); + + private: + friend class InputStateBase; + + DeviceBase* device; + std::bitset attributesSetMask; + std::array attributeInfos; + std::bitset inputsSetMask; + std::array inputInfos; + bool consumed = false; + }; + +} + +#endif // BACKEND_COMMON_INPUTSTATE_H_ diff --git a/src/backend/common/Math.cpp b/src/backend/common/Math.cpp new file mode 100644 index 0000000000..483f524ccc --- /dev/null +++ b/src/backend/common/Math.cpp @@ -0,0 +1,52 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "Math.h" + +#include "Forward.h" + +namespace backend { + + unsigned long ScanForward(unsigned long bits) { + ASSERT(bits != 0); + // TODO(cwallez@chromium.org): handle non-posix platforms + // unsigned long firstBitIndex = 0ul; + // unsigned char ret = _BitScanForward(&firstBitIndex, bits); + // ASSERT(ret != 0); + // return firstBitIndex; + return static_cast(__builtin_ctzl(bits)); + } + + uint32_t Log2(uint32_t value) { + ASSERT(value != 0); + return 31 - __builtin_clz(value); + } + + bool IsPowerOfTwo(size_t n) { + ASSERT(n != 0); + return (n & (n - 1)) == 0; + } + + bool IsAligned(const void* ptr, size_t alignment) { + ASSERT(IsPowerOfTwo(alignment)); + ASSERT(alignment != 0); + return (reinterpret_cast(ptr) & (alignment - 1)) == 0; + } + + void* AlignVoidPtr(void* ptr, size_t alignment) { + ASSERT(alignment != 0); + return reinterpret_cast((reinterpret_cast(ptr) + (alignment - 1)) & ~(alignment - 1)); + } + +} diff --git a/src/backend/common/Math.h b/src/backend/common/Math.h new file mode 100644 index 0000000000..4e9e9fb84d --- /dev/null +++ b/src/backend/common/Math.h @@ -0,0 +1,43 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_MATH_H_ +#define BACKEND_COMMON_MATH_H_ + +#include +#include "cstdint" + +namespace backend { + + // The following are not valid for 0 + unsigned long ScanForward(unsigned long bits); + uint32_t Log2(uint32_t value); + bool IsPowerOfTwo(size_t n); + + bool IsAligned(const void* ptr, size_t alignment); + void* AlignVoidPtr(void* ptr, size_t alignment); + + template + T* Align(T* ptr, size_t alignment) { + return reinterpret_cast(AlignVoidPtr(ptr, alignment)); + } + + template + const T* Align(const T* ptr, size_t alignment) { + return reinterpret_cast(AlignVoidPtr(const_cast(ptr), alignment)); + } + +} + +#endif // BACKEND_COMMON_MATH_H_ diff --git a/src/backend/common/PerStage.cpp b/src/backend/common/PerStage.cpp new file mode 100644 index 0000000000..cdccac5a76 --- /dev/null +++ b/src/backend/common/PerStage.cpp @@ -0,0 +1,29 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "PerStage.h" + +namespace backend { + + BitSetIterator IterateStages(nxt::ShaderStageBit stages) { + std::bitset bits(static_cast(stages)); + return BitSetIterator(bits); + } + + nxt::ShaderStageBit StageBit(nxt::ShaderStage stage) { + ASSERT(static_cast(stage) < kNumStages); + return static_cast(1 << static_cast(stage)); + } + +} diff --git a/src/backend/common/PerStage.h b/src/backend/common/PerStage.h new file mode 100644 index 0000000000..c14dde8795 --- /dev/null +++ b/src/backend/common/PerStage.h @@ -0,0 +1,68 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_PERSTAGE_H_ +#define BACKEND_COMMON_PERSTAGE_H_ + +#include "BitSetIterator.h" + +#include "nxt/nxtcpp.h" + +#include + +namespace backend { + + static_assert(static_cast(nxt::ShaderStage::Vertex) < kNumStages, ""); + static_assert(static_cast(nxt::ShaderStage::Fragment) < kNumStages, ""); + static_assert(static_cast(nxt::ShaderStage::Compute) < kNumStages, ""); + + static_assert(static_cast(nxt::ShaderStageBit::Vertex) == (1 << static_cast(nxt::ShaderStage::Vertex)), ""); + static_assert(static_cast(nxt::ShaderStageBit::Fragment) == (1 << static_cast(nxt::ShaderStage::Fragment)), ""); + static_assert(static_cast(nxt::ShaderStageBit::Compute) == (1 << static_cast(nxt::ShaderStage::Compute)), ""); + + BitSetIterator IterateStages(nxt::ShaderStageBit stages); + nxt::ShaderStageBit StageBit(nxt::ShaderStage stage); + + static constexpr nxt::ShaderStageBit kAllStages = static_cast((1 << kNumStages) - 1); + + template + class PerStage { + public: + T& operator[](nxt::ShaderStage stage) { + ASSERT(static_cast(stage) < kNumStages); + return data[static_cast(stage)]; + } + const T& operator[](nxt::ShaderStage stage) const { + ASSERT(static_cast(stage) < kNumStages); + return data[static_cast(stage)]; + } + + T& operator[](nxt::ShaderStageBit stageBit) { + uint32_t bit = static_cast(stageBit); + ASSERT(bit != 0 && IsPowerOfTwo(bit) && bit <= (1 << kNumStages)); + return data[Log2(bit)]; + } + const T& operator[](nxt::ShaderStageBit stageBit) const { + uint32_t bit = static_cast(stageBit); + ASSERT(bit != 0 && IsPowerOfTwo(bit) && bit <= (1 << kNumStages)); + return data[Log2(bit)]; + } + + private: + std::array data; + }; + +} + +#endif // BACKEND_COMMON_PERSTAGE_H_ diff --git a/src/backend/common/Pipeline.cpp b/src/backend/common/Pipeline.cpp new file mode 100644 index 0000000000..f9901af60a --- /dev/null +++ b/src/backend/common/Pipeline.cpp @@ -0,0 +1,149 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "Pipeline.h" + +#include "Device.h" +#include "InputState.h" +#include "PipelineLayout.h" +#include "ShaderModule.h" + +namespace backend { + + // PipelineBase + + PipelineBase::PipelineBase(PipelineBuilder* builder) + : device(builder->device), stageMask(builder->stageMask), layout(std::move(builder->layout)), + inputState(std::move(builder->inputState)) { + + if (stageMask != (nxt::ShaderStageBit::Vertex | nxt::ShaderStageBit::Fragment) && + stageMask != nxt::ShaderStageBit::Compute) { + device->HandleError("Wrong combination of stage for pipeline"); + return; + } + + auto FillPushConstants = [](const ShaderModuleBase* module, PushConstantInfo* info) { + const auto& moduleInfo = module->GetPushConstants(); + info->mask = moduleInfo.mask; + + for (uint32_t i = 0; i < moduleInfo.names.size(); i++) { + unsigned int size = moduleInfo.sizes[i]; + if (size == 0) { + continue; + } + + for (uint32_t offset = 0; offset < size; offset++) { + info->types[i + offset] = moduleInfo.types[i]; + } + i += size - 1; + } + }; + + for (auto stageBit : IterateStages(builder->stageMask)) { + if (!builder->stages[stageBit].module->IsCompatibleWithPipelineLayout(layout.Get())) { + device->HandleError("Stage not compatible with layout"); + return; + } + + FillPushConstants(builder->stages[stageBit].module.Get(), &pushConstants[stageBit]); + } + + if (!IsCompute()) { + if ((builder->stages[nxt::ShaderStage::Vertex].module->GetUsedVertexAttributes() & ~inputState->GetAttributesSetMask()).any()) { + device->HandleError("Pipeline vertex stage uses inputs not in the input state"); + return; + } + } + } + + const PipelineBase::PushConstantInfo& PipelineBase::GetPushConstants(nxt::ShaderStage stage) const { + return pushConstants[stage]; + } + + nxt::ShaderStageBit PipelineBase::GetStageMask() const { + return stageMask; + } + + PipelineLayoutBase* PipelineBase::GetLayout() { + return layout.Get(); + } + + InputStateBase* PipelineBase::GetInputState() { + return inputState.Get(); + } + + bool PipelineBase::IsCompute() const { + return stageMask == nxt::ShaderStageBit::Compute; + } + + // PipelineBuilder + + PipelineBuilder::PipelineBuilder(DeviceBase* device) + : device(device), stageMask(static_cast(0)) { + } + + bool PipelineBuilder::WasConsumed() const { + return consumed; + } + + const PipelineBuilder::StageInfo& PipelineBuilder::GetStageInfo(nxt::ShaderStage stage) const { + ASSERT(stageMask & StageBit(stage)); + return stages[stage]; + } + + PipelineBase* PipelineBuilder::GetResult() { + // TODO(cwallez@chromium.org): the layout should be required, and put the default objects in the device + if (!layout) { + layout = device->CreatePipelineLayoutBuilder()->GetResult(); + } + if (!inputState) { + inputState = device->CreateInputStateBuilder()->GetResult(); + } + + consumed = true; + return device->CreatePipeline(this); + } + + void PipelineBuilder::SetLayout(PipelineLayoutBase* layout) { + this->layout = layout; + } + + void PipelineBuilder::SetStage(nxt::ShaderStage stage, ShaderModuleBase* module, const char* entryPoint) { + if (entryPoint != std::string("main")) { + device->HandleError("Currently the entry point has to be main()"); + return; + } + + if (stage != module->GetExecutionModel()) { + device->HandleError("Setting module with wrong execution model"); + return; + } + + nxt::ShaderStageBit bit = StageBit(stage); + if (stageMask & bit) { + device->HandleError("Setting already set stage"); + return; + } + stageMask |= bit; + + stages[stage].module = module; + stages[stage].entryPoint = entryPoint; + } + + void PipelineBuilder::SetInputState(InputStateBase* inputState) { + this->inputState = inputState; + } + + +} diff --git a/src/backend/common/Pipeline.h b/src/backend/common/Pipeline.h new file mode 100644 index 0000000000..761ec5aa15 --- /dev/null +++ b/src/backend/common/Pipeline.h @@ -0,0 +1,92 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_PIPELINE_H_ +#define BACKEND_COMMON_PIPELINE_H_ + +#include "Forward.h" +#include "PerStage.h" +#include "RefCounted.h" + +#include "nxt/nxtcpp.h" + +#include +#include + +namespace backend { + + enum PushConstantType : uint8_t { + Int, + UInt, + Float, + }; + + class PipelineBase : public RefCounted { + public: + PipelineBase(PipelineBuilder* builder); + + struct PushConstantInfo { + std::bitset mask; + std::array types; + }; + const PushConstantInfo& GetPushConstants(nxt::ShaderStage stage) const; + nxt::ShaderStageBit GetStageMask() const; + + PipelineLayoutBase* GetLayout(); + InputStateBase* GetInputState(); + + // TODO(cwallez@chromium.org): split compute and render pipelines + bool IsCompute() const; + + private: + DeviceBase* device; + + nxt::ShaderStageBit stageMask; + Ref layout; + PerStage pushConstants; + Ref inputState; + }; + + class PipelineBuilder : public RefCounted { + public: + PipelineBuilder(DeviceBase* device); + + bool WasConsumed() const; + + struct StageInfo { + std::string entryPoint; + Ref module; + }; + const StageInfo& GetStageInfo(nxt::ShaderStage stage) const; + + // NXT API + PipelineBase* GetResult(); + void SetLayout(PipelineLayoutBase* layout); + void SetStage(nxt::ShaderStage stage, ShaderModuleBase* module, const char* entryPoint); + void SetInputState(InputStateBase* inputState); + + private: + friend class PipelineBase; + + DeviceBase* device; + Ref layout; + nxt::ShaderStageBit stageMask; + PerStage stages; + Ref inputState; + bool consumed = false; + }; + +} + +#endif // BACKEND_COMMON_PIPELINE_H_ diff --git a/src/backend/common/PipelineLayout.cpp b/src/backend/common/PipelineLayout.cpp new file mode 100644 index 0000000000..3a01640053 --- /dev/null +++ b/src/backend/common/PipelineLayout.cpp @@ -0,0 +1,73 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "PipelineLayout.h" + +#include "BindGroupLayout.h" +#include "Device.h" + +namespace backend { + + // PipelineLayoutBase + + PipelineLayoutBase::PipelineLayoutBase(PipelineLayoutBuilder* builder) + : bindGroupLayouts(std::move(builder->bindGroupLayouts)), mask(builder->mask) { + } + + const BindGroupLayoutBase* PipelineLayoutBase::GetBindGroupLayout(size_t group) const { + ASSERT(group < kMaxBindGroups); + return bindGroupLayouts[group].Get(); + } + + const std::bitset PipelineLayoutBase::GetBindGroupsLayoutMask() const { + return mask; + } + + // PipelineLayoutBuilder + + PipelineLayoutBuilder::PipelineLayoutBuilder(DeviceBase* device) : device(device) { + } + + bool PipelineLayoutBuilder::WasConsumed() const { + return consumed; + } + + PipelineLayoutBase* PipelineLayoutBuilder::GetResult() { + // TODO(cwallez@chromium.org): this is a hack, have the null bind group layout somewhere in the device + // once we have a cache of BGL + for (size_t group = 0; group < kMaxBindGroups; ++group) { + if (!bindGroupLayouts[group]) { + bindGroupLayouts[group] = device->CreateBindGroupLayoutBuilder()->GetResult(); + } + } + + consumed = true; + return device->CreatePipelineLayout(this); + } + + void PipelineLayoutBuilder::SetBindGroupLayout(uint32_t groupIndex, BindGroupLayoutBase* layout) { + if (groupIndex >= kMaxBindGroups) { + device->HandleError("groupIndex is over the maximum allowed"); + return; + } + if (mask[groupIndex]) { + device->HandleError("Bind group layout already specified"); + return; + } + + bindGroupLayouts[groupIndex] = layout; + mask.set(groupIndex); + } + +} diff --git a/src/backend/common/PipelineLayout.h b/src/backend/common/PipelineLayout.h new file mode 100644 index 0000000000..79e362617f --- /dev/null +++ b/src/backend/common/PipelineLayout.h @@ -0,0 +1,63 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_PIPELINELAYOUT_H_ +#define BACKEND_COMMON_PIPELINELAYOUT_H_ + +#include "Forward.h" +#include "RefCounted.h" + +#include "nxt/nxtcpp.h" + +#include +#include + +namespace backend { + + using BindGroupLayoutArray = std::array, kMaxBindGroups>; + + class PipelineLayoutBase : public RefCounted { + public: + PipelineLayoutBase(PipelineLayoutBuilder* builder); + + const BindGroupLayoutBase* GetBindGroupLayout(size_t group) const; + const std::bitset GetBindGroupsLayoutMask() const; + + protected: + BindGroupLayoutArray bindGroupLayouts; + std::bitset mask; + }; + + class PipelineLayoutBuilder : public RefCounted { + public: + PipelineLayoutBuilder(DeviceBase* device); + + bool WasConsumed() const; + + // NXT API + PipelineLayoutBase* GetResult(); + void SetBindGroupLayout(uint32_t groupIndex, BindGroupLayoutBase* layout); + + private: + friend class PipelineLayoutBase; + + DeviceBase* device; + BindGroupLayoutArray bindGroupLayouts; + std::bitset mask; + bool consumed = false; + }; + +} + +#endif // BACKEND_COMMON_PIPELINELAYOUT_H_ diff --git a/src/backend/common/Queue.cpp b/src/backend/common/Queue.cpp new file mode 100644 index 0000000000..f5483fbffc --- /dev/null +++ b/src/backend/common/Queue.cpp @@ -0,0 +1,42 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "Queue.h" + +#include "Device.h" +#include "CommandBuffer.h" + +namespace backend { + + // QueueBase + + bool QueueBase::ValidateSubmitCommand(CommandBufferBase* command) { + return command->ValidateResourceUsagesImmediate(); + } + + // QueueBuilder + + QueueBuilder::QueueBuilder(DeviceBase* device) : device(device) { + } + + bool QueueBuilder::WasConsumed() const { + return consumed; + } + + QueueBase* QueueBuilder::GetResult() { + consumed = true; + return device->CreateQueue(this); + } + +} diff --git a/src/backend/common/Queue.h b/src/backend/common/Queue.h new file mode 100644 index 0000000000..0c0ce6c35c --- /dev/null +++ b/src/backend/common/Queue.h @@ -0,0 +1,59 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_QUEUE_H_ +#define BACKEND_COMMON_QUEUE_H_ + +#include "Forward.h" +#include "RefCounted.h" + +#include "nxt/nxtcpp.h" + +namespace backend { + + class QueueBase : public RefCounted { + private: + bool ValidateSubmitCommand(CommandBufferBase* command); + + public: + template + bool ValidateSubmit(uint32_t numCommands, T* const * commands) { + static_assert(std::is_base_of::value, "invalid command buffer type"); + + for (uint32_t i = 0; i < numCommands; ++i) { + if (!ValidateSubmitCommand(commands[i])) { + return false; + } + } + return true; + } + }; + + class QueueBuilder : public RefCounted { + public: + QueueBuilder(DeviceBase* device); + + bool WasConsumed() const; + + // NXT API + QueueBase* GetResult(); + + private: + DeviceBase* device; + bool consumed = false; + }; + +} + +#endif // BACKEND_COMMON_QUEUE_H_ diff --git a/src/backend/common/RefCounted.cpp b/src/backend/common/RefCounted.cpp new file mode 100644 index 0000000000..076b57f624 --- /dev/null +++ b/src/backend/common/RefCounted.cpp @@ -0,0 +1,66 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "RefCounted.h" + +#include +#define ASSERT assert + +namespace backend { + + RefCounted::RefCounted() { + } + + RefCounted::~RefCounted() { + } + + void RefCounted::ReferenceInternal() { + ASSERT(internalRefs != 0); + // TODO(cwallez@chromium.org): what to do on overflow? + internalRefs ++; + } + + void RefCounted::ReleaseInternal() { + ASSERT(internalRefs != 0); + internalRefs --; + if (internalRefs == 0) { + ASSERT(externalRefs == 0); + // TODO(cwallez@chromium.org): would this work with custom allocators? + delete this; + } + } + + uint32_t RefCounted::GetExternalRefs() const { + return externalRefs; + } + + uint32_t RefCounted::GetInternalRefs() const { + return internalRefs; + } + + void RefCounted::Reference() { + ASSERT(externalRefs != 0); + // TODO(cwallez@chromium.org): what to do on overflow? + externalRefs ++; + } + + void RefCounted::Release() { + ASSERT(externalRefs != 0); + externalRefs --; + if (externalRefs == 0) { + ReleaseInternal(); + } + } + +} diff --git a/src/backend/common/RefCounted.h b/src/backend/common/RefCounted.h new file mode 100644 index 0000000000..a9aa30466a --- /dev/null +++ b/src/backend/common/RefCounted.h @@ -0,0 +1,126 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_REFCOUNTED_H_ +#define BACKEND_COMMON_REFCOUNTED_H_ + +#include + +namespace backend { + + class RefCounted { + public: + RefCounted(); + virtual ~RefCounted(); + + void ReferenceInternal(); + void ReleaseInternal(); + + uint32_t GetExternalRefs() const; + uint32_t GetInternalRefs() const; + + // NXT API + void Reference(); + void Release(); + + protected: + uint32_t externalRefs = 1; + uint32_t internalRefs = 1; + }; + + template + class Ref { + public: + Ref() {} + + Ref(T* p): pointee(p) { + Reference(); + } + + Ref(Ref& other): pointee(other.pointee) { + Reference(); + } + Ref& operator=(const Ref& other) { + if (&other == this) return *this; + + other.Reference(); + Release(); + pointee = other.pointee; + + return *this; + } + + Ref(Ref&& other) { + pointee = other.pointee; + other.pointee = nullptr; + } + Ref& operator=(Ref&& other) { + if (&other == this) return *this; + + Release(); + pointee = other.pointee; + other.pointee = nullptr; + + return *this; + } + + ~Ref() { + Release(); + pointee = nullptr; + } + + operator bool() { + return pointee != nullptr; + } + + const T& operator*() const { + return *pointee; + } + T& operator*() { + return *pointee; + } + + const T* operator->() const { + return pointee; + } + T* operator->() { + return pointee; + } + + const T* Get() const { + return pointee; + } + T* Get() { + return pointee; + } + + private: + void Reference() const { + if (pointee != nullptr) { + pointee->ReferenceInternal(); + } + } + void Release() const { + if (pointee != nullptr) { + pointee->ReleaseInternal(); + } + } + + //static_assert(std::is_base_of::value, ""); + T* pointee = nullptr; + }; + +} + +#endif // BACKEND_COMMON_REFCOUNTED_H_ diff --git a/src/backend/common/Sampler.cpp b/src/backend/common/Sampler.cpp new file mode 100644 index 0000000000..8a4f2fa4fc --- /dev/null +++ b/src/backend/common/Sampler.cpp @@ -0,0 +1,67 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "Sampler.h" + +#include "Device.h" + +namespace backend { + + // SamplerBase + + SamplerBase::SamplerBase(SamplerBuilder* builder) { + } + + // SamplerBuilder + + enum SamplerSetProperties { + SAMPLER_PROPERTY_FILTER = 0x1, + }; + SamplerBuilder::SamplerBuilder(DeviceBase* device) + :device(device) { + } + + nxt::FilterMode SamplerBuilder::GetMagFilter() const { + return magFilter; + } + + nxt::FilterMode SamplerBuilder::GetMinFilter() const { + return minFilter; + } + + nxt::FilterMode SamplerBuilder::GetMipMapFilter() const { + return mipMapFilter; + } + + bool SamplerBuilder::WasConsumed() const { + return consumed; + } + + SamplerBase* SamplerBuilder::GetResult() { + consumed = true; + return device->CreateSampler(this); + } + + void SamplerBuilder::SetFilterMode(nxt::FilterMode magFilter, nxt::FilterMode minFilter, nxt::FilterMode mipMapFilter) { + if ((propertiesSet & SAMPLER_PROPERTY_FILTER) != 0) { + device->HandleError("Sampler filter property set multiple times"); + return; + } + + this->magFilter = magFilter; + this->minFilter = minFilter; + this->mipMapFilter = mipMapFilter; + propertiesSet |= SAMPLER_PROPERTY_FILTER; + } +} diff --git a/src/backend/common/Sampler.h b/src/backend/common/Sampler.h new file mode 100644 index 0000000000..bbd5c58e6c --- /dev/null +++ b/src/backend/common/Sampler.h @@ -0,0 +1,58 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_SAMPLER_H_ +#define BACKEND_COMMON_SAMPLER_H_ + +#include "Forward.h" +#include "RefCounted.h" + +#include "nxt/nxtcpp.h" + +namespace backend { + + class SamplerBase : public RefCounted { + public: + SamplerBase(SamplerBuilder* builder); + }; + + class SamplerBuilder : public RefCounted { + public: + SamplerBuilder(DeviceBase* device); + + nxt::FilterMode GetMagFilter() const; + nxt::FilterMode GetMinFilter() const; + nxt::FilterMode GetMipMapFilter() const; + + bool WasConsumed() const; + + // NXT API + SamplerBase* GetResult(); + void SetFilterMode(nxt::FilterMode magFilter, nxt::FilterMode minFilter, nxt::FilterMode mipMapFilter); + + private: + friend class SamplerBase; + + DeviceBase* device; + int propertiesSet = 0; + bool consumed = false; + + nxt::FilterMode magFilter = nxt::FilterMode::Nearest; + nxt::FilterMode minFilter = nxt::FilterMode::Nearest; + nxt::FilterMode mipMapFilter = nxt::FilterMode::Nearest; + }; + +} + +#endif // BACKEND_COMMON_SAMPLER_H_ diff --git a/src/backend/common/ShaderModule.cpp b/src/backend/common/ShaderModule.cpp new file mode 100644 index 0000000000..831dcb8f5b --- /dev/null +++ b/src/backend/common/ShaderModule.cpp @@ -0,0 +1,217 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "ShaderModule.h" + +#include "BindGroupLayout.h" +#include "Device.h" +#include "Pipeline.h" +#include "PipelineLayout.h" + +#include + +namespace backend { + + ShaderModuleBase::ShaderModuleBase(ShaderModuleBuilder* builder) + : device(builder->device) { + } + + void ShaderModuleBase::ExtractSpirvInfo(const spirv_cross::Compiler& compiler) { + const auto& resources = compiler.get_shader_resources(); + + switch (compiler.get_execution_model()) { + case spv::ExecutionModelVertex: + executionModel = nxt::ShaderStage::Vertex; + break; + case spv::ExecutionModelFragment: + executionModel = nxt::ShaderStage::Fragment; + break; + case spv::ExecutionModelGLCompute: + executionModel = nxt::ShaderStage::Compute; + break; + default: + ASSERT(false); + break; + } + + // Extract push constants + pushConstants.mask.reset(); + pushConstants.sizes.fill(0); + pushConstants.types.fill(PushConstantType::Int); + + if (resources.push_constant_buffers.size() > 0) { + auto interfaceBlock = resources.push_constant_buffers[0]; + + const auto& blockType = compiler.get_type(interfaceBlock.type_id); + ASSERT(blockType.basetype == spirv_cross::SPIRType::Struct); + + for (uint32_t i = 0; i < blockType.member_types.size(); i++) { + ASSERT(compiler.get_member_decoration_mask(blockType.self, i) & 1ull << spv::DecorationOffset); + uint32_t offset = compiler.get_member_decoration(blockType.self, i, spv::DecorationOffset); + ASSERT(offset % 4 == 0); + offset /= 4; + ASSERT(offset < kMaxPushConstants); + + auto memberType = compiler.get_type(blockType.member_types[i]); + PushConstantType constantType; + if (memberType.basetype == spirv_cross::SPIRType::Int) { + constantType = PushConstantType::Int; + } else if (memberType.basetype == spirv_cross::SPIRType::UInt) { + constantType = PushConstantType::UInt; + } else { + ASSERT(memberType.basetype == spirv_cross::SPIRType::Float); + constantType = PushConstantType::Float; + } + + pushConstants.mask.set(offset); + pushConstants.names[offset] = interfaceBlock.name + "." + compiler.get_member_name(blockType.self, i); + pushConstants.sizes[offset] = memberType.vecsize * memberType.columns; + pushConstants.types[offset] = constantType; + } + } + + // Fill in bindingInfo with the SPIRV bindings + auto ExtractResourcesBinding = [this](const std::vector& resources, + const spirv_cross::Compiler& compiler, nxt::BindingType type) { + constexpr uint64_t requiredBindingDecorationMask = (1ull << spv::DecorationBinding) | (1ull << spv::DecorationDescriptorSet); + + for (const auto& resource : resources) { + ASSERT((compiler.get_decoration_mask(resource.id) & requiredBindingDecorationMask) == requiredBindingDecorationMask); + uint32_t binding = compiler.get_decoration(resource.id, spv::DecorationBinding); + uint32_t set = compiler.get_decoration(resource.id, spv::DecorationDescriptorSet); + + if (binding >= kMaxBindingsPerGroup || set >= kMaxBindGroups) { + device->HandleError("Binding over limits in the SPIRV"); + continue; + } + + auto& info = bindingInfo[set][binding]; + info.used = true; + info.id = resource.id; + info.base_type_id = resource.base_type_id; + info.type = type; + } + }; + + ExtractResourcesBinding(resources.uniform_buffers, compiler, nxt::BindingType::UniformBuffer); + ExtractResourcesBinding(resources.separate_images, compiler, nxt::BindingType::SampledTexture); + ExtractResourcesBinding(resources.separate_samplers, compiler, nxt::BindingType::Sampler); + ExtractResourcesBinding(resources.storage_buffers, compiler, nxt::BindingType::StorageBuffer); + + // Extract the vertex attributes + if (executionModel == nxt::ShaderStage::Vertex) { + for (const auto& attrib : resources.stage_inputs) { + ASSERT(compiler.get_decoration_mask(attrib.id) & (1ull << spv::DecorationLocation)); + uint32_t location = compiler.get_decoration(attrib.id, spv::DecorationLocation); + + if (location >= kMaxVertexAttributes) { + device->HandleError("Attribute location over limits in the SPIRV"); + return; + } + + usedVertexAttributes.set(location); + } + + // Without a location qualifier on vertex outputs, spirv_cross::CompilerMSL gives them all + // the location 0, causing a compile error. + for (const auto& attrib : resources.stage_outputs) { + if (!(compiler.get_decoration_mask(attrib.id) & (1ull << spv::DecorationLocation))) { + device->HandleError("Need location qualifier on vertex output"); + return; + } + } + } + + if (executionModel == nxt::ShaderStage::Fragment) { + // Without a location qualifier on vertex inputs, spirv_cross::CompilerMSL gives them all + // the location 0, causing a compile error. + for (const auto& attrib : resources.stage_inputs) { + if (!(compiler.get_decoration_mask(attrib.id) & (1ull << spv::DecorationLocation))) { + device->HandleError("Need location qualifier on fragment input"); + return; + } + } + } + } + + const ShaderModuleBase::PushConstantInfo& ShaderModuleBase::GetPushConstants() const { + return pushConstants; + } + + const ShaderModuleBase::ModuleBindingInfo& ShaderModuleBase::GetBindingInfo() const { + return bindingInfo; + } + + const std::bitset& ShaderModuleBase::GetUsedVertexAttributes() const { + return usedVertexAttributes; + } + + nxt::ShaderStage ShaderModuleBase::GetExecutionModel() const { + return executionModel; + } + + bool ShaderModuleBase::IsCompatibleWithPipelineLayout(const PipelineLayoutBase* layout) { + for (size_t group = 0; group < kMaxBindGroups; ++group) { + if (!IsCompatibleWithBindGroupLayout(group, layout->GetBindGroupLayout(group))) { + return false; + } + } + return true; + } + + bool ShaderModuleBase::IsCompatibleWithBindGroupLayout(size_t group, const BindGroupLayoutBase* layout) { + const auto& layoutInfo = layout->GetBindingInfo(); + for (size_t i = 0; i < kMaxBindingsPerGroup; ++i) { + const auto& moduleInfo = bindingInfo[group][i]; + + if (!moduleInfo.used) { + continue; + } + + if (moduleInfo.type != layoutInfo.types[i]) { + return false; + } + if ((layoutInfo.visibilities[i] & StageBit(executionModel)) == 0) { + return false; + } + } + + return true; + } + + ShaderModuleBuilder::ShaderModuleBuilder(DeviceBase* device) : device(device) {} + + bool ShaderModuleBuilder::WasConsumed() const { + return consumed; + } + + std::vector ShaderModuleBuilder::AcquireSpirv() { + return std::move(spirv); + } + + ShaderModuleBase* ShaderModuleBuilder::GetResult() { + if (spirv.size() == 0) { + device->HandleError("Shader module needs to have the source set"); + return nullptr; + } + + consumed = true; + return device->CreateShaderModule(this); + } + + void ShaderModuleBuilder::SetSource(uint32_t codeSize, const uint32_t* code) { + spirv.assign(code, code + codeSize); + } + +} diff --git a/src/backend/common/ShaderModule.h b/src/backend/common/ShaderModule.h new file mode 100644 index 0000000000..1407fd9f44 --- /dev/null +++ b/src/backend/common/ShaderModule.h @@ -0,0 +1,95 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_SHADERMODULE_H_ +#define BACKEND_COMMON_SHADERMODULE_H_ + +#include "Forward.h" +#include "RefCounted.h" + +#include "nxt/nxtcpp.h" + +#include +#include +#include + +namespace spirv_cross { + class Compiler; +} + +namespace backend { + + class ShaderModuleBase : public RefCounted { + public: + ShaderModuleBase(ShaderModuleBuilder* builder); + + void ExtractSpirvInfo(const spirv_cross::Compiler& compiler); + + struct PushConstantInfo { + std::bitset mask; + + std::array names; + std::array sizes; + std::array types; + }; + + struct BindingInfo { + // The SPIRV ID of the resource. + uint32_t id; + uint32_t base_type_id; + nxt::BindingType type; + bool used = false; + }; + using ModuleBindingInfo = std::array, kMaxBindGroups>; + + const PushConstantInfo& GetPushConstants() const; + const ModuleBindingInfo& GetBindingInfo() const; + const std::bitset& GetUsedVertexAttributes() const; + nxt::ShaderStage GetExecutionModel() const; + + bool IsCompatibleWithPipelineLayout(const PipelineLayoutBase* layout); + + private: + bool IsCompatibleWithBindGroupLayout(size_t group, const BindGroupLayoutBase* layout); + + DeviceBase* device; + PushConstantInfo pushConstants = {}; + ModuleBindingInfo bindingInfo; + std::bitset usedVertexAttributes; + nxt::ShaderStage executionModel; + }; + + class ShaderModuleBuilder : public RefCounted { + public: + ShaderModuleBuilder(DeviceBase* device); + + bool WasConsumed() const; + + std::vector AcquireSpirv(); + + // NXT API + ShaderModuleBase* GetResult(); + void SetSource(uint32_t codeSize, const uint32_t* code); + + private: + friend class ShaderModuleBase; + + DeviceBase* device; + std::vector spirv; + bool consumed = false; + }; + +} + +#endif // BACKEND_COMMON_SHADERMODULE_H_ diff --git a/src/backend/common/Texture.cpp b/src/backend/common/Texture.cpp new file mode 100644 index 0000000000..4551dbfca6 --- /dev/null +++ b/src/backend/common/Texture.cpp @@ -0,0 +1,239 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "Texture.h" + +#include "Device.h" + +namespace backend { + + size_t TextureFormatPixelSize(nxt::TextureFormat format) { + switch (format) { + case nxt::TextureFormat::R8G8B8A8Unorm: + return 4; + } + } + + // TextureBase + + TextureBase::TextureBase(TextureBuilder* builder) + : device(builder->device), dimension(builder->dimension), format(builder->format), width(builder->width), + height(builder->height), depth(builder->depth), numMipLevels(builder->numMipLevels), + allowedUsage(builder->allowedUsage), currentUsage(builder->currentUsage) { + } + + nxt::TextureDimension TextureBase::GetDimension() const { + return dimension; + } + nxt::TextureFormat TextureBase::GetFormat() const { + return format; + } + uint32_t TextureBase::GetWidth() const { + return width; + } + uint32_t TextureBase::GetHeight() const { + return height; + } + uint32_t TextureBase::GetDepth() const { + return depth; + } + uint32_t TextureBase::GetNumMipLevels() const { + return numMipLevels; + } + nxt::TextureUsageBit TextureBase::GetAllowedUsage() const { + return allowedUsage; + } + nxt::TextureUsageBit TextureBase::GetUsage() const { + return currentUsage; + } + + TextureViewBuilder* TextureBase::CreateTextureViewBuilder() { + return new TextureViewBuilder(device, this); + } + + bool TextureBase::IsFrozen() const { + return frozen; + } + + bool TextureBase::HasFrozenUsage(nxt::TextureUsageBit usage) const { + return frozen && (usage & allowedUsage); + } + + bool TextureBase::IsUsagePossible(nxt::TextureUsageBit allowedUsage, nxt::TextureUsageBit usage) { + bool allowed = (usage & allowedUsage) == usage; + bool singleUse = nxt::HasZeroOrOneBits(usage); + return allowed && singleUse; + } + + bool TextureBase::IsTransitionPossible(nxt::TextureUsageBit usage) const { + if (frozen) { + return false; + } + return IsUsagePossible(allowedUsage, usage); + } + + void TextureBase::TransitionUsageImpl(nxt::TextureUsageBit usage) { + assert(IsTransitionPossible(usage)); + currentUsage = usage; + } + + void TextureBase::TransitionUsage(nxt::TextureUsageBit usage) { + if (!IsTransitionPossible(usage)) { + device->HandleError("Texture frozen or usage not allowed"); + return; + } + TransitionUsageImpl(usage); + } + + void TextureBase::FreezeUsage(nxt::TextureUsageBit usage) { + if (!IsTransitionPossible(usage)) { + device->HandleError("Texture frozen or usage not allowed"); + return; + } + allowedUsage = usage; + currentUsage = usage; + frozen = true; + } + + // TextureBuilder + + enum TextureSetProperties { + TEXTURE_PROPERTY_DIMENSION = 0x1, + TEXTURE_PROPERTY_EXTENT = 0x2, + TEXTURE_PROPERTY_FORMAT = 0x4, + TEXTURE_PROPERTY_MIP_LEVELS = 0x8, + TEXTURE_PROPERTY_ALLOWED_USAGE = 0x10, + TEXTURE_PROPERTY_INITIAL_USAGE = 0x20, + }; + + TextureBuilder::TextureBuilder(DeviceBase* device) + : device(device) { + } + + bool TextureBuilder::WasConsumed() const { + return consumed; + } + + TextureBase* TextureBuilder::GetResult() { + constexpr int allProperties = TEXTURE_PROPERTY_DIMENSION | TEXTURE_PROPERTY_EXTENT | + TEXTURE_PROPERTY_FORMAT | TEXTURE_PROPERTY_MIP_LEVELS | TEXTURE_PROPERTY_ALLOWED_USAGE; + if ((propertiesSet & allProperties) != allProperties) { + device->HandleError("Texture missing properties"); + return nullptr; + } + + if (!TextureBase::IsUsagePossible(allowedUsage, currentUsage)) { + device->HandleError("Initial texture usage is not allowed"); + return nullptr; + } + + // TODO(cwallez@chromium.org): check stuff based on the dimension + + consumed = true; + return device->CreateTexture(this); + } + + void TextureBuilder::SetDimension(nxt::TextureDimension dimension) { + if ((propertiesSet & TEXTURE_PROPERTY_DIMENSION) != 0) { + device->HandleError("Texture dimension property set multiple times"); + return; + } + + propertiesSet |= TEXTURE_PROPERTY_DIMENSION; + this->dimension = dimension; + } + + void TextureBuilder::SetExtent(uint32_t width, uint32_t height, uint32_t depth) { + if ((propertiesSet & TEXTURE_PROPERTY_EXTENT) != 0) { + device->HandleError("Texture extent property set multiple times"); + return; + } + + if (width == 0 || height == 0 || depth == 0) { + device->HandleError("Cannot create an empty texture"); + return; + } + + propertiesSet |= TEXTURE_PROPERTY_EXTENT; + this->width = width; + this->height = height; + this->depth = depth; + } + + void TextureBuilder::SetFormat(nxt::TextureFormat format) { + if ((propertiesSet & TEXTURE_PROPERTY_FORMAT) != 0) { + device->HandleError("Texture format property set multiple times"); + return; + } + + propertiesSet |= TEXTURE_PROPERTY_FORMAT; + this->format = format; + } + + void TextureBuilder::SetMipLevels(uint32_t numMipLevels) { + if ((propertiesSet & TEXTURE_PROPERTY_MIP_LEVELS) != 0) { + device->HandleError("Texture mip levels property set multiple times"); + return; + } + + propertiesSet |= TEXTURE_PROPERTY_MIP_LEVELS; + this->numMipLevels = numMipLevels; + } + + void TextureBuilder::SetAllowedUsage(nxt::TextureUsageBit usage) { + if ((propertiesSet & TEXTURE_PROPERTY_ALLOWED_USAGE) != 0) { + device->HandleError("Texture allowed usage property set multiple times"); + return; + } + + propertiesSet |= TEXTURE_PROPERTY_ALLOWED_USAGE; + this->allowedUsage = usage; + } + + void TextureBuilder::SetInitialUsage(nxt::TextureUsageBit usage) { + if ((propertiesSet & TEXTURE_PROPERTY_INITIAL_USAGE) != 0) { + device->HandleError("Texture initial usage property set multiple times"); + return; + } + + propertiesSet |= TEXTURE_PROPERTY_INITIAL_USAGE; + this->currentUsage = usage; + } + + // TextureViewBase + + TextureViewBase::TextureViewBase(TextureViewBuilder* builder) + : texture(builder->texture) { + } + + TextureBase* TextureViewBase::GetTexture() { + return texture.Get(); + } + + // TextureViewBuilder + + TextureViewBuilder::TextureViewBuilder(DeviceBase* device, TextureBase* texture) + : device(device), texture(texture) { + } + + bool TextureViewBuilder::WasConsumed() const { + return false; + } + + TextureViewBase* TextureViewBuilder::GetResult() { + consumed = true; + return device->CreateTextureView(this); + } + +} diff --git a/src/backend/common/Texture.h b/src/backend/common/Texture.h new file mode 100644 index 0000000000..d76fe802f3 --- /dev/null +++ b/src/backend/common/Texture.h @@ -0,0 +1,121 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_TEXTURE_H_ +#define BACKEND_COMMON_TEXTURE_H_ + +#include "Forward.h" +#include "RefCounted.h" + +#include "nxt/nxtcpp.h" + +namespace backend { + + size_t TextureFormatPixelSize(nxt::TextureFormat format); + + class TextureBase : public RefCounted { + public: + TextureBase(TextureBuilder* builder); + + nxt::TextureDimension GetDimension() const; + nxt::TextureFormat GetFormat() const; + uint32_t GetWidth() const; + uint32_t GetHeight() const; + uint32_t GetDepth() const; + uint32_t GetNumMipLevels() const; + nxt::TextureUsageBit GetAllowedUsage() const; + nxt::TextureUsageBit GetUsage() const; + bool IsFrozen() const; + bool HasFrozenUsage(nxt::TextureUsageBit usage) const; + static bool IsUsagePossible(nxt::TextureUsageBit allowedUsage, nxt::TextureUsageBit usage); + bool IsTransitionPossible(nxt::TextureUsageBit usage) const; + void TransitionUsageImpl(nxt::TextureUsageBit usage); + + // NXT API + TextureViewBuilder* CreateTextureViewBuilder(); + void TransitionUsage(nxt::TextureUsageBit usage); + void FreezeUsage(nxt::TextureUsageBit usage); + + private: + DeviceBase* device; + + nxt::TextureDimension dimension; + nxt::TextureFormat format; + uint32_t width, height, depth; + uint32_t numMipLevels; + nxt::TextureUsageBit allowedUsage = nxt::TextureUsageBit::None; + nxt::TextureUsageBit currentUsage = nxt::TextureUsageBit::None; + bool frozen = false; + }; + + class TextureBuilder : public RefCounted { + public: + TextureBuilder(DeviceBase* device); + + bool WasConsumed() const; + + // NXT API + TextureBase* GetResult(); + void SetDimension(nxt::TextureDimension dimension); + void SetExtent(uint32_t width, uint32_t height, uint32_t depth); + void SetFormat(nxt::TextureFormat format); + void SetMipLevels(uint32_t numMipLevels); + void SetAllowedUsage(nxt::TextureUsageBit usage); + void SetInitialUsage(nxt::TextureUsageBit usage); + + private: + friend class TextureBase; + + DeviceBase* device; + int propertiesSet = 0; + bool consumed = false; + + nxt::TextureDimension dimension; + uint32_t width, height, depth; + nxt::TextureFormat format; + uint32_t numMipLevels; + nxt::TextureUsageBit allowedUsage = nxt::TextureUsageBit::None; + nxt::TextureUsageBit currentUsage = nxt::TextureUsageBit::None; + }; + + class TextureViewBase : public RefCounted { + public: + TextureViewBase(TextureViewBuilder* builder); + + TextureBase* GetTexture(); + + private: + Ref texture; + }; + + class TextureViewBuilder : public RefCounted { + public: + TextureViewBuilder(DeviceBase* device, TextureBase* texture); + + bool WasConsumed() const; + + // NXT API + TextureViewBase* GetResult(); + + private: + friend class TextureViewBase; + + DeviceBase* device; + bool consumed = false; + Ref texture; + }; + +} + +#endif // BACKEND_COMMON_TEXTURE_H_ diff --git a/src/backend/common/ToBackend.h b/src/backend/common/ToBackend.h new file mode 100644 index 0000000000..ff7bd0bcc7 --- /dev/null +++ b/src/backend/common/ToBackend.h @@ -0,0 +1,120 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_COMMON_TOBACKEND_H_ +#define BACKEND_COMMON_TOBACKEND_H_ + +#include "Forward.h" + +namespace backend { + + // ToBackendTraits implements the mapping from base type to member type of BackendTraits + template + struct ToBackendTraits; + + template + struct ToBackendTraits { + using BackendType = typename BackendTraits::BindGroupType; + }; + + template + struct ToBackendTraits { + using BackendType = typename BackendTraits::BindGroupLayoutType; + }; + + template + struct ToBackendTraits { + using BackendType = typename BackendTraits::BufferType; + }; + + template + struct ToBackendTraits { + using BackendType = typename BackendTraits::BufferViewType; + }; + + template + struct ToBackendTraits { + using BackendType = typename BackendTraits::CommandBufferType; + }; + + template + struct ToBackendTraits { + using BackendType = typename BackendTraits::InputStateType; + }; + + template + struct ToBackendTraits { + using BackendType = typename BackendTraits::PipelineType; + }; + + template + struct ToBackendTraits { + using BackendType = typename BackendTraits::PipelineLayoutType; + }; + + template + struct ToBackendTraits { + using BackendType = typename BackendTraits::QueueType; + }; + + template + struct ToBackendTraits { + using BackendType = typename BackendTraits::SamplerType; + }; + + template + struct ToBackendTraits { + using BackendType = typename BackendTraits::ShaderModuleType; + }; + + template + struct ToBackendTraits { + using BackendType = typename BackendTraits::TextureType; + }; + + template + struct ToBackendTraits { + using BackendType = typename BackendTraits::TextureViewType; + }; + + // ToBackendBase implements conversion to the given BackendTraits + // To use it in a backend, use the following: + // template + // auto ToBackend(T&& common) -> decltype(ToBackendBase(common)) { + // return ToBackendBase(common); + // } + + template + Ref::BackendType>& ToBackendBase(Ref& common) { + return reinterpret_cast::BackendType>&>(common); + } + + template + const Ref::BackendType>& ToBackendBase(const Ref& common) { + return reinterpret_cast::BackendType>&>(common); + } + + template + typename ToBackendTraits::BackendType* ToBackendBase(T* common) { + return reinterpret_cast::BackendType*>(common); + } + + template + const typename ToBackendTraits::BackendType* ToBackendBase(const T* common) { + return reinterpret_cast::BackendType*>(common); + } + +} + +#endif // BACKEND_COMMON_TOBACKEND_H_ diff --git a/src/backend/metal/GeneratedCodeIncludes.h b/src/backend/metal/GeneratedCodeIncludes.h new file mode 100644 index 0000000000..16d9bfe4b5 --- /dev/null +++ b/src/backend/metal/GeneratedCodeIncludes.h @@ -0,0 +1,18 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "MetalBackend.h" + +#include "common/Device.h" +#include "common/CommandBuffer.h" diff --git a/src/backend/metal/MetalBackend.h b/src/backend/metal/MetalBackend.h new file mode 100644 index 0000000000..4ebf82befb --- /dev/null +++ b/src/backend/metal/MetalBackend.h @@ -0,0 +1,282 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_METAL_METALBACKEND_H_ +#define BACKEND_METAL_METALBACKEND_H_ + +#include "nxt/nxtcpp.h" + +#include +#include +#include + +#include "common/Buffer.h" +#include "common/BindGroup.h" +#include "common/BindGroupLayout.h" +#include "common/Device.h" +#include "common/CommandBuffer.h" +#include "common/InputState.h" +#include "common/Pipeline.h" +#include "common/PipelineLayout.h" +#include "common/Queue.h" +#include "common/Sampler.h" +#include "common/ShaderModule.h" +#include "common/Texture.h" +#include "common/ToBackend.h" + +#include +#import +#import + +namespace spirv_cross { + class CompilerMSL; +} + +namespace backend { +namespace metal { + + class BindGroup; + class BindGroupLayout; + class Buffer; + class BufferView; + class CommandBuffer; + class InputState; + class Pipeline; + class PipelineLayout; + class Queue; + class Sampler; + class ShaderModule; + class Texture; + class TextureView; + + struct MetalBackendTraits { + using BindGroupType = BindGroup; + using BindGroupLayoutType = BindGroupLayout; + using BufferType = Buffer; + using BufferViewType = BufferView; + using CommandBufferType = CommandBuffer; + using InputStateType = InputState; + using PipelineType = Pipeline; + using PipelineLayoutType = PipelineLayout; + using QueueType = Queue; + using SamplerType = Sampler; + using ShaderModuleType = ShaderModule; + using TextureType = Texture; + using TextureViewType = TextureView; + }; + + template + auto ToBackend(T&& common) -> decltype(ToBackendBase(common)) { + return ToBackendBase(common); + } + + class Device : public DeviceBase { + public: + Device(id mtlDevice); + ~Device(); + + BindGroupBase* CreateBindGroup(BindGroupBuilder* builder) override; + BindGroupLayoutBase* CreateBindGroupLayout(BindGroupLayoutBuilder* builder) override; + BufferBase* CreateBuffer(BufferBuilder* builder) override; + BufferViewBase* CreateBufferView(BufferViewBuilder* builder) override; + CommandBufferBase* CreateCommandBuffer(CommandBufferBuilder* builder) override; + InputStateBase* CreateInputState(InputStateBuilder* builder) override; + PipelineBase* CreatePipeline(PipelineBuilder* builder) override; + PipelineLayoutBase* CreatePipelineLayout(PipelineLayoutBuilder* builder) override; + QueueBase* CreateQueue(QueueBuilder* builder) override; + SamplerBase* CreateSampler(SamplerBuilder* builder) override; + ShaderModuleBase* CreateShaderModule(ShaderModuleBuilder* builder) override; + TextureBase* CreateTexture(TextureBuilder* builder) override; + TextureViewBase* CreateTextureView(TextureViewBuilder* builder) override; + + void SetNextDrawable(id drawable); + void Present(); + + id GetMTLDevice(); + id GetCurrentTexture(); + id GetCurrentDepthTexture(); + + // NXT API + void Reference(); + void Release(); + + private: + id mtlDevice = nil; + id commandQueue = nil; + + id currentDrawable = nil; + id currentTexture = nil; + id currentDepthTexture = nil; + }; + + class BindGroup : public BindGroupBase { + public: + BindGroup(Device* device, BindGroupBuilder* builder); + + private: + Device* device; + }; + + class BindGroupLayout : public BindGroupLayoutBase { + public: + BindGroupLayout(Device* device, BindGroupLayoutBuilder* builder); + + private: + Device* device; + }; + + class Buffer : public BufferBase { + public: + Buffer(Device* device, BufferBuilder* builder); + ~Buffer(); + + id GetMTLBuffer(); + std::mutex& GetMutex(); + + private: + void SetSubDataImpl(uint32_t start, uint32_t count, const uint32_t* data) override; + + Device* device; + std::mutex mutex; + id mtlBuffer = nil; + }; + + class BufferView : public BufferViewBase { + public: + BufferView(Device* device, BufferViewBuilder* builder); + + private: + Device* device; + }; + + class CommandBuffer : public CommandBufferBase { + public: + CommandBuffer(Device* device, CommandBufferBuilder* builder); + ~CommandBuffer(); + + void FillCommands(id commandBuffer, std::unordered_set* mutexes); + + private: + Device* device; + CommandIterator commands; + }; + + class InputState : public InputStateBase { + public: + InputState(Device* device, InputStateBuilder* builder); + ~InputState(); + + MTLVertexDescriptor* GetMTLVertexDescriptor(); + + private: + Device* device; + MTLVertexDescriptor* mtlVertexDescriptor = nil; + }; + + class Pipeline : public PipelineBase { + public: + Pipeline(Device* device, PipelineBuilder* builder); + ~Pipeline(); + + void Encode(id encoder); + void Encode(id encoder); + MTLSize GetLocalWorkGroupSize() const; + + private: + Device* device; + + id mtlRenderPipelineState = nil; + id mtlDepthStencilState = nil; + + id mtlComputePipelineState = nil; + MTLSize localWorkgroupSize; + }; + + class PipelineLayout : public PipelineLayoutBase { + public: + PipelineLayout(Device* device, PipelineLayoutBuilder* builder); + + using BindingIndexInfo = std::array, kMaxBindGroups>; + const BindingIndexInfo& GetBindingIndexInfo(nxt::ShaderStage stage) const; + + private: + Device* device; + PerStage indexInfo; + }; + + class Queue : public QueueBase { + public: + Queue(Device* device, QueueBuilder* builder); + ~Queue(); + + id GetMTLCommandQueue(); + + // NXT API + void Submit(uint32_t numCommands, CommandBuffer* const * commands); + + private: + Device* device; + id commandQueue = nil; + }; + + class Sampler : public SamplerBase { + public: + Sampler(Device* device, SamplerBuilder* builder); + ~Sampler(); + + id GetMTLSamplerState(); + + private: + Device* device; + id mtlSamplerState = nil; + }; + + class ShaderModule : public ShaderModuleBase { + public: + ShaderModule(Device* device, ShaderModuleBuilder* builder); + ~ShaderModule(); + + id GetFunction(const char* functionName) const; + MTLSize GetLocalWorkGroupSize(const std::string& entryPoint) const; + + private: + Device* device; + id mtlLibrary = nil; + spirv_cross::CompilerMSL* compiler = nullptr; + }; + + class Texture : public TextureBase { + public: + Texture(Device* device, TextureBuilder* builder); + ~Texture(); + + id GetMTLTexture(); + + private: + Device* device; + id mtlTexture = nil; + }; + + class TextureView : public TextureViewBase { + public: + TextureView(Device* device, TextureViewBuilder* builder); + + private: + Device* device; + }; + +} +} + +#endif // BACKEND_METAL_METALBACKEND_H_ diff --git a/src/backend/metal/MetalBackend.mm b/src/backend/metal/MetalBackend.mm new file mode 100644 index 0000000000..46a444edd5 --- /dev/null +++ b/src/backend/metal/MetalBackend.mm @@ -0,0 +1,968 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "MetalBackend.h" + +#include + +#include + +#include "common/Commands.h" + +namespace backend { +namespace metal { + nxtProcTable GetNonValidatingProcs(); + nxtProcTable GetValidatingProcs(); + + void Init(id metalDevice, nxtProcTable* procs, nxtDevice* device) { + *device = nullptr; + + *procs = GetValidatingProcs(); + *device = reinterpret_cast(new Device(metalDevice)); + } + + void SetNextDrawable(nxtDevice device, id drawable) { + Device* backendDevice = reinterpret_cast(device); + backendDevice->SetNextDrawable(drawable); + } + + void Present(nxtDevice device) { + Device* backendDevice = reinterpret_cast(device); + backendDevice->Present(); + } + + // Device + + Device::Device(id mtlDevice) : mtlDevice(mtlDevice) { + [mtlDevice retain]; + commandQueue = [mtlDevice newCommandQueue]; + } + + Device::~Device() { + [mtlDevice release]; + mtlDevice = nil; + + [commandQueue release]; + commandQueue = nil; + + [currentTexture release]; + currentTexture = nil; + + [currentDepthTexture release]; + currentDepthTexture = nil; + } + + BindGroupBase* Device::CreateBindGroup(BindGroupBuilder* builder) { + return new BindGroup(this, builder); + } + BindGroupLayoutBase* Device::CreateBindGroupLayout(BindGroupLayoutBuilder* builder) { + return new BindGroupLayout(this, builder); + } + BufferBase* Device::CreateBuffer(BufferBuilder* builder) { + return new Buffer(this, builder); + } + BufferViewBase* Device::CreateBufferView(BufferViewBuilder* builder) { + return new BufferView(this, builder); + } + CommandBufferBase* Device::CreateCommandBuffer(CommandBufferBuilder* builder) { + return new CommandBuffer(this, builder); + } + InputStateBase* Device::CreateInputState(InputStateBuilder* builder) { + return new InputState(this, builder); + } + PipelineBase* Device::CreatePipeline(PipelineBuilder* builder) { + return new Pipeline(this, builder); + } + PipelineLayoutBase* Device::CreatePipelineLayout(PipelineLayoutBuilder* builder) { + return new PipelineLayout(this, builder); + } + QueueBase* Device::CreateQueue(QueueBuilder* builder) { + return new Queue(this, builder); + } + SamplerBase* Device::CreateSampler(SamplerBuilder* builder) { + return new Sampler(this, builder); + } + ShaderModuleBase* Device::CreateShaderModule(ShaderModuleBuilder* builder) { + return new ShaderModule(this, builder); + } + TextureBase* Device::CreateTexture(TextureBuilder* builder) { + return new Texture(this, builder); + } + TextureViewBase* Device::CreateTextureView(TextureViewBuilder* builder) { + return new TextureView(this, builder); + } + + void Device::SetNextDrawable(id drawable) { + [currentDrawable release]; + currentDrawable = drawable; + [currentDrawable retain]; + + [currentTexture release]; + currentTexture = drawable.texture; + [currentTexture retain]; + + if (currentDepthTexture == nil || + currentTexture.width != currentDepthTexture.width || + currentTexture.height != currentDepthTexture.height) { + if (currentDepthTexture != nil) { + [currentDepthTexture release]; + } + MTLTextureDescriptor* depthDescriptor = [MTLTextureDescriptor + texture2DDescriptorWithPixelFormat:MTLPixelFormatDepth32Float + width:currentTexture.width + height:currentTexture.height + mipmapped:NO]; + depthDescriptor.textureType = MTLTextureType2D; + depthDescriptor.usage = MTLTextureUsageRenderTarget; + depthDescriptor.storageMode = MTLStorageModePrivate; + currentDepthTexture = [mtlDevice newTextureWithDescriptor:depthDescriptor]; + } + + MTLRenderPassDescriptor* passDescriptor = [MTLRenderPassDescriptor renderPassDescriptor]; + passDescriptor.colorAttachments[0].texture = currentTexture; + passDescriptor.colorAttachments[0].loadAction = MTLLoadActionClear; + passDescriptor.colorAttachments[0].storeAction = MTLStoreActionStore; + passDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(0.0, 0.0, 0.0, 1.0); + passDescriptor.depthAttachment.texture = currentDepthTexture; + passDescriptor.depthAttachment.loadAction = MTLLoadActionClear; + passDescriptor.depthAttachment.storeAction = MTLStoreActionStore; + passDescriptor.depthAttachment.clearDepth = 1.0; + + + id commandBuffer = [commandQueue commandBuffer]; + id commandEncoder = [commandBuffer + renderCommandEncoderWithDescriptor:passDescriptor]; + [commandEncoder endEncoding]; + [commandBuffer commit]; + } + + void Device::Present() { + id commandBuffer = [commandQueue commandBuffer]; + [commandBuffer presentDrawable: currentDrawable]; + [commandBuffer commit]; + } + + id Device::GetMTLDevice() { + return mtlDevice; + } + + id Device::GetCurrentTexture() { + return currentTexture; + } + + id Device::GetCurrentDepthTexture() { + return currentDepthTexture; + } + + void Device::Reference() { + } + + void Device::Release() { + } + + // Bind Group + + BindGroup::BindGroup(Device* device, BindGroupBuilder* builder) + : BindGroupBase(builder), device(device) { + } + + // Bind Group Layout + + BindGroupLayout::BindGroupLayout(Device* device, BindGroupLayoutBuilder* builder) + : BindGroupLayoutBase(builder), device(device) { + } + + // Buffer + + Buffer::Buffer(Device* device, BufferBuilder* builder) + : BufferBase(builder), device(device) { + mtlBuffer = [device->GetMTLDevice() newBufferWithLength:GetSize() + options:MTLResourceStorageModeManaged]; + } + + Buffer::~Buffer() { + std::lock_guard lock(mutex); + [mtlBuffer release]; + mtlBuffer = nil; + } + + id Buffer::GetMTLBuffer() { + return mtlBuffer; + } + + std::mutex& Buffer::GetMutex() { + return mutex; + } + + void Buffer::SetSubDataImpl(uint32_t start, uint32_t count, const uint32_t* data) { + uint32_t* dest = reinterpret_cast([mtlBuffer contents]); + { + std::lock_guard lock(mutex); + memcpy(&dest[start], data, count * sizeof(uint32_t)); + } + [mtlBuffer didModifyRange:NSMakeRange(start * sizeof(uint32_t), count * sizeof(uint32_t))]; + } + + // BufferView + + BufferView::BufferView(Device* device, BufferViewBuilder* builder) + : BufferViewBase(builder), device(device) { + } + + // CommandBuffer + + static MTLIndexType IndexFormatType(nxt::IndexFormat format) { + switch (format) { + case nxt::IndexFormat::Uint16: + return MTLIndexTypeUInt16; + case nxt::IndexFormat::Uint32: + return MTLIndexTypeUInt32; + } + } + + CommandBuffer::CommandBuffer(Device* device, CommandBufferBuilder* builder) + : CommandBufferBase(builder), device(device), commands(builder->AcquireCommands()) { + } + + CommandBuffer::~CommandBuffer() { + FreeCommands(&commands); + } + + namespace { + + struct CurrentEncoders { + Device* device; + + id blit = nil; + id compute = nil; + id render = nil; + + void FinishEncoders() { + if (blit != nil) { + [blit endEncoding]; + blit = nil; + } + if (compute != nil) { + [compute endEncoding]; + compute = nil; + } + if (render != nil) { + [render endEncoding]; + render = nil; + } + } + + void EnsureBlit(id commandBuffer) { + if (blit == nil) { + FinishEncoders(); + blit = [commandBuffer blitCommandEncoder]; + } + } + void EnsureCompute(id commandBuffer) { + if (compute == nil) { + FinishEncoders(); + compute = [commandBuffer computeCommandEncoder]; + // TODO(cwallez@chromium.org): does any state need to be reset? + } + } + void EnsureRender(id commandBuffer) { + if (render == nil) { + FinishEncoders(); + + // TODO(cwallez@chromium.org): this should be created from a renderpass subpass + MTLRenderPassDescriptor* descriptor = [MTLRenderPassDescriptor renderPassDescriptor]; + descriptor.colorAttachments[0].texture = device->GetCurrentTexture(); + descriptor.colorAttachments[0].loadAction = MTLLoadActionLoad; + descriptor.colorAttachments[0].storeAction = MTLStoreActionStore; + descriptor.depthAttachment.texture = device->GetCurrentDepthTexture(); + descriptor.depthAttachment.loadAction = MTLLoadActionLoad; + descriptor.depthAttachment.storeAction = MTLStoreActionStore; + + render = [commandBuffer renderCommandEncoderWithDescriptor:descriptor]; + // TODO(cwallez@chromium.org): does any state need to be reset? + } + } + }; + + } + + void CommandBuffer::FillCommands(id commandBuffer, std::unordered_set* mutexes) { + Command type; + Pipeline* lastPipeline = nullptr; + id indexBuffer = nil; + uint32_t indexBufferOffset = 0; + MTLIndexType indexType = MTLIndexTypeUInt32; + + CurrentEncoders encoders; + encoders.device = device; + + while (commands.NextCommandId(&type)) { + switch (type) { + case Command::CopyBufferToTexture: + { + CopyBufferToTextureCmd* copy = commands.NextCommand(); + Buffer* buffer = ToBackend(copy->buffer.Get()); + Texture* texture = ToBackend(copy->texture.Get()); + + // TODO(kainino@chromium.org): this has to be in a Blit encoder, not a Render encoder, so ordering is lost here + unsigned rowSize = copy->width * TextureFormatPixelSize(texture->GetFormat()); + MTLOrigin origin; + origin.x = copy->x; + origin.y = copy->y; + origin.z = copy->z; + + MTLSize size; + size.width = copy->width; + size.height = copy->height; + size.depth = copy->depth; + + encoders.EnsureBlit(commandBuffer); + [encoders.blit + copyFromBuffer:buffer->GetMTLBuffer() + sourceOffset:0 + sourceBytesPerRow:rowSize + sourceBytesPerImage:(rowSize * copy->height) + sourceSize:size + toTexture:texture->GetMTLTexture() + destinationSlice:0 + destinationLevel:copy->level + destinationOrigin:origin]; + } + break; + + case Command::Dispatch: + { + DispatchCmd* dispatch = commands.NextCommand(); + encoders.EnsureCompute(commandBuffer); + ASSERT(lastPipeline->IsCompute()); + + [encoders.compute dispatchThreadgroups:MTLSizeMake(dispatch->x, dispatch->y, dispatch->z) + threadsPerThreadgroup: lastPipeline->GetLocalWorkGroupSize()]; + } + break; + + case Command::DrawArrays: + { + DrawArraysCmd* draw = commands.NextCommand(); + + encoders.EnsureRender(commandBuffer); + [encoders.render + drawPrimitives:MTLPrimitiveTypeTriangle + vertexStart:draw->firstVertex + vertexCount:draw->vertexCount + instanceCount:draw->instanceCount + baseInstance:draw->firstInstance]; + } + break; + + case Command::DrawElements: + { + DrawElementsCmd* draw = commands.NextCommand(); + + encoders.EnsureRender(commandBuffer); + [encoders.render + drawIndexedPrimitives:MTLPrimitiveTypeTriangle + indexCount:draw->indexCount + indexType:indexType + indexBuffer:indexBuffer + indexBufferOffset:indexBufferOffset + instanceCount:draw->instanceCount + baseVertex:0 + baseInstance:draw->firstInstance]; + } + break; + + case Command::SetPipeline: + { + SetPipelineCmd* cmd = commands.NextCommand(); + lastPipeline = ToBackend(cmd->pipeline).Get(); + + if (lastPipeline->IsCompute()) { + encoders.EnsureCompute(commandBuffer); + lastPipeline->Encode(encoders.compute); + } else { + encoders.EnsureRender(commandBuffer); + lastPipeline->Encode(encoders.render); + } + } + break; + + case Command::SetPushConstants: + { + SetPushConstantsCmd* cmd = commands.NextCommand(); + uint32_t* valuesUInt = commands.NextData(cmd->count); + int32_t* valuesInt = reinterpret_cast(valuesUInt); + float* valuesFloat = reinterpret_cast(valuesUInt); + + // TODO(kainino@chromium.org): implement SetPushConstants + } + break; + + case Command::SetBindGroup: + { + SetBindGroupCmd* cmd = commands.NextCommand(); + BindGroup* group = ToBackend(cmd->group.Get()); + uint32_t groupIndex = cmd->index; + + const auto& layout = group->GetLayout()->GetBindingInfo(); + + if (lastPipeline->IsCompute()) { + encoders.EnsureCompute(commandBuffer); + } else { + encoders.EnsureRender(commandBuffer); + } + + // TODO(kainino@chromium.org): Maintain buffers and offsets arrays in BindGroup so that we + // only have to do one setVertexBuffers and one setFragmentBuffers call here. + for (size_t binding = 0; binding < layout.mask.size(); ++binding) { + if (!layout.mask[binding]) { + continue; + } + + auto stage = layout.visibilities[binding]; + bool vertStage = stage & nxt::ShaderStageBit::Vertex; + bool fragStage = stage & nxt::ShaderStageBit::Fragment; + bool computeStage = stage & nxt::ShaderStageBit::Compute; + uint32_t vertIndex = 0; + uint32_t fragIndex = 0; + uint32_t computeIndex = 0; + if (vertStage) { + vertIndex = ToBackend(lastPipeline->GetLayout())-> + GetBindingIndexInfo(nxt::ShaderStage::Vertex)[groupIndex][binding]; + } + if (fragStage) { + fragIndex = ToBackend(lastPipeline->GetLayout())-> + GetBindingIndexInfo(nxt::ShaderStage::Fragment)[groupIndex][binding]; + } + if (computeStage) { + computeIndex = ToBackend(lastPipeline->GetLayout())-> + GetBindingIndexInfo(nxt::ShaderStage::Compute)[groupIndex][binding]; + } + + switch (layout.types[binding]) { + case nxt::BindingType::UniformBuffer: + case nxt::BindingType::StorageBuffer: + { + BufferView* view = ToBackend(group->GetBindingAsBufferView(binding)); + auto b = ToBackend(view->GetBuffer()); + mutexes->insert(&b->GetMutex()); + const id buffer = b->GetMTLBuffer(); + const NSUInteger offset = view->GetOffset(); + if (vertStage) { + [encoders.render + setVertexBuffers:&buffer + offsets:&offset + withRange:NSMakeRange(vertIndex, 1)]; + } + if (fragStage) { + [encoders.render + setFragmentBuffers:&buffer + offsets:&offset + withRange:NSMakeRange(fragIndex, 1)]; + } + if (computeStage) { + [encoders.compute + setBuffers:&buffer + offsets:&offset + withRange:NSMakeRange(computeIndex, 1)]; + } + + } + break; + + case nxt::BindingType::Sampler: + { + auto sampler = ToBackend(group->GetBindingAsSampler(binding)); + if (vertStage) { + [encoders.render + setVertexSamplerState:sampler->GetMTLSamplerState() + atIndex:vertIndex]; + } + if (fragStage) { + [encoders.render + setFragmentSamplerState:sampler->GetMTLSamplerState() + atIndex:fragIndex]; + } + if (computeStage) { + [encoders.compute + setSamplerState:sampler->GetMTLSamplerState() + atIndex:computeIndex]; + } + } + break; + + case nxt::BindingType::SampledTexture: + { + auto texture = ToBackend(group->GetBindingAsTextureView(binding)->GetTexture()); + if (vertStage) { + [encoders.render + setVertexTexture:texture->GetMTLTexture() + atIndex:vertIndex]; + } + if (fragStage) { + [encoders.render + setFragmentTexture:texture->GetMTLTexture() + atIndex:fragIndex]; + } + if (computeStage) { + [encoders.compute + setTexture:texture->GetMTLTexture() + atIndex:computeIndex]; + } + } + break; + } + } + } + break; + + case Command::SetIndexBuffer: + { + SetIndexBufferCmd* cmd = commands.NextCommand(); + auto b = ToBackend(cmd->buffer.Get()); + mutexes->insert(&b->GetMutex()); + indexBuffer = b->GetMTLBuffer(); + indexBufferOffset = cmd->offset; + indexType = IndexFormatType(cmd->format); + } + break; + + case Command::SetVertexBuffers: + { + SetVertexBuffersCmd* cmd = commands.NextCommand(); + auto buffers = commands.NextData>(cmd->count); + auto offsets = commands.NextData(cmd->count); + + auto inputState = lastPipeline->GetInputState(); + + std::array, kMaxVertexInputs> mtlBuffers; + std::array mtlOffsets; + + // Perhaps an "array of vertex buffers(+offsets?)" should be + // a NXT API primitive to avoid reconstructing this array? + for (uint32_t i = 0; i < cmd->count; ++i) { + Buffer* buffer = ToBackend(buffers[i].Get()); + mutexes->insert(&buffer->GetMutex()); + mtlBuffers[i] = buffer->GetMTLBuffer(); + mtlOffsets[i] = offsets[i]; + } + + encoders.EnsureRender(commandBuffer); + [encoders.render + setVertexBuffers:mtlBuffers.data() + offsets:mtlOffsets.data() + withRange:NSMakeRange(kMaxBindingsPerGroup + cmd->startSlot, cmd->count)]; + } + break; + + case Command::TransitionBufferUsage: + { + TransitionBufferUsageCmd* cmd = commands.NextCommand(); + + cmd->buffer->TransitionUsageImpl(cmd->usage); + } + break; + + case Command::TransitionTextureUsage: + { + TransitionTextureUsageCmd* cmd = commands.NextCommand(); + + cmd->texture->TransitionUsageImpl(cmd->usage); + } + break; +; + } + } + + encoders.FinishEncoders(); + } + + // InputState + + static MTLVertexFormat VertexFormatType(nxt::VertexFormat format) { + switch (format) { + case nxt::VertexFormat::FloatR32G32B32A32: + return MTLVertexFormatFloat4; + case nxt::VertexFormat::FloatR32G32B32: + return MTLVertexFormatFloat3; + case nxt::VertexFormat::FloatR32G32: + return MTLVertexFormatFloat2; + } + } + + static MTLVertexStepFunction InputStepModeFunction(nxt::InputStepMode mode) { + switch (mode) { + case nxt::InputStepMode::Vertex: + return MTLVertexStepFunctionPerVertex; + case nxt::InputStepMode::Instance: + return MTLVertexStepFunctionPerInstance; + } + } + + InputState::InputState(Device* device, InputStateBuilder* builder) + : InputStateBase(builder), device(device) { + mtlVertexDescriptor = [MTLVertexDescriptor new]; + + const auto& attributesSetMask = GetAttributesSetMask(); + for (size_t i = 0; i < attributesSetMask.size(); ++i) { + if (!attributesSetMask[i]) { + continue; + } + const AttributeInfo& info = GetAttribute(i); + + auto attribDesc = [MTLVertexAttributeDescriptor new]; + attribDesc.format = VertexFormatType(info.format); + attribDesc.offset = info.offset; + attribDesc.bufferIndex = kMaxBindingsPerGroup + info.bindingSlot; + mtlVertexDescriptor.attributes[i] = attribDesc; + [attribDesc release]; + } + + const auto& inputsSetMask = GetInputsSetMask(); + for (size_t i = 0; i < inputsSetMask.size(); ++i) { + if (!inputsSetMask[i]) { + continue; + } + const InputInfo& info = GetInput(i); + + auto layoutDesc = [MTLVertexBufferLayoutDescriptor new]; + if (info.stride == 0) { + // For MTLVertexStepFunctionConstant, the stepRate must be 0, + // but the stride must NOT be 0, so I made up a value (256). + layoutDesc.stepFunction = MTLVertexStepFunctionConstant; + layoutDesc.stepRate = 0; + layoutDesc.stride = 256; + } else { + layoutDesc.stepFunction = InputStepModeFunction(info.stepMode); + layoutDesc.stepRate = 1; + layoutDesc.stride = info.stride; + } + mtlVertexDescriptor.layouts[kMaxBindingsPerGroup + i] = layoutDesc; + [layoutDesc release]; + } + } + + InputState::~InputState() { + [mtlVertexDescriptor release]; + mtlVertexDescriptor = nil; + } + + MTLVertexDescriptor* InputState::GetMTLVertexDescriptor() { + return mtlVertexDescriptor; + } + + // Pipeline + + Pipeline::Pipeline(Device* device, PipelineBuilder* builder) + : PipelineBase(builder), device(device) { + + if (IsCompute()) { + const auto& module = ToBackend(builder->GetStageInfo(nxt::ShaderStage::Compute).module); + const auto& entryPoint = builder->GetStageInfo(nxt::ShaderStage::Compute).entryPoint; + + id function = module->GetFunction(entryPoint.c_str()); + + NSError *error = nil; + mtlComputePipelineState = [device->GetMTLDevice() + newComputePipelineStateWithFunction:function error:&error]; + if (error != nil) { + NSLog(@" error => %@", error); + device->HandleError("Error creating pipeline state"); + return; + } + + // Copy over the local workgroup size as it is passed to dispatch explicitly in Metal + localWorkgroupSize = module->GetLocalWorkGroupSize(entryPoint); + + } else { + MTLRenderPipelineDescriptor* descriptor = [MTLRenderPipelineDescriptor new]; + + for (auto stage : IterateStages(GetStageMask())) { + const auto& module = ToBackend(builder->GetStageInfo(stage).module); + + const auto& entryPoint = builder->GetStageInfo(stage).entryPoint; + id function = module->GetFunction(entryPoint.c_str()); + + switch (stage) { + case nxt::ShaderStage::Vertex: + descriptor.vertexFunction = function; + break; + case nxt::ShaderStage::Fragment: + descriptor.fragmentFunction = function; + break; + case nxt::ShaderStage::Compute: + ASSERT(false); + break; + } + } + + descriptor.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm; + descriptor.depthAttachmentPixelFormat = MTLPixelFormatDepth32Float; + + InputState* inputState = ToBackend(GetInputState()); + descriptor.vertexDescriptor = inputState->GetMTLVertexDescriptor(); + + // TODO(kainino@chromium.org): push constants, textures, samplers + + NSError *error = nil; + mtlRenderPipelineState = [device->GetMTLDevice() + newRenderPipelineStateWithDescriptor:descriptor error:&error]; + if (error != nil) { + NSLog(@" error => %@", error); + device->HandleError("Error creating pipeline state"); + return; + } + + MTLDepthStencilDescriptor* dsDesc = [MTLDepthStencilDescriptor new]; + dsDesc.depthWriteEnabled = true; + dsDesc.depthCompareFunction = MTLCompareFunctionLess; + mtlDepthStencilState = [device->GetMTLDevice() + newDepthStencilStateWithDescriptor:dsDesc]; + + [dsDesc release]; + [descriptor release]; + } + } + + Pipeline::~Pipeline() { + [mtlRenderPipelineState release]; + [mtlDepthStencilState release]; + [mtlComputePipelineState release]; + } + + void Pipeline::Encode(id encoder) { + ASSERT(!IsCompute()); + [encoder setDepthStencilState:mtlDepthStencilState]; + [encoder setRenderPipelineState:mtlRenderPipelineState]; + } + + void Pipeline::Encode(id encoder) { + ASSERT(IsCompute()); + [encoder setComputePipelineState:mtlComputePipelineState]; + } + + MTLSize Pipeline::GetLocalWorkGroupSize() const { + return localWorkgroupSize; + } + + // PipelineLayout + + PipelineLayout::PipelineLayout(Device* device, PipelineLayoutBuilder* builder) + : PipelineLayoutBase(builder), device(device) { + // Each stage has its own numbering namespace in CompilerMSL. + for (auto stage : IterateStages(kAllStages)) { + uint32_t bufferIndex = 0; + uint32_t samplerIndex = 0; + uint32_t textureIndex = 0; + + for (size_t group = 0; group < kMaxBindGroups; ++group) { + const auto& groupInfo = GetBindGroupLayout(group)->GetBindingInfo(); + for (size_t binding = 0; binding < kMaxBindingsPerGroup; ++binding) { + if (!(groupInfo.visibilities[binding] & StageBit(stage))) { + continue; + } + if (!groupInfo.mask[binding]) { + continue; + } + + switch (groupInfo.types[binding]) { + case nxt::BindingType::UniformBuffer: + case nxt::BindingType::StorageBuffer: + indexInfo[stage][group][binding] = bufferIndex; + bufferIndex++; + break; + case nxt::BindingType::Sampler: + indexInfo[stage][group][binding] = samplerIndex; + samplerIndex++; + break; + case nxt::BindingType::SampledTexture: + indexInfo[stage][group][binding] = textureIndex; + textureIndex++; + break; + } + } + } + } + } + + const PipelineLayout::BindingIndexInfo& PipelineLayout::GetBindingIndexInfo(nxt::ShaderStage stage) const { + return indexInfo[stage]; + } + + // Queue + + Queue::Queue(Device* device, QueueBuilder* builder) + : device(device) { + commandQueue = [device->GetMTLDevice() newCommandQueue]; + } + + Queue::~Queue() { + [commandQueue release]; + commandQueue = nil; + } + + id Queue::GetMTLCommandQueue() { + return commandQueue; + } + + void Queue::Submit(uint32_t numCommands, CommandBuffer* const * commands) { + id commandBuffer = [commandQueue commandBuffer]; + + // Mutexes are necessary to prevent buffers from being written from the + // CPU before their previous value has been read from the GPU. + // https://developer.apple.com/library/content/documentation/3DDrawing/Conceptual/MTLBestPracticesGuide/TripleBuffering.html + // TODO(kainino@chromium.org): When we have resource transitions, all of these mutexes will be replaced. + std::unordered_set mutexes; + + for (uint32_t i = 0; i < numCommands; ++i) { + commands[i]->FillCommands(commandBuffer, &mutexes); + } + + for (auto mutex : mutexes) { + mutex->lock(); + } + [commandBuffer addCompletedHandler:^(id commandBuffer) { + // 'mutexes' is copied into this Block + for (auto mutex : mutexes) { + mutex->unlock(); + } + }]; + + [commandBuffer commit]; + } + + // Sampler + + MTLSamplerMinMagFilter FilterModeToMinMagFilter(nxt::FilterMode mode) { + switch (mode) { + case nxt::FilterMode::Nearest: + return MTLSamplerMinMagFilterNearest; + case nxt::FilterMode::Linear: + return MTLSamplerMinMagFilterLinear; + } + } + + MTLSamplerMipFilter FilterModeToMipFilter(nxt::FilterMode mode) { + switch (mode) { + case nxt::FilterMode::Nearest: + return MTLSamplerMipFilterNearest; + case nxt::FilterMode::Linear: + return MTLSamplerMipFilterLinear; + } + } + + Sampler::Sampler(Device* device, SamplerBuilder* builder) + : SamplerBase(builder), device(device) { + auto desc = [MTLSamplerDescriptor new]; + [desc autorelease]; + desc.minFilter = FilterModeToMinMagFilter(builder->GetMinFilter()); + desc.magFilter = FilterModeToMinMagFilter(builder->GetMagFilter()); + desc.mipFilter = FilterModeToMipFilter(builder->GetMipMapFilter()); + // TODO(kainino@chromium.org): wrap modes + mtlSamplerState = [device->GetMTLDevice() newSamplerStateWithDescriptor:desc]; + } + + Sampler::~Sampler() { + [mtlSamplerState release]; + } + + id Sampler::GetMTLSamplerState() { + return mtlSamplerState; + } + + // ShaderModule + + ShaderModule::ShaderModule(Device* device, ShaderModuleBuilder* builder) + : ShaderModuleBase(builder), device(device) { + compiler = new spirv_cross::CompilerMSL(builder->AcquireSpirv()); + ExtractSpirvInfo(*compiler); + + spirv_cross::MSLConfiguration mslConfig; + mslConfig.flip_vert_y = false; + mslConfig.flip_frag_y = false; + std::string msl = compiler->compile(mslConfig); + + NSString* mslSource = [NSString stringWithFormat:@"%s", msl.c_str()]; + NSError *error = nil; + mtlLibrary = [device->GetMTLDevice() newLibraryWithSource:mslSource options:nil error:&error]; + if (error != nil) { + NSLog(@"MTLDevice newLibraryWithSource => %@", error); + device->HandleError("Error creating MTLLibrary from MSL source"); + } + } + + ShaderModule::~ShaderModule() { + delete compiler; + } + + id ShaderModule::GetFunction(const char* functionName) const { + // TODO(kainino@chromium.org): make this somehow more robust; it needs to behave like clean_func_name: + // https://github.com/KhronosGroup/SPIRV-Cross/blob/4e915e8c483e319d0dd7a1fa22318bef28f8cca3/spirv_msl.cpp#L1213 + if (strcmp(functionName, "main") == 0) { + functionName = "main0"; + } + NSString* name = [NSString stringWithFormat:@"%s", functionName]; + return [mtlLibrary newFunctionWithName:name]; + } + + MTLSize ShaderModule::GetLocalWorkGroupSize(const std::string& entryPoint) const { + auto size = compiler->get_entry_point(entryPoint).workgroup_size; + return MTLSizeMake(size.x, size.y, size.z); + } + + // Texture + + MTLPixelFormat TextureFormatPixelFormat(nxt::TextureFormat format) { + switch (format) { + case nxt::TextureFormat::R8G8B8A8Unorm: + return MTLPixelFormatRGBA8Unorm; + } + } + + Texture::Texture(Device* device, TextureBuilder* builder) + : TextureBase(builder), device(device) { + auto desc = [MTLTextureDescriptor new]; + [desc autorelease]; + switch (GetDimension()) { + case nxt::TextureDimension::e2D: + desc.textureType = MTLTextureType2D; + break; + } + desc.usage = MTLTextureUsageShaderRead; + desc.pixelFormat = TextureFormatPixelFormat(GetFormat()); + desc.width = GetWidth(); + desc.height = GetHeight(); + desc.depth = GetDepth(); + desc.mipmapLevelCount = GetNumMipLevels(); + desc.arrayLength = 1; + + mtlTexture = [device->GetMTLDevice() newTextureWithDescriptor:desc]; + } + + Texture::~Texture() { + [mtlTexture release]; + } + + id Texture::GetMTLTexture() { + return mtlTexture; + } + + // TextureView + + TextureView::TextureView(Device* device, TextureViewBuilder* builder) + : TextureViewBase(builder), device(device) { + } + +} +} diff --git a/src/backend/opengl/CommandBufferGL.cpp b/src/backend/opengl/CommandBufferGL.cpp new file mode 100644 index 0000000000..a62da6e5f5 --- /dev/null +++ b/src/backend/opengl/CommandBufferGL.cpp @@ -0,0 +1,303 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "CommandBufferGL.h" + +#include "common/Commands.h" +#include "OpenGLBackend.h" +#include "PipelineGL.h" +#include "PipelineLayoutGL.h" +#include "SamplerGL.h" +#include "TextureGL.h" + +#include + +namespace backend { +namespace opengl { + + CommandBuffer::CommandBuffer(Device* device, CommandBufferBuilder* builder) + : CommandBufferBase(builder), device(device), commands(builder->AcquireCommands()) { + } + + CommandBuffer::~CommandBuffer() { + FreeCommands(&commands); + } + + static GLenum IndexFormatType(nxt::IndexFormat format) { + switch (format) { + case nxt::IndexFormat::Uint16: + return GL_UNSIGNED_SHORT; + case nxt::IndexFormat::Uint32: + return GL_UNSIGNED_INT; + } + } + + static GLenum VertexFormatType(nxt::VertexFormat format) { + switch (format) { + case nxt::VertexFormat::FloatR32G32B32A32: + case nxt::VertexFormat::FloatR32G32B32: + case nxt::VertexFormat::FloatR32G32: + return GL_FLOAT; + } + } + + void CommandBuffer::Execute() { + Command type; + Pipeline* lastPipeline = nullptr; + uint32_t indexBufferOffset = 0; + nxt::IndexFormat indexBufferFormat = nxt::IndexFormat::Uint16; + + while(commands.NextCommandId(&type)) { + switch (type) { + + case Command::CopyBufferToTexture: + { + CopyBufferToTextureCmd* copy = commands.NextCommand(); + Buffer* buffer = ToBackend(copy->buffer.Get()); + Texture* texture = ToBackend(copy->texture.Get()); + GLenum target = texture->GetGLTarget(); + auto format = texture->GetGLFormat(); + + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, buffer->GetHandle()); + glActiveTexture(GL_TEXTURE0); + glBindTexture(target, texture->GetHandle()); + + glTexSubImage2D(target, copy->level, copy->x, copy->y, copy->width, copy->height, + format.format, format.type, nullptr); + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); + } + break; + + case Command::Dispatch: + { + DispatchCmd* dispatch = commands.NextCommand(); + glDispatchCompute(dispatch->x, dispatch->y, dispatch->z); + // TODO(cwallez@chromium.org): add barriers to the API + glMemoryBarrier(GL_ALL_BARRIER_BITS); + } + break; + + case Command::DrawArrays: + { + DrawArraysCmd* draw = commands.NextCommand(); + if (draw->firstInstance > 0) { + glDrawArraysInstancedBaseInstance(GL_TRIANGLES, + draw->firstVertex, draw->vertexCount, draw->instanceCount, draw->firstInstance); + } else { + // This branch is only needed on OpenGL < 4.2 + glDrawArraysInstanced(GL_TRIANGLES, + draw->firstVertex, draw->vertexCount, draw->instanceCount); + } + } + break; + + case Command::DrawElements: + { + DrawElementsCmd* draw = commands.NextCommand(); + size_t formatSize = IndexFormatSize(indexBufferFormat); + GLenum formatType = IndexFormatType(indexBufferFormat); + + if (draw->firstInstance > 0) { + glDrawElementsInstancedBaseInstance(GL_TRIANGLES, + draw->indexCount, formatType, + reinterpret_cast(draw->firstIndex * formatSize + indexBufferOffset), + draw->instanceCount, draw->firstInstance); + } else { + // This branch is only needed on OpenGL < 4.2 + glDrawElementsInstanced(GL_TRIANGLES, + draw->indexCount, formatType, + reinterpret_cast(draw->firstIndex * formatSize + indexBufferOffset), + draw->instanceCount); + } + } + break; + + case Command::SetPipeline: + { + SetPipelineCmd* cmd = commands.NextCommand(); + ToBackend(cmd->pipeline)->ApplyNow(); + lastPipeline = ToBackend(cmd->pipeline).Get(); + } + break; + + case Command::SetPushConstants: + { + SetPushConstantsCmd* cmd = commands.NextCommand(); + uint32_t* valuesUInt = commands.NextData(cmd->count); + int32_t* valuesInt = reinterpret_cast(valuesUInt); + float* valuesFloat = reinterpret_cast(valuesUInt); + + for (auto stage : IterateStages(cmd->stage)) { + const auto& pushConstants = lastPipeline->GetPushConstants(stage); + const auto& glPushConstants = lastPipeline->GetGLPushConstants(stage); + for (size_t i = 0; i < cmd->count; i++) { + GLint location = glPushConstants[cmd->offset + i]; + + switch (pushConstants.types[cmd->offset + i]) { + case PushConstantType::Int: + glUniform1i(location, valuesInt[i]); + break; + case PushConstantType::UInt: + glUniform1ui(location, valuesUInt[i]); + break; + case PushConstantType::Float: + glUniform1f(location, valuesFloat[i]); + break; + } + } + } + } + break; + + case Command::SetBindGroup: + { + SetBindGroupCmd* cmd = commands.NextCommand(); + size_t index = cmd->index; + BindGroup* group = ToBackend(cmd->group.Get()); + + const auto& indices = ToBackend(lastPipeline->GetLayout())->GetBindingIndexInfo()[index]; + const auto& layout = group->GetLayout()->GetBindingInfo(); + + // TODO(cwallez@chromium.org): iterate over the layout bitmask instead + for (size_t binding = 0; binding < kMaxBindingsPerGroup; ++binding) { + if (!layout.mask[binding]) { + continue; + } + + switch (layout.types[binding]) { + case nxt::BindingType::UniformBuffer: + { + BufferView* view = ToBackend(group->GetBindingAsBufferView(binding)); + GLuint buffer = ToBackend(view->GetBuffer())->GetHandle(); + GLuint index = indices[binding]; + + glBindBufferRange(GL_UNIFORM_BUFFER, index, buffer, view->GetOffset(), view->GetSize()); + } + break; + + case nxt::BindingType::Sampler: + { + GLuint sampler = ToBackend(group->GetBindingAsSampler(binding))->GetHandle(); + GLuint index = indices[binding]; + + for (auto unit : lastPipeline->GetTextureUnitsForSampler(index)) { + glBindSampler(unit, sampler); + } + } + break; + + case nxt::BindingType::SampledTexture: + { + TextureView* view = ToBackend(group->GetBindingAsTextureView(binding)); + Texture* texture = ToBackend(view->GetTexture()); + GLuint handle = texture->GetHandle(); + GLenum target = texture->GetGLTarget(); + GLuint index = indices[binding]; + + for (auto unit : lastPipeline->GetTextureUnitsForTexture(index)) { + glActiveTexture(GL_TEXTURE0 + unit); + glBindTexture(target, handle); + } + } + break; + + case nxt::BindingType::StorageBuffer: + { + BufferView* view = ToBackend(group->GetBindingAsBufferView(binding)); + GLuint buffer = ToBackend(view->GetBuffer())->GetHandle(); + GLuint index = indices[binding]; + + glBindBufferRange(GL_SHADER_STORAGE_BUFFER, index, buffer, view->GetOffset(), view->GetSize()); + } + break; + } + } + } + break; + + case Command::SetIndexBuffer: + { + SetIndexBufferCmd* cmd = commands.NextCommand(); + + GLuint buffer = ToBackend(cmd->buffer.Get())->GetHandle(); + indexBufferOffset = cmd->offset; + indexBufferFormat = cmd->format; + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer); + } + break; + + case Command::SetVertexBuffers: + { + SetVertexBuffersCmd* cmd = commands.NextCommand(); + auto buffers = commands.NextData>(cmd->count); + auto offsets = commands.NextData(cmd->count); + + auto inputState = lastPipeline->GetInputState(); + + auto& attributesSetMask = inputState->GetAttributesSetMask(); + for (uint32_t location = 0; location < attributesSetMask.size(); ++location) { + if (!attributesSetMask[location]) { + // This slot is not used in the input state + continue; + } + auto attribute = inputState->GetAttribute(location); + auto slot = attribute.bindingSlot; + ASSERT(slot < kMaxVertexInputs); + if (slot < cmd->startSlot || slot >= cmd->startSlot + cmd->count) { + // This slot is not affected by this call + continue; + } + size_t bufferIndex = slot - cmd->startSlot; + GLuint buffer = ToBackend(buffers[bufferIndex])->GetHandle(); + uint32_t bufferOffset = offsets[bufferIndex]; + + auto input = inputState->GetInput(slot); + + auto components = VertexFormatNumComponents(attribute.format); + auto formatType = VertexFormatType(attribute.format); + + glBindBuffer(GL_ARRAY_BUFFER, buffer); + glVertexAttribPointer( + location, components, formatType, GL_FALSE, + input.stride, + reinterpret_cast(static_cast(bufferOffset + attribute.offset))); + } + } + break; + + case Command::TransitionBufferUsage: + { + TransitionBufferUsageCmd* cmd = commands.NextCommand(); + + cmd->buffer->TransitionUsageImpl(cmd->usage); + } + break; + + case Command::TransitionTextureUsage: + { + TransitionTextureUsageCmd* cmd = commands.NextCommand(); + + cmd->texture->TransitionUsageImpl(cmd->usage); + } + break; + } + } + + // HACK: cleanup a tiny bit of state to make this work with + // virtualized contexts enabled in Chromium + glBindSampler(0, 0); + } + +} +} diff --git a/src/backend/opengl/CommandBufferGL.h b/src/backend/opengl/CommandBufferGL.h new file mode 100644 index 0000000000..1492551ed3 --- /dev/null +++ b/src/backend/opengl/CommandBufferGL.h @@ -0,0 +1,45 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_OPENGL_COMMANDBUFFER_H_ +#define BACKEND_OPENGL_COMMANDBUFFER_H_ + +#include "common/CommandAllocator.h" +#include "common/CommandBuffer.h" + +namespace backend { + class CommandBufferBuilder; +} + +namespace backend { +namespace opengl { + + class Device; + + class CommandBuffer : public CommandBufferBase { + public: + CommandBuffer(Device* device, CommandBufferBuilder* builder); + ~CommandBuffer(); + + void Execute(); + + private: + Device* device; + CommandIterator commands; + }; + +} +} + +#endif // BACKEND_OPENGL_COMMANDBUFFER_H_ diff --git a/src/backend/opengl/GeneratedCodeIncludes.h b/src/backend/opengl/GeneratedCodeIncludes.h new file mode 100644 index 0000000000..f757618d8b --- /dev/null +++ b/src/backend/opengl/GeneratedCodeIncludes.h @@ -0,0 +1,21 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "OpenGLBackend.h" +#include "CommandBufferGL.h" +#include "PipelineGL.h" +#include "PipelineLayoutGL.h" +#include "SamplerGL.h" +#include "ShaderModuleGL.h" +#include "TextureGL.h" diff --git a/src/backend/opengl/OpenGLBackend.cpp b/src/backend/opengl/OpenGLBackend.cpp new file mode 100644 index 0000000000..745562631d --- /dev/null +++ b/src/backend/opengl/OpenGLBackend.cpp @@ -0,0 +1,180 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "OpenGLBackend.h" + +#include "CommandBufferGL.h" +#include "PipelineGL.h" +#include "PipelineLayoutGL.h" +#include "ShaderModuleGL.h" +#include "SamplerGL.h" +#include "TextureGL.h" + +namespace backend { +namespace opengl { + nxtProcTable GetNonValidatingProcs(); + nxtProcTable GetValidatingProcs(); + + void HACKCLEAR() { + glClearColor(0, 0, 0, 1); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + } + + void Init(void* (*getProc)(const char*), nxtProcTable* procs, nxtDevice* device) { + *device = nullptr; + + gladLoadGLLoader(reinterpret_cast(getProc)); + + glEnable(GL_DEPTH_TEST); + HACKCLEAR(); + + *procs = GetValidatingProcs(); + *device = reinterpret_cast(new Device); + } + + // Device + + BindGroupBase* Device::CreateBindGroup(BindGroupBuilder* builder) { + return new BindGroup(this, builder); + } + BindGroupLayoutBase* Device::CreateBindGroupLayout(BindGroupLayoutBuilder* builder) { + return new BindGroupLayout(this, builder); + } + BufferBase* Device::CreateBuffer(BufferBuilder* builder) { + return new Buffer(this, builder); + } + BufferViewBase* Device::CreateBufferView(BufferViewBuilder* builder) { + return new BufferView(this, builder); + } + CommandBufferBase* Device::CreateCommandBuffer(CommandBufferBuilder* builder) { + return new CommandBuffer(this, builder); + } + InputStateBase* Device::CreateInputState(InputStateBuilder* builder) { + return new InputState(this, builder); + } + PipelineBase* Device::CreatePipeline(PipelineBuilder* builder) { + return new Pipeline(this, builder); + } + PipelineLayoutBase* Device::CreatePipelineLayout(PipelineLayoutBuilder* builder) { + return new PipelineLayout(this, builder); + } + QueueBase* Device::CreateQueue(QueueBuilder* builder) { + return new Queue(this, builder); + } + SamplerBase* Device::CreateSampler(SamplerBuilder* builder) { + return new Sampler(this, builder); + } + ShaderModuleBase* Device::CreateShaderModule(ShaderModuleBuilder* builder) { + return new ShaderModule(this, builder); + } + TextureBase* Device::CreateTexture(TextureBuilder* builder) { + return new Texture(this, builder); + } + TextureViewBase* Device::CreateTextureView(TextureViewBuilder* builder) { + return new TextureView(this, builder); + } + + void Device::Reference() { + } + + void Device::Release() { + } + + // Bind Group + + BindGroup::BindGroup(Device* device, BindGroupBuilder* builder) + : BindGroupBase(builder), device(device) { + } + + // Bind Group Layout + + BindGroupLayout::BindGroupLayout(Device* device, BindGroupLayoutBuilder* builder) + : BindGroupLayoutBase(builder), device(device) { + } + + // Buffer + + Buffer::Buffer(Device* device, BufferBuilder* builder) + : BufferBase(builder), device(device) { + glGenBuffers(1, &buffer); + glBindBuffer(GL_ARRAY_BUFFER, buffer); + glBufferData(GL_ARRAY_BUFFER, GetSize(), nullptr, GL_STATIC_DRAW); + } + + GLuint Buffer::GetHandle() const { + return buffer; + } + + void Buffer::SetSubDataImpl(uint32_t start, uint32_t count, const uint32_t* data) { + glBindBuffer(GL_ARRAY_BUFFER, buffer); + glBufferSubData(GL_ARRAY_BUFFER, start * sizeof(uint32_t), count * sizeof(uint32_t), data); + } + + // BufferView + + BufferView::BufferView(Device* device, BufferViewBuilder* builder) + : BufferViewBase(builder), device(device) { + } + + // InputState + + InputState::InputState(Device* device, InputStateBuilder* builder) + : InputStateBase(builder), device(device) { + glGenVertexArrays(1, &vertexArrayObject); + glBindVertexArray(vertexArrayObject); + auto& attributesSetMask = GetAttributesSetMask(); + for (uint32_t location = 0; location < attributesSetMask.size(); ++location) { + if (!attributesSetMask[location]) { + continue; + } + auto attribute = GetAttribute(location); + glEnableVertexAttribArray(location); + + auto input = GetInput(attribute.bindingSlot); + if (input.stride == 0) { + // Emulate a stride of zero (constant vertex attribute) by + // setting the attribute instance divisor to a huge number. + glVertexAttribDivisor(location, 0xffffffff); + } else { + switch (input.stepMode) { + case nxt::InputStepMode::Vertex: + break; + case nxt::InputStepMode::Instance: + glVertexAttribDivisor(location, 1); + break; + default: + ASSERT(false); + break; + } + } + } + } + + GLuint InputState::GetVAO() { + return vertexArrayObject; + } + + // Queue + + Queue::Queue(Device* device, QueueBuilder* builder) : device(device) { + } + + void Queue::Submit(uint32_t numCommands, CommandBuffer* const * commands) { + for (uint32_t i = 0; i < numCommands; ++i) { + commands[i]->Execute(); + } + } + +} +} diff --git a/src/backend/opengl/OpenGLBackend.h b/src/backend/opengl/OpenGLBackend.h new file mode 100644 index 0000000000..41742ea715 --- /dev/null +++ b/src/backend/opengl/OpenGLBackend.h @@ -0,0 +1,151 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_OPENGL_OPENGLBACKEND_H_ +#define BACKEND_OPENGL_OPENGLBACKEND_H_ + +#include "nxt/nxtcpp.h" + +#include "common/Buffer.h" +#include "common/BindGroup.h" +#include "common/BindGroupLayout.h" +#include "common/Device.h" +#include "common/InputState.h" +#include "common/Queue.h" +#include "common/ToBackend.h" + +#include "glad/glad.h" + +namespace backend { +namespace opengl { + + class BindGroup; + class BindGroupLayout; + class Buffer; + class BufferView; + class CommandBuffer; + class InputState; + class Pipeline; + class PipelineLayout; + class Queue; + class Sampler; + class ShaderModule; + class Texture; + class TextureView; + + struct OpenGLBackendTraits { + using BindGroupType = BindGroup; + using BindGroupLayoutType = BindGroupLayout; + using BufferType = Buffer; + using BufferViewType = BufferView; + using CommandBufferType = CommandBuffer; + using InputStateType = InputState; + using PipelineType = Pipeline; + using PipelineLayoutType = PipelineLayout; + using QueueType = Queue; + using SamplerType = Sampler; + using ShaderModuleType = ShaderModule; + using TextureType = Texture; + using TextureViewType = TextureView; + }; + + template + auto ToBackend(T&& common) -> decltype(ToBackendBase(common)) { + return ToBackendBase(common); + } + + // Definition of backend types + class Device : public DeviceBase { + public: + BindGroupBase* CreateBindGroup(BindGroupBuilder* builder) override; + BindGroupLayoutBase* CreateBindGroupLayout(BindGroupLayoutBuilder* builder) override; + BufferBase* CreateBuffer(BufferBuilder* builder) override; + BufferViewBase* CreateBufferView(BufferViewBuilder* builder) override; + CommandBufferBase* CreateCommandBuffer(CommandBufferBuilder* builder) override; + InputStateBase* CreateInputState(InputStateBuilder* builder) override; + PipelineBase* CreatePipeline(PipelineBuilder* builder) override; + PipelineLayoutBase* CreatePipelineLayout(PipelineLayoutBuilder* builder) override; + QueueBase* CreateQueue(QueueBuilder* builder) override; + SamplerBase* CreateSampler(SamplerBuilder* builder) override; + ShaderModuleBase* CreateShaderModule(ShaderModuleBuilder* builder) override; + TextureBase* CreateTexture(TextureBuilder* builder) override; + TextureViewBase* CreateTextureView(TextureViewBuilder* builder) override; + + // NXT API + void Reference(); + void Release(); + }; + + class BindGroup : public BindGroupBase { + public: + BindGroup(Device* device, BindGroupBuilder* builder); + + private: + Device* device; + }; + + class BindGroupLayout : public BindGroupLayoutBase { + public: + BindGroupLayout(Device* device, BindGroupLayoutBuilder* builder); + + private: + Device* device; + }; + + class Buffer : public BufferBase { + public: + Buffer(Device* device, BufferBuilder* builder); + + GLuint GetHandle() const; + + private: + void SetSubDataImpl(uint32_t start, uint32_t count, const uint32_t* data) override; + + Device* device; + GLuint buffer = 0; + }; + + class BufferView : public BufferViewBase { + public: + BufferView(Device* device, BufferViewBuilder* builder); + + private: + Device* device; + }; + + class InputState : public InputStateBase { + public: + InputState(Device* device, InputStateBuilder* builder); + GLuint GetVAO(); + + private: + Device* device; + GLuint vertexArrayObject; + }; + + class Queue : public QueueBase { + public: + Queue(Device* device, QueueBuilder* builder); + + // NXT API + void Submit(uint32_t numCommands, CommandBuffer* const * commands); + + private: + Device* device; + }; + +} +} + +#endif // BACKEND_OPENGL_OPENGLBACKEND_H_ diff --git a/src/backend/opengl/PipelineGL.cpp b/src/backend/opengl/PipelineGL.cpp new file mode 100644 index 0000000000..50b9f082ef --- /dev/null +++ b/src/backend/opengl/PipelineGL.cpp @@ -0,0 +1,213 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "PipelineGL.h" + +#include "OpenGLBackend.h" +#include "PipelineLayoutGL.h" +#include "ShaderModuleGL.h" + +#include +#include + +namespace backend { +namespace opengl { + + namespace { + + GLenum GLShaderType(nxt::ShaderStage stage) { + switch (stage) { + case nxt::ShaderStage::Vertex: + return GL_VERTEX_SHADER; + case nxt::ShaderStage::Fragment: + return GL_FRAGMENT_SHADER; + case nxt::ShaderStage::Compute: + return GL_COMPUTE_SHADER; + } + } + + } + + Pipeline::Pipeline(Device* device, PipelineBuilder* builder) : PipelineBase(builder), device(device) { + auto CreateShader = [](GLenum type, const char* source) -> GLuint { + GLuint shader = glCreateShader(type); + glShaderSource(shader, 1, &source, nullptr); + glCompileShader(shader); + + GLint compileStatus = GL_FALSE; + glGetShaderiv(shader, GL_COMPILE_STATUS, &compileStatus); + if (compileStatus == GL_FALSE) { + GLint infoLogLength = 0; + glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength); + + if (infoLogLength > 1) { + std::vector buffer(infoLogLength); + glGetShaderInfoLog(shader, infoLogLength, nullptr, &buffer[0]); + std::cout << source << std::endl; + std::cout << "Program compilation failed:\n"; + std::cout << buffer.data() << std::endl; + } + } + return shader; + }; + + auto FillPushConstants = [](const ShaderModule* module, GLPushConstantInfo* info, GLuint program) { + const auto& moduleInfo = module->GetPushConstants(); + for (uint32_t i = 0; i < moduleInfo.names.size(); i++) { + (*info)[i] = -1; + + unsigned int size = moduleInfo.sizes[i]; + if (size == 0) { + continue; + } + + GLint location = glGetUniformLocation(program, moduleInfo.names[i].c_str()); + if (location == -1) { + continue; + } + + for (uint32_t offset = 0; offset < size; offset++) { + (*info)[i + offset] = location + offset; + } + i += size - 1; + } + }; + + program = glCreateProgram(); + + for (auto stage : IterateStages(GetStageMask())) { + const ShaderModule* module = ToBackend(builder->GetStageInfo(stage).module.Get()); + + GLuint shader = CreateShader(GLShaderType(stage), module->GetSource()); + glAttachShader(program, shader); + } + + glLinkProgram(program); + + GLint linkStatus = GL_FALSE; + glGetProgramiv(program, GL_LINK_STATUS, &linkStatus); + if (linkStatus == GL_FALSE) { + GLint infoLogLength = 0; + glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength); + + if (infoLogLength > 1) { + std::vector buffer(infoLogLength); + glGetProgramInfoLog(program, infoLogLength, nullptr, &buffer[0]); + std::cout << "Program link failed:\n"; + std::cout << buffer.data() << std::endl; + } + } + + for (auto stage : IterateStages(GetStageMask())) { + const ShaderModule* module = ToBackend(builder->GetStageInfo(stage).module.Get()); + FillPushConstants(module, &glPushConstants[stage], program); + } + + glUseProgram(program); + + // The uniforms are part of the program state so we can pre-bind buffer units, texture units etc. + const auto& layout = ToBackend(GetLayout()); + const auto& indices = layout->GetBindingIndexInfo(); + + for (uint32_t group = 0; group < kMaxBindGroups; ++group) { + const auto& groupInfo = layout->GetBindGroupLayout(group)->GetBindingInfo(); + + for (uint32_t binding = 0; binding < kMaxBindingsPerGroup; ++binding) { + if (!groupInfo.mask[binding]) { + continue; + } + + std::string name = GetBindingName(group, binding); + switch (groupInfo.types[binding]) { + case nxt::BindingType::UniformBuffer: + { + GLint location = glGetUniformBlockIndex(program, name.c_str()); + glUniformBlockBinding(program, location, indices[group][binding]); + } + break; + + case nxt::BindingType::StorageBuffer: + { + GLuint location = glGetProgramResourceIndex(program, GL_SHADER_STORAGE_BLOCK, name.c_str()); + glShaderStorageBlockBinding(program, location, indices[group][binding]); + } + break; + + case nxt::BindingType::Sampler: + case nxt::BindingType::SampledTexture: + // These binding types are handled in the separate sampler and texture emulation + break; + + } + } + } + + // Compute links between stages for combined samplers, then bind them to texture units + { + std::set combinedSamplersSet; + for (auto stage : IterateStages(GetStageMask())) { + const auto& module = ToBackend(builder->GetStageInfo(stage).module); + + for (const auto& combined : module->GetCombinedSamplerInfo()) { + combinedSamplersSet.insert(combined); + } + } + + unitsForSamplers.resize(layout->GetNumSamplers()); + unitsForTextures.resize(layout->GetNumSampledTextures()); + + GLuint textureUnit = layout->GetTextureUnitsUsed(); + for (const auto& combined : combinedSamplersSet) { + std::string name = combined.GetName(); + GLint location = glGetUniformLocation(program, name.c_str()); + glUniform1i(location, textureUnit); + + GLuint samplerIndex = indices[combined.samplerLocation.group][combined.samplerLocation.binding]; + unitsForSamplers[samplerIndex].push_back(textureUnit); + + GLuint textureIndex = indices[combined.textureLocation.group][combined.textureLocation.binding]; + unitsForTextures[textureIndex].push_back(textureUnit); + + textureUnit ++; + } + } + } + + const Pipeline::GLPushConstantInfo& Pipeline::GetGLPushConstants(nxt::ShaderStage stage) const { + return glPushConstants[stage]; + } + + const std::vector& Pipeline::GetTextureUnitsForSampler(GLuint index) const { + ASSERT(index >= 0 && index < unitsForSamplers.size()); + return unitsForSamplers[index]; + } + + const std::vector& Pipeline::GetTextureUnitsForTexture(GLuint index) const { + ASSERT(index >= 0 && index < unitsForSamplers.size()); + return unitsForTextures[index]; + } + + GLuint Pipeline::GetProgramHandle() const { + return program; + } + + void Pipeline::ApplyNow() { + glUseProgram(program); + + auto inputState = ToBackend(GetInputState()); + glBindVertexArray(inputState->GetVAO()); + } + +} +} diff --git a/src/backend/opengl/PipelineGL.h b/src/backend/opengl/PipelineGL.h new file mode 100644 index 0000000000..ec0c0c5fd0 --- /dev/null +++ b/src/backend/opengl/PipelineGL.h @@ -0,0 +1,55 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_OPENGL_PIPELINEGL_H_ +#define BACKEND_OPENGL_PIPELINEGL_H_ + +#include "common/Pipeline.h" + +#include "glad/glad.h" + +#include + +namespace backend { +namespace opengl { + + class Device; + class ShaderModule; + + class Pipeline : public PipelineBase { + public: + Pipeline(Device* device, PipelineBuilder* builder); + + using GLPushConstantInfo = std::array; + using BindingLocations = std::array, kMaxBindGroups>; + + const GLPushConstantInfo& GetGLPushConstants(nxt::ShaderStage stage) const; + const std::vector& GetTextureUnitsForSampler(GLuint index) const; + const std::vector& GetTextureUnitsForTexture(GLuint index) const; + GLuint GetProgramHandle() const; + + void ApplyNow(); + + private: + GLuint program; + PerStage glPushConstants; + std::vector> unitsForSamplers; + std::vector> unitsForTextures; + Device* device; + }; + +} +} + +#endif // BACKEND_OPENGL_PIPELINEGL_H_ diff --git a/src/backend/opengl/PipelineLayoutGL.cpp b/src/backend/opengl/PipelineLayoutGL.cpp new file mode 100644 index 0000000000..1f3cb5eece --- /dev/null +++ b/src/backend/opengl/PipelineLayoutGL.cpp @@ -0,0 +1,80 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "PipelineLayoutGL.h" + +#include "OpenGLBackend.h" + +namespace backend { +namespace opengl { + + PipelineLayout::PipelineLayout(Device* device, PipelineLayoutBuilder* builder) + : PipelineLayoutBase(builder), device(device) { + GLuint uboIndex = 0; + GLuint samplerIndex = 0; + GLuint sampledTextureIndex = 0; + GLuint ssboIndex = 0; + + for (size_t group = 0; group < kMaxBindGroups; ++group) { + const auto& groupInfo = GetBindGroupLayout(group)->GetBindingInfo(); + + for (size_t binding = 0; binding < kMaxBindingsPerGroup; ++binding) { + if (!groupInfo.mask[binding]) { + continue; + } + + switch (groupInfo.types[binding]) { + case nxt::BindingType::UniformBuffer: + indexInfo[group][binding] = uboIndex; + uboIndex ++; + break; + case nxt::BindingType::Sampler: + indexInfo[group][binding] = samplerIndex; + samplerIndex ++; + break; + case nxt::BindingType::SampledTexture: + indexInfo[group][binding] = sampledTextureIndex; + sampledTextureIndex ++; + break; + + case nxt::BindingType::StorageBuffer: + indexInfo[group][binding] = ssboIndex; + ssboIndex ++; + break; + } + } + } + + numSamplers = samplerIndex; + numSampledTextures = sampledTextureIndex; + } + + const PipelineLayout::BindingIndexInfo& PipelineLayout::GetBindingIndexInfo() const { + return indexInfo; + } + + GLuint PipelineLayout::GetTextureUnitsUsed() const { + return 0; + } + + size_t PipelineLayout::GetNumSamplers() const { + return numSamplers; + } + + size_t PipelineLayout::GetNumSampledTextures() const { + return numSampledTextures; + } + +} +} diff --git a/src/backend/opengl/PipelineLayoutGL.h b/src/backend/opengl/PipelineLayoutGL.h new file mode 100644 index 0000000000..fc35099cdb --- /dev/null +++ b/src/backend/opengl/PipelineLayoutGL.h @@ -0,0 +1,48 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_OPENGL_PIPELINELAYOUTGL_H_ +#define BACKEND_OPENGL_PIPELINELAYOUTGL_H_ + +#include "common/PipelineLayout.h" + +#include "glad/glad.h" + +namespace backend { +namespace opengl { + + class Device; + + class PipelineLayout : public PipelineLayoutBase { + public: + PipelineLayout(Device* device, PipelineLayoutBuilder* builder); + + using BindingIndexInfo = std::array, kMaxBindGroups>; + const BindingIndexInfo& GetBindingIndexInfo() const; + + GLuint GetTextureUnitsUsed() const; + size_t GetNumSamplers() const; + size_t GetNumSampledTextures() const; + + private: + Device* device; + BindingIndexInfo indexInfo; + size_t numSamplers; + size_t numSampledTextures; + }; + +} +} + +#endif // BACKEND_OPENGL_PIPELINELAYOUTGL_H_ diff --git a/src/backend/opengl/SamplerGL.cpp b/src/backend/opengl/SamplerGL.cpp new file mode 100644 index 0000000000..73d418bab9 --- /dev/null +++ b/src/backend/opengl/SamplerGL.cpp @@ -0,0 +1,62 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "SamplerGL.h" + +namespace backend { +namespace opengl { + + namespace { + GLenum MagFilterMode(nxt::FilterMode filter) { + switch (filter) { + case nxt::FilterMode::Nearest: + return GL_NEAREST; + case nxt::FilterMode::Linear: + return GL_LINEAR; + } + } + + GLenum MinFilterMode(nxt::FilterMode minFilter, nxt::FilterMode mipMapFilter) { + switch (minFilter) { + case nxt::FilterMode::Nearest: + switch (mipMapFilter) { + case nxt::FilterMode::Nearest: + return GL_NEAREST_MIPMAP_NEAREST; + case nxt::FilterMode::Linear: + return GL_NEAREST_MIPMAP_LINEAR; + } + case nxt::FilterMode::Linear: + switch (mipMapFilter) { + case nxt::FilterMode::Nearest: + return GL_LINEAR_MIPMAP_NEAREST; + case nxt::FilterMode::Linear: + return GL_LINEAR_MIPMAP_LINEAR; + } + } + } + } + + Sampler::Sampler(Device* device, SamplerBuilder* builder) + : SamplerBase(builder), device(device) { + glGenSamplers(1, &handle); + glSamplerParameteri(handle, GL_TEXTURE_MAG_FILTER, MagFilterMode(builder->GetMagFilter())); + glSamplerParameteri(handle, GL_TEXTURE_MIN_FILTER, MinFilterMode(builder->GetMinFilter(), builder->GetMipMapFilter())); + } + + GLuint Sampler::GetHandle() const { + return handle; + } + +} +} diff --git a/src/backend/opengl/SamplerGL.h b/src/backend/opengl/SamplerGL.h new file mode 100644 index 0000000000..c238e8a56e --- /dev/null +++ b/src/backend/opengl/SamplerGL.h @@ -0,0 +1,41 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_OPENGL_SAMPLERGL_H_ +#define BACKEND_OPENGL_SAMPLERGL_H_ + +#include "common/Sampler.h" + +#include "glad/glad.h" + +namespace backend { +namespace opengl { + + class Device; + + class Sampler : public SamplerBase { + public: + Sampler(Device* device, SamplerBuilder* builder); + + GLuint GetHandle() const; + + private: + Device* device; + GLuint handle; + }; + +} +} + +#endif // BACKEND_OPENGL_SAMPLERGL_H_ diff --git a/src/backend/opengl/ShaderModuleGL.cpp b/src/backend/opengl/ShaderModuleGL.cpp new file mode 100644 index 0000000000..afb5706d2a --- /dev/null +++ b/src/backend/opengl/ShaderModuleGL.cpp @@ -0,0 +1,105 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "ShaderModuleGL.h" + +#include + +#include + +namespace backend { +namespace opengl { + + std::string GetBindingName(uint32_t group, uint32_t binding) { + std::ostringstream o; + o << "nxt_binding_" << group << "_" << binding; + return o.str(); + } + + bool operator < (const BindingLocation& a, const BindingLocation& b) { + return std::tie(a.group, a.binding) < std::tie(b.group, b.binding); + } + + bool operator < (const CombinedSampler& a, const CombinedSampler& b) { + return std::tie(a.samplerLocation, a.textureLocation) < std::tie(b.samplerLocation, b.textureLocation); + } + + std::string CombinedSampler::GetName() const { + std::ostringstream o; + o << "nxt_combined"; + o << "_" << samplerLocation.group << "_" << samplerLocation.binding; + o << "_with_" << textureLocation.group << "_" << textureLocation.binding; + return o.str(); + } + + ShaderModule::ShaderModule(Device* device, ShaderModuleBuilder* builder) + : ShaderModuleBase(builder), device(device) { + spirv_cross::CompilerGLSL compiler(builder->AcquireSpirv()); + spirv_cross::CompilerGLSL::Options options; + + // TODO(cwallez@chromium.org): discover the backing context version and use that. +#if defined(__APPLE__) + options.version = 410; +#else + options.version = 450; +#endif + compiler.set_options(options); + + ExtractSpirvInfo(compiler); + + const auto& bindingInfo = GetBindingInfo(); + + // Extract bindings names so that it can be used to get its location in program. + // Now translate the separate sampler / textures into combined ones and store their info. + // We need to do this before removing the set and binding decorations. + compiler.build_combined_image_samplers(); + + for (const auto& combined : compiler.get_combined_image_samplers()) { + combinedInfo.emplace_back(); + + auto& info = combinedInfo.back(); + info.samplerLocation.group = compiler.get_decoration(combined.sampler_id, spv::DecorationDescriptorSet); + info.samplerLocation.binding = compiler.get_decoration(combined.sampler_id, spv::DecorationBinding); + info.textureLocation.group = compiler.get_decoration(combined.image_id, spv::DecorationDescriptorSet); + info.textureLocation.binding = compiler.get_decoration(combined.image_id, spv::DecorationBinding); + compiler.set_name(combined.combined_id, info.GetName()); + } + + // Change binding names to be "nxt_binding__". + // Also unsets the SPIRV "Binding" decoration as it outputs "layout(binding=)" which + // isn't supported on OSX's OpenGL. + for (uint32_t group = 0; group < kMaxBindGroups; ++group) { + for (uint32_t binding = 0; binding < kMaxBindingsPerGroup; ++binding) { + const auto& info = bindingInfo[group][binding]; + if (info.used) { + compiler.set_name(info.base_type_id, GetBindingName(group, binding)); + compiler.unset_decoration(info.id, spv::DecorationBinding); + compiler.unset_decoration(info.id, spv::DecorationDescriptorSet); + } + } + } + + glslSource = compiler.compile(); + } + + const char* ShaderModule::GetSource() const { + return reinterpret_cast(glslSource.data()); + } + + const ShaderModule::CombinedSamplerInfo& ShaderModule::GetCombinedSamplerInfo() const { + return combinedInfo; + } + +} +} diff --git a/src/backend/opengl/ShaderModuleGL.h b/src/backend/opengl/ShaderModuleGL.h new file mode 100644 index 0000000000..d9855273b1 --- /dev/null +++ b/src/backend/opengl/ShaderModuleGL.h @@ -0,0 +1,60 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_OPENGL_SHADERMODULEGL_H_ +#define BACKEND_OPENGL_SHADERMODULEGL_H_ + +#include "common/ShaderModule.h" + +#include "glad/glad.h" + +namespace backend { +namespace opengl { + + class Device; + + std::string GetBindingName(uint32_t group, uint32_t binding); + + struct BindingLocation { + uint32_t group; + uint32_t binding; + }; + bool operator < (const BindingLocation& a, const BindingLocation& b); + + struct CombinedSampler { + BindingLocation samplerLocation; + BindingLocation textureLocation; + std::string GetName() const; + }; + bool operator < (const CombinedSampler& a, const CombinedSampler& b); + + class ShaderModule : public ShaderModuleBase { + public: + ShaderModule(Device* device, ShaderModuleBuilder* builder); + + using CombinedSamplerInfo = std::vector; + + const char* GetSource() const; + const CombinedSamplerInfo& GetCombinedSamplerInfo() const; + + private: + Device* device; + CombinedSamplerInfo combinedInfo; + std::string glslSource; + }; + +} +} + +#endif // BACKEND_OPENGL_SHADERMODULEGL_H_ diff --git a/src/backend/opengl/TextureGL.cpp b/src/backend/opengl/TextureGL.cpp new file mode 100644 index 0000000000..fc1a733303 --- /dev/null +++ b/src/backend/opengl/TextureGL.cpp @@ -0,0 +1,86 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "TextureGL.h" + +#include +#include + +namespace backend { +namespace opengl { + + namespace { + + GLenum TargetForDimension(nxt::TextureDimension dimension) { + switch (dimension) { + case nxt::TextureDimension::e2D: + return GL_TEXTURE_2D; + } + } + + TextureFormatInfo GetGLFormatInfo(nxt::TextureFormat format) { + switch (format) { + case nxt::TextureFormat::R8G8B8A8Unorm: + return {GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE}; + } + } + + } + + // Texture + + Texture::Texture(Device* device, TextureBuilder* builder) + : TextureBase(builder), device(device) { + target = TargetForDimension(GetDimension()); + + uint32_t width = GetWidth(); + uint32_t height = GetHeight(); + uint32_t levels = GetNumMipLevels(); + + auto formatInfo = GetGLFormatInfo(GetFormat()); + + glGenTextures(1, &handle); + glBindTexture(target, handle); + + for (uint32_t i = 0; i < levels; ++i) { + glTexImage2D(target, i, formatInfo.internalFormat, width, height, 0, formatInfo.format, formatInfo.type, nullptr); + width = std::max(uint32_t(1), width / 2); + height = std::max(uint32_t(1), height / 2); + } + + // The texture is not complete if it uses mipmapping and not all levels up to + // MAX_LEVEL have been defined. + glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, levels - 1); + } + + GLuint Texture::GetHandle() const { + return handle; + } + + GLenum Texture::GetGLTarget() const { + return target; + } + + TextureFormatInfo Texture::GetGLFormat() const { + return GetGLFormatInfo(GetFormat()); + } + + // TextureView + + TextureView::TextureView(Device* device, TextureViewBuilder* builder) + : TextureViewBase(builder), device(device) { + } + +} +} diff --git a/src/backend/opengl/TextureGL.h b/src/backend/opengl/TextureGL.h new file mode 100644 index 0000000000..6bdf534a07 --- /dev/null +++ b/src/backend/opengl/TextureGL.h @@ -0,0 +1,59 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef BACKEND_OPENGL_TEXTUREGL_H_ +#define BACKEND_OPENGL_TEXTUREGL_H_ + +#include "common/Texture.h" + +#include "glad/glad.h" + +namespace backend { +namespace opengl { + + class Device; + + struct TextureFormatInfo { + GLenum internalFormat; + GLenum format; + GLenum type; + }; + + class Texture : public TextureBase { + public: + Texture(Device* device, TextureBuilder* builder); + + GLuint GetHandle() const; + GLenum GetGLTarget() const; + TextureFormatInfo GetGLFormat() const; + + private: + Device* device; + GLuint handle; + GLenum target; + }; + + class TextureView : public TextureViewBase { + public: + TextureView(Device* device, TextureViewBuilder* builder); + + private: + Device* device; + }; + + +} +} + +#endif // BACKEND_OPENGL_TEXTUREGL_H_ diff --git a/src/backend/tests/BitSetIteratorTests.cpp b/src/backend/tests/BitSetIteratorTests.cpp new file mode 100644 index 0000000000..b1ac2e70dc --- /dev/null +++ b/src/backend/tests/BitSetIteratorTests.cpp @@ -0,0 +1,85 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include + +#include "common/BitSetIterator.h" + +// This is ANGLE's BitSetIterator_unittests.cpp file. + +using namespace backend; + +class BitSetIteratorTest : public testing::Test { + protected: + std::bitset<40> mStateBits; +}; + +// Simple iterator test. +TEST_F(BitSetIteratorTest, Iterator) { + std::set originalValues; + originalValues.insert(2); + originalValues.insert(6); + originalValues.insert(8); + originalValues.insert(35); + + for (unsigned long value : originalValues) { + mStateBits.set(value); + } + + std::set readValues; + for (unsigned long bit : IterateBitSet(mStateBits)) { + EXPECT_EQ(1u, originalValues.count(bit)); + EXPECT_EQ(0u, readValues.count(bit)); + readValues.insert(bit); + } + + EXPECT_EQ(originalValues.size(), readValues.size()); +} + +// Test an empty iterator. +TEST_F(BitSetIteratorTest, EmptySet) { + // We don't use the FAIL gtest macro here since it returns immediately, + // causing an unreachable code warning in MSVS + bool sawBit = false; + for (unsigned long bit : IterateBitSet(mStateBits)) { + sawBit = true; + } + EXPECT_FALSE(sawBit); +} + +// Test iterating a result of combining two bitsets. +TEST_F(BitSetIteratorTest, NonLValueBitset) { + std::bitset<40> otherBits; + + mStateBits.set(1); + mStateBits.set(2); + mStateBits.set(3); + mStateBits.set(4); + + otherBits.set(0); + otherBits.set(1); + otherBits.set(3); + otherBits.set(5); + + std::set seenBits; + + for (unsigned long bit : IterateBitSet(mStateBits & otherBits)) { + EXPECT_EQ(0u, seenBits.count(bit)); + seenBits.insert(bit); + EXPECT_TRUE(mStateBits[bit]); + EXPECT_TRUE(otherBits[bit]); + } + + EXPECT_EQ((mStateBits & otherBits).count(), seenBits.size()); +} diff --git a/src/backend/tests/CommandAllocatorTests.cpp b/src/backend/tests/CommandAllocatorTests.cpp new file mode 100644 index 0000000000..9ebb1d7c50 --- /dev/null +++ b/src/backend/tests/CommandAllocatorTests.cpp @@ -0,0 +1,361 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include + +#include "common/CommandAllocator.h" + +using namespace backend; + +// Definition of the command types used in the tests +enum class CommandType { + Draw, + Pipeline, + PushConstants, + Big, + Small, +}; + +struct CommandDraw { + uint32_t first; + uint32_t count; +}; + +struct CommandPipeline { + uint64_t pipeline; + uint32_t attachmentPoint; +}; + +struct CommandPushConstants { + uint8_t size; + uint8_t offset; +}; + +constexpr int kBigBufferSize = 65536; + +struct CommandBig { + uint32_t buffer[kBigBufferSize]; +}; + +struct CommandSmall { + uint16_t data; +}; + +// Test allocating nothing works +TEST(CommandAllocator, DoNothingAllocator) { + CommandAllocator allocator; +} + +// Test iterating over nothing works +TEST(CommandAllocator, DoNothingAllocatorWithIterator) { + CommandAllocator allocator; + CommandIterator iterator(std::move(allocator)); + iterator.DataWasDestroyed(); +} + +// Test basic usage of allocator + iterator +TEST(CommandAllocator, Basic) { + CommandAllocator allocator; + + uint64_t myPipeline = 0xDEADBEEFBEEFDEAD; + uint32_t myAttachmentPoint = 2; + uint32_t myFirst = 42; + uint32_t myCount = 16; + + { + CommandPipeline* pipeline = allocator.Allocate(CommandType::Pipeline); + pipeline->pipeline = myPipeline; + pipeline->attachmentPoint = myAttachmentPoint; + + CommandDraw* draw = allocator.Allocate(CommandType::Draw); + draw->first = myFirst; + draw->count = myCount; + } + + { + CommandIterator iterator(std::move(allocator)); + CommandType type; + + bool hasNext = iterator.NextCommandId(&type); + ASSERT_TRUE(hasNext); + ASSERT_EQ(type, CommandType::Pipeline); + + CommandPipeline* pipeline = iterator.NextCommand(); + ASSERT_EQ(pipeline->pipeline, myPipeline); + ASSERT_EQ(pipeline->attachmentPoint, myAttachmentPoint); + + hasNext = iterator.NextCommandId(&type); + ASSERT_TRUE(hasNext); + ASSERT_EQ(type, CommandType::Draw); + + CommandDraw* draw = iterator.NextCommand(); + ASSERT_EQ(draw->first, myFirst); + ASSERT_EQ(draw->count, myCount); + + hasNext = iterator.NextCommandId(&type); + ASSERT_FALSE(hasNext); + + iterator.DataWasDestroyed(); + } +} + +// Test basic usage of allocator + iterator with data +TEST(CommandAllocator, BasicWithData) { + CommandAllocator allocator; + + uint8_t mySize = 8; + uint8_t myOffset = 3; + uint32_t myValues[5] = {6, 42, 0xFFFFFFFF, 0, 54}; + + { + CommandPushConstants* pushConstants = allocator.Allocate(CommandType::PushConstants); + pushConstants->size = mySize; + pushConstants->offset = myOffset; + + uint32_t* values = allocator.AllocateData(5); + for (size_t i = 0; i < 5; i++) { + values[i] = myValues[i]; + } + } + + { + CommandIterator iterator(std::move(allocator)); + CommandType type; + + bool hasNext = iterator.NextCommandId(&type); + ASSERT_TRUE(hasNext); + ASSERT_EQ(type, CommandType::PushConstants); + + CommandPushConstants* pushConstants = iterator.NextCommand(); + ASSERT_EQ(pushConstants->size, mySize); + ASSERT_EQ(pushConstants->offset, myOffset); + + uint32_t* values = iterator.NextData(5); + for (size_t i = 0; i < 5; i++) { + ASSERT_EQ(values[i], myValues[i]); + } + + hasNext = iterator.NextCommandId(&type); + ASSERT_FALSE(hasNext); + + iterator.DataWasDestroyed(); + } +} + +// Test basic iterating several times +TEST(CommandAllocator, MultipleIterations) { + CommandAllocator allocator; + + uint32_t myFirst = 42; + uint32_t myCount = 16; + + CommandDraw* draw = allocator.Allocate(CommandType::Draw); + draw->first = myFirst; + draw->count = myCount; + + { + CommandIterator iterator(std::move(allocator)); + CommandType type; + + // First iteration + bool hasNext = iterator.NextCommandId(&type); + ASSERT_TRUE(hasNext); + ASSERT_EQ(type, CommandType::Draw); + + CommandDraw* draw = iterator.NextCommand(); + ASSERT_EQ(draw->first, myFirst); + ASSERT_EQ(draw->count, myCount); + + hasNext = iterator.NextCommandId(&type); + ASSERT_FALSE(hasNext); + + // Second iteration + hasNext = iterator.NextCommandId(&type); + ASSERT_TRUE(hasNext); + ASSERT_EQ(type, CommandType::Draw); + + draw = iterator.NextCommand(); + ASSERT_EQ(draw->first, myFirst); + ASSERT_EQ(draw->count, myCount); + + hasNext = iterator.NextCommandId(&type); + ASSERT_FALSE(hasNext); + + iterator.DataWasDestroyed(); + } +} +// Test large commands work +TEST(CommandAllocator, LargeCommands) { + CommandAllocator allocator; + + const int kCommandCount = 5; + + int count = 0; + for (int i = 0; i < kCommandCount; i++) { + CommandBig* big = allocator.Allocate(CommandType::Big); + for (int j = 0; j < kBigBufferSize; j++) { + big->buffer[j] = count ++; + } + } + + CommandIterator iterator(std::move(allocator)); + CommandType type; + count = 0; + int numCommands = 0; + while (iterator.NextCommandId(&type)) { + ASSERT_EQ(type, CommandType::Big); + + CommandBig* big = iterator.NextCommand(); + for (int i = 0; i < kBigBufferSize; i++) { + ASSERT_EQ(big->buffer[i], count); + count ++; + } + numCommands ++; + } + ASSERT_EQ(numCommands, kCommandCount); + + iterator.DataWasDestroyed(); +} + +// Test many small commands work +TEST(CommandAllocator, ManySmallCommands) { + CommandAllocator allocator; + + // Stay under max representable uint16_t + const int kCommandCount = 50000; + + int count = 0; + for (int i = 0; i < kCommandCount; i++) { + CommandSmall* small = allocator.Allocate(CommandType::Small); + small->data = count ++; + } + + CommandIterator iterator(std::move(allocator)); + CommandType type; + count = 0; + int numCommands = 0; + while (iterator.NextCommandId(&type)) { + ASSERT_EQ(type, CommandType::Small); + + CommandSmall* small = iterator.NextCommand(); + ASSERT_EQ(small->data, count); + count ++; + numCommands ++; + } + ASSERT_EQ(numCommands, kCommandCount); + + iterator.DataWasDestroyed(); +} + +// ________ +// / \ +// | POUIC! | +// \_ ______/ +// v +// ()_() +// (O.o) +// (> <)o + +// Test usage of iterator.Reset +TEST(CommandAllocator, IteratorReset) { + CommandAllocator allocator; + + uint64_t myPipeline = 0xDEADBEEFBEEFDEAD; + uint32_t myAttachmentPoint = 2; + uint32_t myFirst = 42; + uint32_t myCount = 16; + + { + CommandPipeline* pipeline = allocator.Allocate(CommandType::Pipeline); + pipeline->pipeline = myPipeline; + pipeline->attachmentPoint = myAttachmentPoint; + + CommandDraw* draw = allocator.Allocate(CommandType::Draw); + draw->first = myFirst; + draw->count = myCount; + } + + { + CommandIterator iterator(std::move(allocator)); + CommandType type; + + bool hasNext = iterator.NextCommandId(&type); + ASSERT_TRUE(hasNext); + ASSERT_EQ(type, CommandType::Pipeline); + + CommandPipeline* pipeline = iterator.NextCommand(); + ASSERT_EQ(pipeline->pipeline, myPipeline); + ASSERT_EQ(pipeline->attachmentPoint, myAttachmentPoint); + + iterator.Reset(); + + hasNext = iterator.NextCommandId(&type); + ASSERT_TRUE(hasNext); + ASSERT_EQ(type, CommandType::Pipeline); + + pipeline = iterator.NextCommand(); + ASSERT_EQ(pipeline->pipeline, myPipeline); + ASSERT_EQ(pipeline->attachmentPoint, myAttachmentPoint); + + hasNext = iterator.NextCommandId(&type); + ASSERT_TRUE(hasNext); + ASSERT_EQ(type, CommandType::Draw); + + CommandDraw* draw = iterator.NextCommand(); + ASSERT_EQ(draw->first, myFirst); + ASSERT_EQ(draw->count, myCount); + + hasNext = iterator.NextCommandId(&type); + ASSERT_FALSE(hasNext); + + iterator.DataWasDestroyed(); + } +} + +// Test iterating empty iterators +TEST(CommandAllocator, EmptyIterator) { + { + CommandAllocator allocator; + CommandIterator iterator(std::move(allocator)); + + CommandType type; + bool hasNext = iterator.NextCommandId(&type); + ASSERT_FALSE(hasNext); + + iterator.DataWasDestroyed(); + } + { + CommandAllocator allocator; + CommandIterator iterator1(std::move(allocator)); + CommandIterator iterator2(std::move(iterator1)); + + CommandType type; + bool hasNext = iterator2.NextCommandId(&type); + ASSERT_FALSE(hasNext); + + iterator1.DataWasDestroyed(); + iterator2.DataWasDestroyed(); + } + { + CommandIterator iterator1; + CommandIterator iterator2(std::move(iterator1)); + + CommandType type; + bool hasNext = iterator2.NextCommandId(&type); + ASSERT_FALSE(hasNext); + + iterator1.DataWasDestroyed(); + iterator2.DataWasDestroyed(); + } +} diff --git a/src/backend/tests/MathTests.cpp b/src/backend/tests/MathTests.cpp new file mode 100644 index 0000000000..3264a8fd7e --- /dev/null +++ b/src/backend/tests/MathTests.cpp @@ -0,0 +1,85 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include + +#include "common/Math.h" + +using namespace backend; + +// Tests for ScanForward +TEST(Math, ScanForward) { + // Test extrema + ASSERT_EQ(ScanForward(1), 0); + ASSERT_EQ(ScanForward(0x8000000000000000), 63); + + // Test with more than one bit set. + ASSERT_EQ(ScanForward(256), 8); + ASSERT_EQ(ScanForward(256 + 32), 5); + ASSERT_EQ(ScanForward(1024 + 256 + 32), 5); +} + +// Tests for Log2 +TEST(Math, Log2) { + // Test extrema + ASSERT_EQ(Log2(1), 0); + ASSERT_EQ(Log2(0xFFFFFFFF), 31); + + // Test boundary between two logs + ASSERT_EQ(Log2(0x80000000), 31); + ASSERT_EQ(Log2(0x7FFFFFFF), 30); + + ASSERT_EQ(Log2(16), 4); + ASSERT_EQ(Log2(15), 3); +} + +// Tests for IsPowerOfTwo +TEST(Math, IsPowerOfTwo) { + ASSERT_TRUE(IsPowerOfTwo(1)); + ASSERT_TRUE(IsPowerOfTwo(2)); + ASSERT_FALSE(IsPowerOfTwo(3)); + + ASSERT_TRUE(IsPowerOfTwo(0x8000000)); + ASSERT_FALSE(IsPowerOfTwo(0x8000400)); +} + +// Tests for Align +TEST(Math, Align) { + constexpr size_t kTestAlignment = 8; + + char buffer[kTestAlignment * 4]; + + for (size_t i = 0; i < 2 * kTestAlignment; ++i) { + char* unaligned = &buffer[i]; + char* aligned = Align(unaligned, kTestAlignment); + + ASSERT_GE(aligned - unaligned, 0); + ASSERT_LT(aligned - unaligned, kTestAlignment); + ASSERT_EQ(reinterpret_cast(aligned) & (kTestAlignment -1), 0); + } +} + +// Tests for IsAligned +TEST(Math, IsAligned) { + constexpr size_t kTestAlignment = 8; + + char buffer[kTestAlignment * 4]; + + for (size_t i = 0; i < 2 * kTestAlignment; ++i) { + char* unaligned = &buffer[i]; + char* aligned = Align(unaligned, kTestAlignment); + + ASSERT_EQ(IsAligned(unaligned, kTestAlignment), unaligned == aligned); + } +} diff --git a/src/backend/tests/PerStageTests.cpp b/src/backend/tests/PerStageTests.cpp new file mode 100644 index 0000000000..c9496bc62a --- /dev/null +++ b/src/backend/tests/PerStageTests.cpp @@ -0,0 +1,89 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include + +#include "common/PerStage.h" + +using namespace backend; + +// Tests for StageBit +TEST(PerStage, StageBit) { + ASSERT_EQ(StageBit(nxt::ShaderStage::Vertex), nxt::ShaderStageBit::Vertex); + ASSERT_EQ(StageBit(nxt::ShaderStage::Fragment), nxt::ShaderStageBit::Fragment); + ASSERT_EQ(StageBit(nxt::ShaderStage::Compute), nxt::ShaderStageBit::Compute); +} + +// Basic test for the PerStage container +TEST(PerStage, PerStage) { + PerStage data; + + // Store data using nxt::ShaderStage + data[nxt::ShaderStage::Vertex] = 42; + data[nxt::ShaderStage::Fragment] = 3; + data[nxt::ShaderStage::Compute] = -1; + + // Load it using nxt::ShaderStageBit + ASSERT_EQ(data[nxt::ShaderStageBit::Vertex], 42); + ASSERT_EQ(data[nxt::ShaderStageBit::Fragment], 3); + ASSERT_EQ(data[nxt::ShaderStageBit::Compute], -1); +} + +// Test IterateStages with kAllStages +TEST(PerStage, IterateAllStages) { + PerStage counts; + counts[nxt::ShaderStage::Vertex] = 0; + counts[nxt::ShaderStage::Fragment] = 0; + counts[nxt::ShaderStage::Compute] = 0; + + for (auto stage : IterateStages(kAllStages)) { + counts[stage] ++; + } + + ASSERT_EQ(counts[nxt::ShaderStageBit::Vertex], 1); + ASSERT_EQ(counts[nxt::ShaderStageBit::Fragment], 1); + ASSERT_EQ(counts[nxt::ShaderStageBit::Compute], 1); +} + +// Test IterateStages with one stage +TEST(PerStage, IterateOneStage) { + PerStage counts; + counts[nxt::ShaderStage::Vertex] = 0; + counts[nxt::ShaderStage::Fragment] = 0; + counts[nxt::ShaderStage::Compute] = 0; + + for (auto stage : IterateStages(nxt::ShaderStageBit::Fragment)) { + counts[stage] ++; + } + + ASSERT_EQ(counts[nxt::ShaderStageBit::Vertex], 0); + ASSERT_EQ(counts[nxt::ShaderStageBit::Fragment], 1); + ASSERT_EQ(counts[nxt::ShaderStageBit::Compute], 0); +} + +// Test IterateStages with no stage +TEST(PerStage, IterateNoStages) { + PerStage counts; + counts[nxt::ShaderStage::Vertex] = 0; + counts[nxt::ShaderStage::Fragment] = 0; + counts[nxt::ShaderStage::Compute] = 0; + + for (auto stage : IterateStages(nxt::ShaderStageBit::Fragment & nxt::ShaderStageBit::Vertex)) { + counts[stage] ++; + } + + ASSERT_EQ(counts[nxt::ShaderStageBit::Vertex], 0); + ASSERT_EQ(counts[nxt::ShaderStageBit::Fragment], 0); + ASSERT_EQ(counts[nxt::ShaderStageBit::Compute], 0); +} diff --git a/src/backend/tests/RefCountedTests.cpp b/src/backend/tests/RefCountedTests.cpp new file mode 100644 index 0000000000..0136491b82 --- /dev/null +++ b/src/backend/tests/RefCountedTests.cpp @@ -0,0 +1,178 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include + +#include "common/RefCounted.h" + +using namespace backend; + +struct RCTest : public RefCounted { + RCTest() { + } + + RCTest(bool* deleted): deleted(deleted) { + } + + ~RCTest() override { + if (deleted != nullptr) { + *deleted = true; + } + } + + RCTest* GetThis() { + return this; + } + + bool* deleted = nullptr; +}; + +// Test that RCs start with one external ref, and removing it destroys the object. +TEST(RefCounted, StartsWithOneExternalRef) { + bool deleted = false; + auto test = new RCTest(&deleted); + + test->Release(); + ASSERT_TRUE(deleted); +} + +// Test internal refs keep the RC alive. +TEST(RefCounted, InternalRefKeepsAlive) { + bool deleted = false; + auto test = new RCTest(&deleted); + + test->ReferenceInternal(); + test->Release(); + ASSERT_FALSE(deleted); + + test->ReleaseInternal(); + ASSERT_TRUE(deleted); +} + +// Test Ref remove internal reference when going out of scope +TEST(Ref, EndOfScopeRemovesInternalRef) { + bool deleted = false; + { + Ref test(new RCTest(&deleted)); + test->Release(); + } + ASSERT_TRUE(deleted); +} + +// Test getting pointer out of the Ref +TEST(Ref, Gets) { + RCTest* original = new RCTest; + Ref test(original); + test->Release(); + + ASSERT_EQ(test.Get(), original); + ASSERT_EQ(&*test, original); + ASSERT_EQ(test->GetThis(), original); +} + +// Test Refs default to null +TEST(Ref, DefaultsToNull) { + Ref test; + + ASSERT_EQ(test.Get(), nullptr); + ASSERT_EQ(&*test, nullptr); + ASSERT_EQ(test->GetThis(), nullptr); +} + +// Test Refs can be used inside ifs +TEST(Ref, BoolConversion) { + Ref empty; + Ref full(new RCTest); + full->Release(); + + if (!full || empty) { + ASSERT_TRUE(false); + } +} + +// Test Ref's copy constructor +TEST(Ref, CopyConstructor) { + bool deleted; + RCTest* original = new RCTest(&deleted); + + Ref source(original); + Ref destination(source); + original->Release(); + + ASSERT_EQ(source.Get(), original); + ASSERT_EQ(destination.Get(), original); + + source = nullptr; + ASSERT_FALSE(deleted); + destination = nullptr; + ASSERT_TRUE(deleted); +} + +// Test Ref's copy assignment +TEST(Ref, CopyAssignment) { + bool deleted; + RCTest* original = new RCTest(&deleted); + + Ref source(original); + original->Release(); + + Ref destination; + destination = source; + + ASSERT_EQ(source.Get(), original); + ASSERT_EQ(destination.Get(), original); + + source = nullptr; + // This fails when address sanitizer is turned on + ASSERT_FALSE(deleted); + + destination = nullptr; + ASSERT_TRUE(deleted); +} + +// Test Ref's move constructor +TEST(Ref, MoveConstructor) { + bool deleted; + RCTest* original = new RCTest(&deleted); + + Ref source(original); + Ref destination(std::move(source)); + original->Release(); + + ASSERT_EQ(source.Get(), nullptr); + ASSERT_EQ(destination.Get(), original); + ASSERT_FALSE(deleted); + + destination = nullptr; + ASSERT_TRUE(deleted); +} + +// Test Ref's move assignment +TEST(Ref, MoveAssignment) { + bool deleted; + RCTest* original = new RCTest(&deleted); + + Ref source(original); + original->Release(); + + Ref destination; + destination = std::move(source); + + ASSERT_EQ(source.Get(), nullptr); + ASSERT_EQ(destination.Get(), original); + ASSERT_FALSE(deleted); + + destination = nullptr; + ASSERT_TRUE(deleted); +} diff --git a/src/backend/tests/ToBackendTests.cpp b/src/backend/tests/ToBackendTests.cpp new file mode 100644 index 0000000000..3ce65cbc75 --- /dev/null +++ b/src/backend/tests/ToBackendTests.cpp @@ -0,0 +1,89 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include + +#include "common/RefCounted.h" +#include "common/ToBackend.h" + +#include + +// Make our own Base - Backend object pair, reusing the CommandBuffer name +namespace backend { + class CommandBufferBase : public RefCounted { + }; +} + +using namespace backend; + +class MyCommandBuffer : public CommandBufferBase { +}; + +struct MyBackendTraits { + using CommandBufferType = MyCommandBuffer; +}; + +// Instanciate ToBackend for our "backend" +template +auto ToBackend(T&& common) -> decltype(ToBackendBase(common)) { + return ToBackendBase(common); +} + +// Test that ToBackend correctly converts pointers to base classes. +TEST(ToBackend, Pointers) { + { + MyCommandBuffer* cmdBuf = new MyCommandBuffer; + const CommandBufferBase* base = cmdBuf; + + auto backendCmdBuf = ToBackend(base); + static_assert(std::is_same::value, ""); + ASSERT_EQ(cmdBuf, backendCmdBuf); + + cmdBuf->Release(); + } + { + MyCommandBuffer* cmdBuf = new MyCommandBuffer; + CommandBufferBase* base = cmdBuf; + + auto backendCmdBuf = ToBackend(base); + static_assert(std::is_same::value, ""); + ASSERT_EQ(cmdBuf, backendCmdBuf); + + cmdBuf->Release(); + } +} + +// Test that ToBackend correctly converts Refs to base classes. +TEST(ToBackend, Ref) { + { + MyCommandBuffer* cmdBuf = new MyCommandBuffer; + const Ref base(cmdBuf); + + const auto& backendCmdBuf = ToBackend(base); + static_assert(std::is_same&>::value, ""); + ASSERT_EQ(cmdBuf, backendCmdBuf.Get()); + + cmdBuf->Release(); + } + { + MyCommandBuffer* cmdBuf = new MyCommandBuffer; + Ref base(cmdBuf); + + auto backendCmdBuf = ToBackend(base); + static_assert(std::is_same&>::value, ""); + ASSERT_EQ(cmdBuf, backendCmdBuf.Get()); + + cmdBuf->Release(); + } +} diff --git a/src/backend/tests/UnittestsMain.cpp b/src/backend/tests/UnittestsMain.cpp new file mode 100644 index 0000000000..73870aa9f0 --- /dev/null +++ b/src/backend/tests/UnittestsMain.cpp @@ -0,0 +1,20 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include + +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/src/include/nxt/EnumClassBitmasks.h b/src/include/nxt/EnumClassBitmasks.h new file mode 100644 index 0000000000..63804a416d --- /dev/null +++ b/src/include/nxt/EnumClassBitmasks.h @@ -0,0 +1,150 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef NXT_ENUM_CLASS_BITMASKS_H_ +#define NXT_ENUM_CLASS_BITMASKS_H_ + +#include + +namespace nxt { + +// std::underlying_type doesn't work in old GLIBC still used in Chrome +#define CR_GLIBCXX_4_7_0 20120322 +#define CR_GLIBCXX_4_5_4 20120702 +#define CR_GLIBCXX_4_6_4 20121127 +#if defined(__GLIBCXX__) && \ + (__GLIBCXX__ < CR_GLIBCXX_4_7_0 || __GLIBCXX__ == CR_GLIBCXX_4_5_4 || \ + __GLIBCXX__ == CR_GLIBCXX_4_6_4) +#define CR_USE_FALLBACKS_FOR_OLD_GLIBCXX +#endif + +#if defined(CR_USE_FALLBACKS_FOR_OLD_GLIBCXX) + template + struct UnderlyingType { + using type = __underlying_type(T); + }; +#else + template + using UnderlyingType = std::underlying_type; +#endif + + template + struct IsNXTBitmask { + static constexpr bool enable = false; + }; + + template + struct LowerBitmask { + static constexpr bool enable = false; + }; + + template + struct LowerBitmask::enable>::type> { + static constexpr bool enable = true; + using type = T; + static T Lower(T t) {return t;} + }; + + template + struct BoolConvertible { + using Integral = typename UnderlyingType::type; + + BoolConvertible(Integral value) : value(value) {} + operator bool() const {return value != 0;} + operator T() const {return static_cast(value);} + + Integral value; + }; + + template + struct LowerBitmask> { + static constexpr bool enable = true; + using type = T; + static type Lower(BoolConvertible t) {return t;} + }; + + template + constexpr bool HasZeroOrOneBits(T value) { + using Integral = typename UnderlyingType::type; + Integral v = static_cast(value); + return (v & (v - 1)) == 0; + } + + template::enable && LowerBitmask::enable + >::type> + constexpr BoolConvertible::type> operator | (T1 left, T2 right) { + using T = typename LowerBitmask::type; + using Integral = typename UnderlyingType::type; + return static_cast(LowerBitmask::Lower(left)) | + static_cast(LowerBitmask::Lower(right)); + } + + template::enable && LowerBitmask::enable + >::type> + constexpr BoolConvertible::type> operator & (T1 left, T2 right) { + using T = typename LowerBitmask::type; + using Integral = typename UnderlyingType::type; + return static_cast(LowerBitmask::Lower(left)) & + static_cast(LowerBitmask::Lower(right)); + } + + template::enable && LowerBitmask::enable + >::type> + constexpr BoolConvertible::type> operator ^ (T1 left, T2 right) { + using T = typename LowerBitmask::type; + using Integral = typename UnderlyingType::type; + return static_cast(LowerBitmask::Lower(left)) ^ + static_cast(LowerBitmask::Lower(right)); + } + + template + constexpr BoolConvertible::type> operator ~ (T1 t) { + using T = typename LowerBitmask::type; + using Integral = typename UnderlyingType::type; + return ~static_cast(LowerBitmask::Lower(t)); + } + + template::enable && LowerBitmask::enable + >::type> + T& operator &= (T& l, T2 right) { + T r = LowerBitmask::Lower(right); + l = l & r; + return l; + } + + template::enable && LowerBitmask::enable + >::type> + T& operator |= (T& l, T2 right) { + T r = LowerBitmask::Lower(right); + l = l | r; + return l; + } + + template::enable && LowerBitmask::enable + >::type> + T& operator ^= (T& l, T2 right) { + T r = LowerBitmask::Lower(right); + l = l ^ r; + return l; + } + +} + +#endif // NXT_ENUM_CLASS_BITMASKS_H_ diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt new file mode 100644 index 0000000000..8a42014683 --- /dev/null +++ b/src/tests/CMakeLists.txt @@ -0,0 +1,22 @@ +# Copyright 2017 The NXT Authors +# +# 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. + +set(TESTS_DIR ${CMAKE_CURRENT_SOURCE_DIR}) + +add_executable(nxt_unittests + ${TESTS_DIR}/EnumClassBitmasksTests.cpp + ${TESTS_DIR}/UnittestsMain.cpp +) +target_link_libraries(nxt_unittests gtest nxtcpp) +SetCXX14(nxt_unittests) diff --git a/src/tests/EnumClassBitmasksTests.cpp b/src/tests/EnumClassBitmasksTests.cpp new file mode 100644 index 0000000000..7851047a81 --- /dev/null +++ b/src/tests/EnumClassBitmasksTests.cpp @@ -0,0 +1,93 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "gtest/gtest.h" + +#include "nxt/EnumClassBitmasks.h" + +namespace nxt { + + enum class Color : uint32_t { + R = 1, + G = 2, + B = 4, + A = 8, + }; + + template<> + struct IsNXTBitmask { + static constexpr bool enable = true; + }; + + TEST(BitmaskTests, BasicOperations) { + Color test1 = Color::R | Color::G; + ASSERT_EQ(1 | 2, static_cast(test1)); + + Color test2 = test1 ^ (Color::R | Color::A); + ASSERT_EQ(2 | 8, static_cast(test2)); + + Color test3 = test2 & Color::A; + ASSERT_EQ(8, static_cast(test3)); + + Color test4 = ~test3; + ASSERT_EQ(~uint32_t(8), static_cast(test4)); + } + + TEST(BitmaskTests, AssignOperations) { + Color test1 = Color::R; + test1 |= Color::G; + ASSERT_EQ(1 | 2, static_cast(test1)); + + Color test2 = test1; + test2 ^= (Color::R | Color::A); + ASSERT_EQ(2 | 8, static_cast(test2)); + + Color test3 = test2; + test3 &= Color::A; + ASSERT_EQ(8, static_cast(test3)); + } + + TEST(BitmaskTests, BoolConversion) { + bool test1 = Color::R | Color::G; + ASSERT_TRUE(test1); + + bool test2 = Color::R & Color::G; + ASSERT_FALSE(test2); + + bool test3 = Color::R ^ Color::G; + ASSERT_TRUE(test3); + + if (Color::R & ~Color::R) { + ASSERT_TRUE(false); + } + } + + TEST(BitmaskTests, ThreeOrs) { + Color c = Color::R | Color::G | Color::B; + ASSERT_EQ(7, static_cast(c)); + } + + TEST(BitmaskTests, ZeroOrOneBits) { + Color zero = static_cast(0); + ASSERT_TRUE(HasZeroOrOneBits(zero)); + ASSERT_TRUE(HasZeroOrOneBits(Color::R)); + ASSERT_TRUE(HasZeroOrOneBits(Color::G)); + ASSERT_TRUE(HasZeroOrOneBits(Color::B)); + ASSERT_TRUE(HasZeroOrOneBits(Color::A)); + ASSERT_FALSE(HasZeroOrOneBits(static_cast(Color::R | Color::G))); + ASSERT_FALSE(HasZeroOrOneBits(static_cast(Color::G | Color::B))); + ASSERT_FALSE(HasZeroOrOneBits(static_cast(Color::B | Color::A))); + } + +} diff --git a/src/tests/UnittestsMain.cpp b/src/tests/UnittestsMain.cpp new file mode 100644 index 0000000000..73870aa9f0 --- /dev/null +++ b/src/tests/UnittestsMain.cpp @@ -0,0 +1,20 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include + +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/src/wire/CMakeLists.txt b/src/wire/CMakeLists.txt new file mode 100644 index 0000000000..5ade76a71d --- /dev/null +++ b/src/wire/CMakeLists.txt @@ -0,0 +1,43 @@ +# Copyright 2017 The NXT Authors +# +# 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. + +set(WIRE_DIR ${CMAKE_CURRENT_SOURCE_DIR}) +set(TESTS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/tests) + +Generate( + LIB_NAME wire_autogen + LIB_TYPE STATIC + PRINT_NAME "Wire serialization/deserialization autogenerated files" + COMMAND_LINE_ARGS + ${GENERATOR_COMMON_ARGS} + -T wire +) +target_include_directories(wire_autogen PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) +target_include_directories(wire_autogen PUBLIC ${GENERATED_DIR}) +SetCXX14(wire_autogen) +SetPic(wire_autogen) + +add_library(nxt_wire SHARED + ${WIRE_DIR}/TerribleCommandBuffer.h +) +target_link_libraries(nxt_wire wire_autogen) +SetCXX14(nxt_wire) + +add_executable(wire_unittests + ${TESTS_DIR}/UnittestsMain.cpp + ${TESTS_DIR}/WireTests.cpp +) +target_link_libraries(wire_unittests mock_nxt nxt_wire) +target_include_directories(wire_unittests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) +SetCXX14(wire_unittests) diff --git a/src/wire/TerribleCommandBuffer.h b/src/wire/TerribleCommandBuffer.h new file mode 100644 index 0000000000..408e418cb7 --- /dev/null +++ b/src/wire/TerribleCommandBuffer.h @@ -0,0 +1,58 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef WIRE_TERRIBLE_COMMAND_BUFFER_H_ +#define WIRE_TERRIBLE_COMMAND_BUFFER_H_ + +#include + +#include "Wire.h" + +namespace nxt { +namespace wire { + +class TerribleCommandBuffer : public CommandSerializer { + public: + TerribleCommandBuffer(CommandHandler* handler) : handler(handler) { + } + void* GetCmdSpace(size_t size) { + if (size > sizeof(buffer)) { + return nullptr; + } + + uint8_t* result = &buffer[offset]; + offset += size; + + if (offset > sizeof(buffer)) { + Flush(); + return GetCmdSpace(size); + } + + return result; + } + void Flush() { + handler->HandleCommands(buffer, offset); + offset = 0; + } + + private: + CommandHandler* handler = nullptr; + size_t offset; + uint8_t buffer[10000000]; +}; + +} +} + +#endif // WIRE_TERRIBLE_COMMAND_BUFFER_H_ diff --git a/src/wire/Wire.h b/src/wire/Wire.h new file mode 100644 index 0000000000..bf3f30f00c --- /dev/null +++ b/src/wire/Wire.h @@ -0,0 +1,47 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef WIRE_WIRE_H_ +#define WIRE_WIRE_H_ + +#include + +#include "nxt/nxt.h" + +namespace nxt { +namespace wire { + + class CommandSerializer { + public: + virtual ~CommandSerializer() = default; + virtual void* GetCmdSpace(size_t size) = 0; + virtual void Flush() = 0; + }; + + void NewClientDevice(nxtProcTable* procs, nxtDevice* device, CommandSerializer* serializer); + + class CommandHandler { + public: + virtual ~CommandHandler() = default; + virtual const uint8_t* HandleCommands(const uint8_t* commands, size_t size) = 0; + + virtual void OnSynchronousError() = 0; + }; + + CommandHandler* CreateCommandHandler(nxtDevice device, const nxtProcTable& procs); + +} +} + +#endif // WIRE_WIRE_H_ diff --git a/src/wire/WireCmd.h b/src/wire/WireCmd.h new file mode 100644 index 0000000000..7114f401af --- /dev/null +++ b/src/wire/WireCmd.h @@ -0,0 +1,20 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#ifndef WIRE_WIRECMD_H_ +#define WIRE_WIRECMD_H_ + +#include "wire/WireCmd_autogen.h" + +#endif // WIRE_WIRECMD_H_ diff --git a/src/wire/tests/UnittestsMain.cpp b/src/wire/tests/UnittestsMain.cpp new file mode 100644 index 0000000000..73870aa9f0 --- /dev/null +++ b/src/wire/tests/UnittestsMain.cpp @@ -0,0 +1,20 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include + +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/src/wire/tests/WireTests.cpp b/src/wire/tests/WireTests.cpp new file mode 100644 index 0000000000..0e3139bc30 --- /dev/null +++ b/src/wire/tests/WireTests.cpp @@ -0,0 +1,182 @@ +// Copyright 2017 The NXT Authors +// +// 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. + +#include "gtest/gtest.h" +#include "mock/mock_nxt.h" + +#include "TerribleCommandBuffer.h" +#include "Wire.h" + +using namespace testing; +using namespace nxt::wire; + +class WireTests : public Test { + protected: + void SetUp() override { + nxtProcTable mockProcs; + nxtDevice mockDevice; + api.GetProcTableAndDevice(&mockProcs, &mockDevice); + + wireServer = CreateCommandHandler(mockDevice, mockProcs); + + cmdBuf = new TerribleCommandBuffer(wireServer); + + nxtDevice clientDevice; + nxtProcTable clientProcs; + NewClientDevice(&clientProcs, &clientDevice, cmdBuf); + + nxtSetProcs(&clientProcs); + device = clientDevice; + apiDevice = mockDevice; + } + + void TearDown() override { + nxtSetProcs(nullptr); + delete wireServer; + delete cmdBuf; + } + + void Flush() { + cmdBuf->Flush(); + } + + MockProcTable api; + nxtDevice apiDevice; + nxtDevice device; + + private: + CommandHandler* wireServer = nullptr; + TerribleCommandBuffer* cmdBuf = nullptr; +}; + +// One call gets forwarded correctly. +TEST_F(WireTests, CallForwarded) { + nxtCommandBufferBuilder builder = nxtDeviceCreateCommandBufferBuilder(device); + + nxtCommandBufferBuilder apiCmdBufBuilder = api.GetNewCommandBufferBuilder(); + EXPECT_CALL(api, DeviceCreateCommandBufferBuilder(apiDevice)) + .WillOnce(Return(apiCmdBufBuilder)); + + Flush(); +} + +// Test that calling methods on a new object works as expected. +TEST_F(WireTests, CreateThenCall) { + nxtCommandBufferBuilder builder = nxtDeviceCreateCommandBufferBuilder(device); + nxtCommandBuffer cmdBuf = nxtCommandBufferBuilderGetResult(builder); + + nxtCommandBufferBuilder apiCmdBufBuilder = api.GetNewCommandBufferBuilder(); + EXPECT_CALL(api, DeviceCreateCommandBufferBuilder(apiDevice)) + .WillOnce(Return(apiCmdBufBuilder)); + + nxtCommandBuffer apiCmdBuf = api.GetNewCommandBuffer(); + EXPECT_CALL(api, CommandBufferBuilderGetResult(apiCmdBufBuilder)) + .WillOnce(Return(apiCmdBuf)); + + Flush(); +} + +// Test that client reference/release do not call the backend API. +TEST_F(WireTests, RefCountKeptInClient) { + nxtCommandBufferBuilder builder = nxtDeviceCreateCommandBufferBuilder(device); + + nxtCommandBufferBuilderReference(builder); + nxtCommandBufferBuilderRelease(builder); + + nxtCommandBufferBuilder apiCmdBufBuilder = api.GetNewCommandBufferBuilder(); + EXPECT_CALL(api, DeviceCreateCommandBufferBuilder(apiDevice)) + .WillOnce(Return(apiCmdBufBuilder)); + + Flush(); +} + +// Test that client reference/release do not call the backend API. +TEST_F(WireTests, ReleaseCalledOnRefCount0) { + nxtCommandBufferBuilder builder = nxtDeviceCreateCommandBufferBuilder(device); + + nxtCommandBufferBuilderRelease(builder); + + nxtCommandBufferBuilder apiCmdBufBuilder = api.GetNewCommandBufferBuilder(); + EXPECT_CALL(api, DeviceCreateCommandBufferBuilder(apiDevice)) + .WillOnce(Return(apiCmdBufBuilder)); + + EXPECT_CALL(api, CommandBufferBuilderRelease(apiCmdBufBuilder)); + + Flush(); +} + +TEST_F(WireTests, ObjectAsValueArgument) { + // Create pipeline + nxtPipelineBuilder pipelineBuilder = nxtDeviceCreatePipelineBuilder(device); + nxtPipeline pipeline = nxtPipelineBuilderGetResult(pipelineBuilder); + + nxtPipelineBuilder apiPipelineBuilder = api.GetNewPipelineBuilder(); + EXPECT_CALL(api, DeviceCreatePipelineBuilder(apiDevice)) + .WillOnce(Return(apiPipelineBuilder)); + + nxtPipeline apiPipeline = api.GetNewPipeline(); + EXPECT_CALL(api, PipelineBuilderGetResult(apiPipelineBuilder)) + .WillOnce(Return(apiPipeline)); + + // Create command buffer builder, setting pipeline + nxtCommandBufferBuilder cmdBufBuilder = nxtDeviceCreateCommandBufferBuilder(device); + nxtCommandBufferBuilderSetPipeline(cmdBufBuilder, pipeline); + + nxtCommandBufferBuilder apiCmdBufBuilder = api.GetNewCommandBufferBuilder(); + EXPECT_CALL(api, DeviceCreateCommandBufferBuilder(apiDevice)) + .WillOnce(Return(apiCmdBufBuilder)); + + EXPECT_CALL(api, CommandBufferBuilderSetPipeline(apiCmdBufBuilder, apiPipeline)); + + Flush(); +} + +TEST_F(WireTests, OneObjectAsPointerArgument) { + // Create command buffer + nxtCommandBufferBuilder cmdBufBuilder = nxtDeviceCreateCommandBufferBuilder(device); + nxtCommandBuffer cmdBuf = nxtCommandBufferBuilderGetResult(cmdBufBuilder); + + nxtCommandBufferBuilder apiCmdBufBuilder = api.GetNewCommandBufferBuilder(); + EXPECT_CALL(api, DeviceCreateCommandBufferBuilder(apiDevice)) + .WillOnce(Return(apiCmdBufBuilder)); + + nxtCommandBuffer apiCmdBuf = api.GetNewCommandBuffer(); + EXPECT_CALL(api, CommandBufferBuilderGetResult(apiCmdBufBuilder)) + .WillOnce(Return(apiCmdBuf)); + + // Create queue + nxtQueueBuilder queueBuilder = nxtDeviceCreateQueueBuilder(device); + nxtQueue queue = nxtQueueBuilderGetResult(queueBuilder); + + nxtQueueBuilder apiQueueBuilder = api.GetNewQueueBuilder(); + EXPECT_CALL(api, DeviceCreateQueueBuilder(apiDevice)) + .WillOnce(Return(apiQueueBuilder)); + + nxtQueue apiQueue = api.GetNewQueue(); + EXPECT_CALL(api, QueueBuilderGetResult(apiQueueBuilder)) + .WillOnce(Return(apiQueue)); + + // Submit command buffer + nxtQueueSubmit(queue, 1, &cmdBuf); + + EXPECT_CALL(api, QueueSubmit(apiQueue, 1, Pointee(apiCmdBuf))); + + Flush(); +} + +// TODO +// - Test values work +// - Test multiple objects as value work +// - Object creation, then calls do nothing after error on builder +// - Object creation then error then create object, then should do nothing. diff --git a/third_party/CMakeLists.txt b/third_party/CMakeLists.txt new file mode 100644 index 0000000000..7561787ae3 --- /dev/null +++ b/third_party/CMakeLists.txt @@ -0,0 +1,73 @@ +# Copyright 2017 The NXT Authors +# +# 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. + +# GLFW, only build the library +set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE) +set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) +set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE) +set(GLFW_INSTALL OFF CACHE BOOL "" FORCE) +add_subdirectory(glfw) + +# GoogleTest +set(GTEST_DIR ${CMAKE_CURRENT_SOURCE_DIR}/googletest/googletest) +set(GMOCK_DIR ${CMAKE_CURRENT_SOURCE_DIR}/googletest/googlemock) +add_library(gtest STATIC ${GTEST_DIR}/src/gtest-all.cc ${GMOCK_DIR}/src/gmock-all.cc) +target_include_directories(gtest SYSTEM PUBLIC ${GTEST_DIR}/include ${GMOCK_DIR}/include) +target_include_directories(gtest PRIVATE ${GTEST_DIR} ${GMOCK_DIR}) +find_package(Threads) +target_link_libraries(gtest ${CMAKE_THREAD_LIBS_INIT}) + +# Glad +add_library(glad SHARED + ${CMAKE_CURRENT_SOURCE_DIR}/glad/src/glad.c + ${CMAKE_CURRENT_SOURCE_DIR}/glad/include/glad/glad.h + ${CMAKE_CURRENT_SOURCE_DIR}/glad/include/KHR/khrplatform.h +) +target_include_directories(glad PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/glad/include) + +# ShaderC +set(SHADERC_SKIP_TESTS ON) +set(SHADERC_GOOGLE_TEST_DIR ${CMAKE_CURRENT_SOURCE_DIR}/googletest CACHE STRING "Location of googletest source") +set(SHADERC_GLSLANG_DIR "${CMAKE_CURRENT_SOURCE_DIR}/glslang" CACHE STRING "Location of glslang source") +set(SHADERC_SPIRV_TOOLS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/spirv-tools CACHE STRING "Location of spirv-tools source") +# Need to include this for spirv-tools to find it +add_subdirectory(spirv-headers) +add_subdirectory(shaderc) +SetPIC(shaderc) +SetPIC(shaderc_util) + +# SPIRV-Cross +add_library(spirv-cross SHARED + ${CMAKE_CURRENT_SOURCE_DIR}/spirv-cross/GLSL.std.450.h + ${CMAKE_CURRENT_SOURCE_DIR}/spirv-cross/spirv_common.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/spirv-cross/spirv_cfg.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/spirv-cross/spirv_cfg.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/spirv-cross/spirv_cpp.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/spirv-cross/spirv_cpp.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/spirv-cross/spirv_cross.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/spirv-cross/spirv_cross.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/spirv-cross/spirv_glsl.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/spirv-cross/spirv_glsl.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/spirv-cross/spirv.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/spirv-cross/spirv_msl.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/spirv-cross/spirv_msl.hpp +) +target_include_directories(spirv-cross PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +SetCXX14(spirv-cross) + +# STB, used for stb_image +set(STB_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/stb PARENT_SCOPE) + +# glm matrix math library +set(GLM_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/glm PARENT_SCOPE) diff --git a/third_party/glad/include/KHR/khrplatform.h b/third_party/glad/include/KHR/khrplatform.h new file mode 100644 index 0000000000..07b61b9bd6 --- /dev/null +++ b/third_party/glad/include/KHR/khrplatform.h @@ -0,0 +1,285 @@ +#ifndef __khrplatform_h_ +#define __khrplatform_h_ + +/* +** Copyright (c) 2008-2009 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a +** copy of this software and/or associated documentation files (the +** "Materials"), to deal in the Materials without restriction, including +** without limitation the rights to use, copy, modify, merge, publish, +** distribute, sublicense, and/or sell copies of the Materials, and to +** permit persons to whom the Materials are furnished to do so, subject to +** the following conditions: +** +** The above copyright notice and this permission notice shall be included +** in all copies or substantial portions of the Materials. +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +*/ + +/* Khronos platform-specific types and definitions. + * + * $Revision: 32517 $ on $Date: 2016-03-11 02:41:19 -0800 (Fri, 11 Mar 2016) $ + * + * Adopters may modify this file to suit their platform. Adopters are + * encouraged to submit platform specific modifications to the Khronos + * group so that they can be included in future versions of this file. + * Please submit changes by sending them to the public Khronos Bugzilla + * (http://khronos.org/bugzilla) by filing a bug against product + * "Khronos (general)" component "Registry". + * + * A predefined template which fills in some of the bug fields can be + * reached using http://tinyurl.com/khrplatform-h-bugreport, but you + * must create a Bugzilla login first. + * + * + * See the Implementer's Guidelines for information about where this file + * should be located on your system and for more details of its use: + * http://www.khronos.org/registry/implementers_guide.pdf + * + * This file should be included as + * #include + * by Khronos client API header files that use its types and defines. + * + * The types in khrplatform.h should only be used to define API-specific types. + * + * Types defined in khrplatform.h: + * khronos_int8_t signed 8 bit + * khronos_uint8_t unsigned 8 bit + * khronos_int16_t signed 16 bit + * khronos_uint16_t unsigned 16 bit + * khronos_int32_t signed 32 bit + * khronos_uint32_t unsigned 32 bit + * khronos_int64_t signed 64 bit + * khronos_uint64_t unsigned 64 bit + * khronos_intptr_t signed same number of bits as a pointer + * khronos_uintptr_t unsigned same number of bits as a pointer + * khronos_ssize_t signed size + * khronos_usize_t unsigned size + * khronos_float_t signed 32 bit floating point + * khronos_time_ns_t unsigned 64 bit time in nanoseconds + * khronos_utime_nanoseconds_t unsigned time interval or absolute time in + * nanoseconds + * khronos_stime_nanoseconds_t signed time interval in nanoseconds + * khronos_boolean_enum_t enumerated boolean type. This should + * only be used as a base type when a client API's boolean type is + * an enum. Client APIs which use an integer or other type for + * booleans cannot use this as the base type for their boolean. + * + * Tokens defined in khrplatform.h: + * + * KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values. + * + * KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0. + * KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0. + * + * Calling convention macros defined in this file: + * KHRONOS_APICALL + * KHRONOS_APIENTRY + * KHRONOS_APIATTRIBUTES + * + * These may be used in function prototypes as: + * + * KHRONOS_APICALL void KHRONOS_APIENTRY funcname( + * int arg1, + * int arg2) KHRONOS_APIATTRIBUTES; + */ + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APICALL + *------------------------------------------------------------------------- + * This precedes the return type of the function in the function prototype. + */ +#if defined(_WIN32) && !defined(__SCITECH_SNAP__) +# define KHRONOS_APICALL __declspec(dllimport) +#elif defined (__SYMBIAN32__) +# define KHRONOS_APICALL IMPORT_C +#elif defined(__ANDROID__) +# include +# define KHRONOS_APICALL __attribute__((visibility("default"))) __NDK_FPABI__ +#else +# define KHRONOS_APICALL +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APIENTRY + *------------------------------------------------------------------------- + * This follows the return type of the function and precedes the function + * name in the function prototype. + */ +#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__) + /* Win32 but not WinCE */ +# define KHRONOS_APIENTRY __stdcall +#else +# define KHRONOS_APIENTRY +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APIATTRIBUTES + *------------------------------------------------------------------------- + * This follows the closing parenthesis of the function prototype arguments. + */ +#if defined (__ARMCC_2__) +#define KHRONOS_APIATTRIBUTES __softfp +#else +#define KHRONOS_APIATTRIBUTES +#endif + +/*------------------------------------------------------------------------- + * basic type definitions + *-----------------------------------------------------------------------*/ +#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__) + + +/* + * Using + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(__VMS ) || defined(__sgi) + +/* + * Using + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(_WIN32) && !defined(__SCITECH_SNAP__) + +/* + * Win32 + */ +typedef __int32 khronos_int32_t; +typedef unsigned __int32 khronos_uint32_t; +typedef __int64 khronos_int64_t; +typedef unsigned __int64 khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(__sun__) || defined(__digital__) + +/* + * Sun or Digital + */ +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#if defined(__arch64__) || defined(_LP64) +typedef long int khronos_int64_t; +typedef unsigned long int khronos_uint64_t; +#else +typedef long long int khronos_int64_t; +typedef unsigned long long int khronos_uint64_t; +#endif /* __arch64__ */ +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif 0 + +/* + * Hypothetical platform with no float or int64 support + */ +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#define KHRONOS_SUPPORT_INT64 0 +#define KHRONOS_SUPPORT_FLOAT 0 + +#else + +/* + * Generic fallback + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#endif + + +/* + * Types that are (so far) the same on all platforms + */ +typedef signed char khronos_int8_t; +typedef unsigned char khronos_uint8_t; +typedef signed short int khronos_int16_t; +typedef unsigned short int khronos_uint16_t; + +/* + * Types that differ between LLP64 and LP64 architectures - in LLP64, + * pointers are 64 bits, but 'long' is still 32 bits. Win64 appears + * to be the only LLP64 architecture in current use. + */ +#ifdef _WIN64 +typedef signed long long int khronos_intptr_t; +typedef unsigned long long int khronos_uintptr_t; +typedef signed long long int khronos_ssize_t; +typedef unsigned long long int khronos_usize_t; +#else +typedef signed long int khronos_intptr_t; +typedef unsigned long int khronos_uintptr_t; +typedef signed long int khronos_ssize_t; +typedef unsigned long int khronos_usize_t; +#endif + +#if KHRONOS_SUPPORT_FLOAT +/* + * Float type + */ +typedef float khronos_float_t; +#endif + +#if KHRONOS_SUPPORT_INT64 +/* Time types + * + * These types can be used to represent a time interval in nanoseconds or + * an absolute Unadjusted System Time. Unadjusted System Time is the number + * of nanoseconds since some arbitrary system event (e.g. since the last + * time the system booted). The Unadjusted System Time is an unsigned + * 64 bit value that wraps back to 0 every 584 years. Time intervals + * may be either signed or unsigned. + */ +typedef khronos_uint64_t khronos_utime_nanoseconds_t; +typedef khronos_int64_t khronos_stime_nanoseconds_t; +#endif + +/* + * Dummy value used to pad enum types to 32 bits. + */ +#ifndef KHRONOS_MAX_ENUM +#define KHRONOS_MAX_ENUM 0x7FFFFFFF +#endif + +/* + * Enumerated boolean type + * + * Values other than zero should be considered to be true. Therefore + * comparisons should not be made against KHRONOS_TRUE. + */ +typedef enum { + KHRONOS_FALSE = 0, + KHRONOS_TRUE = 1, + KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM +} khronos_boolean_enum_t; + +#endif /* __khrplatform_h_ */ diff --git a/third_party/glad/include/glad/glad.h b/third_party/glad/include/glad/glad.h new file mode 100644 index 0000000000..26695017d3 --- /dev/null +++ b/third_party/glad/include/glad/glad.h @@ -0,0 +1,3670 @@ +/* + + OpenGL loader generated by glad 0.1.12a0 on Tue Aug 16 10:59:45 2016. + + Language/Generator: C/C++ + Specification: gl + APIs: gl=4.5 + Profile: core + Extensions: + + Loader: True + Local files: False + Omit khrplatform: False + + Commandline: + --profile="core" --api="gl=4.5" --generator="c" --spec="gl" --extensions="" + Online: + http://glad.dav1d.de/#profile=core&language=c&specification=gl&loader=on&api=gl%3D4.5 +*/ + + +#ifndef __glad_h_ +#define __glad_h_ + +#ifdef __gl_h_ +#error OpenGL header already included, remove this include, glad already provides it +#endif +#define __gl_h_ + +#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN 1 +#endif +#include +#endif + +#ifndef APIENTRY +#define APIENTRY +#endif +#ifndef APIENTRYP +#define APIENTRYP APIENTRY * +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +struct gladGLversionStruct { + int major; + int minor; +}; + +typedef void* (* GLADloadproc)(const char *name); + +#ifndef GLAPI +# if defined(GLAD_GLAPI_EXPORT) +# if defined(WIN32) || defined(__CYGWIN__) +# if defined(GLAD_GLAPI_EXPORT_BUILD) +# if defined(__GNUC__) +# define GLAPI __attribute__ ((dllexport)) extern +# else +# define GLAPI __declspec(dllexport) extern +# endif +# else +# if defined(__GNUC__) +# define GLAPI __attribute__ ((dllimport)) extern +# else +# define GLAPI __declspec(dllimport) extern +# endif +# endif +# elif defined(__GNUC__) && defined(GLAD_GLAPI_EXPORT_BUILD) +# define GLAPI __attribute__ ((visibility ("default"))) extern +# else +# define GLAPI extern +# endif +# else +# define GLAPI extern +# endif +#endif + +GLAPI struct gladGLversionStruct GLVersion; + +GLAPI int gladLoadGL(void); + +GLAPI int gladLoadGLLoader(GLADloadproc); + +#include +#include +#ifndef GLEXT_64_TYPES_DEFINED +/* This code block is duplicated in glxext.h, so must be protected */ +#define GLEXT_64_TYPES_DEFINED +/* Define int32_t, int64_t, and uint64_t types for UST/MSC */ +/* (as used in the GL_EXT_timer_query extension). */ +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L +#include +#elif defined(__sun__) || defined(__digital__) +#include +#if defined(__STDC__) +#if defined(__arch64__) || defined(_LP64) +typedef long int int64_t; +typedef unsigned long int uint64_t; +#else +typedef long long int int64_t; +typedef unsigned long long int uint64_t; +#endif /* __arch64__ */ +#endif /* __STDC__ */ +#elif defined( __VMS ) || defined(__sgi) +#include +#elif defined(__SCO__) || defined(__USLC__) +#include +#elif defined(__UNIXOS2__) || defined(__SOL64__) +typedef long int int32_t; +typedef long long int int64_t; +typedef unsigned long long int uint64_t; +#elif defined(_WIN32) && defined(__GNUC__) +#include +#elif defined(_WIN32) +typedef __int32 int32_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +#else +/* Fallback if nothing above works */ +#include +#endif +#endif +typedef unsigned int GLenum; +typedef unsigned char GLboolean; +typedef unsigned int GLbitfield; +typedef void GLvoid; +typedef signed char GLbyte; +typedef short GLshort; +typedef int GLint; +typedef int GLclampx; +typedef unsigned char GLubyte; +typedef unsigned short GLushort; +typedef unsigned int GLuint; +typedef int GLsizei; +typedef float GLfloat; +typedef float GLclampf; +typedef double GLdouble; +typedef double GLclampd; +typedef void *GLeglImageOES; +typedef char GLchar; +typedef char GLcharARB; +#ifdef __APPLE__ +typedef void *GLhandleARB; +#else +typedef unsigned int GLhandleARB; +#endif +typedef unsigned short GLhalfARB; +typedef unsigned short GLhalf; +typedef GLint GLfixed; +typedef ptrdiff_t GLintptr; +typedef ptrdiff_t GLsizeiptr; +typedef int64_t GLint64; +typedef uint64_t GLuint64; +typedef ptrdiff_t GLintptrARB; +typedef ptrdiff_t GLsizeiptrARB; +typedef int64_t GLint64EXT; +typedef uint64_t GLuint64EXT; +typedef struct __GLsync *GLsync; +struct _cl_context; +struct _cl_event; +typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +typedef void (APIENTRY *GLDEBUGPROCKHR)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +typedef void (APIENTRY *GLDEBUGPROCAMD)(GLuint id,GLenum category,GLenum severity,GLsizei length,const GLchar *message,void *userParam); +typedef unsigned short GLhalfNV; +typedef GLintptr GLvdpauSurfaceNV; +#define GL_DEPTH_BUFFER_BIT 0x00000100 +#define GL_STENCIL_BUFFER_BIT 0x00000400 +#define GL_COLOR_BUFFER_BIT 0x00004000 +#define GL_FALSE 0 +#define GL_TRUE 1 +#define GL_POINTS 0x0000 +#define GL_LINES 0x0001 +#define GL_LINE_LOOP 0x0002 +#define GL_LINE_STRIP 0x0003 +#define GL_TRIANGLES 0x0004 +#define GL_TRIANGLE_STRIP 0x0005 +#define GL_TRIANGLE_FAN 0x0006 +#define GL_NEVER 0x0200 +#define GL_LESS 0x0201 +#define GL_EQUAL 0x0202 +#define GL_LEQUAL 0x0203 +#define GL_GREATER 0x0204 +#define GL_NOTEQUAL 0x0205 +#define GL_GEQUAL 0x0206 +#define GL_ALWAYS 0x0207 +#define GL_ZERO 0 +#define GL_ONE 1 +#define GL_SRC_COLOR 0x0300 +#define GL_ONE_MINUS_SRC_COLOR 0x0301 +#define GL_SRC_ALPHA 0x0302 +#define GL_ONE_MINUS_SRC_ALPHA 0x0303 +#define GL_DST_ALPHA 0x0304 +#define GL_ONE_MINUS_DST_ALPHA 0x0305 +#define GL_DST_COLOR 0x0306 +#define GL_ONE_MINUS_DST_COLOR 0x0307 +#define GL_SRC_ALPHA_SATURATE 0x0308 +#define GL_NONE 0 +#define GL_FRONT_LEFT 0x0400 +#define GL_FRONT_RIGHT 0x0401 +#define GL_BACK_LEFT 0x0402 +#define GL_BACK_RIGHT 0x0403 +#define GL_FRONT 0x0404 +#define GL_BACK 0x0405 +#define GL_LEFT 0x0406 +#define GL_RIGHT 0x0407 +#define GL_FRONT_AND_BACK 0x0408 +#define GL_NO_ERROR 0 +#define GL_INVALID_ENUM 0x0500 +#define GL_INVALID_VALUE 0x0501 +#define GL_INVALID_OPERATION 0x0502 +#define GL_OUT_OF_MEMORY 0x0505 +#define GL_CW 0x0900 +#define GL_CCW 0x0901 +#define GL_POINT_SIZE 0x0B11 +#define GL_POINT_SIZE_RANGE 0x0B12 +#define GL_POINT_SIZE_GRANULARITY 0x0B13 +#define GL_LINE_SMOOTH 0x0B20 +#define GL_LINE_WIDTH 0x0B21 +#define GL_LINE_WIDTH_RANGE 0x0B22 +#define GL_LINE_WIDTH_GRANULARITY 0x0B23 +#define GL_POLYGON_MODE 0x0B40 +#define GL_POLYGON_SMOOTH 0x0B41 +#define GL_CULL_FACE 0x0B44 +#define GL_CULL_FACE_MODE 0x0B45 +#define GL_FRONT_FACE 0x0B46 +#define GL_DEPTH_RANGE 0x0B70 +#define GL_DEPTH_TEST 0x0B71 +#define GL_DEPTH_WRITEMASK 0x0B72 +#define GL_DEPTH_CLEAR_VALUE 0x0B73 +#define GL_DEPTH_FUNC 0x0B74 +#define GL_STENCIL_TEST 0x0B90 +#define GL_STENCIL_CLEAR_VALUE 0x0B91 +#define GL_STENCIL_FUNC 0x0B92 +#define GL_STENCIL_VALUE_MASK 0x0B93 +#define GL_STENCIL_FAIL 0x0B94 +#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 +#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 +#define GL_STENCIL_REF 0x0B97 +#define GL_STENCIL_WRITEMASK 0x0B98 +#define GL_VIEWPORT 0x0BA2 +#define GL_DITHER 0x0BD0 +#define GL_BLEND_DST 0x0BE0 +#define GL_BLEND_SRC 0x0BE1 +#define GL_BLEND 0x0BE2 +#define GL_LOGIC_OP_MODE 0x0BF0 +#define GL_COLOR_LOGIC_OP 0x0BF2 +#define GL_DRAW_BUFFER 0x0C01 +#define GL_READ_BUFFER 0x0C02 +#define GL_SCISSOR_BOX 0x0C10 +#define GL_SCISSOR_TEST 0x0C11 +#define GL_COLOR_CLEAR_VALUE 0x0C22 +#define GL_COLOR_WRITEMASK 0x0C23 +#define GL_DOUBLEBUFFER 0x0C32 +#define GL_STEREO 0x0C33 +#define GL_LINE_SMOOTH_HINT 0x0C52 +#define GL_POLYGON_SMOOTH_HINT 0x0C53 +#define GL_UNPACK_SWAP_BYTES 0x0CF0 +#define GL_UNPACK_LSB_FIRST 0x0CF1 +#define GL_UNPACK_ROW_LENGTH 0x0CF2 +#define GL_UNPACK_SKIP_ROWS 0x0CF3 +#define GL_UNPACK_SKIP_PIXELS 0x0CF4 +#define GL_UNPACK_ALIGNMENT 0x0CF5 +#define GL_PACK_SWAP_BYTES 0x0D00 +#define GL_PACK_LSB_FIRST 0x0D01 +#define GL_PACK_ROW_LENGTH 0x0D02 +#define GL_PACK_SKIP_ROWS 0x0D03 +#define GL_PACK_SKIP_PIXELS 0x0D04 +#define GL_PACK_ALIGNMENT 0x0D05 +#define GL_MAX_TEXTURE_SIZE 0x0D33 +#define GL_MAX_VIEWPORT_DIMS 0x0D3A +#define GL_SUBPIXEL_BITS 0x0D50 +#define GL_TEXTURE_1D 0x0DE0 +#define GL_TEXTURE_2D 0x0DE1 +#define GL_POLYGON_OFFSET_UNITS 0x2A00 +#define GL_POLYGON_OFFSET_POINT 0x2A01 +#define GL_POLYGON_OFFSET_LINE 0x2A02 +#define GL_POLYGON_OFFSET_FILL 0x8037 +#define GL_POLYGON_OFFSET_FACTOR 0x8038 +#define GL_TEXTURE_BINDING_1D 0x8068 +#define GL_TEXTURE_BINDING_2D 0x8069 +#define GL_TEXTURE_WIDTH 0x1000 +#define GL_TEXTURE_HEIGHT 0x1001 +#define GL_TEXTURE_INTERNAL_FORMAT 0x1003 +#define GL_TEXTURE_BORDER_COLOR 0x1004 +#define GL_TEXTURE_RED_SIZE 0x805C +#define GL_TEXTURE_GREEN_SIZE 0x805D +#define GL_TEXTURE_BLUE_SIZE 0x805E +#define GL_TEXTURE_ALPHA_SIZE 0x805F +#define GL_DONT_CARE 0x1100 +#define GL_FASTEST 0x1101 +#define GL_NICEST 0x1102 +#define GL_BYTE 0x1400 +#define GL_UNSIGNED_BYTE 0x1401 +#define GL_SHORT 0x1402 +#define GL_UNSIGNED_SHORT 0x1403 +#define GL_INT 0x1404 +#define GL_UNSIGNED_INT 0x1405 +#define GL_FLOAT 0x1406 +#define GL_DOUBLE 0x140A +#define GL_CLEAR 0x1500 +#define GL_AND 0x1501 +#define GL_AND_REVERSE 0x1502 +#define GL_COPY 0x1503 +#define GL_AND_INVERTED 0x1504 +#define GL_NOOP 0x1505 +#define GL_XOR 0x1506 +#define GL_OR 0x1507 +#define GL_NOR 0x1508 +#define GL_EQUIV 0x1509 +#define GL_INVERT 0x150A +#define GL_OR_REVERSE 0x150B +#define GL_COPY_INVERTED 0x150C +#define GL_OR_INVERTED 0x150D +#define GL_NAND 0x150E +#define GL_SET 0x150F +#define GL_TEXTURE 0x1702 +#define GL_COLOR 0x1800 +#define GL_DEPTH 0x1801 +#define GL_STENCIL 0x1802 +#define GL_STENCIL_INDEX 0x1901 +#define GL_DEPTH_COMPONENT 0x1902 +#define GL_RED 0x1903 +#define GL_GREEN 0x1904 +#define GL_BLUE 0x1905 +#define GL_ALPHA 0x1906 +#define GL_RGB 0x1907 +#define GL_RGBA 0x1908 +#define GL_POINT 0x1B00 +#define GL_LINE 0x1B01 +#define GL_FILL 0x1B02 +#define GL_KEEP 0x1E00 +#define GL_REPLACE 0x1E01 +#define GL_INCR 0x1E02 +#define GL_DECR 0x1E03 +#define GL_VENDOR 0x1F00 +#define GL_RENDERER 0x1F01 +#define GL_VERSION 0x1F02 +#define GL_EXTENSIONS 0x1F03 +#define GL_NEAREST 0x2600 +#define GL_LINEAR 0x2601 +#define GL_NEAREST_MIPMAP_NEAREST 0x2700 +#define GL_LINEAR_MIPMAP_NEAREST 0x2701 +#define GL_NEAREST_MIPMAP_LINEAR 0x2702 +#define GL_LINEAR_MIPMAP_LINEAR 0x2703 +#define GL_TEXTURE_MAG_FILTER 0x2800 +#define GL_TEXTURE_MIN_FILTER 0x2801 +#define GL_TEXTURE_WRAP_S 0x2802 +#define GL_TEXTURE_WRAP_T 0x2803 +#define GL_PROXY_TEXTURE_1D 0x8063 +#define GL_PROXY_TEXTURE_2D 0x8064 +#define GL_REPEAT 0x2901 +#define GL_R3_G3_B2 0x2A10 +#define GL_RGB4 0x804F +#define GL_RGB5 0x8050 +#define GL_RGB8 0x8051 +#define GL_RGB10 0x8052 +#define GL_RGB12 0x8053 +#define GL_RGB16 0x8054 +#define GL_RGBA2 0x8055 +#define GL_RGBA4 0x8056 +#define GL_RGB5_A1 0x8057 +#define GL_RGBA8 0x8058 +#define GL_RGB10_A2 0x8059 +#define GL_RGBA12 0x805A +#define GL_RGBA16 0x805B +#define GL_UNSIGNED_BYTE_3_3_2 0x8032 +#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 +#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 +#define GL_UNSIGNED_INT_8_8_8_8 0x8035 +#define GL_UNSIGNED_INT_10_10_10_2 0x8036 +#define GL_TEXTURE_BINDING_3D 0x806A +#define GL_PACK_SKIP_IMAGES 0x806B +#define GL_PACK_IMAGE_HEIGHT 0x806C +#define GL_UNPACK_SKIP_IMAGES 0x806D +#define GL_UNPACK_IMAGE_HEIGHT 0x806E +#define GL_TEXTURE_3D 0x806F +#define GL_PROXY_TEXTURE_3D 0x8070 +#define GL_TEXTURE_DEPTH 0x8071 +#define GL_TEXTURE_WRAP_R 0x8072 +#define GL_MAX_3D_TEXTURE_SIZE 0x8073 +#define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 +#define GL_UNSIGNED_SHORT_5_6_5 0x8363 +#define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 +#define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 +#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 +#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 +#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 +#define GL_BGR 0x80E0 +#define GL_BGRA 0x80E1 +#define GL_MAX_ELEMENTS_VERTICES 0x80E8 +#define GL_MAX_ELEMENTS_INDICES 0x80E9 +#define GL_CLAMP_TO_EDGE 0x812F +#define GL_TEXTURE_MIN_LOD 0x813A +#define GL_TEXTURE_MAX_LOD 0x813B +#define GL_TEXTURE_BASE_LEVEL 0x813C +#define GL_TEXTURE_MAX_LEVEL 0x813D +#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 +#define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 +#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 +#define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 +#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E +#define GL_TEXTURE0 0x84C0 +#define GL_TEXTURE1 0x84C1 +#define GL_TEXTURE2 0x84C2 +#define GL_TEXTURE3 0x84C3 +#define GL_TEXTURE4 0x84C4 +#define GL_TEXTURE5 0x84C5 +#define GL_TEXTURE6 0x84C6 +#define GL_TEXTURE7 0x84C7 +#define GL_TEXTURE8 0x84C8 +#define GL_TEXTURE9 0x84C9 +#define GL_TEXTURE10 0x84CA +#define GL_TEXTURE11 0x84CB +#define GL_TEXTURE12 0x84CC +#define GL_TEXTURE13 0x84CD +#define GL_TEXTURE14 0x84CE +#define GL_TEXTURE15 0x84CF +#define GL_TEXTURE16 0x84D0 +#define GL_TEXTURE17 0x84D1 +#define GL_TEXTURE18 0x84D2 +#define GL_TEXTURE19 0x84D3 +#define GL_TEXTURE20 0x84D4 +#define GL_TEXTURE21 0x84D5 +#define GL_TEXTURE22 0x84D6 +#define GL_TEXTURE23 0x84D7 +#define GL_TEXTURE24 0x84D8 +#define GL_TEXTURE25 0x84D9 +#define GL_TEXTURE26 0x84DA +#define GL_TEXTURE27 0x84DB +#define GL_TEXTURE28 0x84DC +#define GL_TEXTURE29 0x84DD +#define GL_TEXTURE30 0x84DE +#define GL_TEXTURE31 0x84DF +#define GL_ACTIVE_TEXTURE 0x84E0 +#define GL_MULTISAMPLE 0x809D +#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE 0x809F +#define GL_SAMPLE_COVERAGE 0x80A0 +#define GL_SAMPLE_BUFFERS 0x80A8 +#define GL_SAMPLES 0x80A9 +#define GL_SAMPLE_COVERAGE_VALUE 0x80AA +#define GL_SAMPLE_COVERAGE_INVERT 0x80AB +#define GL_TEXTURE_CUBE_MAP 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A +#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C +#define GL_COMPRESSED_RGB 0x84ED +#define GL_COMPRESSED_RGBA 0x84EE +#define GL_TEXTURE_COMPRESSION_HINT 0x84EF +#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 +#define GL_TEXTURE_COMPRESSED 0x86A1 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 +#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 +#define GL_CLAMP_TO_BORDER 0x812D +#define GL_BLEND_DST_RGB 0x80C8 +#define GL_BLEND_SRC_RGB 0x80C9 +#define GL_BLEND_DST_ALPHA 0x80CA +#define GL_BLEND_SRC_ALPHA 0x80CB +#define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 +#define GL_DEPTH_COMPONENT16 0x81A5 +#define GL_DEPTH_COMPONENT24 0x81A6 +#define GL_DEPTH_COMPONENT32 0x81A7 +#define GL_MIRRORED_REPEAT 0x8370 +#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD +#define GL_TEXTURE_LOD_BIAS 0x8501 +#define GL_INCR_WRAP 0x8507 +#define GL_DECR_WRAP 0x8508 +#define GL_TEXTURE_DEPTH_SIZE 0x884A +#define GL_TEXTURE_COMPARE_MODE 0x884C +#define GL_TEXTURE_COMPARE_FUNC 0x884D +#define GL_FUNC_ADD 0x8006 +#define GL_FUNC_SUBTRACT 0x800A +#define GL_FUNC_REVERSE_SUBTRACT 0x800B +#define GL_MIN 0x8007 +#define GL_MAX 0x8008 +#define GL_CONSTANT_COLOR 0x8001 +#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 +#define GL_CONSTANT_ALPHA 0x8003 +#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 +#define GL_BUFFER_SIZE 0x8764 +#define GL_BUFFER_USAGE 0x8765 +#define GL_QUERY_COUNTER_BITS 0x8864 +#define GL_CURRENT_QUERY 0x8865 +#define GL_QUERY_RESULT 0x8866 +#define GL_QUERY_RESULT_AVAILABLE 0x8867 +#define GL_ARRAY_BUFFER 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 +#define GL_ARRAY_BUFFER_BINDING 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 +#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F +#define GL_READ_ONLY 0x88B8 +#define GL_WRITE_ONLY 0x88B9 +#define GL_READ_WRITE 0x88BA +#define GL_BUFFER_ACCESS 0x88BB +#define GL_BUFFER_MAPPED 0x88BC +#define GL_BUFFER_MAP_POINTER 0x88BD +#define GL_STREAM_DRAW 0x88E0 +#define GL_STREAM_READ 0x88E1 +#define GL_STREAM_COPY 0x88E2 +#define GL_STATIC_DRAW 0x88E4 +#define GL_STATIC_READ 0x88E5 +#define GL_STATIC_COPY 0x88E6 +#define GL_DYNAMIC_DRAW 0x88E8 +#define GL_DYNAMIC_READ 0x88E9 +#define GL_DYNAMIC_COPY 0x88EA +#define GL_SAMPLES_PASSED 0x8914 +#define GL_SRC1_ALPHA 0x8589 +#define GL_BLEND_EQUATION_RGB 0x8009 +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 +#define GL_CURRENT_VERTEX_ATTRIB 0x8626 +#define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642 +#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 +#define GL_STENCIL_BACK_FUNC 0x8800 +#define GL_STENCIL_BACK_FAIL 0x8801 +#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 +#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 +#define GL_MAX_DRAW_BUFFERS 0x8824 +#define GL_DRAW_BUFFER0 0x8825 +#define GL_DRAW_BUFFER1 0x8826 +#define GL_DRAW_BUFFER2 0x8827 +#define GL_DRAW_BUFFER3 0x8828 +#define GL_DRAW_BUFFER4 0x8829 +#define GL_DRAW_BUFFER5 0x882A +#define GL_DRAW_BUFFER6 0x882B +#define GL_DRAW_BUFFER7 0x882C +#define GL_DRAW_BUFFER8 0x882D +#define GL_DRAW_BUFFER9 0x882E +#define GL_DRAW_BUFFER10 0x882F +#define GL_DRAW_BUFFER11 0x8830 +#define GL_DRAW_BUFFER12 0x8831 +#define GL_DRAW_BUFFER13 0x8832 +#define GL_DRAW_BUFFER14 0x8833 +#define GL_DRAW_BUFFER15 0x8834 +#define GL_BLEND_EQUATION_ALPHA 0x883D +#define GL_MAX_VERTEX_ATTRIBS 0x8869 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A +#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 +#define GL_FRAGMENT_SHADER 0x8B30 +#define GL_VERTEX_SHADER 0x8B31 +#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 +#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A +#define GL_MAX_VARYING_FLOATS 0x8B4B +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C +#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D +#define GL_SHADER_TYPE 0x8B4F +#define GL_FLOAT_VEC2 0x8B50 +#define GL_FLOAT_VEC3 0x8B51 +#define GL_FLOAT_VEC4 0x8B52 +#define GL_INT_VEC2 0x8B53 +#define GL_INT_VEC3 0x8B54 +#define GL_INT_VEC4 0x8B55 +#define GL_BOOL 0x8B56 +#define GL_BOOL_VEC2 0x8B57 +#define GL_BOOL_VEC3 0x8B58 +#define GL_BOOL_VEC4 0x8B59 +#define GL_FLOAT_MAT2 0x8B5A +#define GL_FLOAT_MAT3 0x8B5B +#define GL_FLOAT_MAT4 0x8B5C +#define GL_SAMPLER_1D 0x8B5D +#define GL_SAMPLER_2D 0x8B5E +#define GL_SAMPLER_3D 0x8B5F +#define GL_SAMPLER_CUBE 0x8B60 +#define GL_SAMPLER_1D_SHADOW 0x8B61 +#define GL_SAMPLER_2D_SHADOW 0x8B62 +#define GL_DELETE_STATUS 0x8B80 +#define GL_COMPILE_STATUS 0x8B81 +#define GL_LINK_STATUS 0x8B82 +#define GL_VALIDATE_STATUS 0x8B83 +#define GL_INFO_LOG_LENGTH 0x8B84 +#define GL_ATTACHED_SHADERS 0x8B85 +#define GL_ACTIVE_UNIFORMS 0x8B86 +#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 +#define GL_SHADER_SOURCE_LENGTH 0x8B88 +#define GL_ACTIVE_ATTRIBUTES 0x8B89 +#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B +#define GL_SHADING_LANGUAGE_VERSION 0x8B8C +#define GL_CURRENT_PROGRAM 0x8B8D +#define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0 +#define GL_LOWER_LEFT 0x8CA1 +#define GL_UPPER_LEFT 0x8CA2 +#define GL_STENCIL_BACK_REF 0x8CA3 +#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 +#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 +#define GL_PIXEL_PACK_BUFFER 0x88EB +#define GL_PIXEL_UNPACK_BUFFER 0x88EC +#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED +#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF +#define GL_FLOAT_MAT2x3 0x8B65 +#define GL_FLOAT_MAT2x4 0x8B66 +#define GL_FLOAT_MAT3x2 0x8B67 +#define GL_FLOAT_MAT3x4 0x8B68 +#define GL_FLOAT_MAT4x2 0x8B69 +#define GL_FLOAT_MAT4x3 0x8B6A +#define GL_SRGB 0x8C40 +#define GL_SRGB8 0x8C41 +#define GL_SRGB_ALPHA 0x8C42 +#define GL_SRGB8_ALPHA8 0x8C43 +#define GL_COMPRESSED_SRGB 0x8C48 +#define GL_COMPRESSED_SRGB_ALPHA 0x8C49 +#define GL_COMPARE_REF_TO_TEXTURE 0x884E +#define GL_CLIP_DISTANCE0 0x3000 +#define GL_CLIP_DISTANCE1 0x3001 +#define GL_CLIP_DISTANCE2 0x3002 +#define GL_CLIP_DISTANCE3 0x3003 +#define GL_CLIP_DISTANCE4 0x3004 +#define GL_CLIP_DISTANCE5 0x3005 +#define GL_CLIP_DISTANCE6 0x3006 +#define GL_CLIP_DISTANCE7 0x3007 +#define GL_MAX_CLIP_DISTANCES 0x0D32 +#define GL_MAJOR_VERSION 0x821B +#define GL_MINOR_VERSION 0x821C +#define GL_NUM_EXTENSIONS 0x821D +#define GL_CONTEXT_FLAGS 0x821E +#define GL_COMPRESSED_RED 0x8225 +#define GL_COMPRESSED_RG 0x8226 +#define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x00000001 +#define GL_RGBA32F 0x8814 +#define GL_RGB32F 0x8815 +#define GL_RGBA16F 0x881A +#define GL_RGB16F 0x881B +#define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD +#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF +#define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 +#define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 +#define GL_CLAMP_READ_COLOR 0x891C +#define GL_FIXED_ONLY 0x891D +#define GL_MAX_VARYING_COMPONENTS 0x8B4B +#define GL_TEXTURE_1D_ARRAY 0x8C18 +#define GL_PROXY_TEXTURE_1D_ARRAY 0x8C19 +#define GL_TEXTURE_2D_ARRAY 0x8C1A +#define GL_PROXY_TEXTURE_2D_ARRAY 0x8C1B +#define GL_TEXTURE_BINDING_1D_ARRAY 0x8C1C +#define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D +#define GL_R11F_G11F_B10F 0x8C3A +#define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B +#define GL_RGB9_E5 0x8C3D +#define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E +#define GL_TEXTURE_SHARED_SIZE 0x8C3F +#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 +#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 +#define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 +#define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 +#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 +#define GL_PRIMITIVES_GENERATED 0x8C87 +#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 +#define GL_RASTERIZER_DISCARD 0x8C89 +#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B +#define GL_INTERLEAVED_ATTRIBS 0x8C8C +#define GL_SEPARATE_ATTRIBS 0x8C8D +#define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E +#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F +#define GL_RGBA32UI 0x8D70 +#define GL_RGB32UI 0x8D71 +#define GL_RGBA16UI 0x8D76 +#define GL_RGB16UI 0x8D77 +#define GL_RGBA8UI 0x8D7C +#define GL_RGB8UI 0x8D7D +#define GL_RGBA32I 0x8D82 +#define GL_RGB32I 0x8D83 +#define GL_RGBA16I 0x8D88 +#define GL_RGB16I 0x8D89 +#define GL_RGBA8I 0x8D8E +#define GL_RGB8I 0x8D8F +#define GL_RED_INTEGER 0x8D94 +#define GL_GREEN_INTEGER 0x8D95 +#define GL_BLUE_INTEGER 0x8D96 +#define GL_RGB_INTEGER 0x8D98 +#define GL_RGBA_INTEGER 0x8D99 +#define GL_BGR_INTEGER 0x8D9A +#define GL_BGRA_INTEGER 0x8D9B +#define GL_SAMPLER_1D_ARRAY 0x8DC0 +#define GL_SAMPLER_2D_ARRAY 0x8DC1 +#define GL_SAMPLER_1D_ARRAY_SHADOW 0x8DC3 +#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 +#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 +#define GL_UNSIGNED_INT_VEC2 0x8DC6 +#define GL_UNSIGNED_INT_VEC3 0x8DC7 +#define GL_UNSIGNED_INT_VEC4 0x8DC8 +#define GL_INT_SAMPLER_1D 0x8DC9 +#define GL_INT_SAMPLER_2D 0x8DCA +#define GL_INT_SAMPLER_3D 0x8DCB +#define GL_INT_SAMPLER_CUBE 0x8DCC +#define GL_INT_SAMPLER_1D_ARRAY 0x8DCE +#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF +#define GL_UNSIGNED_INT_SAMPLER_1D 0x8DD1 +#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 +#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 +#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 +#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY 0x8DD6 +#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 +#define GL_QUERY_WAIT 0x8E13 +#define GL_QUERY_NO_WAIT 0x8E14 +#define GL_QUERY_BY_REGION_WAIT 0x8E15 +#define GL_QUERY_BY_REGION_NO_WAIT 0x8E16 +#define GL_BUFFER_ACCESS_FLAGS 0x911F +#define GL_BUFFER_MAP_LENGTH 0x9120 +#define GL_BUFFER_MAP_OFFSET 0x9121 +#define GL_DEPTH_COMPONENT32F 0x8CAC +#define GL_DEPTH32F_STENCIL8 0x8CAD +#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD +#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 +#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 +#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 +#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 +#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 +#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 +#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 +#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 +#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 +#define GL_FRAMEBUFFER_DEFAULT 0x8218 +#define GL_FRAMEBUFFER_UNDEFINED 0x8219 +#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A +#define GL_MAX_RENDERBUFFER_SIZE 0x84E8 +#define GL_DEPTH_STENCIL 0x84F9 +#define GL_UNSIGNED_INT_24_8 0x84FA +#define GL_DEPTH24_STENCIL8 0x88F0 +#define GL_TEXTURE_STENCIL_SIZE 0x88F1 +#define GL_TEXTURE_RED_TYPE 0x8C10 +#define GL_TEXTURE_GREEN_TYPE 0x8C11 +#define GL_TEXTURE_BLUE_TYPE 0x8C12 +#define GL_TEXTURE_ALPHA_TYPE 0x8C13 +#define GL_TEXTURE_DEPTH_TYPE 0x8C16 +#define GL_UNSIGNED_NORMALIZED 0x8C17 +#define GL_FRAMEBUFFER_BINDING 0x8CA6 +#define GL_DRAW_FRAMEBUFFER_BINDING 0x8CA6 +#define GL_RENDERBUFFER_BINDING 0x8CA7 +#define GL_READ_FRAMEBUFFER 0x8CA8 +#define GL_DRAW_FRAMEBUFFER 0x8CA9 +#define GL_READ_FRAMEBUFFER_BINDING 0x8CAA +#define GL_RENDERBUFFER_SAMPLES 0x8CAB +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 +#define GL_FRAMEBUFFER_COMPLETE 0x8CD5 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER 0x8CDB +#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER 0x8CDC +#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD +#define GL_MAX_COLOR_ATTACHMENTS 0x8CDF +#define GL_COLOR_ATTACHMENT0 0x8CE0 +#define GL_COLOR_ATTACHMENT1 0x8CE1 +#define GL_COLOR_ATTACHMENT2 0x8CE2 +#define GL_COLOR_ATTACHMENT3 0x8CE3 +#define GL_COLOR_ATTACHMENT4 0x8CE4 +#define GL_COLOR_ATTACHMENT5 0x8CE5 +#define GL_COLOR_ATTACHMENT6 0x8CE6 +#define GL_COLOR_ATTACHMENT7 0x8CE7 +#define GL_COLOR_ATTACHMENT8 0x8CE8 +#define GL_COLOR_ATTACHMENT9 0x8CE9 +#define GL_COLOR_ATTACHMENT10 0x8CEA +#define GL_COLOR_ATTACHMENT11 0x8CEB +#define GL_COLOR_ATTACHMENT12 0x8CEC +#define GL_COLOR_ATTACHMENT13 0x8CED +#define GL_COLOR_ATTACHMENT14 0x8CEE +#define GL_COLOR_ATTACHMENT15 0x8CEF +#define GL_COLOR_ATTACHMENT16 0x8CF0 +#define GL_COLOR_ATTACHMENT17 0x8CF1 +#define GL_COLOR_ATTACHMENT18 0x8CF2 +#define GL_COLOR_ATTACHMENT19 0x8CF3 +#define GL_COLOR_ATTACHMENT20 0x8CF4 +#define GL_COLOR_ATTACHMENT21 0x8CF5 +#define GL_COLOR_ATTACHMENT22 0x8CF6 +#define GL_COLOR_ATTACHMENT23 0x8CF7 +#define GL_COLOR_ATTACHMENT24 0x8CF8 +#define GL_COLOR_ATTACHMENT25 0x8CF9 +#define GL_COLOR_ATTACHMENT26 0x8CFA +#define GL_COLOR_ATTACHMENT27 0x8CFB +#define GL_COLOR_ATTACHMENT28 0x8CFC +#define GL_COLOR_ATTACHMENT29 0x8CFD +#define GL_COLOR_ATTACHMENT30 0x8CFE +#define GL_COLOR_ATTACHMENT31 0x8CFF +#define GL_DEPTH_ATTACHMENT 0x8D00 +#define GL_STENCIL_ATTACHMENT 0x8D20 +#define GL_FRAMEBUFFER 0x8D40 +#define GL_RENDERBUFFER 0x8D41 +#define GL_RENDERBUFFER_WIDTH 0x8D42 +#define GL_RENDERBUFFER_HEIGHT 0x8D43 +#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 +#define GL_STENCIL_INDEX1 0x8D46 +#define GL_STENCIL_INDEX4 0x8D47 +#define GL_STENCIL_INDEX8 0x8D48 +#define GL_STENCIL_INDEX16 0x8D49 +#define GL_RENDERBUFFER_RED_SIZE 0x8D50 +#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 +#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 +#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 +#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 +#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 +#define GL_MAX_SAMPLES 0x8D57 +#define GL_INDEX 0x8222 +#define GL_FRAMEBUFFER_SRGB 0x8DB9 +#define GL_HALF_FLOAT 0x140B +#define GL_MAP_READ_BIT 0x0001 +#define GL_MAP_WRITE_BIT 0x0002 +#define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 +#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 +#define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 +#define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 +#define GL_COMPRESSED_RED_RGTC1 0x8DBB +#define GL_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC +#define GL_COMPRESSED_RG_RGTC2 0x8DBD +#define GL_COMPRESSED_SIGNED_RG_RGTC2 0x8DBE +#define GL_RG 0x8227 +#define GL_RG_INTEGER 0x8228 +#define GL_R8 0x8229 +#define GL_R16 0x822A +#define GL_RG8 0x822B +#define GL_RG16 0x822C +#define GL_R16F 0x822D +#define GL_R32F 0x822E +#define GL_RG16F 0x822F +#define GL_RG32F 0x8230 +#define GL_R8I 0x8231 +#define GL_R8UI 0x8232 +#define GL_R16I 0x8233 +#define GL_R16UI 0x8234 +#define GL_R32I 0x8235 +#define GL_R32UI 0x8236 +#define GL_RG8I 0x8237 +#define GL_RG8UI 0x8238 +#define GL_RG16I 0x8239 +#define GL_RG16UI 0x823A +#define GL_RG32I 0x823B +#define GL_RG32UI 0x823C +#define GL_VERTEX_ARRAY_BINDING 0x85B5 +#define GL_SAMPLER_2D_RECT 0x8B63 +#define GL_SAMPLER_2D_RECT_SHADOW 0x8B64 +#define GL_SAMPLER_BUFFER 0x8DC2 +#define GL_INT_SAMPLER_2D_RECT 0x8DCD +#define GL_INT_SAMPLER_BUFFER 0x8DD0 +#define GL_UNSIGNED_INT_SAMPLER_2D_RECT 0x8DD5 +#define GL_UNSIGNED_INT_SAMPLER_BUFFER 0x8DD8 +#define GL_TEXTURE_BUFFER 0x8C2A +#define GL_MAX_TEXTURE_BUFFER_SIZE 0x8C2B +#define GL_TEXTURE_BINDING_BUFFER 0x8C2C +#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING 0x8C2D +#define GL_TEXTURE_RECTANGLE 0x84F5 +#define GL_TEXTURE_BINDING_RECTANGLE 0x84F6 +#define GL_PROXY_TEXTURE_RECTANGLE 0x84F7 +#define GL_MAX_RECTANGLE_TEXTURE_SIZE 0x84F8 +#define GL_R8_SNORM 0x8F94 +#define GL_RG8_SNORM 0x8F95 +#define GL_RGB8_SNORM 0x8F96 +#define GL_RGBA8_SNORM 0x8F97 +#define GL_R16_SNORM 0x8F98 +#define GL_RG16_SNORM 0x8F99 +#define GL_RGB16_SNORM 0x8F9A +#define GL_RGBA16_SNORM 0x8F9B +#define GL_SIGNED_NORMALIZED 0x8F9C +#define GL_PRIMITIVE_RESTART 0x8F9D +#define GL_PRIMITIVE_RESTART_INDEX 0x8F9E +#define GL_COPY_READ_BUFFER 0x8F36 +#define GL_COPY_WRITE_BUFFER 0x8F37 +#define GL_UNIFORM_BUFFER 0x8A11 +#define GL_UNIFORM_BUFFER_BINDING 0x8A28 +#define GL_UNIFORM_BUFFER_START 0x8A29 +#define GL_UNIFORM_BUFFER_SIZE 0x8A2A +#define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B +#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS 0x8A2C +#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D +#define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E +#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F +#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 +#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 +#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS 0x8A32 +#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 +#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 +#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 +#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 +#define GL_UNIFORM_TYPE 0x8A37 +#define GL_UNIFORM_SIZE 0x8A38 +#define GL_UNIFORM_NAME_LENGTH 0x8A39 +#define GL_UNIFORM_BLOCK_INDEX 0x8A3A +#define GL_UNIFORM_OFFSET 0x8A3B +#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C +#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D +#define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E +#define GL_UNIFORM_BLOCK_BINDING 0x8A3F +#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 +#define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 +#define GL_INVALID_INDEX 0xFFFFFFFF +#define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001 +#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 +#define GL_LINES_ADJACENCY 0x000A +#define GL_LINE_STRIP_ADJACENCY 0x000B +#define GL_TRIANGLES_ADJACENCY 0x000C +#define GL_TRIANGLE_STRIP_ADJACENCY 0x000D +#define GL_PROGRAM_POINT_SIZE 0x8642 +#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS 0x8C29 +#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED 0x8DA7 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS 0x8DA8 +#define GL_GEOMETRY_SHADER 0x8DD9 +#define GL_GEOMETRY_VERTICES_OUT 0x8916 +#define GL_GEOMETRY_INPUT_TYPE 0x8917 +#define GL_GEOMETRY_OUTPUT_TYPE 0x8918 +#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS 0x8DDF +#define GL_MAX_GEOMETRY_OUTPUT_VERTICES 0x8DE0 +#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS 0x8DE1 +#define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 +#define GL_MAX_GEOMETRY_INPUT_COMPONENTS 0x9123 +#define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS 0x9124 +#define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 +#define GL_CONTEXT_PROFILE_MASK 0x9126 +#define GL_DEPTH_CLAMP 0x864F +#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION 0x8E4C +#define GL_FIRST_VERTEX_CONVENTION 0x8E4D +#define GL_LAST_VERTEX_CONVENTION 0x8E4E +#define GL_PROVOKING_VERTEX 0x8E4F +#define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F +#define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 +#define GL_OBJECT_TYPE 0x9112 +#define GL_SYNC_CONDITION 0x9113 +#define GL_SYNC_STATUS 0x9114 +#define GL_SYNC_FLAGS 0x9115 +#define GL_SYNC_FENCE 0x9116 +#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 +#define GL_UNSIGNALED 0x9118 +#define GL_SIGNALED 0x9119 +#define GL_ALREADY_SIGNALED 0x911A +#define GL_TIMEOUT_EXPIRED 0x911B +#define GL_CONDITION_SATISFIED 0x911C +#define GL_WAIT_FAILED 0x911D +#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFF +#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 +#define GL_SAMPLE_POSITION 0x8E50 +#define GL_SAMPLE_MASK 0x8E51 +#define GL_SAMPLE_MASK_VALUE 0x8E52 +#define GL_MAX_SAMPLE_MASK_WORDS 0x8E59 +#define GL_TEXTURE_2D_MULTISAMPLE 0x9100 +#define GL_PROXY_TEXTURE_2D_MULTISAMPLE 0x9101 +#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102 +#define GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9103 +#define GL_TEXTURE_BINDING_2D_MULTISAMPLE 0x9104 +#define GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY 0x9105 +#define GL_TEXTURE_SAMPLES 0x9106 +#define GL_TEXTURE_FIXED_SAMPLE_LOCATIONS 0x9107 +#define GL_SAMPLER_2D_MULTISAMPLE 0x9108 +#define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109 +#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A +#define GL_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910B +#define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910C +#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910D +#define GL_MAX_COLOR_TEXTURE_SAMPLES 0x910E +#define GL_MAX_DEPTH_TEXTURE_SAMPLES 0x910F +#define GL_MAX_INTEGER_SAMPLES 0x9110 +#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE +#define GL_SRC1_COLOR 0x88F9 +#define GL_ONE_MINUS_SRC1_COLOR 0x88FA +#define GL_ONE_MINUS_SRC1_ALPHA 0x88FB +#define GL_MAX_DUAL_SOURCE_DRAW_BUFFERS 0x88FC +#define GL_ANY_SAMPLES_PASSED 0x8C2F +#define GL_SAMPLER_BINDING 0x8919 +#define GL_RGB10_A2UI 0x906F +#define GL_TEXTURE_SWIZZLE_R 0x8E42 +#define GL_TEXTURE_SWIZZLE_G 0x8E43 +#define GL_TEXTURE_SWIZZLE_B 0x8E44 +#define GL_TEXTURE_SWIZZLE_A 0x8E45 +#define GL_TEXTURE_SWIZZLE_RGBA 0x8E46 +#define GL_TIME_ELAPSED 0x88BF +#define GL_TIMESTAMP 0x8E28 +#define GL_INT_2_10_10_10_REV 0x8D9F +#define GL_SAMPLE_SHADING 0x8C36 +#define GL_MIN_SAMPLE_SHADING_VALUE 0x8C37 +#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5E +#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5F +#define GL_TEXTURE_CUBE_MAP_ARRAY 0x9009 +#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY 0x900A +#define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY 0x900B +#define GL_SAMPLER_CUBE_MAP_ARRAY 0x900C +#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW 0x900D +#define GL_INT_SAMPLER_CUBE_MAP_ARRAY 0x900E +#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY 0x900F +#define GL_DRAW_INDIRECT_BUFFER 0x8F3F +#define GL_DRAW_INDIRECT_BUFFER_BINDING 0x8F43 +#define GL_GEOMETRY_SHADER_INVOCATIONS 0x887F +#define GL_MAX_GEOMETRY_SHADER_INVOCATIONS 0x8E5A +#define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET 0x8E5B +#define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET 0x8E5C +#define GL_FRAGMENT_INTERPOLATION_OFFSET_BITS 0x8E5D +#define GL_MAX_VERTEX_STREAMS 0x8E71 +#define GL_DOUBLE_VEC2 0x8FFC +#define GL_DOUBLE_VEC3 0x8FFD +#define GL_DOUBLE_VEC4 0x8FFE +#define GL_DOUBLE_MAT2 0x8F46 +#define GL_DOUBLE_MAT3 0x8F47 +#define GL_DOUBLE_MAT4 0x8F48 +#define GL_DOUBLE_MAT2x3 0x8F49 +#define GL_DOUBLE_MAT2x4 0x8F4A +#define GL_DOUBLE_MAT3x2 0x8F4B +#define GL_DOUBLE_MAT3x4 0x8F4C +#define GL_DOUBLE_MAT4x2 0x8F4D +#define GL_DOUBLE_MAT4x3 0x8F4E +#define GL_ACTIVE_SUBROUTINES 0x8DE5 +#define GL_ACTIVE_SUBROUTINE_UNIFORMS 0x8DE6 +#define GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS 0x8E47 +#define GL_ACTIVE_SUBROUTINE_MAX_LENGTH 0x8E48 +#define GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH 0x8E49 +#define GL_MAX_SUBROUTINES 0x8DE7 +#define GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS 0x8DE8 +#define GL_NUM_COMPATIBLE_SUBROUTINES 0x8E4A +#define GL_COMPATIBLE_SUBROUTINES 0x8E4B +#define GL_PATCHES 0x000E +#define GL_PATCH_VERTICES 0x8E72 +#define GL_PATCH_DEFAULT_INNER_LEVEL 0x8E73 +#define GL_PATCH_DEFAULT_OUTER_LEVEL 0x8E74 +#define GL_TESS_CONTROL_OUTPUT_VERTICES 0x8E75 +#define GL_TESS_GEN_MODE 0x8E76 +#define GL_TESS_GEN_SPACING 0x8E77 +#define GL_TESS_GEN_VERTEX_ORDER 0x8E78 +#define GL_TESS_GEN_POINT_MODE 0x8E79 +#define GL_ISOLINES 0x8E7A +#define GL_FRACTIONAL_ODD 0x8E7B +#define GL_FRACTIONAL_EVEN 0x8E7C +#define GL_MAX_PATCH_VERTICES 0x8E7D +#define GL_MAX_TESS_GEN_LEVEL 0x8E7E +#define GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E7F +#define GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E80 +#define GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS 0x8E81 +#define GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS 0x8E82 +#define GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS 0x8E83 +#define GL_MAX_TESS_PATCH_COMPONENTS 0x8E84 +#define GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS 0x8E85 +#define GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS 0x8E86 +#define GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS 0x8E89 +#define GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS 0x8E8A +#define GL_MAX_TESS_CONTROL_INPUT_COMPONENTS 0x886C +#define GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS 0x886D +#define GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E1E +#define GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E1F +#define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER 0x84F0 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER 0x84F1 +#define GL_TESS_EVALUATION_SHADER 0x8E87 +#define GL_TESS_CONTROL_SHADER 0x8E88 +#define GL_TRANSFORM_FEEDBACK 0x8E22 +#define GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED 0x8E23 +#define GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE 0x8E24 +#define GL_TRANSFORM_FEEDBACK_BINDING 0x8E25 +#define GL_MAX_TRANSFORM_FEEDBACK_BUFFERS 0x8E70 +#define GL_FIXED 0x140C +#define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A +#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B +#define GL_LOW_FLOAT 0x8DF0 +#define GL_MEDIUM_FLOAT 0x8DF1 +#define GL_HIGH_FLOAT 0x8DF2 +#define GL_LOW_INT 0x8DF3 +#define GL_MEDIUM_INT 0x8DF4 +#define GL_HIGH_INT 0x8DF5 +#define GL_SHADER_COMPILER 0x8DFA +#define GL_SHADER_BINARY_FORMATS 0x8DF8 +#define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9 +#define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB +#define GL_MAX_VARYING_VECTORS 0x8DFC +#define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD +#define GL_RGB565 0x8D62 +#define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0x8257 +#define GL_PROGRAM_BINARY_LENGTH 0x8741 +#define GL_NUM_PROGRAM_BINARY_FORMATS 0x87FE +#define GL_PROGRAM_BINARY_FORMATS 0x87FF +#define GL_VERTEX_SHADER_BIT 0x00000001 +#define GL_FRAGMENT_SHADER_BIT 0x00000002 +#define GL_GEOMETRY_SHADER_BIT 0x00000004 +#define GL_TESS_CONTROL_SHADER_BIT 0x00000008 +#define GL_TESS_EVALUATION_SHADER_BIT 0x00000010 +#define GL_ALL_SHADER_BITS 0xFFFFFFFF +#define GL_PROGRAM_SEPARABLE 0x8258 +#define GL_ACTIVE_PROGRAM 0x8259 +#define GL_PROGRAM_PIPELINE_BINDING 0x825A +#define GL_MAX_VIEWPORTS 0x825B +#define GL_VIEWPORT_SUBPIXEL_BITS 0x825C +#define GL_VIEWPORT_BOUNDS_RANGE 0x825D +#define GL_LAYER_PROVOKING_VERTEX 0x825E +#define GL_VIEWPORT_INDEX_PROVOKING_VERTEX 0x825F +#define GL_UNDEFINED_VERTEX 0x8260 +#define GL_COPY_READ_BUFFER_BINDING 0x8F36 +#define GL_COPY_WRITE_BUFFER_BINDING 0x8F37 +#define GL_TRANSFORM_FEEDBACK_ACTIVE 0x8E24 +#define GL_TRANSFORM_FEEDBACK_PAUSED 0x8E23 +#define GL_UNPACK_COMPRESSED_BLOCK_WIDTH 0x9127 +#define GL_UNPACK_COMPRESSED_BLOCK_HEIGHT 0x9128 +#define GL_UNPACK_COMPRESSED_BLOCK_DEPTH 0x9129 +#define GL_UNPACK_COMPRESSED_BLOCK_SIZE 0x912A +#define GL_PACK_COMPRESSED_BLOCK_WIDTH 0x912B +#define GL_PACK_COMPRESSED_BLOCK_HEIGHT 0x912C +#define GL_PACK_COMPRESSED_BLOCK_DEPTH 0x912D +#define GL_PACK_COMPRESSED_BLOCK_SIZE 0x912E +#define GL_NUM_SAMPLE_COUNTS 0x9380 +#define GL_MIN_MAP_BUFFER_ALIGNMENT 0x90BC +#define GL_ATOMIC_COUNTER_BUFFER 0x92C0 +#define GL_ATOMIC_COUNTER_BUFFER_BINDING 0x92C1 +#define GL_ATOMIC_COUNTER_BUFFER_START 0x92C2 +#define GL_ATOMIC_COUNTER_BUFFER_SIZE 0x92C3 +#define GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE 0x92C4 +#define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS 0x92C5 +#define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES 0x92C6 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER 0x92C7 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER 0x92C8 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER 0x92C9 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER 0x92CA +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER 0x92CB +#define GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS 0x92CC +#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS 0x92CD +#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS 0x92CE +#define GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS 0x92CF +#define GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS 0x92D0 +#define GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS 0x92D1 +#define GL_MAX_VERTEX_ATOMIC_COUNTERS 0x92D2 +#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS 0x92D3 +#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS 0x92D4 +#define GL_MAX_GEOMETRY_ATOMIC_COUNTERS 0x92D5 +#define GL_MAX_FRAGMENT_ATOMIC_COUNTERS 0x92D6 +#define GL_MAX_COMBINED_ATOMIC_COUNTERS 0x92D7 +#define GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE 0x92D8 +#define GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS 0x92DC +#define GL_ACTIVE_ATOMIC_COUNTER_BUFFERS 0x92D9 +#define GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX 0x92DA +#define GL_UNSIGNED_INT_ATOMIC_COUNTER 0x92DB +#define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001 +#define GL_ELEMENT_ARRAY_BARRIER_BIT 0x00000002 +#define GL_UNIFORM_BARRIER_BIT 0x00000004 +#define GL_TEXTURE_FETCH_BARRIER_BIT 0x00000008 +#define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020 +#define GL_COMMAND_BARRIER_BIT 0x00000040 +#define GL_PIXEL_BUFFER_BARRIER_BIT 0x00000080 +#define GL_TEXTURE_UPDATE_BARRIER_BIT 0x00000100 +#define GL_BUFFER_UPDATE_BARRIER_BIT 0x00000200 +#define GL_FRAMEBUFFER_BARRIER_BIT 0x00000400 +#define GL_TRANSFORM_FEEDBACK_BARRIER_BIT 0x00000800 +#define GL_ATOMIC_COUNTER_BARRIER_BIT 0x00001000 +#define GL_ALL_BARRIER_BITS 0xFFFFFFFF +#define GL_MAX_IMAGE_UNITS 0x8F38 +#define GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS 0x8F39 +#define GL_IMAGE_BINDING_NAME 0x8F3A +#define GL_IMAGE_BINDING_LEVEL 0x8F3B +#define GL_IMAGE_BINDING_LAYERED 0x8F3C +#define GL_IMAGE_BINDING_LAYER 0x8F3D +#define GL_IMAGE_BINDING_ACCESS 0x8F3E +#define GL_IMAGE_1D 0x904C +#define GL_IMAGE_2D 0x904D +#define GL_IMAGE_3D 0x904E +#define GL_IMAGE_2D_RECT 0x904F +#define GL_IMAGE_CUBE 0x9050 +#define GL_IMAGE_BUFFER 0x9051 +#define GL_IMAGE_1D_ARRAY 0x9052 +#define GL_IMAGE_2D_ARRAY 0x9053 +#define GL_IMAGE_CUBE_MAP_ARRAY 0x9054 +#define GL_IMAGE_2D_MULTISAMPLE 0x9055 +#define GL_IMAGE_2D_MULTISAMPLE_ARRAY 0x9056 +#define GL_INT_IMAGE_1D 0x9057 +#define GL_INT_IMAGE_2D 0x9058 +#define GL_INT_IMAGE_3D 0x9059 +#define GL_INT_IMAGE_2D_RECT 0x905A +#define GL_INT_IMAGE_CUBE 0x905B +#define GL_INT_IMAGE_BUFFER 0x905C +#define GL_INT_IMAGE_1D_ARRAY 0x905D +#define GL_INT_IMAGE_2D_ARRAY 0x905E +#define GL_INT_IMAGE_CUBE_MAP_ARRAY 0x905F +#define GL_INT_IMAGE_2D_MULTISAMPLE 0x9060 +#define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x9061 +#define GL_UNSIGNED_INT_IMAGE_1D 0x9062 +#define GL_UNSIGNED_INT_IMAGE_2D 0x9063 +#define GL_UNSIGNED_INT_IMAGE_3D 0x9064 +#define GL_UNSIGNED_INT_IMAGE_2D_RECT 0x9065 +#define GL_UNSIGNED_INT_IMAGE_CUBE 0x9066 +#define GL_UNSIGNED_INT_IMAGE_BUFFER 0x9067 +#define GL_UNSIGNED_INT_IMAGE_1D_ARRAY 0x9068 +#define GL_UNSIGNED_INT_IMAGE_2D_ARRAY 0x9069 +#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY 0x906A +#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE 0x906B +#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x906C +#define GL_MAX_IMAGE_SAMPLES 0x906D +#define GL_IMAGE_BINDING_FORMAT 0x906E +#define GL_IMAGE_FORMAT_COMPATIBILITY_TYPE 0x90C7 +#define GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE 0x90C8 +#define GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS 0x90C9 +#define GL_MAX_VERTEX_IMAGE_UNIFORMS 0x90CA +#define GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS 0x90CB +#define GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS 0x90CC +#define GL_MAX_GEOMETRY_IMAGE_UNIFORMS 0x90CD +#define GL_MAX_FRAGMENT_IMAGE_UNIFORMS 0x90CE +#define GL_MAX_COMBINED_IMAGE_UNIFORMS 0x90CF +#define GL_COMPRESSED_RGBA_BPTC_UNORM 0x8E8C +#define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM 0x8E8D +#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT 0x8E8E +#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT 0x8E8F +#define GL_TEXTURE_IMMUTABLE_FORMAT 0x912F +#define GL_NUM_SHADING_LANGUAGE_VERSIONS 0x82E9 +#define GL_VERTEX_ATTRIB_ARRAY_LONG 0x874E +#define GL_COMPRESSED_RGB8_ETC2 0x9274 +#define GL_COMPRESSED_SRGB8_ETC2 0x9275 +#define GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276 +#define GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9277 +#define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 +#define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279 +#define GL_COMPRESSED_R11_EAC 0x9270 +#define GL_COMPRESSED_SIGNED_R11_EAC 0x9271 +#define GL_COMPRESSED_RG11_EAC 0x9272 +#define GL_COMPRESSED_SIGNED_RG11_EAC 0x9273 +#define GL_PRIMITIVE_RESTART_FIXED_INDEX 0x8D69 +#define GL_ANY_SAMPLES_PASSED_CONSERVATIVE 0x8D6A +#define GL_MAX_ELEMENT_INDEX 0x8D6B +#define GL_COMPUTE_SHADER 0x91B9 +#define GL_MAX_COMPUTE_UNIFORM_BLOCKS 0x91BB +#define GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS 0x91BC +#define GL_MAX_COMPUTE_IMAGE_UNIFORMS 0x91BD +#define GL_MAX_COMPUTE_SHARED_MEMORY_SIZE 0x8262 +#define GL_MAX_COMPUTE_UNIFORM_COMPONENTS 0x8263 +#define GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS 0x8264 +#define GL_MAX_COMPUTE_ATOMIC_COUNTERS 0x8265 +#define GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS 0x8266 +#define GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS 0x90EB +#define GL_MAX_COMPUTE_WORK_GROUP_COUNT 0x91BE +#define GL_MAX_COMPUTE_WORK_GROUP_SIZE 0x91BF +#define GL_COMPUTE_WORK_GROUP_SIZE 0x8267 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER 0x90EC +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER 0x90ED +#define GL_DISPATCH_INDIRECT_BUFFER 0x90EE +#define GL_DISPATCH_INDIRECT_BUFFER_BINDING 0x90EF +#define GL_COMPUTE_SHADER_BIT 0x00000020 +#define GL_DEBUG_OUTPUT_SYNCHRONOUS 0x8242 +#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH 0x8243 +#define GL_DEBUG_CALLBACK_FUNCTION 0x8244 +#define GL_DEBUG_CALLBACK_USER_PARAM 0x8245 +#define GL_DEBUG_SOURCE_API 0x8246 +#define GL_DEBUG_SOURCE_WINDOW_SYSTEM 0x8247 +#define GL_DEBUG_SOURCE_SHADER_COMPILER 0x8248 +#define GL_DEBUG_SOURCE_THIRD_PARTY 0x8249 +#define GL_DEBUG_SOURCE_APPLICATION 0x824A +#define GL_DEBUG_SOURCE_OTHER 0x824B +#define GL_DEBUG_TYPE_ERROR 0x824C +#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR 0x824D +#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR 0x824E +#define GL_DEBUG_TYPE_PORTABILITY 0x824F +#define GL_DEBUG_TYPE_PERFORMANCE 0x8250 +#define GL_DEBUG_TYPE_OTHER 0x8251 +#define GL_MAX_DEBUG_MESSAGE_LENGTH 0x9143 +#define GL_MAX_DEBUG_LOGGED_MESSAGES 0x9144 +#define GL_DEBUG_LOGGED_MESSAGES 0x9145 +#define GL_DEBUG_SEVERITY_HIGH 0x9146 +#define GL_DEBUG_SEVERITY_MEDIUM 0x9147 +#define GL_DEBUG_SEVERITY_LOW 0x9148 +#define GL_DEBUG_TYPE_MARKER 0x8268 +#define GL_DEBUG_TYPE_PUSH_GROUP 0x8269 +#define GL_DEBUG_TYPE_POP_GROUP 0x826A +#define GL_DEBUG_SEVERITY_NOTIFICATION 0x826B +#define GL_MAX_DEBUG_GROUP_STACK_DEPTH 0x826C +#define GL_DEBUG_GROUP_STACK_DEPTH 0x826D +#define GL_BUFFER 0x82E0 +#define GL_SHADER 0x82E1 +#define GL_PROGRAM 0x82E2 +#define GL_QUERY 0x82E3 +#define GL_PROGRAM_PIPELINE 0x82E4 +#define GL_SAMPLER 0x82E6 +#define GL_MAX_LABEL_LENGTH 0x82E8 +#define GL_DEBUG_OUTPUT 0x92E0 +#define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002 +#define GL_MAX_UNIFORM_LOCATIONS 0x826E +#define GL_FRAMEBUFFER_DEFAULT_WIDTH 0x9310 +#define GL_FRAMEBUFFER_DEFAULT_HEIGHT 0x9311 +#define GL_FRAMEBUFFER_DEFAULT_LAYERS 0x9312 +#define GL_FRAMEBUFFER_DEFAULT_SAMPLES 0x9313 +#define GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS 0x9314 +#define GL_MAX_FRAMEBUFFER_WIDTH 0x9315 +#define GL_MAX_FRAMEBUFFER_HEIGHT 0x9316 +#define GL_MAX_FRAMEBUFFER_LAYERS 0x9317 +#define GL_MAX_FRAMEBUFFER_SAMPLES 0x9318 +#define GL_INTERNALFORMAT_SUPPORTED 0x826F +#define GL_INTERNALFORMAT_PREFERRED 0x8270 +#define GL_INTERNALFORMAT_RED_SIZE 0x8271 +#define GL_INTERNALFORMAT_GREEN_SIZE 0x8272 +#define GL_INTERNALFORMAT_BLUE_SIZE 0x8273 +#define GL_INTERNALFORMAT_ALPHA_SIZE 0x8274 +#define GL_INTERNALFORMAT_DEPTH_SIZE 0x8275 +#define GL_INTERNALFORMAT_STENCIL_SIZE 0x8276 +#define GL_INTERNALFORMAT_SHARED_SIZE 0x8277 +#define GL_INTERNALFORMAT_RED_TYPE 0x8278 +#define GL_INTERNALFORMAT_GREEN_TYPE 0x8279 +#define GL_INTERNALFORMAT_BLUE_TYPE 0x827A +#define GL_INTERNALFORMAT_ALPHA_TYPE 0x827B +#define GL_INTERNALFORMAT_DEPTH_TYPE 0x827C +#define GL_INTERNALFORMAT_STENCIL_TYPE 0x827D +#define GL_MAX_WIDTH 0x827E +#define GL_MAX_HEIGHT 0x827F +#define GL_MAX_DEPTH 0x8280 +#define GL_MAX_LAYERS 0x8281 +#define GL_MAX_COMBINED_DIMENSIONS 0x8282 +#define GL_COLOR_COMPONENTS 0x8283 +#define GL_DEPTH_COMPONENTS 0x8284 +#define GL_STENCIL_COMPONENTS 0x8285 +#define GL_COLOR_RENDERABLE 0x8286 +#define GL_DEPTH_RENDERABLE 0x8287 +#define GL_STENCIL_RENDERABLE 0x8288 +#define GL_FRAMEBUFFER_RENDERABLE 0x8289 +#define GL_FRAMEBUFFER_RENDERABLE_LAYERED 0x828A +#define GL_FRAMEBUFFER_BLEND 0x828B +#define GL_READ_PIXELS 0x828C +#define GL_READ_PIXELS_FORMAT 0x828D +#define GL_READ_PIXELS_TYPE 0x828E +#define GL_TEXTURE_IMAGE_FORMAT 0x828F +#define GL_TEXTURE_IMAGE_TYPE 0x8290 +#define GL_GET_TEXTURE_IMAGE_FORMAT 0x8291 +#define GL_GET_TEXTURE_IMAGE_TYPE 0x8292 +#define GL_MIPMAP 0x8293 +#define GL_MANUAL_GENERATE_MIPMAP 0x8294 +#define GL_AUTO_GENERATE_MIPMAP 0x8295 +#define GL_COLOR_ENCODING 0x8296 +#define GL_SRGB_READ 0x8297 +#define GL_SRGB_WRITE 0x8298 +#define GL_FILTER 0x829A +#define GL_VERTEX_TEXTURE 0x829B +#define GL_TESS_CONTROL_TEXTURE 0x829C +#define GL_TESS_EVALUATION_TEXTURE 0x829D +#define GL_GEOMETRY_TEXTURE 0x829E +#define GL_FRAGMENT_TEXTURE 0x829F +#define GL_COMPUTE_TEXTURE 0x82A0 +#define GL_TEXTURE_SHADOW 0x82A1 +#define GL_TEXTURE_GATHER 0x82A2 +#define GL_TEXTURE_GATHER_SHADOW 0x82A3 +#define GL_SHADER_IMAGE_LOAD 0x82A4 +#define GL_SHADER_IMAGE_STORE 0x82A5 +#define GL_SHADER_IMAGE_ATOMIC 0x82A6 +#define GL_IMAGE_TEXEL_SIZE 0x82A7 +#define GL_IMAGE_COMPATIBILITY_CLASS 0x82A8 +#define GL_IMAGE_PIXEL_FORMAT 0x82A9 +#define GL_IMAGE_PIXEL_TYPE 0x82AA +#define GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST 0x82AC +#define GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST 0x82AD +#define GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE 0x82AE +#define GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE 0x82AF +#define GL_TEXTURE_COMPRESSED_BLOCK_WIDTH 0x82B1 +#define GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT 0x82B2 +#define GL_TEXTURE_COMPRESSED_BLOCK_SIZE 0x82B3 +#define GL_CLEAR_BUFFER 0x82B4 +#define GL_TEXTURE_VIEW 0x82B5 +#define GL_VIEW_COMPATIBILITY_CLASS 0x82B6 +#define GL_FULL_SUPPORT 0x82B7 +#define GL_CAVEAT_SUPPORT 0x82B8 +#define GL_IMAGE_CLASS_4_X_32 0x82B9 +#define GL_IMAGE_CLASS_2_X_32 0x82BA +#define GL_IMAGE_CLASS_1_X_32 0x82BB +#define GL_IMAGE_CLASS_4_X_16 0x82BC +#define GL_IMAGE_CLASS_2_X_16 0x82BD +#define GL_IMAGE_CLASS_1_X_16 0x82BE +#define GL_IMAGE_CLASS_4_X_8 0x82BF +#define GL_IMAGE_CLASS_2_X_8 0x82C0 +#define GL_IMAGE_CLASS_1_X_8 0x82C1 +#define GL_IMAGE_CLASS_11_11_10 0x82C2 +#define GL_IMAGE_CLASS_10_10_10_2 0x82C3 +#define GL_VIEW_CLASS_128_BITS 0x82C4 +#define GL_VIEW_CLASS_96_BITS 0x82C5 +#define GL_VIEW_CLASS_64_BITS 0x82C6 +#define GL_VIEW_CLASS_48_BITS 0x82C7 +#define GL_VIEW_CLASS_32_BITS 0x82C8 +#define GL_VIEW_CLASS_24_BITS 0x82C9 +#define GL_VIEW_CLASS_16_BITS 0x82CA +#define GL_VIEW_CLASS_8_BITS 0x82CB +#define GL_VIEW_CLASS_S3TC_DXT1_RGB 0x82CC +#define GL_VIEW_CLASS_S3TC_DXT1_RGBA 0x82CD +#define GL_VIEW_CLASS_S3TC_DXT3_RGBA 0x82CE +#define GL_VIEW_CLASS_S3TC_DXT5_RGBA 0x82CF +#define GL_VIEW_CLASS_RGTC1_RED 0x82D0 +#define GL_VIEW_CLASS_RGTC2_RG 0x82D1 +#define GL_VIEW_CLASS_BPTC_UNORM 0x82D2 +#define GL_VIEW_CLASS_BPTC_FLOAT 0x82D3 +#define GL_UNIFORM 0x92E1 +#define GL_UNIFORM_BLOCK 0x92E2 +#define GL_PROGRAM_INPUT 0x92E3 +#define GL_PROGRAM_OUTPUT 0x92E4 +#define GL_BUFFER_VARIABLE 0x92E5 +#define GL_SHADER_STORAGE_BLOCK 0x92E6 +#define GL_VERTEX_SUBROUTINE 0x92E8 +#define GL_TESS_CONTROL_SUBROUTINE 0x92E9 +#define GL_TESS_EVALUATION_SUBROUTINE 0x92EA +#define GL_GEOMETRY_SUBROUTINE 0x92EB +#define GL_FRAGMENT_SUBROUTINE 0x92EC +#define GL_COMPUTE_SUBROUTINE 0x92ED +#define GL_VERTEX_SUBROUTINE_UNIFORM 0x92EE +#define GL_TESS_CONTROL_SUBROUTINE_UNIFORM 0x92EF +#define GL_TESS_EVALUATION_SUBROUTINE_UNIFORM 0x92F0 +#define GL_GEOMETRY_SUBROUTINE_UNIFORM 0x92F1 +#define GL_FRAGMENT_SUBROUTINE_UNIFORM 0x92F2 +#define GL_COMPUTE_SUBROUTINE_UNIFORM 0x92F3 +#define GL_TRANSFORM_FEEDBACK_VARYING 0x92F4 +#define GL_ACTIVE_RESOURCES 0x92F5 +#define GL_MAX_NAME_LENGTH 0x92F6 +#define GL_MAX_NUM_ACTIVE_VARIABLES 0x92F7 +#define GL_MAX_NUM_COMPATIBLE_SUBROUTINES 0x92F8 +#define GL_NAME_LENGTH 0x92F9 +#define GL_TYPE 0x92FA +#define GL_ARRAY_SIZE 0x92FB +#define GL_OFFSET 0x92FC +#define GL_BLOCK_INDEX 0x92FD +#define GL_ARRAY_STRIDE 0x92FE +#define GL_MATRIX_STRIDE 0x92FF +#define GL_IS_ROW_MAJOR 0x9300 +#define GL_ATOMIC_COUNTER_BUFFER_INDEX 0x9301 +#define GL_BUFFER_BINDING 0x9302 +#define GL_BUFFER_DATA_SIZE 0x9303 +#define GL_NUM_ACTIVE_VARIABLES 0x9304 +#define GL_ACTIVE_VARIABLES 0x9305 +#define GL_REFERENCED_BY_VERTEX_SHADER 0x9306 +#define GL_REFERENCED_BY_TESS_CONTROL_SHADER 0x9307 +#define GL_REFERENCED_BY_TESS_EVALUATION_SHADER 0x9308 +#define GL_REFERENCED_BY_GEOMETRY_SHADER 0x9309 +#define GL_REFERENCED_BY_FRAGMENT_SHADER 0x930A +#define GL_REFERENCED_BY_COMPUTE_SHADER 0x930B +#define GL_TOP_LEVEL_ARRAY_SIZE 0x930C +#define GL_TOP_LEVEL_ARRAY_STRIDE 0x930D +#define GL_LOCATION 0x930E +#define GL_LOCATION_INDEX 0x930F +#define GL_IS_PER_PATCH 0x92E7 +#define GL_SHADER_STORAGE_BUFFER 0x90D2 +#define GL_SHADER_STORAGE_BUFFER_BINDING 0x90D3 +#define GL_SHADER_STORAGE_BUFFER_START 0x90D4 +#define GL_SHADER_STORAGE_BUFFER_SIZE 0x90D5 +#define GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS 0x90D6 +#define GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS 0x90D7 +#define GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS 0x90D8 +#define GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS 0x90D9 +#define GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS 0x90DA +#define GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS 0x90DB +#define GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS 0x90DC +#define GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS 0x90DD +#define GL_MAX_SHADER_STORAGE_BLOCK_SIZE 0x90DE +#define GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT 0x90DF +#define GL_SHADER_STORAGE_BARRIER_BIT 0x00002000 +#define GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES 0x8F39 +#define GL_DEPTH_STENCIL_TEXTURE_MODE 0x90EA +#define GL_TEXTURE_BUFFER_OFFSET 0x919D +#define GL_TEXTURE_BUFFER_SIZE 0x919E +#define GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT 0x919F +#define GL_TEXTURE_VIEW_MIN_LEVEL 0x82DB +#define GL_TEXTURE_VIEW_NUM_LEVELS 0x82DC +#define GL_TEXTURE_VIEW_MIN_LAYER 0x82DD +#define GL_TEXTURE_VIEW_NUM_LAYERS 0x82DE +#define GL_TEXTURE_IMMUTABLE_LEVELS 0x82DF +#define GL_VERTEX_ATTRIB_BINDING 0x82D4 +#define GL_VERTEX_ATTRIB_RELATIVE_OFFSET 0x82D5 +#define GL_VERTEX_BINDING_DIVISOR 0x82D6 +#define GL_VERTEX_BINDING_OFFSET 0x82D7 +#define GL_VERTEX_BINDING_STRIDE 0x82D8 +#define GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET 0x82D9 +#define GL_MAX_VERTEX_ATTRIB_BINDINGS 0x82DA +#define GL_VERTEX_BINDING_BUFFER 0x8F4F +#define GL_DISPLAY_LIST 0x82E7 +#define GL_MAX_VERTEX_ATTRIB_STRIDE 0x82E5 +#define GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED 0x8221 +#define GL_TEXTURE_BUFFER_BINDING 0x8C2A +#define GL_MAP_PERSISTENT_BIT 0x0040 +#define GL_MAP_COHERENT_BIT 0x0080 +#define GL_DYNAMIC_STORAGE_BIT 0x0100 +#define GL_CLIENT_STORAGE_BIT 0x0200 +#define GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT 0x00004000 +#define GL_BUFFER_IMMUTABLE_STORAGE 0x821F +#define GL_BUFFER_STORAGE_FLAGS 0x8220 +#define GL_CLEAR_TEXTURE 0x9365 +#define GL_LOCATION_COMPONENT 0x934A +#define GL_TRANSFORM_FEEDBACK_BUFFER_INDEX 0x934B +#define GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE 0x934C +#define GL_QUERY_BUFFER 0x9192 +#define GL_QUERY_BUFFER_BARRIER_BIT 0x00008000 +#define GL_QUERY_BUFFER_BINDING 0x9193 +#define GL_QUERY_RESULT_NO_WAIT 0x9194 +#define GL_MIRROR_CLAMP_TO_EDGE 0x8743 +#define GL_CONTEXT_LOST 0x0507 +#define GL_NEGATIVE_ONE_TO_ONE 0x935E +#define GL_ZERO_TO_ONE 0x935F +#define GL_CLIP_ORIGIN 0x935C +#define GL_CLIP_DEPTH_MODE 0x935D +#define GL_QUERY_WAIT_INVERTED 0x8E17 +#define GL_QUERY_NO_WAIT_INVERTED 0x8E18 +#define GL_QUERY_BY_REGION_WAIT_INVERTED 0x8E19 +#define GL_QUERY_BY_REGION_NO_WAIT_INVERTED 0x8E1A +#define GL_MAX_CULL_DISTANCES 0x82F9 +#define GL_MAX_COMBINED_CLIP_AND_CULL_DISTANCES 0x82FA +#define GL_TEXTURE_TARGET 0x1006 +#define GL_QUERY_TARGET 0x82EA +#define GL_GUILTY_CONTEXT_RESET 0x8253 +#define GL_INNOCENT_CONTEXT_RESET 0x8254 +#define GL_UNKNOWN_CONTEXT_RESET 0x8255 +#define GL_RESET_NOTIFICATION_STRATEGY 0x8256 +#define GL_LOSE_CONTEXT_ON_RESET 0x8252 +#define GL_NO_RESET_NOTIFICATION 0x8261 +#define GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT 0x00000004 +#define GL_CONTEXT_RELEASE_BEHAVIOR 0x82FB +#define GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH 0x82FC +#ifndef GL_VERSION_1_0 +#define GL_VERSION_1_0 1 +GLAPI int GLAD_GL_VERSION_1_0; +typedef void (APIENTRYP PFNGLCULLFACEPROC)(GLenum mode); +GLAPI PFNGLCULLFACEPROC glad_glCullFace; +#define glCullFace glad_glCullFace +typedef void (APIENTRYP PFNGLFRONTFACEPROC)(GLenum mode); +GLAPI PFNGLFRONTFACEPROC glad_glFrontFace; +#define glFrontFace glad_glFrontFace +typedef void (APIENTRYP PFNGLHINTPROC)(GLenum target, GLenum mode); +GLAPI PFNGLHINTPROC glad_glHint; +#define glHint glad_glHint +typedef void (APIENTRYP PFNGLLINEWIDTHPROC)(GLfloat width); +GLAPI PFNGLLINEWIDTHPROC glad_glLineWidth; +#define glLineWidth glad_glLineWidth +typedef void (APIENTRYP PFNGLPOINTSIZEPROC)(GLfloat size); +GLAPI PFNGLPOINTSIZEPROC glad_glPointSize; +#define glPointSize glad_glPointSize +typedef void (APIENTRYP PFNGLPOLYGONMODEPROC)(GLenum face, GLenum mode); +GLAPI PFNGLPOLYGONMODEPROC glad_glPolygonMode; +#define glPolygonMode glad_glPolygonMode +typedef void (APIENTRYP PFNGLSCISSORPROC)(GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI PFNGLSCISSORPROC glad_glScissor; +#define glScissor glad_glScissor +typedef void (APIENTRYP PFNGLTEXPARAMETERFPROC)(GLenum target, GLenum pname, GLfloat param); +GLAPI PFNGLTEXPARAMETERFPROC glad_glTexParameterf; +#define glTexParameterf glad_glTexParameterf +typedef void (APIENTRYP PFNGLTEXPARAMETERFVPROC)(GLenum target, GLenum pname, const GLfloat *params); +GLAPI PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv; +#define glTexParameterfv glad_glTexParameterfv +typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC)(GLenum target, GLenum pname, GLint param); +GLAPI PFNGLTEXPARAMETERIPROC glad_glTexParameteri; +#define glTexParameteri glad_glTexParameteri +typedef void (APIENTRYP PFNGLTEXPARAMETERIVPROC)(GLenum target, GLenum pname, const GLint *params); +GLAPI PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv; +#define glTexParameteriv glad_glTexParameteriv +typedef void (APIENTRYP PFNGLTEXIMAGE1DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXIMAGE1DPROC glad_glTexImage1D; +#define glTexImage1D glad_glTexImage1D +typedef void (APIENTRYP PFNGLTEXIMAGE2DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXIMAGE2DPROC glad_glTexImage2D; +#define glTexImage2D glad_glTexImage2D +typedef void (APIENTRYP PFNGLDRAWBUFFERPROC)(GLenum buf); +GLAPI PFNGLDRAWBUFFERPROC glad_glDrawBuffer; +#define glDrawBuffer glad_glDrawBuffer +typedef void (APIENTRYP PFNGLCLEARPROC)(GLbitfield mask); +GLAPI PFNGLCLEARPROC glad_glClear; +#define glClear glad_glClear +typedef void (APIENTRYP PFNGLCLEARCOLORPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +GLAPI PFNGLCLEARCOLORPROC glad_glClearColor; +#define glClearColor glad_glClearColor +typedef void (APIENTRYP PFNGLCLEARSTENCILPROC)(GLint s); +GLAPI PFNGLCLEARSTENCILPROC glad_glClearStencil; +#define glClearStencil glad_glClearStencil +typedef void (APIENTRYP PFNGLCLEARDEPTHPROC)(GLdouble depth); +GLAPI PFNGLCLEARDEPTHPROC glad_glClearDepth; +#define glClearDepth glad_glClearDepth +typedef void (APIENTRYP PFNGLSTENCILMASKPROC)(GLuint mask); +GLAPI PFNGLSTENCILMASKPROC glad_glStencilMask; +#define glStencilMask glad_glStencilMask +typedef void (APIENTRYP PFNGLCOLORMASKPROC)(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); +GLAPI PFNGLCOLORMASKPROC glad_glColorMask; +#define glColorMask glad_glColorMask +typedef void (APIENTRYP PFNGLDEPTHMASKPROC)(GLboolean flag); +GLAPI PFNGLDEPTHMASKPROC glad_glDepthMask; +#define glDepthMask glad_glDepthMask +typedef void (APIENTRYP PFNGLDISABLEPROC)(GLenum cap); +GLAPI PFNGLDISABLEPROC glad_glDisable; +#define glDisable glad_glDisable +typedef void (APIENTRYP PFNGLENABLEPROC)(GLenum cap); +GLAPI PFNGLENABLEPROC glad_glEnable; +#define glEnable glad_glEnable +typedef void (APIENTRYP PFNGLFINISHPROC)(); +GLAPI PFNGLFINISHPROC glad_glFinish; +#define glFinish glad_glFinish +typedef void (APIENTRYP PFNGLFLUSHPROC)(); +GLAPI PFNGLFLUSHPROC glad_glFlush; +#define glFlush glad_glFlush +typedef void (APIENTRYP PFNGLBLENDFUNCPROC)(GLenum sfactor, GLenum dfactor); +GLAPI PFNGLBLENDFUNCPROC glad_glBlendFunc; +#define glBlendFunc glad_glBlendFunc +typedef void (APIENTRYP PFNGLLOGICOPPROC)(GLenum opcode); +GLAPI PFNGLLOGICOPPROC glad_glLogicOp; +#define glLogicOp glad_glLogicOp +typedef void (APIENTRYP PFNGLSTENCILFUNCPROC)(GLenum func, GLint ref, GLuint mask); +GLAPI PFNGLSTENCILFUNCPROC glad_glStencilFunc; +#define glStencilFunc glad_glStencilFunc +typedef void (APIENTRYP PFNGLSTENCILOPPROC)(GLenum fail, GLenum zfail, GLenum zpass); +GLAPI PFNGLSTENCILOPPROC glad_glStencilOp; +#define glStencilOp glad_glStencilOp +typedef void (APIENTRYP PFNGLDEPTHFUNCPROC)(GLenum func); +GLAPI PFNGLDEPTHFUNCPROC glad_glDepthFunc; +#define glDepthFunc glad_glDepthFunc +typedef void (APIENTRYP PFNGLPIXELSTOREFPROC)(GLenum pname, GLfloat param); +GLAPI PFNGLPIXELSTOREFPROC glad_glPixelStoref; +#define glPixelStoref glad_glPixelStoref +typedef void (APIENTRYP PFNGLPIXELSTOREIPROC)(GLenum pname, GLint param); +GLAPI PFNGLPIXELSTOREIPROC glad_glPixelStorei; +#define glPixelStorei glad_glPixelStorei +typedef void (APIENTRYP PFNGLREADBUFFERPROC)(GLenum src); +GLAPI PFNGLREADBUFFERPROC glad_glReadBuffer; +#define glReadBuffer glad_glReadBuffer +typedef void (APIENTRYP PFNGLREADPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); +GLAPI PFNGLREADPIXELSPROC glad_glReadPixels; +#define glReadPixels glad_glReadPixels +typedef void (APIENTRYP PFNGLGETBOOLEANVPROC)(GLenum pname, GLboolean *data); +GLAPI PFNGLGETBOOLEANVPROC glad_glGetBooleanv; +#define glGetBooleanv glad_glGetBooleanv +typedef void (APIENTRYP PFNGLGETDOUBLEVPROC)(GLenum pname, GLdouble *data); +GLAPI PFNGLGETDOUBLEVPROC glad_glGetDoublev; +#define glGetDoublev glad_glGetDoublev +typedef GLenum (APIENTRYP PFNGLGETERRORPROC)(); +GLAPI PFNGLGETERRORPROC glad_glGetError; +#define glGetError glad_glGetError +typedef void (APIENTRYP PFNGLGETFLOATVPROC)(GLenum pname, GLfloat *data); +GLAPI PFNGLGETFLOATVPROC glad_glGetFloatv; +#define glGetFloatv glad_glGetFloatv +typedef void (APIENTRYP PFNGLGETINTEGERVPROC)(GLenum pname, GLint *data); +GLAPI PFNGLGETINTEGERVPROC glad_glGetIntegerv; +#define glGetIntegerv glad_glGetIntegerv +typedef const GLubyte * (APIENTRYP PFNGLGETSTRINGPROC)(GLenum name); +GLAPI PFNGLGETSTRINGPROC glad_glGetString; +#define glGetString glad_glGetString +typedef void (APIENTRYP PFNGLGETTEXIMAGEPROC)(GLenum target, GLint level, GLenum format, GLenum type, void *pixels); +GLAPI PFNGLGETTEXIMAGEPROC glad_glGetTexImage; +#define glGetTexImage glad_glGetTexImage +typedef void (APIENTRYP PFNGLGETTEXPARAMETERFVPROC)(GLenum target, GLenum pname, GLfloat *params); +GLAPI PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv; +#define glGetTexParameterfv glad_glGetTexParameterfv +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); +GLAPI PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv; +#define glGetTexParameteriv glad_glGetTexParameteriv +typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERFVPROC)(GLenum target, GLint level, GLenum pname, GLfloat *params); +GLAPI PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv; +#define glGetTexLevelParameterfv glad_glGetTexLevelParameterfv +typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERIVPROC)(GLenum target, GLint level, GLenum pname, GLint *params); +GLAPI PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv; +#define glGetTexLevelParameteriv glad_glGetTexLevelParameteriv +typedef GLboolean (APIENTRYP PFNGLISENABLEDPROC)(GLenum cap); +GLAPI PFNGLISENABLEDPROC glad_glIsEnabled; +#define glIsEnabled glad_glIsEnabled +typedef void (APIENTRYP PFNGLDEPTHRANGEPROC)(GLdouble near, GLdouble far); +GLAPI PFNGLDEPTHRANGEPROC glad_glDepthRange; +#define glDepthRange glad_glDepthRange +typedef void (APIENTRYP PFNGLVIEWPORTPROC)(GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI PFNGLVIEWPORTPROC glad_glViewport; +#define glViewport glad_glViewport +#endif +#ifndef GL_VERSION_1_1 +#define GL_VERSION_1_1 1 +GLAPI int GLAD_GL_VERSION_1_1; +typedef void (APIENTRYP PFNGLDRAWARRAYSPROC)(GLenum mode, GLint first, GLsizei count); +GLAPI PFNGLDRAWARRAYSPROC glad_glDrawArrays; +#define glDrawArrays glad_glDrawArrays +typedef void (APIENTRYP PFNGLDRAWELEMENTSPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices); +GLAPI PFNGLDRAWELEMENTSPROC glad_glDrawElements; +#define glDrawElements glad_glDrawElements +typedef void (APIENTRYP PFNGLPOLYGONOFFSETPROC)(GLfloat factor, GLfloat units); +GLAPI PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset; +#define glPolygonOffset glad_glPolygonOffset +typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +GLAPI PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D; +#define glCopyTexImage1D glad_glCopyTexImage1D +typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +GLAPI PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D; +#define glCopyTexImage2D glad_glCopyTexImage2D +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +GLAPI PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D; +#define glCopyTexSubImage1D glad_glCopyTexSubImage1D +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D; +#define glCopyTexSubImage2D glad_glCopyTexSubImage2D +typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D; +#define glTexSubImage1D glad_glTexSubImage1D +typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D; +#define glTexSubImage2D glad_glTexSubImage2D +typedef void (APIENTRYP PFNGLBINDTEXTUREPROC)(GLenum target, GLuint texture); +GLAPI PFNGLBINDTEXTUREPROC glad_glBindTexture; +#define glBindTexture glad_glBindTexture +typedef void (APIENTRYP PFNGLDELETETEXTURESPROC)(GLsizei n, const GLuint *textures); +GLAPI PFNGLDELETETEXTURESPROC glad_glDeleteTextures; +#define glDeleteTextures glad_glDeleteTextures +typedef void (APIENTRYP PFNGLGENTEXTURESPROC)(GLsizei n, GLuint *textures); +GLAPI PFNGLGENTEXTURESPROC glad_glGenTextures; +#define glGenTextures glad_glGenTextures +typedef GLboolean (APIENTRYP PFNGLISTEXTUREPROC)(GLuint texture); +GLAPI PFNGLISTEXTUREPROC glad_glIsTexture; +#define glIsTexture glad_glIsTexture +#endif +#ifndef GL_VERSION_1_2 +#define GL_VERSION_1_2 1 +GLAPI int GLAD_GL_VERSION_1_2; +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); +GLAPI PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements; +#define glDrawRangeElements glad_glDrawRangeElements +typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXIMAGE3DPROC glad_glTexImage3D; +#define glTexImage3D glad_glTexImage3D +typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D; +#define glTexSubImage3D glad_glTexSubImage3D +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D; +#define glCopyTexSubImage3D glad_glCopyTexSubImage3D +#endif +#ifndef GL_VERSION_1_3 +#define GL_VERSION_1_3 1 +GLAPI int GLAD_GL_VERSION_1_3; +typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC)(GLenum texture); +GLAPI PFNGLACTIVETEXTUREPROC glad_glActiveTexture; +#define glActiveTexture glad_glActiveTexture +typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC)(GLfloat value, GLboolean invert); +GLAPI PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage; +#define glSampleCoverage glad_glSampleCoverage +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D; +#define glCompressedTexImage3D glad_glCompressedTexImage3D +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D; +#define glCompressedTexImage2D glad_glCompressedTexImage2D +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D; +#define glCompressedTexImage1D glad_glCompressedTexImage1D +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D; +#define glCompressedTexSubImage3D glad_glCompressedTexSubImage3D +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D; +#define glCompressedTexSubImage2D glad_glCompressedTexSubImage2D +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D; +#define glCompressedTexSubImage1D glad_glCompressedTexSubImage1D +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC)(GLenum target, GLint level, void *img); +GLAPI PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage; +#define glGetCompressedTexImage glad_glGetCompressedTexImage +#endif +#ifndef GL_VERSION_1_4 +#define GL_VERSION_1_4 1 +GLAPI int GLAD_GL_VERSION_1_4; +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC)(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +GLAPI PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate; +#define glBlendFuncSeparate glad_glBlendFuncSeparate +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC)(GLenum mode, const GLint *first, const GLsizei *count, GLsizei drawcount); +GLAPI PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays; +#define glMultiDrawArrays glad_glMultiDrawArrays +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC)(GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount); +GLAPI PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements; +#define glMultiDrawElements glad_glMultiDrawElements +typedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC)(GLenum pname, GLfloat param); +GLAPI PFNGLPOINTPARAMETERFPROC glad_glPointParameterf; +#define glPointParameterf glad_glPointParameterf +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC)(GLenum pname, const GLfloat *params); +GLAPI PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv; +#define glPointParameterfv glad_glPointParameterfv +typedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC)(GLenum pname, GLint param); +GLAPI PFNGLPOINTPARAMETERIPROC glad_glPointParameteri; +#define glPointParameteri glad_glPointParameteri +typedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC)(GLenum pname, const GLint *params); +GLAPI PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv; +#define glPointParameteriv glad_glPointParameteriv +typedef void (APIENTRYP PFNGLBLENDCOLORPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +GLAPI PFNGLBLENDCOLORPROC glad_glBlendColor; +#define glBlendColor glad_glBlendColor +typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC)(GLenum mode); +GLAPI PFNGLBLENDEQUATIONPROC glad_glBlendEquation; +#define glBlendEquation glad_glBlendEquation +#endif +#ifndef GL_VERSION_1_5 +#define GL_VERSION_1_5 1 +GLAPI int GLAD_GL_VERSION_1_5; +typedef void (APIENTRYP PFNGLGENQUERIESPROC)(GLsizei n, GLuint *ids); +GLAPI PFNGLGENQUERIESPROC glad_glGenQueries; +#define glGenQueries glad_glGenQueries +typedef void (APIENTRYP PFNGLDELETEQUERIESPROC)(GLsizei n, const GLuint *ids); +GLAPI PFNGLDELETEQUERIESPROC glad_glDeleteQueries; +#define glDeleteQueries glad_glDeleteQueries +typedef GLboolean (APIENTRYP PFNGLISQUERYPROC)(GLuint id); +GLAPI PFNGLISQUERYPROC glad_glIsQuery; +#define glIsQuery glad_glIsQuery +typedef void (APIENTRYP PFNGLBEGINQUERYPROC)(GLenum target, GLuint id); +GLAPI PFNGLBEGINQUERYPROC glad_glBeginQuery; +#define glBeginQuery glad_glBeginQuery +typedef void (APIENTRYP PFNGLENDQUERYPROC)(GLenum target); +GLAPI PFNGLENDQUERYPROC glad_glEndQuery; +#define glEndQuery glad_glEndQuery +typedef void (APIENTRYP PFNGLGETQUERYIVPROC)(GLenum target, GLenum pname, GLint *params); +GLAPI PFNGLGETQUERYIVPROC glad_glGetQueryiv; +#define glGetQueryiv glad_glGetQueryiv +typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC)(GLuint id, GLenum pname, GLint *params); +GLAPI PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv; +#define glGetQueryObjectiv glad_glGetQueryObjectiv +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC)(GLuint id, GLenum pname, GLuint *params); +GLAPI PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv; +#define glGetQueryObjectuiv glad_glGetQueryObjectuiv +typedef void (APIENTRYP PFNGLBINDBUFFERPROC)(GLenum target, GLuint buffer); +GLAPI PFNGLBINDBUFFERPROC glad_glBindBuffer; +#define glBindBuffer glad_glBindBuffer +typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC)(GLsizei n, const GLuint *buffers); +GLAPI PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers; +#define glDeleteBuffers glad_glDeleteBuffers +typedef void (APIENTRYP PFNGLGENBUFFERSPROC)(GLsizei n, GLuint *buffers); +GLAPI PFNGLGENBUFFERSPROC glad_glGenBuffers; +#define glGenBuffers glad_glGenBuffers +typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC)(GLuint buffer); +GLAPI PFNGLISBUFFERPROC glad_glIsBuffer; +#define glIsBuffer glad_glIsBuffer +typedef void (APIENTRYP PFNGLBUFFERDATAPROC)(GLenum target, GLsizeiptr size, const void *data, GLenum usage); +GLAPI PFNGLBUFFERDATAPROC glad_glBufferData; +#define glBufferData glad_glBufferData +typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC)(GLenum target, GLintptr offset, GLsizeiptr size, const void *data); +GLAPI PFNGLBUFFERSUBDATAPROC glad_glBufferSubData; +#define glBufferSubData glad_glBufferSubData +typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC)(GLenum target, GLintptr offset, GLsizeiptr size, void *data); +GLAPI PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData; +#define glGetBufferSubData glad_glGetBufferSubData +typedef void * (APIENTRYP PFNGLMAPBUFFERPROC)(GLenum target, GLenum access); +GLAPI PFNGLMAPBUFFERPROC glad_glMapBuffer; +#define glMapBuffer glad_glMapBuffer +typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC)(GLenum target); +GLAPI PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer; +#define glUnmapBuffer glad_glUnmapBuffer +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); +GLAPI PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv; +#define glGetBufferParameteriv glad_glGetBufferParameteriv +typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC)(GLenum target, GLenum pname, void **params); +GLAPI PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv; +#define glGetBufferPointerv glad_glGetBufferPointerv +#endif +#ifndef GL_VERSION_2_0 +#define GL_VERSION_2_0 1 +GLAPI int GLAD_GL_VERSION_2_0; +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC)(GLenum modeRGB, GLenum modeAlpha); +GLAPI PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate; +#define glBlendEquationSeparate glad_glBlendEquationSeparate +typedef void (APIENTRYP PFNGLDRAWBUFFERSPROC)(GLsizei n, const GLenum *bufs); +GLAPI PFNGLDRAWBUFFERSPROC glad_glDrawBuffers; +#define glDrawBuffers glad_glDrawBuffers +typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC)(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +GLAPI PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate; +#define glStencilOpSeparate glad_glStencilOpSeparate +typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC)(GLenum face, GLenum func, GLint ref, GLuint mask); +GLAPI PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate; +#define glStencilFuncSeparate glad_glStencilFuncSeparate +typedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC)(GLenum face, GLuint mask); +GLAPI PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate; +#define glStencilMaskSeparate glad_glStencilMaskSeparate +typedef void (APIENTRYP PFNGLATTACHSHADERPROC)(GLuint program, GLuint shader); +GLAPI PFNGLATTACHSHADERPROC glad_glAttachShader; +#define glAttachShader glad_glAttachShader +typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC)(GLuint program, GLuint index, const GLchar *name); +GLAPI PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation; +#define glBindAttribLocation glad_glBindAttribLocation +typedef void (APIENTRYP PFNGLCOMPILESHADERPROC)(GLuint shader); +GLAPI PFNGLCOMPILESHADERPROC glad_glCompileShader; +#define glCompileShader glad_glCompileShader +typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC)(); +GLAPI PFNGLCREATEPROGRAMPROC glad_glCreateProgram; +#define glCreateProgram glad_glCreateProgram +typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC)(GLenum type); +GLAPI PFNGLCREATESHADERPROC glad_glCreateShader; +#define glCreateShader glad_glCreateShader +typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC)(GLuint program); +GLAPI PFNGLDELETEPROGRAMPROC glad_glDeleteProgram; +#define glDeleteProgram glad_glDeleteProgram +typedef void (APIENTRYP PFNGLDELETESHADERPROC)(GLuint shader); +GLAPI PFNGLDELETESHADERPROC glad_glDeleteShader; +#define glDeleteShader glad_glDeleteShader +typedef void (APIENTRYP PFNGLDETACHSHADERPROC)(GLuint program, GLuint shader); +GLAPI PFNGLDETACHSHADERPROC glad_glDetachShader; +#define glDetachShader glad_glDetachShader +typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC)(GLuint index); +GLAPI PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray; +#define glDisableVertexAttribArray glad_glDisableVertexAttribArray +typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC)(GLuint index); +GLAPI PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray; +#define glEnableVertexAttribArray glad_glEnableVertexAttribArray +typedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +GLAPI PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib; +#define glGetActiveAttrib glad_glGetActiveAttrib +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +GLAPI PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform; +#define glGetActiveUniform glad_glGetActiveUniform +typedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC)(GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); +GLAPI PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders; +#define glGetAttachedShaders glad_glGetAttachedShaders +typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC)(GLuint program, const GLchar *name); +GLAPI PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation; +#define glGetAttribLocation glad_glGetAttribLocation +typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC)(GLuint program, GLenum pname, GLint *params); +GLAPI PFNGLGETPROGRAMIVPROC glad_glGetProgramiv; +#define glGetProgramiv glad_glGetProgramiv +typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC)(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GLAPI PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog; +#define glGetProgramInfoLog glad_glGetProgramInfoLog +typedef void (APIENTRYP PFNGLGETSHADERIVPROC)(GLuint shader, GLenum pname, GLint *params); +GLAPI PFNGLGETSHADERIVPROC glad_glGetShaderiv; +#define glGetShaderiv glad_glGetShaderiv +typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GLAPI PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog; +#define glGetShaderInfoLog glad_glGetShaderInfoLog +typedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); +GLAPI PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource; +#define glGetShaderSource glad_glGetShaderSource +typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC)(GLuint program, const GLchar *name); +GLAPI PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation; +#define glGetUniformLocation glad_glGetUniformLocation +typedef void (APIENTRYP PFNGLGETUNIFORMFVPROC)(GLuint program, GLint location, GLfloat *params); +GLAPI PFNGLGETUNIFORMFVPROC glad_glGetUniformfv; +#define glGetUniformfv glad_glGetUniformfv +typedef void (APIENTRYP PFNGLGETUNIFORMIVPROC)(GLuint program, GLint location, GLint *params); +GLAPI PFNGLGETUNIFORMIVPROC glad_glGetUniformiv; +#define glGetUniformiv glad_glGetUniformiv +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC)(GLuint index, GLenum pname, GLdouble *params); +GLAPI PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv; +#define glGetVertexAttribdv glad_glGetVertexAttribdv +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC)(GLuint index, GLenum pname, GLfloat *params); +GLAPI PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv; +#define glGetVertexAttribfv glad_glGetVertexAttribfv +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC)(GLuint index, GLenum pname, GLint *params); +GLAPI PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv; +#define glGetVertexAttribiv glad_glGetVertexAttribiv +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC)(GLuint index, GLenum pname, void **pointer); +GLAPI PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv; +#define glGetVertexAttribPointerv glad_glGetVertexAttribPointerv +typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC)(GLuint program); +GLAPI PFNGLISPROGRAMPROC glad_glIsProgram; +#define glIsProgram glad_glIsProgram +typedef GLboolean (APIENTRYP PFNGLISSHADERPROC)(GLuint shader); +GLAPI PFNGLISSHADERPROC glad_glIsShader; +#define glIsShader glad_glIsShader +typedef void (APIENTRYP PFNGLLINKPROGRAMPROC)(GLuint program); +GLAPI PFNGLLINKPROGRAMPROC glad_glLinkProgram; +#define glLinkProgram glad_glLinkProgram +typedef void (APIENTRYP PFNGLSHADERSOURCEPROC)(GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); +GLAPI PFNGLSHADERSOURCEPROC glad_glShaderSource; +#define glShaderSource glad_glShaderSource +typedef void (APIENTRYP PFNGLUSEPROGRAMPROC)(GLuint program); +GLAPI PFNGLUSEPROGRAMPROC glad_glUseProgram; +#define glUseProgram glad_glUseProgram +typedef void (APIENTRYP PFNGLUNIFORM1FPROC)(GLint location, GLfloat v0); +GLAPI PFNGLUNIFORM1FPROC glad_glUniform1f; +#define glUniform1f glad_glUniform1f +typedef void (APIENTRYP PFNGLUNIFORM2FPROC)(GLint location, GLfloat v0, GLfloat v1); +GLAPI PFNGLUNIFORM2FPROC glad_glUniform2f; +#define glUniform2f glad_glUniform2f +typedef void (APIENTRYP PFNGLUNIFORM3FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +GLAPI PFNGLUNIFORM3FPROC glad_glUniform3f; +#define glUniform3f glad_glUniform3f +typedef void (APIENTRYP PFNGLUNIFORM4FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +GLAPI PFNGLUNIFORM4FPROC glad_glUniform4f; +#define glUniform4f glad_glUniform4f +typedef void (APIENTRYP PFNGLUNIFORM1IPROC)(GLint location, GLint v0); +GLAPI PFNGLUNIFORM1IPROC glad_glUniform1i; +#define glUniform1i glad_glUniform1i +typedef void (APIENTRYP PFNGLUNIFORM2IPROC)(GLint location, GLint v0, GLint v1); +GLAPI PFNGLUNIFORM2IPROC glad_glUniform2i; +#define glUniform2i glad_glUniform2i +typedef void (APIENTRYP PFNGLUNIFORM3IPROC)(GLint location, GLint v0, GLint v1, GLint v2); +GLAPI PFNGLUNIFORM3IPROC glad_glUniform3i; +#define glUniform3i glad_glUniform3i +typedef void (APIENTRYP PFNGLUNIFORM4IPROC)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +GLAPI PFNGLUNIFORM4IPROC glad_glUniform4i; +#define glUniform4i glad_glUniform4i +typedef void (APIENTRYP PFNGLUNIFORM1FVPROC)(GLint location, GLsizei count, const GLfloat *value); +GLAPI PFNGLUNIFORM1FVPROC glad_glUniform1fv; +#define glUniform1fv glad_glUniform1fv +typedef void (APIENTRYP PFNGLUNIFORM2FVPROC)(GLint location, GLsizei count, const GLfloat *value); +GLAPI PFNGLUNIFORM2FVPROC glad_glUniform2fv; +#define glUniform2fv glad_glUniform2fv +typedef void (APIENTRYP PFNGLUNIFORM3FVPROC)(GLint location, GLsizei count, const GLfloat *value); +GLAPI PFNGLUNIFORM3FVPROC glad_glUniform3fv; +#define glUniform3fv glad_glUniform3fv +typedef void (APIENTRYP PFNGLUNIFORM4FVPROC)(GLint location, GLsizei count, const GLfloat *value); +GLAPI PFNGLUNIFORM4FVPROC glad_glUniform4fv; +#define glUniform4fv glad_glUniform4fv +typedef void (APIENTRYP PFNGLUNIFORM1IVPROC)(GLint location, GLsizei count, const GLint *value); +GLAPI PFNGLUNIFORM1IVPROC glad_glUniform1iv; +#define glUniform1iv glad_glUniform1iv +typedef void (APIENTRYP PFNGLUNIFORM2IVPROC)(GLint location, GLsizei count, const GLint *value); +GLAPI PFNGLUNIFORM2IVPROC glad_glUniform2iv; +#define glUniform2iv glad_glUniform2iv +typedef void (APIENTRYP PFNGLUNIFORM3IVPROC)(GLint location, GLsizei count, const GLint *value); +GLAPI PFNGLUNIFORM3IVPROC glad_glUniform3iv; +#define glUniform3iv glad_glUniform3iv +typedef void (APIENTRYP PFNGLUNIFORM4IVPROC)(GLint location, GLsizei count, const GLint *value); +GLAPI PFNGLUNIFORM4IVPROC glad_glUniform4iv; +#define glUniform4iv glad_glUniform4iv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv; +#define glUniformMatrix2fv glad_glUniformMatrix2fv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv; +#define glUniformMatrix3fv glad_glUniformMatrix3fv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv; +#define glUniformMatrix4fv glad_glUniformMatrix4fv +typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC)(GLuint program); +GLAPI PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram; +#define glValidateProgram glad_glValidateProgram +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC)(GLuint index, GLdouble x); +GLAPI PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d; +#define glVertexAttrib1d glad_glVertexAttrib1d +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC)(GLuint index, const GLdouble *v); +GLAPI PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv; +#define glVertexAttrib1dv glad_glVertexAttrib1dv +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC)(GLuint index, GLfloat x); +GLAPI PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f; +#define glVertexAttrib1f glad_glVertexAttrib1f +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC)(GLuint index, const GLfloat *v); +GLAPI PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv; +#define glVertexAttrib1fv glad_glVertexAttrib1fv +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC)(GLuint index, GLshort x); +GLAPI PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s; +#define glVertexAttrib1s glad_glVertexAttrib1s +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC)(GLuint index, const GLshort *v); +GLAPI PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv; +#define glVertexAttrib1sv glad_glVertexAttrib1sv +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC)(GLuint index, GLdouble x, GLdouble y); +GLAPI PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d; +#define glVertexAttrib2d glad_glVertexAttrib2d +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC)(GLuint index, const GLdouble *v); +GLAPI PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv; +#define glVertexAttrib2dv glad_glVertexAttrib2dv +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC)(GLuint index, GLfloat x, GLfloat y); +GLAPI PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f; +#define glVertexAttrib2f glad_glVertexAttrib2f +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC)(GLuint index, const GLfloat *v); +GLAPI PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv; +#define glVertexAttrib2fv glad_glVertexAttrib2fv +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC)(GLuint index, GLshort x, GLshort y); +GLAPI PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s; +#define glVertexAttrib2s glad_glVertexAttrib2s +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC)(GLuint index, const GLshort *v); +GLAPI PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv; +#define glVertexAttrib2sv glad_glVertexAttrib2sv +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d; +#define glVertexAttrib3d glad_glVertexAttrib3d +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC)(GLuint index, const GLdouble *v); +GLAPI PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv; +#define glVertexAttrib3dv glad_glVertexAttrib3dv +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z); +GLAPI PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f; +#define glVertexAttrib3f glad_glVertexAttrib3f +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC)(GLuint index, const GLfloat *v); +GLAPI PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv; +#define glVertexAttrib3fv glad_glVertexAttrib3fv +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC)(GLuint index, GLshort x, GLshort y, GLshort z); +GLAPI PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s; +#define glVertexAttrib3s glad_glVertexAttrib3s +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC)(GLuint index, const GLshort *v); +GLAPI PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv; +#define glVertexAttrib3sv glad_glVertexAttrib3sv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC)(GLuint index, const GLbyte *v); +GLAPI PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv; +#define glVertexAttrib4Nbv glad_glVertexAttrib4Nbv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC)(GLuint index, const GLint *v); +GLAPI PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv; +#define glVertexAttrib4Niv glad_glVertexAttrib4Niv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC)(GLuint index, const GLshort *v); +GLAPI PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv; +#define glVertexAttrib4Nsv glad_glVertexAttrib4Nsv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +GLAPI PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub; +#define glVertexAttrib4Nub glad_glVertexAttrib4Nub +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC)(GLuint index, const GLubyte *v); +GLAPI PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv; +#define glVertexAttrib4Nubv glad_glVertexAttrib4Nubv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC)(GLuint index, const GLuint *v); +GLAPI PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv; +#define glVertexAttrib4Nuiv glad_glVertexAttrib4Nuiv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC)(GLuint index, const GLushort *v); +GLAPI PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv; +#define glVertexAttrib4Nusv glad_glVertexAttrib4Nusv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC)(GLuint index, const GLbyte *v); +GLAPI PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv; +#define glVertexAttrib4bv glad_glVertexAttrib4bv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d; +#define glVertexAttrib4d glad_glVertexAttrib4d +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC)(GLuint index, const GLdouble *v); +GLAPI PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv; +#define glVertexAttrib4dv glad_glVertexAttrib4dv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f; +#define glVertexAttrib4f glad_glVertexAttrib4f +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC)(GLuint index, const GLfloat *v); +GLAPI PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv; +#define glVertexAttrib4fv glad_glVertexAttrib4fv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC)(GLuint index, const GLint *v); +GLAPI PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv; +#define glVertexAttrib4iv glad_glVertexAttrib4iv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC)(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s; +#define glVertexAttrib4s glad_glVertexAttrib4s +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC)(GLuint index, const GLshort *v); +GLAPI PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv; +#define glVertexAttrib4sv glad_glVertexAttrib4sv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC)(GLuint index, const GLubyte *v); +GLAPI PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv; +#define glVertexAttrib4ubv glad_glVertexAttrib4ubv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC)(GLuint index, const GLuint *v); +GLAPI PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv; +#define glVertexAttrib4uiv glad_glVertexAttrib4uiv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC)(GLuint index, const GLushort *v); +GLAPI PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv; +#define glVertexAttrib4usv glad_glVertexAttrib4usv +typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +GLAPI PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer; +#define glVertexAttribPointer glad_glVertexAttribPointer +#endif +#ifndef GL_VERSION_2_1 +#define GL_VERSION_2_1 1 +GLAPI int GLAD_GL_VERSION_2_1; +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX2X3FVPROC glad_glUniformMatrix2x3fv; +#define glUniformMatrix2x3fv glad_glUniformMatrix2x3fv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX3X2FVPROC glad_glUniformMatrix3x2fv; +#define glUniformMatrix3x2fv glad_glUniformMatrix3x2fv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX2X4FVPROC glad_glUniformMatrix2x4fv; +#define glUniformMatrix2x4fv glad_glUniformMatrix2x4fv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX4X2FVPROC glad_glUniformMatrix4x2fv; +#define glUniformMatrix4x2fv glad_glUniformMatrix4x2fv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX3X4FVPROC glad_glUniformMatrix3x4fv; +#define glUniformMatrix3x4fv glad_glUniformMatrix3x4fv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX4X3FVPROC glad_glUniformMatrix4x3fv; +#define glUniformMatrix4x3fv glad_glUniformMatrix4x3fv +#endif +#ifndef GL_VERSION_3_0 +#define GL_VERSION_3_0 1 +GLAPI int GLAD_GL_VERSION_3_0; +typedef void (APIENTRYP PFNGLCOLORMASKIPROC)(GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +GLAPI PFNGLCOLORMASKIPROC glad_glColorMaski; +#define glColorMaski glad_glColorMaski +typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC)(GLenum target, GLuint index, GLboolean *data); +GLAPI PFNGLGETBOOLEANI_VPROC glad_glGetBooleani_v; +#define glGetBooleani_v glad_glGetBooleani_v +typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC)(GLenum target, GLuint index, GLint *data); +GLAPI PFNGLGETINTEGERI_VPROC glad_glGetIntegeri_v; +#define glGetIntegeri_v glad_glGetIntegeri_v +typedef void (APIENTRYP PFNGLENABLEIPROC)(GLenum target, GLuint index); +GLAPI PFNGLENABLEIPROC glad_glEnablei; +#define glEnablei glad_glEnablei +typedef void (APIENTRYP PFNGLDISABLEIPROC)(GLenum target, GLuint index); +GLAPI PFNGLDISABLEIPROC glad_glDisablei; +#define glDisablei glad_glDisablei +typedef GLboolean (APIENTRYP PFNGLISENABLEDIPROC)(GLenum target, GLuint index); +GLAPI PFNGLISENABLEDIPROC glad_glIsEnabledi; +#define glIsEnabledi glad_glIsEnabledi +typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKPROC)(GLenum primitiveMode); +GLAPI PFNGLBEGINTRANSFORMFEEDBACKPROC glad_glBeginTransformFeedback; +#define glBeginTransformFeedback glad_glBeginTransformFeedback +typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKPROC)(); +GLAPI PFNGLENDTRANSFORMFEEDBACKPROC glad_glEndTransformFeedback; +#define glEndTransformFeedback glad_glEndTransformFeedback +typedef void (APIENTRYP PFNGLBINDBUFFERRANGEPROC)(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI PFNGLBINDBUFFERRANGEPROC glad_glBindBufferRange; +#define glBindBufferRange glad_glBindBufferRange +typedef void (APIENTRYP PFNGLBINDBUFFERBASEPROC)(GLenum target, GLuint index, GLuint buffer); +GLAPI PFNGLBINDBUFFERBASEPROC glad_glBindBufferBase; +#define glBindBufferBase glad_glBindBufferBase +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSPROC)(GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); +GLAPI PFNGLTRANSFORMFEEDBACKVARYINGSPROC glad_glTransformFeedbackVaryings; +#define glTransformFeedbackVaryings glad_glTransformFeedbackVaryings +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +GLAPI PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glad_glGetTransformFeedbackVarying; +#define glGetTransformFeedbackVarying glad_glGetTransformFeedbackVarying +typedef void (APIENTRYP PFNGLCLAMPCOLORPROC)(GLenum target, GLenum clamp); +GLAPI PFNGLCLAMPCOLORPROC glad_glClampColor; +#define glClampColor glad_glClampColor +typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERPROC)(GLuint id, GLenum mode); +GLAPI PFNGLBEGINCONDITIONALRENDERPROC glad_glBeginConditionalRender; +#define glBeginConditionalRender glad_glBeginConditionalRender +typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERPROC)(); +GLAPI PFNGLENDCONDITIONALRENDERPROC glad_glEndConditionalRender; +#define glEndConditionalRender glad_glEndConditionalRender +typedef void (APIENTRYP PFNGLVERTEXATTRIBIPOINTERPROC)(GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI PFNGLVERTEXATTRIBIPOINTERPROC glad_glVertexAttribIPointer; +#define glVertexAttribIPointer glad_glVertexAttribIPointer +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIIVPROC)(GLuint index, GLenum pname, GLint *params); +GLAPI PFNGLGETVERTEXATTRIBIIVPROC glad_glGetVertexAttribIiv; +#define glGetVertexAttribIiv glad_glGetVertexAttribIiv +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIUIVPROC)(GLuint index, GLenum pname, GLuint *params); +GLAPI PFNGLGETVERTEXATTRIBIUIVPROC glad_glGetVertexAttribIuiv; +#define glGetVertexAttribIuiv glad_glGetVertexAttribIuiv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IPROC)(GLuint index, GLint x); +GLAPI PFNGLVERTEXATTRIBI1IPROC glad_glVertexAttribI1i; +#define glVertexAttribI1i glad_glVertexAttribI1i +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IPROC)(GLuint index, GLint x, GLint y); +GLAPI PFNGLVERTEXATTRIBI2IPROC glad_glVertexAttribI2i; +#define glVertexAttribI2i glad_glVertexAttribI2i +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IPROC)(GLuint index, GLint x, GLint y, GLint z); +GLAPI PFNGLVERTEXATTRIBI3IPROC glad_glVertexAttribI3i; +#define glVertexAttribI3i glad_glVertexAttribI3i +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IPROC)(GLuint index, GLint x, GLint y, GLint z, GLint w); +GLAPI PFNGLVERTEXATTRIBI4IPROC glad_glVertexAttribI4i; +#define glVertexAttribI4i glad_glVertexAttribI4i +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIPROC)(GLuint index, GLuint x); +GLAPI PFNGLVERTEXATTRIBI1UIPROC glad_glVertexAttribI1ui; +#define glVertexAttribI1ui glad_glVertexAttribI1ui +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIPROC)(GLuint index, GLuint x, GLuint y); +GLAPI PFNGLVERTEXATTRIBI2UIPROC glad_glVertexAttribI2ui; +#define glVertexAttribI2ui glad_glVertexAttribI2ui +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIPROC)(GLuint index, GLuint x, GLuint y, GLuint z); +GLAPI PFNGLVERTEXATTRIBI3UIPROC glad_glVertexAttribI3ui; +#define glVertexAttribI3ui glad_glVertexAttribI3ui +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIPROC)(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +GLAPI PFNGLVERTEXATTRIBI4UIPROC glad_glVertexAttribI4ui; +#define glVertexAttribI4ui glad_glVertexAttribI4ui +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IVPROC)(GLuint index, const GLint *v); +GLAPI PFNGLVERTEXATTRIBI1IVPROC glad_glVertexAttribI1iv; +#define glVertexAttribI1iv glad_glVertexAttribI1iv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IVPROC)(GLuint index, const GLint *v); +GLAPI PFNGLVERTEXATTRIBI2IVPROC glad_glVertexAttribI2iv; +#define glVertexAttribI2iv glad_glVertexAttribI2iv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IVPROC)(GLuint index, const GLint *v); +GLAPI PFNGLVERTEXATTRIBI3IVPROC glad_glVertexAttribI3iv; +#define glVertexAttribI3iv glad_glVertexAttribI3iv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IVPROC)(GLuint index, const GLint *v); +GLAPI PFNGLVERTEXATTRIBI4IVPROC glad_glVertexAttribI4iv; +#define glVertexAttribI4iv glad_glVertexAttribI4iv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIVPROC)(GLuint index, const GLuint *v); +GLAPI PFNGLVERTEXATTRIBI1UIVPROC glad_glVertexAttribI1uiv; +#define glVertexAttribI1uiv glad_glVertexAttribI1uiv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIVPROC)(GLuint index, const GLuint *v); +GLAPI PFNGLVERTEXATTRIBI2UIVPROC glad_glVertexAttribI2uiv; +#define glVertexAttribI2uiv glad_glVertexAttribI2uiv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIVPROC)(GLuint index, const GLuint *v); +GLAPI PFNGLVERTEXATTRIBI3UIVPROC glad_glVertexAttribI3uiv; +#define glVertexAttribI3uiv glad_glVertexAttribI3uiv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIVPROC)(GLuint index, const GLuint *v); +GLAPI PFNGLVERTEXATTRIBI4UIVPROC glad_glVertexAttribI4uiv; +#define glVertexAttribI4uiv glad_glVertexAttribI4uiv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4BVPROC)(GLuint index, const GLbyte *v); +GLAPI PFNGLVERTEXATTRIBI4BVPROC glad_glVertexAttribI4bv; +#define glVertexAttribI4bv glad_glVertexAttribI4bv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4SVPROC)(GLuint index, const GLshort *v); +GLAPI PFNGLVERTEXATTRIBI4SVPROC glad_glVertexAttribI4sv; +#define glVertexAttribI4sv glad_glVertexAttribI4sv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UBVPROC)(GLuint index, const GLubyte *v); +GLAPI PFNGLVERTEXATTRIBI4UBVPROC glad_glVertexAttribI4ubv; +#define glVertexAttribI4ubv glad_glVertexAttribI4ubv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4USVPROC)(GLuint index, const GLushort *v); +GLAPI PFNGLVERTEXATTRIBI4USVPROC glad_glVertexAttribI4usv; +#define glVertexAttribI4usv glad_glVertexAttribI4usv +typedef void (APIENTRYP PFNGLGETUNIFORMUIVPROC)(GLuint program, GLint location, GLuint *params); +GLAPI PFNGLGETUNIFORMUIVPROC glad_glGetUniformuiv; +#define glGetUniformuiv glad_glGetUniformuiv +typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONPROC)(GLuint program, GLuint color, const GLchar *name); +GLAPI PFNGLBINDFRAGDATALOCATIONPROC glad_glBindFragDataLocation; +#define glBindFragDataLocation glad_glBindFragDataLocation +typedef GLint (APIENTRYP PFNGLGETFRAGDATALOCATIONPROC)(GLuint program, const GLchar *name); +GLAPI PFNGLGETFRAGDATALOCATIONPROC glad_glGetFragDataLocation; +#define glGetFragDataLocation glad_glGetFragDataLocation +typedef void (APIENTRYP PFNGLUNIFORM1UIPROC)(GLint location, GLuint v0); +GLAPI PFNGLUNIFORM1UIPROC glad_glUniform1ui; +#define glUniform1ui glad_glUniform1ui +typedef void (APIENTRYP PFNGLUNIFORM2UIPROC)(GLint location, GLuint v0, GLuint v1); +GLAPI PFNGLUNIFORM2UIPROC glad_glUniform2ui; +#define glUniform2ui glad_glUniform2ui +typedef void (APIENTRYP PFNGLUNIFORM3UIPROC)(GLint location, GLuint v0, GLuint v1, GLuint v2); +GLAPI PFNGLUNIFORM3UIPROC glad_glUniform3ui; +#define glUniform3ui glad_glUniform3ui +typedef void (APIENTRYP PFNGLUNIFORM4UIPROC)(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +GLAPI PFNGLUNIFORM4UIPROC glad_glUniform4ui; +#define glUniform4ui glad_glUniform4ui +typedef void (APIENTRYP PFNGLUNIFORM1UIVPROC)(GLint location, GLsizei count, const GLuint *value); +GLAPI PFNGLUNIFORM1UIVPROC glad_glUniform1uiv; +#define glUniform1uiv glad_glUniform1uiv +typedef void (APIENTRYP PFNGLUNIFORM2UIVPROC)(GLint location, GLsizei count, const GLuint *value); +GLAPI PFNGLUNIFORM2UIVPROC glad_glUniform2uiv; +#define glUniform2uiv glad_glUniform2uiv +typedef void (APIENTRYP PFNGLUNIFORM3UIVPROC)(GLint location, GLsizei count, const GLuint *value); +GLAPI PFNGLUNIFORM3UIVPROC glad_glUniform3uiv; +#define glUniform3uiv glad_glUniform3uiv +typedef void (APIENTRYP PFNGLUNIFORM4UIVPROC)(GLint location, GLsizei count, const GLuint *value); +GLAPI PFNGLUNIFORM4UIVPROC glad_glUniform4uiv; +#define glUniform4uiv glad_glUniform4uiv +typedef void (APIENTRYP PFNGLTEXPARAMETERIIVPROC)(GLenum target, GLenum pname, const GLint *params); +GLAPI PFNGLTEXPARAMETERIIVPROC glad_glTexParameterIiv; +#define glTexParameterIiv glad_glTexParameterIiv +typedef void (APIENTRYP PFNGLTEXPARAMETERIUIVPROC)(GLenum target, GLenum pname, const GLuint *params); +GLAPI PFNGLTEXPARAMETERIUIVPROC glad_glTexParameterIuiv; +#define glTexParameterIuiv glad_glTexParameterIuiv +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIIVPROC)(GLenum target, GLenum pname, GLint *params); +GLAPI PFNGLGETTEXPARAMETERIIVPROC glad_glGetTexParameterIiv; +#define glGetTexParameterIiv glad_glGetTexParameterIiv +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIUIVPROC)(GLenum target, GLenum pname, GLuint *params); +GLAPI PFNGLGETTEXPARAMETERIUIVPROC glad_glGetTexParameterIuiv; +#define glGetTexParameterIuiv glad_glGetTexParameterIuiv +typedef void (APIENTRYP PFNGLCLEARBUFFERIVPROC)(GLenum buffer, GLint drawbuffer, const GLint *value); +GLAPI PFNGLCLEARBUFFERIVPROC glad_glClearBufferiv; +#define glClearBufferiv glad_glClearBufferiv +typedef void (APIENTRYP PFNGLCLEARBUFFERUIVPROC)(GLenum buffer, GLint drawbuffer, const GLuint *value); +GLAPI PFNGLCLEARBUFFERUIVPROC glad_glClearBufferuiv; +#define glClearBufferuiv glad_glClearBufferuiv +typedef void (APIENTRYP PFNGLCLEARBUFFERFVPROC)(GLenum buffer, GLint drawbuffer, const GLfloat *value); +GLAPI PFNGLCLEARBUFFERFVPROC glad_glClearBufferfv; +#define glClearBufferfv glad_glClearBufferfv +typedef void (APIENTRYP PFNGLCLEARBUFFERFIPROC)(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); +GLAPI PFNGLCLEARBUFFERFIPROC glad_glClearBufferfi; +#define glClearBufferfi glad_glClearBufferfi +typedef const GLubyte * (APIENTRYP PFNGLGETSTRINGIPROC)(GLenum name, GLuint index); +GLAPI PFNGLGETSTRINGIPROC glad_glGetStringi; +#define glGetStringi glad_glGetStringi +typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFERPROC)(GLuint renderbuffer); +GLAPI PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer; +#define glIsRenderbuffer glad_glIsRenderbuffer +typedef void (APIENTRYP PFNGLBINDRENDERBUFFERPROC)(GLenum target, GLuint renderbuffer); +GLAPI PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer; +#define glBindRenderbuffer glad_glBindRenderbuffer +typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSPROC)(GLsizei n, const GLuint *renderbuffers); +GLAPI PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers; +#define glDeleteRenderbuffers glad_glDeleteRenderbuffers +typedef void (APIENTRYP PFNGLGENRENDERBUFFERSPROC)(GLsizei n, GLuint *renderbuffers); +GLAPI PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers; +#define glGenRenderbuffers glad_glGenRenderbuffers +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEPROC)(GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage; +#define glRenderbufferStorage glad_glRenderbufferStorage +typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); +GLAPI PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv; +#define glGetRenderbufferParameteriv glad_glGetRenderbufferParameteriv +typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFERPROC)(GLuint framebuffer); +GLAPI PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer; +#define glIsFramebuffer glad_glIsFramebuffer +typedef void (APIENTRYP PFNGLBINDFRAMEBUFFERPROC)(GLenum target, GLuint framebuffer); +GLAPI PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer; +#define glBindFramebuffer glad_glBindFramebuffer +typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSPROC)(GLsizei n, const GLuint *framebuffers); +GLAPI PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers; +#define glDeleteFramebuffers glad_glDeleteFramebuffers +typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSPROC)(GLsizei n, GLuint *framebuffers); +GLAPI PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers; +#define glGenFramebuffers glad_glGenFramebuffers +typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSPROC)(GLenum target); +GLAPI PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus; +#define glCheckFramebufferStatus glad_glCheckFramebufferStatus +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI PFNGLFRAMEBUFFERTEXTURE1DPROC glad_glFramebufferTexture1D; +#define glFramebufferTexture1D glad_glFramebufferTexture1D +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D; +#define glFramebufferTexture2D glad_glFramebufferTexture2D +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +GLAPI PFNGLFRAMEBUFFERTEXTURE3DPROC glad_glFramebufferTexture3D; +#define glFramebufferTexture3D glad_glFramebufferTexture3D +typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFERPROC)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +GLAPI PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer; +#define glFramebufferRenderbuffer glad_glFramebufferRenderbuffer +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)(GLenum target, GLenum attachment, GLenum pname, GLint *params); +GLAPI PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv; +#define glGetFramebufferAttachmentParameteriv glad_glGetFramebufferAttachmentParameteriv +typedef void (APIENTRYP PFNGLGENERATEMIPMAPPROC)(GLenum target); +GLAPI PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap; +#define glGenerateMipmap glad_glGenerateMipmap +typedef void (APIENTRYP PFNGLBLITFRAMEBUFFERPROC)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +GLAPI PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer; +#define glBlitFramebuffer glad_glBlitFramebuffer +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glRenderbufferStorageMultisample; +#define glRenderbufferStorageMultisample glad_glRenderbufferStorageMultisample +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +GLAPI PFNGLFRAMEBUFFERTEXTURELAYERPROC glad_glFramebufferTextureLayer; +#define glFramebufferTextureLayer glad_glFramebufferTextureLayer +typedef void * (APIENTRYP PFNGLMAPBUFFERRANGEPROC)(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); +GLAPI PFNGLMAPBUFFERRANGEPROC glad_glMapBufferRange; +#define glMapBufferRange glad_glMapBufferRange +typedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEPROC)(GLenum target, GLintptr offset, GLsizeiptr length); +GLAPI PFNGLFLUSHMAPPEDBUFFERRANGEPROC glad_glFlushMappedBufferRange; +#define glFlushMappedBufferRange glad_glFlushMappedBufferRange +typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC)(GLuint array); +GLAPI PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray; +#define glBindVertexArray glad_glBindVertexArray +typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC)(GLsizei n, const GLuint *arrays); +GLAPI PFNGLDELETEVERTEXARRAYSPROC glad_glDeleteVertexArrays; +#define glDeleteVertexArrays glad_glDeleteVertexArrays +typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC)(GLsizei n, GLuint *arrays); +GLAPI PFNGLGENVERTEXARRAYSPROC glad_glGenVertexArrays; +#define glGenVertexArrays glad_glGenVertexArrays +typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYPROC)(GLuint array); +GLAPI PFNGLISVERTEXARRAYPROC glad_glIsVertexArray; +#define glIsVertexArray glad_glIsVertexArray +#endif +#ifndef GL_VERSION_3_1 +#define GL_VERSION_3_1 1 +GLAPI int GLAD_GL_VERSION_3_1; +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDPROC)(GLenum mode, GLint first, GLsizei count, GLsizei instancecount); +GLAPI PFNGLDRAWARRAYSINSTANCEDPROC glad_glDrawArraysInstanced; +#define glDrawArraysInstanced glad_glDrawArraysInstanced +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount); +GLAPI PFNGLDRAWELEMENTSINSTANCEDPROC glad_glDrawElementsInstanced; +#define glDrawElementsInstanced glad_glDrawElementsInstanced +typedef void (APIENTRYP PFNGLTEXBUFFERPROC)(GLenum target, GLenum internalformat, GLuint buffer); +GLAPI PFNGLTEXBUFFERPROC glad_glTexBuffer; +#define glTexBuffer glad_glTexBuffer +typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXPROC)(GLuint index); +GLAPI PFNGLPRIMITIVERESTARTINDEXPROC glad_glPrimitiveRestartIndex; +#define glPrimitiveRestartIndex glad_glPrimitiveRestartIndex +typedef void (APIENTRYP PFNGLCOPYBUFFERSUBDATAPROC)(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +GLAPI PFNGLCOPYBUFFERSUBDATAPROC glad_glCopyBufferSubData; +#define glCopyBufferSubData glad_glCopyBufferSubData +typedef void (APIENTRYP PFNGLGETUNIFORMINDICESPROC)(GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices); +GLAPI PFNGLGETUNIFORMINDICESPROC glad_glGetUniformIndices; +#define glGetUniformIndices glad_glGetUniformIndices +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMSIVPROC)(GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); +GLAPI PFNGLGETACTIVEUNIFORMSIVPROC glad_glGetActiveUniformsiv; +#define glGetActiveUniformsiv glad_glGetActiveUniformsiv +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMNAMEPROC)(GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName); +GLAPI PFNGLGETACTIVEUNIFORMNAMEPROC glad_glGetActiveUniformName; +#define glGetActiveUniformName glad_glGetActiveUniformName +typedef GLuint (APIENTRYP PFNGLGETUNIFORMBLOCKINDEXPROC)(GLuint program, const GLchar *uniformBlockName); +GLAPI PFNGLGETUNIFORMBLOCKINDEXPROC glad_glGetUniformBlockIndex; +#define glGetUniformBlockIndex glad_glGetUniformBlockIndex +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKIVPROC)(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); +GLAPI PFNGLGETACTIVEUNIFORMBLOCKIVPROC glad_glGetActiveUniformBlockiv; +#define glGetActiveUniformBlockiv glad_glGetActiveUniformBlockiv +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); +GLAPI PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glad_glGetActiveUniformBlockName; +#define glGetActiveUniformBlockName glad_glGetActiveUniformBlockName +typedef void (APIENTRYP PFNGLUNIFORMBLOCKBINDINGPROC)(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); +GLAPI PFNGLUNIFORMBLOCKBINDINGPROC glad_glUniformBlockBinding; +#define glUniformBlockBinding glad_glUniformBlockBinding +#endif +#ifndef GL_VERSION_3_2 +#define GL_VERSION_3_2 1 +GLAPI int GLAD_GL_VERSION_3_2; +typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); +GLAPI PFNGLDRAWELEMENTSBASEVERTEXPROC glad_glDrawElementsBaseVertex; +#define glDrawElementsBaseVertex glad_glDrawElementsBaseVertex +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); +GLAPI PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glad_glDrawRangeElementsBaseVertex; +#define glDrawRangeElementsBaseVertex glad_glDrawRangeElementsBaseVertex +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); +GLAPI PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex; +#define glDrawElementsInstancedBaseVertex glad_glDrawElementsInstancedBaseVertex +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)(GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount, const GLint *basevertex); +GLAPI PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glad_glMultiDrawElementsBaseVertex; +#define glMultiDrawElementsBaseVertex glad_glMultiDrawElementsBaseVertex +typedef void (APIENTRYP PFNGLPROVOKINGVERTEXPROC)(GLenum mode); +GLAPI PFNGLPROVOKINGVERTEXPROC glad_glProvokingVertex; +#define glProvokingVertex glad_glProvokingVertex +typedef GLsync (APIENTRYP PFNGLFENCESYNCPROC)(GLenum condition, GLbitfield flags); +GLAPI PFNGLFENCESYNCPROC glad_glFenceSync; +#define glFenceSync glad_glFenceSync +typedef GLboolean (APIENTRYP PFNGLISSYNCPROC)(GLsync sync); +GLAPI PFNGLISSYNCPROC glad_glIsSync; +#define glIsSync glad_glIsSync +typedef void (APIENTRYP PFNGLDELETESYNCPROC)(GLsync sync); +GLAPI PFNGLDELETESYNCPROC glad_glDeleteSync; +#define glDeleteSync glad_glDeleteSync +typedef GLenum (APIENTRYP PFNGLCLIENTWAITSYNCPROC)(GLsync sync, GLbitfield flags, GLuint64 timeout); +GLAPI PFNGLCLIENTWAITSYNCPROC glad_glClientWaitSync; +#define glClientWaitSync glad_glClientWaitSync +typedef void (APIENTRYP PFNGLWAITSYNCPROC)(GLsync sync, GLbitfield flags, GLuint64 timeout); +GLAPI PFNGLWAITSYNCPROC glad_glWaitSync; +#define glWaitSync glad_glWaitSync +typedef void (APIENTRYP PFNGLGETINTEGER64VPROC)(GLenum pname, GLint64 *data); +GLAPI PFNGLGETINTEGER64VPROC glad_glGetInteger64v; +#define glGetInteger64v glad_glGetInteger64v +typedef void (APIENTRYP PFNGLGETSYNCIVPROC)(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); +GLAPI PFNGLGETSYNCIVPROC glad_glGetSynciv; +#define glGetSynciv glad_glGetSynciv +typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC)(GLenum target, GLuint index, GLint64 *data); +GLAPI PFNGLGETINTEGER64I_VPROC glad_glGetInteger64i_v; +#define glGetInteger64i_v glad_glGetInteger64i_v +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERI64VPROC)(GLenum target, GLenum pname, GLint64 *params); +GLAPI PFNGLGETBUFFERPARAMETERI64VPROC glad_glGetBufferParameteri64v; +#define glGetBufferParameteri64v glad_glGetBufferParameteri64v +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level); +GLAPI PFNGLFRAMEBUFFERTEXTUREPROC glad_glFramebufferTexture; +#define glFramebufferTexture glad_glFramebufferTexture +typedef void (APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +GLAPI PFNGLTEXIMAGE2DMULTISAMPLEPROC glad_glTexImage2DMultisample; +#define glTexImage2DMultisample glad_glTexImage2DMultisample +typedef void (APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +GLAPI PFNGLTEXIMAGE3DMULTISAMPLEPROC glad_glTexImage3DMultisample; +#define glTexImage3DMultisample glad_glTexImage3DMultisample +typedef void (APIENTRYP PFNGLGETMULTISAMPLEFVPROC)(GLenum pname, GLuint index, GLfloat *val); +GLAPI PFNGLGETMULTISAMPLEFVPROC glad_glGetMultisamplefv; +#define glGetMultisamplefv glad_glGetMultisamplefv +typedef void (APIENTRYP PFNGLSAMPLEMASKIPROC)(GLuint maskNumber, GLbitfield mask); +GLAPI PFNGLSAMPLEMASKIPROC glad_glSampleMaski; +#define glSampleMaski glad_glSampleMaski +#endif +#ifndef GL_VERSION_3_3 +#define GL_VERSION_3_3 1 +GLAPI int GLAD_GL_VERSION_3_3; +typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONINDEXEDPROC)(GLuint program, GLuint colorNumber, GLuint index, const GLchar *name); +GLAPI PFNGLBINDFRAGDATALOCATIONINDEXEDPROC glad_glBindFragDataLocationIndexed; +#define glBindFragDataLocationIndexed glad_glBindFragDataLocationIndexed +typedef GLint (APIENTRYP PFNGLGETFRAGDATAINDEXPROC)(GLuint program, const GLchar *name); +GLAPI PFNGLGETFRAGDATAINDEXPROC glad_glGetFragDataIndex; +#define glGetFragDataIndex glad_glGetFragDataIndex +typedef void (APIENTRYP PFNGLGENSAMPLERSPROC)(GLsizei count, GLuint *samplers); +GLAPI PFNGLGENSAMPLERSPROC glad_glGenSamplers; +#define glGenSamplers glad_glGenSamplers +typedef void (APIENTRYP PFNGLDELETESAMPLERSPROC)(GLsizei count, const GLuint *samplers); +GLAPI PFNGLDELETESAMPLERSPROC glad_glDeleteSamplers; +#define glDeleteSamplers glad_glDeleteSamplers +typedef GLboolean (APIENTRYP PFNGLISSAMPLERPROC)(GLuint sampler); +GLAPI PFNGLISSAMPLERPROC glad_glIsSampler; +#define glIsSampler glad_glIsSampler +typedef void (APIENTRYP PFNGLBINDSAMPLERPROC)(GLuint unit, GLuint sampler); +GLAPI PFNGLBINDSAMPLERPROC glad_glBindSampler; +#define glBindSampler glad_glBindSampler +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIPROC)(GLuint sampler, GLenum pname, GLint param); +GLAPI PFNGLSAMPLERPARAMETERIPROC glad_glSamplerParameteri; +#define glSamplerParameteri glad_glSamplerParameteri +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIVPROC)(GLuint sampler, GLenum pname, const GLint *param); +GLAPI PFNGLSAMPLERPARAMETERIVPROC glad_glSamplerParameteriv; +#define glSamplerParameteriv glad_glSamplerParameteriv +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERFPROC)(GLuint sampler, GLenum pname, GLfloat param); +GLAPI PFNGLSAMPLERPARAMETERFPROC glad_glSamplerParameterf; +#define glSamplerParameterf glad_glSamplerParameterf +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERFVPROC)(GLuint sampler, GLenum pname, const GLfloat *param); +GLAPI PFNGLSAMPLERPARAMETERFVPROC glad_glSamplerParameterfv; +#define glSamplerParameterfv glad_glSamplerParameterfv +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIIVPROC)(GLuint sampler, GLenum pname, const GLint *param); +GLAPI PFNGLSAMPLERPARAMETERIIVPROC glad_glSamplerParameterIiv; +#define glSamplerParameterIiv glad_glSamplerParameterIiv +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIUIVPROC)(GLuint sampler, GLenum pname, const GLuint *param); +GLAPI PFNGLSAMPLERPARAMETERIUIVPROC glad_glSamplerParameterIuiv; +#define glSamplerParameterIuiv glad_glSamplerParameterIuiv +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIVPROC)(GLuint sampler, GLenum pname, GLint *params); +GLAPI PFNGLGETSAMPLERPARAMETERIVPROC glad_glGetSamplerParameteriv; +#define glGetSamplerParameteriv glad_glGetSamplerParameteriv +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIIVPROC)(GLuint sampler, GLenum pname, GLint *params); +GLAPI PFNGLGETSAMPLERPARAMETERIIVPROC glad_glGetSamplerParameterIiv; +#define glGetSamplerParameterIiv glad_glGetSamplerParameterIiv +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERFVPROC)(GLuint sampler, GLenum pname, GLfloat *params); +GLAPI PFNGLGETSAMPLERPARAMETERFVPROC glad_glGetSamplerParameterfv; +#define glGetSamplerParameterfv glad_glGetSamplerParameterfv +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVPROC)(GLuint sampler, GLenum pname, GLuint *params); +GLAPI PFNGLGETSAMPLERPARAMETERIUIVPROC glad_glGetSamplerParameterIuiv; +#define glGetSamplerParameterIuiv glad_glGetSamplerParameterIuiv +typedef void (APIENTRYP PFNGLQUERYCOUNTERPROC)(GLuint id, GLenum target); +GLAPI PFNGLQUERYCOUNTERPROC glad_glQueryCounter; +#define glQueryCounter glad_glQueryCounter +typedef void (APIENTRYP PFNGLGETQUERYOBJECTI64VPROC)(GLuint id, GLenum pname, GLint64 *params); +GLAPI PFNGLGETQUERYOBJECTI64VPROC glad_glGetQueryObjecti64v; +#define glGetQueryObjecti64v glad_glGetQueryObjecti64v +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUI64VPROC)(GLuint id, GLenum pname, GLuint64 *params); +GLAPI PFNGLGETQUERYOBJECTUI64VPROC glad_glGetQueryObjectui64v; +#define glGetQueryObjectui64v glad_glGetQueryObjectui64v +typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORPROC)(GLuint index, GLuint divisor); +GLAPI PFNGLVERTEXATTRIBDIVISORPROC glad_glVertexAttribDivisor; +#define glVertexAttribDivisor glad_glVertexAttribDivisor +typedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI PFNGLVERTEXATTRIBP1UIPROC glad_glVertexAttribP1ui; +#define glVertexAttribP1ui glad_glVertexAttribP1ui +typedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI PFNGLVERTEXATTRIBP1UIVPROC glad_glVertexAttribP1uiv; +#define glVertexAttribP1uiv glad_glVertexAttribP1uiv +typedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI PFNGLVERTEXATTRIBP2UIPROC glad_glVertexAttribP2ui; +#define glVertexAttribP2ui glad_glVertexAttribP2ui +typedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI PFNGLVERTEXATTRIBP2UIVPROC glad_glVertexAttribP2uiv; +#define glVertexAttribP2uiv glad_glVertexAttribP2uiv +typedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI PFNGLVERTEXATTRIBP3UIPROC glad_glVertexAttribP3ui; +#define glVertexAttribP3ui glad_glVertexAttribP3ui +typedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI PFNGLVERTEXATTRIBP3UIVPROC glad_glVertexAttribP3uiv; +#define glVertexAttribP3uiv glad_glVertexAttribP3uiv +typedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI PFNGLVERTEXATTRIBP4UIPROC glad_glVertexAttribP4ui; +#define glVertexAttribP4ui glad_glVertexAttribP4ui +typedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI PFNGLVERTEXATTRIBP4UIVPROC glad_glVertexAttribP4uiv; +#define glVertexAttribP4uiv glad_glVertexAttribP4uiv +typedef void (APIENTRYP PFNGLVERTEXP2UIPROC)(GLenum type, GLuint value); +GLAPI PFNGLVERTEXP2UIPROC glad_glVertexP2ui; +#define glVertexP2ui glad_glVertexP2ui +typedef void (APIENTRYP PFNGLVERTEXP2UIVPROC)(GLenum type, const GLuint *value); +GLAPI PFNGLVERTEXP2UIVPROC glad_glVertexP2uiv; +#define glVertexP2uiv glad_glVertexP2uiv +typedef void (APIENTRYP PFNGLVERTEXP3UIPROC)(GLenum type, GLuint value); +GLAPI PFNGLVERTEXP3UIPROC glad_glVertexP3ui; +#define glVertexP3ui glad_glVertexP3ui +typedef void (APIENTRYP PFNGLVERTEXP3UIVPROC)(GLenum type, const GLuint *value); +GLAPI PFNGLVERTEXP3UIVPROC glad_glVertexP3uiv; +#define glVertexP3uiv glad_glVertexP3uiv +typedef void (APIENTRYP PFNGLVERTEXP4UIPROC)(GLenum type, GLuint value); +GLAPI PFNGLVERTEXP4UIPROC glad_glVertexP4ui; +#define glVertexP4ui glad_glVertexP4ui +typedef void (APIENTRYP PFNGLVERTEXP4UIVPROC)(GLenum type, const GLuint *value); +GLAPI PFNGLVERTEXP4UIVPROC glad_glVertexP4uiv; +#define glVertexP4uiv glad_glVertexP4uiv +typedef void (APIENTRYP PFNGLTEXCOORDP1UIPROC)(GLenum type, GLuint coords); +GLAPI PFNGLTEXCOORDP1UIPROC glad_glTexCoordP1ui; +#define glTexCoordP1ui glad_glTexCoordP1ui +typedef void (APIENTRYP PFNGLTEXCOORDP1UIVPROC)(GLenum type, const GLuint *coords); +GLAPI PFNGLTEXCOORDP1UIVPROC glad_glTexCoordP1uiv; +#define glTexCoordP1uiv glad_glTexCoordP1uiv +typedef void (APIENTRYP PFNGLTEXCOORDP2UIPROC)(GLenum type, GLuint coords); +GLAPI PFNGLTEXCOORDP2UIPROC glad_glTexCoordP2ui; +#define glTexCoordP2ui glad_glTexCoordP2ui +typedef void (APIENTRYP PFNGLTEXCOORDP2UIVPROC)(GLenum type, const GLuint *coords); +GLAPI PFNGLTEXCOORDP2UIVPROC glad_glTexCoordP2uiv; +#define glTexCoordP2uiv glad_glTexCoordP2uiv +typedef void (APIENTRYP PFNGLTEXCOORDP3UIPROC)(GLenum type, GLuint coords); +GLAPI PFNGLTEXCOORDP3UIPROC glad_glTexCoordP3ui; +#define glTexCoordP3ui glad_glTexCoordP3ui +typedef void (APIENTRYP PFNGLTEXCOORDP3UIVPROC)(GLenum type, const GLuint *coords); +GLAPI PFNGLTEXCOORDP3UIVPROC glad_glTexCoordP3uiv; +#define glTexCoordP3uiv glad_glTexCoordP3uiv +typedef void (APIENTRYP PFNGLTEXCOORDP4UIPROC)(GLenum type, GLuint coords); +GLAPI PFNGLTEXCOORDP4UIPROC glad_glTexCoordP4ui; +#define glTexCoordP4ui glad_glTexCoordP4ui +typedef void (APIENTRYP PFNGLTEXCOORDP4UIVPROC)(GLenum type, const GLuint *coords); +GLAPI PFNGLTEXCOORDP4UIVPROC glad_glTexCoordP4uiv; +#define glTexCoordP4uiv glad_glTexCoordP4uiv +typedef void (APIENTRYP PFNGLMULTITEXCOORDP1UIPROC)(GLenum texture, GLenum type, GLuint coords); +GLAPI PFNGLMULTITEXCOORDP1UIPROC glad_glMultiTexCoordP1ui; +#define glMultiTexCoordP1ui glad_glMultiTexCoordP1ui +typedef void (APIENTRYP PFNGLMULTITEXCOORDP1UIVPROC)(GLenum texture, GLenum type, const GLuint *coords); +GLAPI PFNGLMULTITEXCOORDP1UIVPROC glad_glMultiTexCoordP1uiv; +#define glMultiTexCoordP1uiv glad_glMultiTexCoordP1uiv +typedef void (APIENTRYP PFNGLMULTITEXCOORDP2UIPROC)(GLenum texture, GLenum type, GLuint coords); +GLAPI PFNGLMULTITEXCOORDP2UIPROC glad_glMultiTexCoordP2ui; +#define glMultiTexCoordP2ui glad_glMultiTexCoordP2ui +typedef void (APIENTRYP PFNGLMULTITEXCOORDP2UIVPROC)(GLenum texture, GLenum type, const GLuint *coords); +GLAPI PFNGLMULTITEXCOORDP2UIVPROC glad_glMultiTexCoordP2uiv; +#define glMultiTexCoordP2uiv glad_glMultiTexCoordP2uiv +typedef void (APIENTRYP PFNGLMULTITEXCOORDP3UIPROC)(GLenum texture, GLenum type, GLuint coords); +GLAPI PFNGLMULTITEXCOORDP3UIPROC glad_glMultiTexCoordP3ui; +#define glMultiTexCoordP3ui glad_glMultiTexCoordP3ui +typedef void (APIENTRYP PFNGLMULTITEXCOORDP3UIVPROC)(GLenum texture, GLenum type, const GLuint *coords); +GLAPI PFNGLMULTITEXCOORDP3UIVPROC glad_glMultiTexCoordP3uiv; +#define glMultiTexCoordP3uiv glad_glMultiTexCoordP3uiv +typedef void (APIENTRYP PFNGLMULTITEXCOORDP4UIPROC)(GLenum texture, GLenum type, GLuint coords); +GLAPI PFNGLMULTITEXCOORDP4UIPROC glad_glMultiTexCoordP4ui; +#define glMultiTexCoordP4ui glad_glMultiTexCoordP4ui +typedef void (APIENTRYP PFNGLMULTITEXCOORDP4UIVPROC)(GLenum texture, GLenum type, const GLuint *coords); +GLAPI PFNGLMULTITEXCOORDP4UIVPROC glad_glMultiTexCoordP4uiv; +#define glMultiTexCoordP4uiv glad_glMultiTexCoordP4uiv +typedef void (APIENTRYP PFNGLNORMALP3UIPROC)(GLenum type, GLuint coords); +GLAPI PFNGLNORMALP3UIPROC glad_glNormalP3ui; +#define glNormalP3ui glad_glNormalP3ui +typedef void (APIENTRYP PFNGLNORMALP3UIVPROC)(GLenum type, const GLuint *coords); +GLAPI PFNGLNORMALP3UIVPROC glad_glNormalP3uiv; +#define glNormalP3uiv glad_glNormalP3uiv +typedef void (APIENTRYP PFNGLCOLORP3UIPROC)(GLenum type, GLuint color); +GLAPI PFNGLCOLORP3UIPROC glad_glColorP3ui; +#define glColorP3ui glad_glColorP3ui +typedef void (APIENTRYP PFNGLCOLORP3UIVPROC)(GLenum type, const GLuint *color); +GLAPI PFNGLCOLORP3UIVPROC glad_glColorP3uiv; +#define glColorP3uiv glad_glColorP3uiv +typedef void (APIENTRYP PFNGLCOLORP4UIPROC)(GLenum type, GLuint color); +GLAPI PFNGLCOLORP4UIPROC glad_glColorP4ui; +#define glColorP4ui glad_glColorP4ui +typedef void (APIENTRYP PFNGLCOLORP4UIVPROC)(GLenum type, const GLuint *color); +GLAPI PFNGLCOLORP4UIVPROC glad_glColorP4uiv; +#define glColorP4uiv glad_glColorP4uiv +typedef void (APIENTRYP PFNGLSECONDARYCOLORP3UIPROC)(GLenum type, GLuint color); +GLAPI PFNGLSECONDARYCOLORP3UIPROC glad_glSecondaryColorP3ui; +#define glSecondaryColorP3ui glad_glSecondaryColorP3ui +typedef void (APIENTRYP PFNGLSECONDARYCOLORP3UIVPROC)(GLenum type, const GLuint *color); +GLAPI PFNGLSECONDARYCOLORP3UIVPROC glad_glSecondaryColorP3uiv; +#define glSecondaryColorP3uiv glad_glSecondaryColorP3uiv +#endif +#ifndef GL_VERSION_4_0 +#define GL_VERSION_4_0 1 +GLAPI int GLAD_GL_VERSION_4_0; +typedef void (APIENTRYP PFNGLMINSAMPLESHADINGPROC)(GLfloat value); +GLAPI PFNGLMINSAMPLESHADINGPROC glad_glMinSampleShading; +#define glMinSampleShading glad_glMinSampleShading +typedef void (APIENTRYP PFNGLBLENDEQUATIONIPROC)(GLuint buf, GLenum mode); +GLAPI PFNGLBLENDEQUATIONIPROC glad_glBlendEquationi; +#define glBlendEquationi glad_glBlendEquationi +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEIPROC)(GLuint buf, GLenum modeRGB, GLenum modeAlpha); +GLAPI PFNGLBLENDEQUATIONSEPARATEIPROC glad_glBlendEquationSeparatei; +#define glBlendEquationSeparatei glad_glBlendEquationSeparatei +typedef void (APIENTRYP PFNGLBLENDFUNCIPROC)(GLuint buf, GLenum src, GLenum dst); +GLAPI PFNGLBLENDFUNCIPROC glad_glBlendFunci; +#define glBlendFunci glad_glBlendFunci +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEIPROC)(GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +GLAPI PFNGLBLENDFUNCSEPARATEIPROC glad_glBlendFuncSeparatei; +#define glBlendFuncSeparatei glad_glBlendFuncSeparatei +typedef void (APIENTRYP PFNGLDRAWARRAYSINDIRECTPROC)(GLenum mode, const void *indirect); +GLAPI PFNGLDRAWARRAYSINDIRECTPROC glad_glDrawArraysIndirect; +#define glDrawArraysIndirect glad_glDrawArraysIndirect +typedef void (APIENTRYP PFNGLDRAWELEMENTSINDIRECTPROC)(GLenum mode, GLenum type, const void *indirect); +GLAPI PFNGLDRAWELEMENTSINDIRECTPROC glad_glDrawElementsIndirect; +#define glDrawElementsIndirect glad_glDrawElementsIndirect +typedef void (APIENTRYP PFNGLUNIFORM1DPROC)(GLint location, GLdouble x); +GLAPI PFNGLUNIFORM1DPROC glad_glUniform1d; +#define glUniform1d glad_glUniform1d +typedef void (APIENTRYP PFNGLUNIFORM2DPROC)(GLint location, GLdouble x, GLdouble y); +GLAPI PFNGLUNIFORM2DPROC glad_glUniform2d; +#define glUniform2d glad_glUniform2d +typedef void (APIENTRYP PFNGLUNIFORM3DPROC)(GLint location, GLdouble x, GLdouble y, GLdouble z); +GLAPI PFNGLUNIFORM3DPROC glad_glUniform3d; +#define glUniform3d glad_glUniform3d +typedef void (APIENTRYP PFNGLUNIFORM4DPROC)(GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI PFNGLUNIFORM4DPROC glad_glUniform4d; +#define glUniform4d glad_glUniform4d +typedef void (APIENTRYP PFNGLUNIFORM1DVPROC)(GLint location, GLsizei count, const GLdouble *value); +GLAPI PFNGLUNIFORM1DVPROC glad_glUniform1dv; +#define glUniform1dv glad_glUniform1dv +typedef void (APIENTRYP PFNGLUNIFORM2DVPROC)(GLint location, GLsizei count, const GLdouble *value); +GLAPI PFNGLUNIFORM2DVPROC glad_glUniform2dv; +#define glUniform2dv glad_glUniform2dv +typedef void (APIENTRYP PFNGLUNIFORM3DVPROC)(GLint location, GLsizei count, const GLdouble *value); +GLAPI PFNGLUNIFORM3DVPROC glad_glUniform3dv; +#define glUniform3dv glad_glUniform3dv +typedef void (APIENTRYP PFNGLUNIFORM4DVPROC)(GLint location, GLsizei count, const GLdouble *value); +GLAPI PFNGLUNIFORM4DVPROC glad_glUniform4dv; +#define glUniform4dv glad_glUniform4dv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI PFNGLUNIFORMMATRIX2DVPROC glad_glUniformMatrix2dv; +#define glUniformMatrix2dv glad_glUniformMatrix2dv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI PFNGLUNIFORMMATRIX3DVPROC glad_glUniformMatrix3dv; +#define glUniformMatrix3dv glad_glUniformMatrix3dv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI PFNGLUNIFORMMATRIX4DVPROC glad_glUniformMatrix4dv; +#define glUniformMatrix4dv glad_glUniformMatrix4dv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI PFNGLUNIFORMMATRIX2X3DVPROC glad_glUniformMatrix2x3dv; +#define glUniformMatrix2x3dv glad_glUniformMatrix2x3dv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI PFNGLUNIFORMMATRIX2X4DVPROC glad_glUniformMatrix2x4dv; +#define glUniformMatrix2x4dv glad_glUniformMatrix2x4dv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI PFNGLUNIFORMMATRIX3X2DVPROC glad_glUniformMatrix3x2dv; +#define glUniformMatrix3x2dv glad_glUniformMatrix3x2dv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI PFNGLUNIFORMMATRIX3X4DVPROC glad_glUniformMatrix3x4dv; +#define glUniformMatrix3x4dv glad_glUniformMatrix3x4dv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI PFNGLUNIFORMMATRIX4X2DVPROC glad_glUniformMatrix4x2dv; +#define glUniformMatrix4x2dv glad_glUniformMatrix4x2dv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI PFNGLUNIFORMMATRIX4X3DVPROC glad_glUniformMatrix4x3dv; +#define glUniformMatrix4x3dv glad_glUniformMatrix4x3dv +typedef void (APIENTRYP PFNGLGETUNIFORMDVPROC)(GLuint program, GLint location, GLdouble *params); +GLAPI PFNGLGETUNIFORMDVPROC glad_glGetUniformdv; +#define glGetUniformdv glad_glGetUniformdv +typedef GLint (APIENTRYP PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC)(GLuint program, GLenum shadertype, const GLchar *name); +GLAPI PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC glad_glGetSubroutineUniformLocation; +#define glGetSubroutineUniformLocation glad_glGetSubroutineUniformLocation +typedef GLuint (APIENTRYP PFNGLGETSUBROUTINEINDEXPROC)(GLuint program, GLenum shadertype, const GLchar *name); +GLAPI PFNGLGETSUBROUTINEINDEXPROC glad_glGetSubroutineIndex; +#define glGetSubroutineIndex glad_glGetSubroutineIndex +typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC)(GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint *values); +GLAPI PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC glad_glGetActiveSubroutineUniformiv; +#define glGetActiveSubroutineUniformiv glad_glGetActiveSubroutineUniformiv +typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC)(GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name); +GLAPI PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC glad_glGetActiveSubroutineUniformName; +#define glGetActiveSubroutineUniformName glad_glGetActiveSubroutineUniformName +typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINENAMEPROC)(GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name); +GLAPI PFNGLGETACTIVESUBROUTINENAMEPROC glad_glGetActiveSubroutineName; +#define glGetActiveSubroutineName glad_glGetActiveSubroutineName +typedef void (APIENTRYP PFNGLUNIFORMSUBROUTINESUIVPROC)(GLenum shadertype, GLsizei count, const GLuint *indices); +GLAPI PFNGLUNIFORMSUBROUTINESUIVPROC glad_glUniformSubroutinesuiv; +#define glUniformSubroutinesuiv glad_glUniformSubroutinesuiv +typedef void (APIENTRYP PFNGLGETUNIFORMSUBROUTINEUIVPROC)(GLenum shadertype, GLint location, GLuint *params); +GLAPI PFNGLGETUNIFORMSUBROUTINEUIVPROC glad_glGetUniformSubroutineuiv; +#define glGetUniformSubroutineuiv glad_glGetUniformSubroutineuiv +typedef void (APIENTRYP PFNGLGETPROGRAMSTAGEIVPROC)(GLuint program, GLenum shadertype, GLenum pname, GLint *values); +GLAPI PFNGLGETPROGRAMSTAGEIVPROC glad_glGetProgramStageiv; +#define glGetProgramStageiv glad_glGetProgramStageiv +typedef void (APIENTRYP PFNGLPATCHPARAMETERIPROC)(GLenum pname, GLint value); +GLAPI PFNGLPATCHPARAMETERIPROC glad_glPatchParameteri; +#define glPatchParameteri glad_glPatchParameteri +typedef void (APIENTRYP PFNGLPATCHPARAMETERFVPROC)(GLenum pname, const GLfloat *values); +GLAPI PFNGLPATCHPARAMETERFVPROC glad_glPatchParameterfv; +#define glPatchParameterfv glad_glPatchParameterfv +typedef void (APIENTRYP PFNGLBINDTRANSFORMFEEDBACKPROC)(GLenum target, GLuint id); +GLAPI PFNGLBINDTRANSFORMFEEDBACKPROC glad_glBindTransformFeedback; +#define glBindTransformFeedback glad_glBindTransformFeedback +typedef void (APIENTRYP PFNGLDELETETRANSFORMFEEDBACKSPROC)(GLsizei n, const GLuint *ids); +GLAPI PFNGLDELETETRANSFORMFEEDBACKSPROC glad_glDeleteTransformFeedbacks; +#define glDeleteTransformFeedbacks glad_glDeleteTransformFeedbacks +typedef void (APIENTRYP PFNGLGENTRANSFORMFEEDBACKSPROC)(GLsizei n, GLuint *ids); +GLAPI PFNGLGENTRANSFORMFEEDBACKSPROC glad_glGenTransformFeedbacks; +#define glGenTransformFeedbacks glad_glGenTransformFeedbacks +typedef GLboolean (APIENTRYP PFNGLISTRANSFORMFEEDBACKPROC)(GLuint id); +GLAPI PFNGLISTRANSFORMFEEDBACKPROC glad_glIsTransformFeedback; +#define glIsTransformFeedback glad_glIsTransformFeedback +typedef void (APIENTRYP PFNGLPAUSETRANSFORMFEEDBACKPROC)(); +GLAPI PFNGLPAUSETRANSFORMFEEDBACKPROC glad_glPauseTransformFeedback; +#define glPauseTransformFeedback glad_glPauseTransformFeedback +typedef void (APIENTRYP PFNGLRESUMETRANSFORMFEEDBACKPROC)(); +GLAPI PFNGLRESUMETRANSFORMFEEDBACKPROC glad_glResumeTransformFeedback; +#define glResumeTransformFeedback glad_glResumeTransformFeedback +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKPROC)(GLenum mode, GLuint id); +GLAPI PFNGLDRAWTRANSFORMFEEDBACKPROC glad_glDrawTransformFeedback; +#define glDrawTransformFeedback glad_glDrawTransformFeedback +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC)(GLenum mode, GLuint id, GLuint stream); +GLAPI PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC glad_glDrawTransformFeedbackStream; +#define glDrawTransformFeedbackStream glad_glDrawTransformFeedbackStream +typedef void (APIENTRYP PFNGLBEGINQUERYINDEXEDPROC)(GLenum target, GLuint index, GLuint id); +GLAPI PFNGLBEGINQUERYINDEXEDPROC glad_glBeginQueryIndexed; +#define glBeginQueryIndexed glad_glBeginQueryIndexed +typedef void (APIENTRYP PFNGLENDQUERYINDEXEDPROC)(GLenum target, GLuint index); +GLAPI PFNGLENDQUERYINDEXEDPROC glad_glEndQueryIndexed; +#define glEndQueryIndexed glad_glEndQueryIndexed +typedef void (APIENTRYP PFNGLGETQUERYINDEXEDIVPROC)(GLenum target, GLuint index, GLenum pname, GLint *params); +GLAPI PFNGLGETQUERYINDEXEDIVPROC glad_glGetQueryIndexediv; +#define glGetQueryIndexediv glad_glGetQueryIndexediv +#endif +#ifndef GL_VERSION_4_1 +#define GL_VERSION_4_1 1 +GLAPI int GLAD_GL_VERSION_4_1; +typedef void (APIENTRYP PFNGLRELEASESHADERCOMPILERPROC)(); +GLAPI PFNGLRELEASESHADERCOMPILERPROC glad_glReleaseShaderCompiler; +#define glReleaseShaderCompiler glad_glReleaseShaderCompiler +typedef void (APIENTRYP PFNGLSHADERBINARYPROC)(GLsizei count, const GLuint *shaders, GLenum binaryformat, const void *binary, GLsizei length); +GLAPI PFNGLSHADERBINARYPROC glad_glShaderBinary; +#define glShaderBinary glad_glShaderBinary +typedef void (APIENTRYP PFNGLGETSHADERPRECISIONFORMATPROC)(GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); +GLAPI PFNGLGETSHADERPRECISIONFORMATPROC glad_glGetShaderPrecisionFormat; +#define glGetShaderPrecisionFormat glad_glGetShaderPrecisionFormat +typedef void (APIENTRYP PFNGLDEPTHRANGEFPROC)(GLfloat n, GLfloat f); +GLAPI PFNGLDEPTHRANGEFPROC glad_glDepthRangef; +#define glDepthRangef glad_glDepthRangef +typedef void (APIENTRYP PFNGLCLEARDEPTHFPROC)(GLfloat d); +GLAPI PFNGLCLEARDEPTHFPROC glad_glClearDepthf; +#define glClearDepthf glad_glClearDepthf +typedef void (APIENTRYP PFNGLGETPROGRAMBINARYPROC)(GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); +GLAPI PFNGLGETPROGRAMBINARYPROC glad_glGetProgramBinary; +#define glGetProgramBinary glad_glGetProgramBinary +typedef void (APIENTRYP PFNGLPROGRAMBINARYPROC)(GLuint program, GLenum binaryFormat, const void *binary, GLsizei length); +GLAPI PFNGLPROGRAMBINARYPROC glad_glProgramBinary; +#define glProgramBinary glad_glProgramBinary +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIPROC)(GLuint program, GLenum pname, GLint value); +GLAPI PFNGLPROGRAMPARAMETERIPROC glad_glProgramParameteri; +#define glProgramParameteri glad_glProgramParameteri +typedef void (APIENTRYP PFNGLUSEPROGRAMSTAGESPROC)(GLuint pipeline, GLbitfield stages, GLuint program); +GLAPI PFNGLUSEPROGRAMSTAGESPROC glad_glUseProgramStages; +#define glUseProgramStages glad_glUseProgramStages +typedef void (APIENTRYP PFNGLACTIVESHADERPROGRAMPROC)(GLuint pipeline, GLuint program); +GLAPI PFNGLACTIVESHADERPROGRAMPROC glad_glActiveShaderProgram; +#define glActiveShaderProgram glad_glActiveShaderProgram +typedef GLuint (APIENTRYP PFNGLCREATESHADERPROGRAMVPROC)(GLenum type, GLsizei count, const GLchar *const*strings); +GLAPI PFNGLCREATESHADERPROGRAMVPROC glad_glCreateShaderProgramv; +#define glCreateShaderProgramv glad_glCreateShaderProgramv +typedef void (APIENTRYP PFNGLBINDPROGRAMPIPELINEPROC)(GLuint pipeline); +GLAPI PFNGLBINDPROGRAMPIPELINEPROC glad_glBindProgramPipeline; +#define glBindProgramPipeline glad_glBindProgramPipeline +typedef void (APIENTRYP PFNGLDELETEPROGRAMPIPELINESPROC)(GLsizei n, const GLuint *pipelines); +GLAPI PFNGLDELETEPROGRAMPIPELINESPROC glad_glDeleteProgramPipelines; +#define glDeleteProgramPipelines glad_glDeleteProgramPipelines +typedef void (APIENTRYP PFNGLGENPROGRAMPIPELINESPROC)(GLsizei n, GLuint *pipelines); +GLAPI PFNGLGENPROGRAMPIPELINESPROC glad_glGenProgramPipelines; +#define glGenProgramPipelines glad_glGenProgramPipelines +typedef GLboolean (APIENTRYP PFNGLISPROGRAMPIPELINEPROC)(GLuint pipeline); +GLAPI PFNGLISPROGRAMPIPELINEPROC glad_glIsProgramPipeline; +#define glIsProgramPipeline glad_glIsProgramPipeline +typedef void (APIENTRYP PFNGLGETPROGRAMPIPELINEIVPROC)(GLuint pipeline, GLenum pname, GLint *params); +GLAPI PFNGLGETPROGRAMPIPELINEIVPROC glad_glGetProgramPipelineiv; +#define glGetProgramPipelineiv glad_glGetProgramPipelineiv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IPROC)(GLuint program, GLint location, GLint v0); +GLAPI PFNGLPROGRAMUNIFORM1IPROC glad_glProgramUniform1i; +#define glProgramUniform1i glad_glProgramUniform1i +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IVPROC)(GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI PFNGLPROGRAMUNIFORM1IVPROC glad_glProgramUniform1iv; +#define glProgramUniform1iv glad_glProgramUniform1iv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FPROC)(GLuint program, GLint location, GLfloat v0); +GLAPI PFNGLPROGRAMUNIFORM1FPROC glad_glProgramUniform1f; +#define glProgramUniform1f glad_glProgramUniform1f +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FVPROC)(GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI PFNGLPROGRAMUNIFORM1FVPROC glad_glProgramUniform1fv; +#define glProgramUniform1fv glad_glProgramUniform1fv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DPROC)(GLuint program, GLint location, GLdouble v0); +GLAPI PFNGLPROGRAMUNIFORM1DPROC glad_glProgramUniform1d; +#define glProgramUniform1d glad_glProgramUniform1d +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DVPROC)(GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI PFNGLPROGRAMUNIFORM1DVPROC glad_glProgramUniform1dv; +#define glProgramUniform1dv glad_glProgramUniform1dv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIPROC)(GLuint program, GLint location, GLuint v0); +GLAPI PFNGLPROGRAMUNIFORM1UIPROC glad_glProgramUniform1ui; +#define glProgramUniform1ui glad_glProgramUniform1ui +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIVPROC)(GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI PFNGLPROGRAMUNIFORM1UIVPROC glad_glProgramUniform1uiv; +#define glProgramUniform1uiv glad_glProgramUniform1uiv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IPROC)(GLuint program, GLint location, GLint v0, GLint v1); +GLAPI PFNGLPROGRAMUNIFORM2IPROC glad_glProgramUniform2i; +#define glProgramUniform2i glad_glProgramUniform2i +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IVPROC)(GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI PFNGLPROGRAMUNIFORM2IVPROC glad_glProgramUniform2iv; +#define glProgramUniform2iv glad_glProgramUniform2iv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FPROC)(GLuint program, GLint location, GLfloat v0, GLfloat v1); +GLAPI PFNGLPROGRAMUNIFORM2FPROC glad_glProgramUniform2f; +#define glProgramUniform2f glad_glProgramUniform2f +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FVPROC)(GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI PFNGLPROGRAMUNIFORM2FVPROC glad_glProgramUniform2fv; +#define glProgramUniform2fv glad_glProgramUniform2fv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DPROC)(GLuint program, GLint location, GLdouble v0, GLdouble v1); +GLAPI PFNGLPROGRAMUNIFORM2DPROC glad_glProgramUniform2d; +#define glProgramUniform2d glad_glProgramUniform2d +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DVPROC)(GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI PFNGLPROGRAMUNIFORM2DVPROC glad_glProgramUniform2dv; +#define glProgramUniform2dv glad_glProgramUniform2dv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIPROC)(GLuint program, GLint location, GLuint v0, GLuint v1); +GLAPI PFNGLPROGRAMUNIFORM2UIPROC glad_glProgramUniform2ui; +#define glProgramUniform2ui glad_glProgramUniform2ui +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIVPROC)(GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI PFNGLPROGRAMUNIFORM2UIVPROC glad_glProgramUniform2uiv; +#define glProgramUniform2uiv glad_glProgramUniform2uiv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IPROC)(GLuint program, GLint location, GLint v0, GLint v1, GLint v2); +GLAPI PFNGLPROGRAMUNIFORM3IPROC glad_glProgramUniform3i; +#define glProgramUniform3i glad_glProgramUniform3i +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IVPROC)(GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI PFNGLPROGRAMUNIFORM3IVPROC glad_glProgramUniform3iv; +#define glProgramUniform3iv glad_glProgramUniform3iv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FPROC)(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +GLAPI PFNGLPROGRAMUNIFORM3FPROC glad_glProgramUniform3f; +#define glProgramUniform3f glad_glProgramUniform3f +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FVPROC)(GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI PFNGLPROGRAMUNIFORM3FVPROC glad_glProgramUniform3fv; +#define glProgramUniform3fv glad_glProgramUniform3fv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DPROC)(GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2); +GLAPI PFNGLPROGRAMUNIFORM3DPROC glad_glProgramUniform3d; +#define glProgramUniform3d glad_glProgramUniform3d +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DVPROC)(GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI PFNGLPROGRAMUNIFORM3DVPROC glad_glProgramUniform3dv; +#define glProgramUniform3dv glad_glProgramUniform3dv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIPROC)(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); +GLAPI PFNGLPROGRAMUNIFORM3UIPROC glad_glProgramUniform3ui; +#define glProgramUniform3ui glad_glProgramUniform3ui +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIVPROC)(GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI PFNGLPROGRAMUNIFORM3UIVPROC glad_glProgramUniform3uiv; +#define glProgramUniform3uiv glad_glProgramUniform3uiv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IPROC)(GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +GLAPI PFNGLPROGRAMUNIFORM4IPROC glad_glProgramUniform4i; +#define glProgramUniform4i glad_glProgramUniform4i +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IVPROC)(GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI PFNGLPROGRAMUNIFORM4IVPROC glad_glProgramUniform4iv; +#define glProgramUniform4iv glad_glProgramUniform4iv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FPROC)(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +GLAPI PFNGLPROGRAMUNIFORM4FPROC glad_glProgramUniform4f; +#define glProgramUniform4f glad_glProgramUniform4f +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FVPROC)(GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI PFNGLPROGRAMUNIFORM4FVPROC glad_glProgramUniform4fv; +#define glProgramUniform4fv glad_glProgramUniform4fv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DPROC)(GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3); +GLAPI PFNGLPROGRAMUNIFORM4DPROC glad_glProgramUniform4d; +#define glProgramUniform4d glad_glProgramUniform4d +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DVPROC)(GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI PFNGLPROGRAMUNIFORM4DVPROC glad_glProgramUniform4dv; +#define glProgramUniform4dv glad_glProgramUniform4dv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIPROC)(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +GLAPI PFNGLPROGRAMUNIFORM4UIPROC glad_glProgramUniform4ui; +#define glProgramUniform4ui glad_glProgramUniform4ui +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIVPROC)(GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI PFNGLPROGRAMUNIFORM4UIVPROC glad_glProgramUniform4uiv; +#define glProgramUniform4uiv glad_glProgramUniform4uiv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLPROGRAMUNIFORMMATRIX2FVPROC glad_glProgramUniformMatrix2fv; +#define glProgramUniformMatrix2fv glad_glProgramUniformMatrix2fv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLPROGRAMUNIFORMMATRIX3FVPROC glad_glProgramUniformMatrix3fv; +#define glProgramUniformMatrix3fv glad_glProgramUniformMatrix3fv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLPROGRAMUNIFORMMATRIX4FVPROC glad_glProgramUniformMatrix4fv; +#define glProgramUniformMatrix4fv glad_glProgramUniformMatrix4fv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI PFNGLPROGRAMUNIFORMMATRIX2DVPROC glad_glProgramUniformMatrix2dv; +#define glProgramUniformMatrix2dv glad_glProgramUniformMatrix2dv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI PFNGLPROGRAMUNIFORMMATRIX3DVPROC glad_glProgramUniformMatrix3dv; +#define glProgramUniformMatrix3dv glad_glProgramUniformMatrix3dv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI PFNGLPROGRAMUNIFORMMATRIX4DVPROC glad_glProgramUniformMatrix4dv; +#define glProgramUniformMatrix4dv glad_glProgramUniformMatrix4dv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC glad_glProgramUniformMatrix2x3fv; +#define glProgramUniformMatrix2x3fv glad_glProgramUniformMatrix2x3fv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC glad_glProgramUniformMatrix3x2fv; +#define glProgramUniformMatrix3x2fv glad_glProgramUniformMatrix3x2fv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC glad_glProgramUniformMatrix2x4fv; +#define glProgramUniformMatrix2x4fv glad_glProgramUniformMatrix2x4fv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC glad_glProgramUniformMatrix4x2fv; +#define glProgramUniformMatrix4x2fv glad_glProgramUniformMatrix4x2fv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC glad_glProgramUniformMatrix3x4fv; +#define glProgramUniformMatrix3x4fv glad_glProgramUniformMatrix3x4fv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC glad_glProgramUniformMatrix4x3fv; +#define glProgramUniformMatrix4x3fv glad_glProgramUniformMatrix4x3fv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC glad_glProgramUniformMatrix2x3dv; +#define glProgramUniformMatrix2x3dv glad_glProgramUniformMatrix2x3dv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC glad_glProgramUniformMatrix3x2dv; +#define glProgramUniformMatrix3x2dv glad_glProgramUniformMatrix3x2dv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC glad_glProgramUniformMatrix2x4dv; +#define glProgramUniformMatrix2x4dv glad_glProgramUniformMatrix2x4dv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC glad_glProgramUniformMatrix4x2dv; +#define glProgramUniformMatrix4x2dv glad_glProgramUniformMatrix4x2dv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC glad_glProgramUniformMatrix3x4dv; +#define glProgramUniformMatrix3x4dv glad_glProgramUniformMatrix3x4dv +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC glad_glProgramUniformMatrix4x3dv; +#define glProgramUniformMatrix4x3dv glad_glProgramUniformMatrix4x3dv +typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPIPELINEPROC)(GLuint pipeline); +GLAPI PFNGLVALIDATEPROGRAMPIPELINEPROC glad_glValidateProgramPipeline; +#define glValidateProgramPipeline glad_glValidateProgramPipeline +typedef void (APIENTRYP PFNGLGETPROGRAMPIPELINEINFOLOGPROC)(GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GLAPI PFNGLGETPROGRAMPIPELINEINFOLOGPROC glad_glGetProgramPipelineInfoLog; +#define glGetProgramPipelineInfoLog glad_glGetProgramPipelineInfoLog +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DPROC)(GLuint index, GLdouble x); +GLAPI PFNGLVERTEXATTRIBL1DPROC glad_glVertexAttribL1d; +#define glVertexAttribL1d glad_glVertexAttribL1d +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DPROC)(GLuint index, GLdouble x, GLdouble y); +GLAPI PFNGLVERTEXATTRIBL2DPROC glad_glVertexAttribL2d; +#define glVertexAttribL2d glad_glVertexAttribL2d +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI PFNGLVERTEXATTRIBL3DPROC glad_glVertexAttribL3d; +#define glVertexAttribL3d glad_glVertexAttribL3d +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI PFNGLVERTEXATTRIBL4DPROC glad_glVertexAttribL4d; +#define glVertexAttribL4d glad_glVertexAttribL4d +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DVPROC)(GLuint index, const GLdouble *v); +GLAPI PFNGLVERTEXATTRIBL1DVPROC glad_glVertexAttribL1dv; +#define glVertexAttribL1dv glad_glVertexAttribL1dv +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DVPROC)(GLuint index, const GLdouble *v); +GLAPI PFNGLVERTEXATTRIBL2DVPROC glad_glVertexAttribL2dv; +#define glVertexAttribL2dv glad_glVertexAttribL2dv +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DVPROC)(GLuint index, const GLdouble *v); +GLAPI PFNGLVERTEXATTRIBL3DVPROC glad_glVertexAttribL3dv; +#define glVertexAttribL3dv glad_glVertexAttribL3dv +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DVPROC)(GLuint index, const GLdouble *v); +GLAPI PFNGLVERTEXATTRIBL4DVPROC glad_glVertexAttribL4dv; +#define glVertexAttribL4dv glad_glVertexAttribL4dv +typedef void (APIENTRYP PFNGLVERTEXATTRIBLPOINTERPROC)(GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI PFNGLVERTEXATTRIBLPOINTERPROC glad_glVertexAttribLPointer; +#define glVertexAttribLPointer glad_glVertexAttribLPointer +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLDVPROC)(GLuint index, GLenum pname, GLdouble *params); +GLAPI PFNGLGETVERTEXATTRIBLDVPROC glad_glGetVertexAttribLdv; +#define glGetVertexAttribLdv glad_glGetVertexAttribLdv +typedef void (APIENTRYP PFNGLVIEWPORTARRAYVPROC)(GLuint first, GLsizei count, const GLfloat *v); +GLAPI PFNGLVIEWPORTARRAYVPROC glad_glViewportArrayv; +#define glViewportArrayv glad_glViewportArrayv +typedef void (APIENTRYP PFNGLVIEWPORTINDEXEDFPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); +GLAPI PFNGLVIEWPORTINDEXEDFPROC glad_glViewportIndexedf; +#define glViewportIndexedf glad_glViewportIndexedf +typedef void (APIENTRYP PFNGLVIEWPORTINDEXEDFVPROC)(GLuint index, const GLfloat *v); +GLAPI PFNGLVIEWPORTINDEXEDFVPROC glad_glViewportIndexedfv; +#define glViewportIndexedfv glad_glViewportIndexedfv +typedef void (APIENTRYP PFNGLSCISSORARRAYVPROC)(GLuint first, GLsizei count, const GLint *v); +GLAPI PFNGLSCISSORARRAYVPROC glad_glScissorArrayv; +#define glScissorArrayv glad_glScissorArrayv +typedef void (APIENTRYP PFNGLSCISSORINDEXEDPROC)(GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height); +GLAPI PFNGLSCISSORINDEXEDPROC glad_glScissorIndexed; +#define glScissorIndexed glad_glScissorIndexed +typedef void (APIENTRYP PFNGLSCISSORINDEXEDVPROC)(GLuint index, const GLint *v); +GLAPI PFNGLSCISSORINDEXEDVPROC glad_glScissorIndexedv; +#define glScissorIndexedv glad_glScissorIndexedv +typedef void (APIENTRYP PFNGLDEPTHRANGEARRAYVPROC)(GLuint first, GLsizei count, const GLdouble *v); +GLAPI PFNGLDEPTHRANGEARRAYVPROC glad_glDepthRangeArrayv; +#define glDepthRangeArrayv glad_glDepthRangeArrayv +typedef void (APIENTRYP PFNGLDEPTHRANGEINDEXEDPROC)(GLuint index, GLdouble n, GLdouble f); +GLAPI PFNGLDEPTHRANGEINDEXEDPROC glad_glDepthRangeIndexed; +#define glDepthRangeIndexed glad_glDepthRangeIndexed +typedef void (APIENTRYP PFNGLGETFLOATI_VPROC)(GLenum target, GLuint index, GLfloat *data); +GLAPI PFNGLGETFLOATI_VPROC glad_glGetFloati_v; +#define glGetFloati_v glad_glGetFloati_v +typedef void (APIENTRYP PFNGLGETDOUBLEI_VPROC)(GLenum target, GLuint index, GLdouble *data); +GLAPI PFNGLGETDOUBLEI_VPROC glad_glGetDoublei_v; +#define glGetDoublei_v glad_glGetDoublei_v +#endif +#ifndef GL_VERSION_4_2 +#define GL_VERSION_4_2 1 +GLAPI int GLAD_GL_VERSION_4_2; +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC)(GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance); +GLAPI PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC glad_glDrawArraysInstancedBaseInstance; +#define glDrawArraysInstancedBaseInstance glad_glDrawArraysInstancedBaseInstance +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance); +GLAPI PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC glad_glDrawElementsInstancedBaseInstance; +#define glDrawElementsInstancedBaseInstance glad_glDrawElementsInstancedBaseInstance +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance); +GLAPI PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC glad_glDrawElementsInstancedBaseVertexBaseInstance; +#define glDrawElementsInstancedBaseVertexBaseInstance glad_glDrawElementsInstancedBaseVertexBaseInstance +typedef void (APIENTRYP PFNGLGETINTERNALFORMATIVPROC)(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params); +GLAPI PFNGLGETINTERNALFORMATIVPROC glad_glGetInternalformativ; +#define glGetInternalformativ glad_glGetInternalformativ +typedef void (APIENTRYP PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC)(GLuint program, GLuint bufferIndex, GLenum pname, GLint *params); +GLAPI PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC glad_glGetActiveAtomicCounterBufferiv; +#define glGetActiveAtomicCounterBufferiv glad_glGetActiveAtomicCounterBufferiv +typedef void (APIENTRYP PFNGLBINDIMAGETEXTUREPROC)(GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format); +GLAPI PFNGLBINDIMAGETEXTUREPROC glad_glBindImageTexture; +#define glBindImageTexture glad_glBindImageTexture +typedef void (APIENTRYP PFNGLMEMORYBARRIERPROC)(GLbitfield barriers); +GLAPI PFNGLMEMORYBARRIERPROC glad_glMemoryBarrier; +#define glMemoryBarrier glad_glMemoryBarrier +typedef void (APIENTRYP PFNGLTEXSTORAGE1DPROC)(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +GLAPI PFNGLTEXSTORAGE1DPROC glad_glTexStorage1D; +#define glTexStorage1D glad_glTexStorage1D +typedef void (APIENTRYP PFNGLTEXSTORAGE2DPROC)(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI PFNGLTEXSTORAGE2DPROC glad_glTexStorage2D; +#define glTexStorage2D glad_glTexStorage2D +typedef void (APIENTRYP PFNGLTEXSTORAGE3DPROC)(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +GLAPI PFNGLTEXSTORAGE3DPROC glad_glTexStorage3D; +#define glTexStorage3D glad_glTexStorage3D +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC)(GLenum mode, GLuint id, GLsizei instancecount); +GLAPI PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC glad_glDrawTransformFeedbackInstanced; +#define glDrawTransformFeedbackInstanced glad_glDrawTransformFeedbackInstanced +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC)(GLenum mode, GLuint id, GLuint stream, GLsizei instancecount); +GLAPI PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC glad_glDrawTransformFeedbackStreamInstanced; +#define glDrawTransformFeedbackStreamInstanced glad_glDrawTransformFeedbackStreamInstanced +#endif +#ifndef GL_VERSION_4_3 +#define GL_VERSION_4_3 1 +GLAPI int GLAD_GL_VERSION_4_3; +typedef void (APIENTRYP PFNGLCLEARBUFFERDATAPROC)(GLenum target, GLenum internalformat, GLenum format, GLenum type, const void *data); +GLAPI PFNGLCLEARBUFFERDATAPROC glad_glClearBufferData; +#define glClearBufferData glad_glClearBufferData +typedef void (APIENTRYP PFNGLCLEARBUFFERSUBDATAPROC)(GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); +GLAPI PFNGLCLEARBUFFERSUBDATAPROC glad_glClearBufferSubData; +#define glClearBufferSubData glad_glClearBufferSubData +typedef void (APIENTRYP PFNGLDISPATCHCOMPUTEPROC)(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z); +GLAPI PFNGLDISPATCHCOMPUTEPROC glad_glDispatchCompute; +#define glDispatchCompute glad_glDispatchCompute +typedef void (APIENTRYP PFNGLDISPATCHCOMPUTEINDIRECTPROC)(GLintptr indirect); +GLAPI PFNGLDISPATCHCOMPUTEINDIRECTPROC glad_glDispatchComputeIndirect; +#define glDispatchComputeIndirect glad_glDispatchComputeIndirect +typedef void (APIENTRYP PFNGLCOPYIMAGESUBDATAPROC)(GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); +GLAPI PFNGLCOPYIMAGESUBDATAPROC glad_glCopyImageSubData; +#define glCopyImageSubData glad_glCopyImageSubData +typedef void (APIENTRYP PFNGLFRAMEBUFFERPARAMETERIPROC)(GLenum target, GLenum pname, GLint param); +GLAPI PFNGLFRAMEBUFFERPARAMETERIPROC glad_glFramebufferParameteri; +#define glFramebufferParameteri glad_glFramebufferParameteri +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); +GLAPI PFNGLGETFRAMEBUFFERPARAMETERIVPROC glad_glGetFramebufferParameteriv; +#define glGetFramebufferParameteriv glad_glGetFramebufferParameteriv +typedef void (APIENTRYP PFNGLGETINTERNALFORMATI64VPROC)(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint64 *params); +GLAPI PFNGLGETINTERNALFORMATI64VPROC glad_glGetInternalformati64v; +#define glGetInternalformati64v glad_glGetInternalformati64v +typedef void (APIENTRYP PFNGLINVALIDATETEXSUBIMAGEPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth); +GLAPI PFNGLINVALIDATETEXSUBIMAGEPROC glad_glInvalidateTexSubImage; +#define glInvalidateTexSubImage glad_glInvalidateTexSubImage +typedef void (APIENTRYP PFNGLINVALIDATETEXIMAGEPROC)(GLuint texture, GLint level); +GLAPI PFNGLINVALIDATETEXIMAGEPROC glad_glInvalidateTexImage; +#define glInvalidateTexImage glad_glInvalidateTexImage +typedef void (APIENTRYP PFNGLINVALIDATEBUFFERSUBDATAPROC)(GLuint buffer, GLintptr offset, GLsizeiptr length); +GLAPI PFNGLINVALIDATEBUFFERSUBDATAPROC glad_glInvalidateBufferSubData; +#define glInvalidateBufferSubData glad_glInvalidateBufferSubData +typedef void (APIENTRYP PFNGLINVALIDATEBUFFERDATAPROC)(GLuint buffer); +GLAPI PFNGLINVALIDATEBUFFERDATAPROC glad_glInvalidateBufferData; +#define glInvalidateBufferData glad_glInvalidateBufferData +typedef void (APIENTRYP PFNGLINVALIDATEFRAMEBUFFERPROC)(GLenum target, GLsizei numAttachments, const GLenum *attachments); +GLAPI PFNGLINVALIDATEFRAMEBUFFERPROC glad_glInvalidateFramebuffer; +#define glInvalidateFramebuffer glad_glInvalidateFramebuffer +typedef void (APIENTRYP PFNGLINVALIDATESUBFRAMEBUFFERPROC)(GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI PFNGLINVALIDATESUBFRAMEBUFFERPROC glad_glInvalidateSubFramebuffer; +#define glInvalidateSubFramebuffer glad_glInvalidateSubFramebuffer +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTPROC)(GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride); +GLAPI PFNGLMULTIDRAWARRAYSINDIRECTPROC glad_glMultiDrawArraysIndirect; +#define glMultiDrawArraysIndirect glad_glMultiDrawArraysIndirect +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTPROC)(GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride); +GLAPI PFNGLMULTIDRAWELEMENTSINDIRECTPROC glad_glMultiDrawElementsIndirect; +#define glMultiDrawElementsIndirect glad_glMultiDrawElementsIndirect +typedef void (APIENTRYP PFNGLGETPROGRAMINTERFACEIVPROC)(GLuint program, GLenum programInterface, GLenum pname, GLint *params); +GLAPI PFNGLGETPROGRAMINTERFACEIVPROC glad_glGetProgramInterfaceiv; +#define glGetProgramInterfaceiv glad_glGetProgramInterfaceiv +typedef GLuint (APIENTRYP PFNGLGETPROGRAMRESOURCEINDEXPROC)(GLuint program, GLenum programInterface, const GLchar *name); +GLAPI PFNGLGETPROGRAMRESOURCEINDEXPROC glad_glGetProgramResourceIndex; +#define glGetProgramResourceIndex glad_glGetProgramResourceIndex +typedef void (APIENTRYP PFNGLGETPROGRAMRESOURCENAMEPROC)(GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); +GLAPI PFNGLGETPROGRAMRESOURCENAMEPROC glad_glGetProgramResourceName; +#define glGetProgramResourceName glad_glGetProgramResourceName +typedef void (APIENTRYP PFNGLGETPROGRAMRESOURCEIVPROC)(GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLint *params); +GLAPI PFNGLGETPROGRAMRESOURCEIVPROC glad_glGetProgramResourceiv; +#define glGetProgramResourceiv glad_glGetProgramResourceiv +typedef GLint (APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONPROC)(GLuint program, GLenum programInterface, const GLchar *name); +GLAPI PFNGLGETPROGRAMRESOURCELOCATIONPROC glad_glGetProgramResourceLocation; +#define glGetProgramResourceLocation glad_glGetProgramResourceLocation +typedef GLint (APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC)(GLuint program, GLenum programInterface, const GLchar *name); +GLAPI PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC glad_glGetProgramResourceLocationIndex; +#define glGetProgramResourceLocationIndex glad_glGetProgramResourceLocationIndex +typedef void (APIENTRYP PFNGLSHADERSTORAGEBLOCKBINDINGPROC)(GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding); +GLAPI PFNGLSHADERSTORAGEBLOCKBINDINGPROC glad_glShaderStorageBlockBinding; +#define glShaderStorageBlockBinding glad_glShaderStorageBlockBinding +typedef void (APIENTRYP PFNGLTEXBUFFERRANGEPROC)(GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI PFNGLTEXBUFFERRANGEPROC glad_glTexBufferRange; +#define glTexBufferRange glad_glTexBufferRange +typedef void (APIENTRYP PFNGLTEXSTORAGE2DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +GLAPI PFNGLTEXSTORAGE2DMULTISAMPLEPROC glad_glTexStorage2DMultisample; +#define glTexStorage2DMultisample glad_glTexStorage2DMultisample +typedef void (APIENTRYP PFNGLTEXSTORAGE3DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +GLAPI PFNGLTEXSTORAGE3DMULTISAMPLEPROC glad_glTexStorage3DMultisample; +#define glTexStorage3DMultisample glad_glTexStorage3DMultisample +typedef void (APIENTRYP PFNGLTEXTUREVIEWPROC)(GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); +GLAPI PFNGLTEXTUREVIEWPROC glad_glTextureView; +#define glTextureView glad_glTextureView +typedef void (APIENTRYP PFNGLBINDVERTEXBUFFERPROC)(GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +GLAPI PFNGLBINDVERTEXBUFFERPROC glad_glBindVertexBuffer; +#define glBindVertexBuffer glad_glBindVertexBuffer +typedef void (APIENTRYP PFNGLVERTEXATTRIBFORMATPROC)(GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +GLAPI PFNGLVERTEXATTRIBFORMATPROC glad_glVertexAttribFormat; +#define glVertexAttribFormat glad_glVertexAttribFormat +typedef void (APIENTRYP PFNGLVERTEXATTRIBIFORMATPROC)(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI PFNGLVERTEXATTRIBIFORMATPROC glad_glVertexAttribIFormat; +#define glVertexAttribIFormat glad_glVertexAttribIFormat +typedef void (APIENTRYP PFNGLVERTEXATTRIBLFORMATPROC)(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI PFNGLVERTEXATTRIBLFORMATPROC glad_glVertexAttribLFormat; +#define glVertexAttribLFormat glad_glVertexAttribLFormat +typedef void (APIENTRYP PFNGLVERTEXATTRIBBINDINGPROC)(GLuint attribindex, GLuint bindingindex); +GLAPI PFNGLVERTEXATTRIBBINDINGPROC glad_glVertexAttribBinding; +#define glVertexAttribBinding glad_glVertexAttribBinding +typedef void (APIENTRYP PFNGLVERTEXBINDINGDIVISORPROC)(GLuint bindingindex, GLuint divisor); +GLAPI PFNGLVERTEXBINDINGDIVISORPROC glad_glVertexBindingDivisor; +#define glVertexBindingDivisor glad_glVertexBindingDivisor +typedef void (APIENTRYP PFNGLDEBUGMESSAGECONTROLPROC)(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +GLAPI PFNGLDEBUGMESSAGECONTROLPROC glad_glDebugMessageControl; +#define glDebugMessageControl glad_glDebugMessageControl +typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTPROC)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); +GLAPI PFNGLDEBUGMESSAGEINSERTPROC glad_glDebugMessageInsert; +#define glDebugMessageInsert glad_glDebugMessageInsert +typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKPROC)(GLDEBUGPROC callback, const void *userParam); +GLAPI PFNGLDEBUGMESSAGECALLBACKPROC glad_glDebugMessageCallback; +#define glDebugMessageCallback glad_glDebugMessageCallback +typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGPROC)(GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); +GLAPI PFNGLGETDEBUGMESSAGELOGPROC glad_glGetDebugMessageLog; +#define glGetDebugMessageLog glad_glGetDebugMessageLog +typedef void (APIENTRYP PFNGLPUSHDEBUGGROUPPROC)(GLenum source, GLuint id, GLsizei length, const GLchar *message); +GLAPI PFNGLPUSHDEBUGGROUPPROC glad_glPushDebugGroup; +#define glPushDebugGroup glad_glPushDebugGroup +typedef void (APIENTRYP PFNGLPOPDEBUGGROUPPROC)(); +GLAPI PFNGLPOPDEBUGGROUPPROC glad_glPopDebugGroup; +#define glPopDebugGroup glad_glPopDebugGroup +typedef void (APIENTRYP PFNGLOBJECTLABELPROC)(GLenum identifier, GLuint name, GLsizei length, const GLchar *label); +GLAPI PFNGLOBJECTLABELPROC glad_glObjectLabel; +#define glObjectLabel glad_glObjectLabel +typedef void (APIENTRYP PFNGLGETOBJECTLABELPROC)(GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label); +GLAPI PFNGLGETOBJECTLABELPROC glad_glGetObjectLabel; +#define glGetObjectLabel glad_glGetObjectLabel +typedef void (APIENTRYP PFNGLOBJECTPTRLABELPROC)(const void *ptr, GLsizei length, const GLchar *label); +GLAPI PFNGLOBJECTPTRLABELPROC glad_glObjectPtrLabel; +#define glObjectPtrLabel glad_glObjectPtrLabel +typedef void (APIENTRYP PFNGLGETOBJECTPTRLABELPROC)(const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label); +GLAPI PFNGLGETOBJECTPTRLABELPROC glad_glGetObjectPtrLabel; +#define glGetObjectPtrLabel glad_glGetObjectPtrLabel +#endif +#ifndef GL_VERSION_4_4 +#define GL_VERSION_4_4 1 +GLAPI int GLAD_GL_VERSION_4_4; +typedef void (APIENTRYP PFNGLBUFFERSTORAGEPROC)(GLenum target, GLsizeiptr size, const void *data, GLbitfield flags); +GLAPI PFNGLBUFFERSTORAGEPROC glad_glBufferStorage; +#define glBufferStorage glad_glBufferStorage +typedef void (APIENTRYP PFNGLCLEARTEXIMAGEPROC)(GLuint texture, GLint level, GLenum format, GLenum type, const void *data); +GLAPI PFNGLCLEARTEXIMAGEPROC glad_glClearTexImage; +#define glClearTexImage glad_glClearTexImage +typedef void (APIENTRYP PFNGLCLEARTEXSUBIMAGEPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data); +GLAPI PFNGLCLEARTEXSUBIMAGEPROC glad_glClearTexSubImage; +#define glClearTexSubImage glad_glClearTexSubImage +typedef void (APIENTRYP PFNGLBINDBUFFERSBASEPROC)(GLenum target, GLuint first, GLsizei count, const GLuint *buffers); +GLAPI PFNGLBINDBUFFERSBASEPROC glad_glBindBuffersBase; +#define glBindBuffersBase glad_glBindBuffersBase +typedef void (APIENTRYP PFNGLBINDBUFFERSRANGEPROC)(GLenum target, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizeiptr *sizes); +GLAPI PFNGLBINDBUFFERSRANGEPROC glad_glBindBuffersRange; +#define glBindBuffersRange glad_glBindBuffersRange +typedef void (APIENTRYP PFNGLBINDTEXTURESPROC)(GLuint first, GLsizei count, const GLuint *textures); +GLAPI PFNGLBINDTEXTURESPROC glad_glBindTextures; +#define glBindTextures glad_glBindTextures +typedef void (APIENTRYP PFNGLBINDSAMPLERSPROC)(GLuint first, GLsizei count, const GLuint *samplers); +GLAPI PFNGLBINDSAMPLERSPROC glad_glBindSamplers; +#define glBindSamplers glad_glBindSamplers +typedef void (APIENTRYP PFNGLBINDIMAGETEXTURESPROC)(GLuint first, GLsizei count, const GLuint *textures); +GLAPI PFNGLBINDIMAGETEXTURESPROC glad_glBindImageTextures; +#define glBindImageTextures glad_glBindImageTextures +typedef void (APIENTRYP PFNGLBINDVERTEXBUFFERSPROC)(GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); +GLAPI PFNGLBINDVERTEXBUFFERSPROC glad_glBindVertexBuffers; +#define glBindVertexBuffers glad_glBindVertexBuffers +#endif +#ifndef GL_VERSION_4_5 +#define GL_VERSION_4_5 1 +GLAPI int GLAD_GL_VERSION_4_5; +typedef void (APIENTRYP PFNGLCLIPCONTROLPROC)(GLenum origin, GLenum depth); +GLAPI PFNGLCLIPCONTROLPROC glad_glClipControl; +#define glClipControl glad_glClipControl +typedef void (APIENTRYP PFNGLCREATETRANSFORMFEEDBACKSPROC)(GLsizei n, GLuint *ids); +GLAPI PFNGLCREATETRANSFORMFEEDBACKSPROC glad_glCreateTransformFeedbacks; +#define glCreateTransformFeedbacks glad_glCreateTransformFeedbacks +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKBUFFERBASEPROC)(GLuint xfb, GLuint index, GLuint buffer); +GLAPI PFNGLTRANSFORMFEEDBACKBUFFERBASEPROC glad_glTransformFeedbackBufferBase; +#define glTransformFeedbackBufferBase glad_glTransformFeedbackBufferBase +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKBUFFERRANGEPROC)(GLuint xfb, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI PFNGLTRANSFORMFEEDBACKBUFFERRANGEPROC glad_glTransformFeedbackBufferRange; +#define glTransformFeedbackBufferRange glad_glTransformFeedbackBufferRange +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKIVPROC)(GLuint xfb, GLenum pname, GLint *param); +GLAPI PFNGLGETTRANSFORMFEEDBACKIVPROC glad_glGetTransformFeedbackiv; +#define glGetTransformFeedbackiv glad_glGetTransformFeedbackiv +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI_VPROC)(GLuint xfb, GLenum pname, GLuint index, GLint *param); +GLAPI PFNGLGETTRANSFORMFEEDBACKI_VPROC glad_glGetTransformFeedbacki_v; +#define glGetTransformFeedbacki_v glad_glGetTransformFeedbacki_v +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI64_VPROC)(GLuint xfb, GLenum pname, GLuint index, GLint64 *param); +GLAPI PFNGLGETTRANSFORMFEEDBACKI64_VPROC glad_glGetTransformFeedbacki64_v; +#define glGetTransformFeedbacki64_v glad_glGetTransformFeedbacki64_v +typedef void (APIENTRYP PFNGLCREATEBUFFERSPROC)(GLsizei n, GLuint *buffers); +GLAPI PFNGLCREATEBUFFERSPROC glad_glCreateBuffers; +#define glCreateBuffers glad_glCreateBuffers +typedef void (APIENTRYP PFNGLNAMEDBUFFERSTORAGEPROC)(GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags); +GLAPI PFNGLNAMEDBUFFERSTORAGEPROC glad_glNamedBufferStorage; +#define glNamedBufferStorage glad_glNamedBufferStorage +typedef void (APIENTRYP PFNGLNAMEDBUFFERDATAPROC)(GLuint buffer, GLsizeiptr size, const void *data, GLenum usage); +GLAPI PFNGLNAMEDBUFFERDATAPROC glad_glNamedBufferData; +#define glNamedBufferData glad_glNamedBufferData +typedef void (APIENTRYP PFNGLNAMEDBUFFERSUBDATAPROC)(GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); +GLAPI PFNGLNAMEDBUFFERSUBDATAPROC glad_glNamedBufferSubData; +#define glNamedBufferSubData glad_glNamedBufferSubData +typedef void (APIENTRYP PFNGLCOPYNAMEDBUFFERSUBDATAPROC)(GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +GLAPI PFNGLCOPYNAMEDBUFFERSUBDATAPROC glad_glCopyNamedBufferSubData; +#define glCopyNamedBufferSubData glad_glCopyNamedBufferSubData +typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERDATAPROC)(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); +GLAPI PFNGLCLEARNAMEDBUFFERDATAPROC glad_glClearNamedBufferData; +#define glClearNamedBufferData glad_glClearNamedBufferData +typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERSUBDATAPROC)(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); +GLAPI PFNGLCLEARNAMEDBUFFERSUBDATAPROC glad_glClearNamedBufferSubData; +#define glClearNamedBufferSubData glad_glClearNamedBufferSubData +typedef void * (APIENTRYP PFNGLMAPNAMEDBUFFERPROC)(GLuint buffer, GLenum access); +GLAPI PFNGLMAPNAMEDBUFFERPROC glad_glMapNamedBuffer; +#define glMapNamedBuffer glad_glMapNamedBuffer +typedef void * (APIENTRYP PFNGLMAPNAMEDBUFFERRANGEPROC)(GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access); +GLAPI PFNGLMAPNAMEDBUFFERRANGEPROC glad_glMapNamedBufferRange; +#define glMapNamedBufferRange glad_glMapNamedBufferRange +typedef GLboolean (APIENTRYP PFNGLUNMAPNAMEDBUFFERPROC)(GLuint buffer); +GLAPI PFNGLUNMAPNAMEDBUFFERPROC glad_glUnmapNamedBuffer; +#define glUnmapNamedBuffer glad_glUnmapNamedBuffer +typedef void (APIENTRYP PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEPROC)(GLuint buffer, GLintptr offset, GLsizeiptr length); +GLAPI PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEPROC glad_glFlushMappedNamedBufferRange; +#define glFlushMappedNamedBufferRange glad_glFlushMappedNamedBufferRange +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERIVPROC)(GLuint buffer, GLenum pname, GLint *params); +GLAPI PFNGLGETNAMEDBUFFERPARAMETERIVPROC glad_glGetNamedBufferParameteriv; +#define glGetNamedBufferParameteriv glad_glGetNamedBufferParameteriv +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERI64VPROC)(GLuint buffer, GLenum pname, GLint64 *params); +GLAPI PFNGLGETNAMEDBUFFERPARAMETERI64VPROC glad_glGetNamedBufferParameteri64v; +#define glGetNamedBufferParameteri64v glad_glGetNamedBufferParameteri64v +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPOINTERVPROC)(GLuint buffer, GLenum pname, void **params); +GLAPI PFNGLGETNAMEDBUFFERPOINTERVPROC glad_glGetNamedBufferPointerv; +#define glGetNamedBufferPointerv glad_glGetNamedBufferPointerv +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERSUBDATAPROC)(GLuint buffer, GLintptr offset, GLsizeiptr size, void *data); +GLAPI PFNGLGETNAMEDBUFFERSUBDATAPROC glad_glGetNamedBufferSubData; +#define glGetNamedBufferSubData glad_glGetNamedBufferSubData +typedef void (APIENTRYP PFNGLCREATEFRAMEBUFFERSPROC)(GLsizei n, GLuint *framebuffers); +GLAPI PFNGLCREATEFRAMEBUFFERSPROC glad_glCreateFramebuffers; +#define glCreateFramebuffers glad_glCreateFramebuffers +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERRENDERBUFFERPROC)(GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +GLAPI PFNGLNAMEDFRAMEBUFFERRENDERBUFFERPROC glad_glNamedFramebufferRenderbuffer; +#define glNamedFramebufferRenderbuffer glad_glNamedFramebufferRenderbuffer +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERPARAMETERIPROC)(GLuint framebuffer, GLenum pname, GLint param); +GLAPI PFNGLNAMEDFRAMEBUFFERPARAMETERIPROC glad_glNamedFramebufferParameteri; +#define glNamedFramebufferParameteri glad_glNamedFramebufferParameteri +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTUREPROC)(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); +GLAPI PFNGLNAMEDFRAMEBUFFERTEXTUREPROC glad_glNamedFramebufferTexture; +#define glNamedFramebufferTexture glad_glNamedFramebufferTexture +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC)(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); +GLAPI PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC glad_glNamedFramebufferTextureLayer; +#define glNamedFramebufferTextureLayer glad_glNamedFramebufferTextureLayer +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERDRAWBUFFERPROC)(GLuint framebuffer, GLenum buf); +GLAPI PFNGLNAMEDFRAMEBUFFERDRAWBUFFERPROC glad_glNamedFramebufferDrawBuffer; +#define glNamedFramebufferDrawBuffer glad_glNamedFramebufferDrawBuffer +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERDRAWBUFFERSPROC)(GLuint framebuffer, GLsizei n, const GLenum *bufs); +GLAPI PFNGLNAMEDFRAMEBUFFERDRAWBUFFERSPROC glad_glNamedFramebufferDrawBuffers; +#define glNamedFramebufferDrawBuffers glad_glNamedFramebufferDrawBuffers +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERREADBUFFERPROC)(GLuint framebuffer, GLenum src); +GLAPI PFNGLNAMEDFRAMEBUFFERREADBUFFERPROC glad_glNamedFramebufferReadBuffer; +#define glNamedFramebufferReadBuffer glad_glNamedFramebufferReadBuffer +typedef void (APIENTRYP PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC)(GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments); +GLAPI PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC glad_glInvalidateNamedFramebufferData; +#define glInvalidateNamedFramebufferData glad_glInvalidateNamedFramebufferData +typedef void (APIENTRYP PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC)(GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC glad_glInvalidateNamedFramebufferSubData; +#define glInvalidateNamedFramebufferSubData glad_glInvalidateNamedFramebufferSubData +typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERIVPROC)(GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLint *value); +GLAPI PFNGLCLEARNAMEDFRAMEBUFFERIVPROC glad_glClearNamedFramebufferiv; +#define glClearNamedFramebufferiv glad_glClearNamedFramebufferiv +typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERUIVPROC)(GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLuint *value); +GLAPI PFNGLCLEARNAMEDFRAMEBUFFERUIVPROC glad_glClearNamedFramebufferuiv; +#define glClearNamedFramebufferuiv glad_glClearNamedFramebufferuiv +typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERFVPROC)(GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLfloat *value); +GLAPI PFNGLCLEARNAMEDFRAMEBUFFERFVPROC glad_glClearNamedFramebufferfv; +#define glClearNamedFramebufferfv glad_glClearNamedFramebufferfv +typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERFIPROC)(GLuint framebuffer, GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); +GLAPI PFNGLCLEARNAMEDFRAMEBUFFERFIPROC glad_glClearNamedFramebufferfi; +#define glClearNamedFramebufferfi glad_glClearNamedFramebufferfi +typedef void (APIENTRYP PFNGLBLITNAMEDFRAMEBUFFERPROC)(GLuint readFramebuffer, GLuint drawFramebuffer, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +GLAPI PFNGLBLITNAMEDFRAMEBUFFERPROC glad_glBlitNamedFramebuffer; +#define glBlitNamedFramebuffer glad_glBlitNamedFramebuffer +typedef GLenum (APIENTRYP PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC)(GLuint framebuffer, GLenum target); +GLAPI PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC glad_glCheckNamedFramebufferStatus; +#define glCheckNamedFramebufferStatus glad_glCheckNamedFramebufferStatus +typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVPROC)(GLuint framebuffer, GLenum pname, GLint *param); +GLAPI PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVPROC glad_glGetNamedFramebufferParameteriv; +#define glGetNamedFramebufferParameteriv glad_glGetNamedFramebufferParameteriv +typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC)(GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params); +GLAPI PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetNamedFramebufferAttachmentParameteriv; +#define glGetNamedFramebufferAttachmentParameteriv glad_glGetNamedFramebufferAttachmentParameteriv +typedef void (APIENTRYP PFNGLCREATERENDERBUFFERSPROC)(GLsizei n, GLuint *renderbuffers); +GLAPI PFNGLCREATERENDERBUFFERSPROC glad_glCreateRenderbuffers; +#define glCreateRenderbuffers glad_glCreateRenderbuffers +typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEPROC)(GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI PFNGLNAMEDRENDERBUFFERSTORAGEPROC glad_glNamedRenderbufferStorage; +#define glNamedRenderbufferStorage glad_glNamedRenderbufferStorage +typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC)(GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glNamedRenderbufferStorageMultisample; +#define glNamedRenderbufferStorageMultisample glad_glNamedRenderbufferStorageMultisample +typedef void (APIENTRYP PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC)(GLuint renderbuffer, GLenum pname, GLint *params); +GLAPI PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC glad_glGetNamedRenderbufferParameteriv; +#define glGetNamedRenderbufferParameteriv glad_glGetNamedRenderbufferParameteriv +typedef void (APIENTRYP PFNGLCREATETEXTURESPROC)(GLenum target, GLsizei n, GLuint *textures); +GLAPI PFNGLCREATETEXTURESPROC glad_glCreateTextures; +#define glCreateTextures glad_glCreateTextures +typedef void (APIENTRYP PFNGLTEXTUREBUFFERPROC)(GLuint texture, GLenum internalformat, GLuint buffer); +GLAPI PFNGLTEXTUREBUFFERPROC glad_glTextureBuffer; +#define glTextureBuffer glad_glTextureBuffer +typedef void (APIENTRYP PFNGLTEXTUREBUFFERRANGEPROC)(GLuint texture, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI PFNGLTEXTUREBUFFERRANGEPROC glad_glTextureBufferRange; +#define glTextureBufferRange glad_glTextureBufferRange +typedef void (APIENTRYP PFNGLTEXTURESTORAGE1DPROC)(GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width); +GLAPI PFNGLTEXTURESTORAGE1DPROC glad_glTextureStorage1D; +#define glTextureStorage1D glad_glTextureStorage1D +typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DPROC)(GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI PFNGLTEXTURESTORAGE2DPROC glad_glTextureStorage2D; +#define glTextureStorage2D glad_glTextureStorage2D +typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DPROC)(GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +GLAPI PFNGLTEXTURESTORAGE3DPROC glad_glTextureStorage3D; +#define glTextureStorage3D glad_glTextureStorage3D +typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC)(GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +GLAPI PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC glad_glTextureStorage2DMultisample; +#define glTextureStorage2DMultisample glad_glTextureStorage2DMultisample +typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC)(GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +GLAPI PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC glad_glTextureStorage3DMultisample; +#define glTextureStorage3DMultisample glad_glTextureStorage3DMultisample +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE1DPROC)(GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXTURESUBIMAGE1DPROC glad_glTextureSubImage1D; +#define glTextureSubImage1D glad_glTextureSubImage1D +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE2DPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXTURESUBIMAGE2DPROC glad_glTextureSubImage2D; +#define glTextureSubImage2D glad_glTextureSubImage2D +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE3DPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXTURESUBIMAGE3DPROC glad_glTextureSubImage3D; +#define glTextureSubImage3D glad_glTextureSubImage3D +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC)(GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC glad_glCompressedTextureSubImage1D; +#define glCompressedTextureSubImage1D glad_glCompressedTextureSubImage1D +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC glad_glCompressedTextureSubImage2D; +#define glCompressedTextureSubImage2D glad_glCompressedTextureSubImage2D +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC glad_glCompressedTextureSubImage3D; +#define glCompressedTextureSubImage3D glad_glCompressedTextureSubImage3D +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE1DPROC)(GLuint texture, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +GLAPI PFNGLCOPYTEXTURESUBIMAGE1DPROC glad_glCopyTextureSubImage1D; +#define glCopyTextureSubImage1D glad_glCopyTextureSubImage1D +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE2DPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI PFNGLCOPYTEXTURESUBIMAGE2DPROC glad_glCopyTextureSubImage2D; +#define glCopyTextureSubImage2D glad_glCopyTextureSubImage2D +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE3DPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI PFNGLCOPYTEXTURESUBIMAGE3DPROC glad_glCopyTextureSubImage3D; +#define glCopyTextureSubImage3D glad_glCopyTextureSubImage3D +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFPROC)(GLuint texture, GLenum pname, GLfloat param); +GLAPI PFNGLTEXTUREPARAMETERFPROC glad_glTextureParameterf; +#define glTextureParameterf glad_glTextureParameterf +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFVPROC)(GLuint texture, GLenum pname, const GLfloat *param); +GLAPI PFNGLTEXTUREPARAMETERFVPROC glad_glTextureParameterfv; +#define glTextureParameterfv glad_glTextureParameterfv +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIPROC)(GLuint texture, GLenum pname, GLint param); +GLAPI PFNGLTEXTUREPARAMETERIPROC glad_glTextureParameteri; +#define glTextureParameteri glad_glTextureParameteri +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIIVPROC)(GLuint texture, GLenum pname, const GLint *params); +GLAPI PFNGLTEXTUREPARAMETERIIVPROC glad_glTextureParameterIiv; +#define glTextureParameterIiv glad_glTextureParameterIiv +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIUIVPROC)(GLuint texture, GLenum pname, const GLuint *params); +GLAPI PFNGLTEXTUREPARAMETERIUIVPROC glad_glTextureParameterIuiv; +#define glTextureParameterIuiv glad_glTextureParameterIuiv +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIVPROC)(GLuint texture, GLenum pname, const GLint *param); +GLAPI PFNGLTEXTUREPARAMETERIVPROC glad_glTextureParameteriv; +#define glTextureParameteriv glad_glTextureParameteriv +typedef void (APIENTRYP PFNGLGENERATETEXTUREMIPMAPPROC)(GLuint texture); +GLAPI PFNGLGENERATETEXTUREMIPMAPPROC glad_glGenerateTextureMipmap; +#define glGenerateTextureMipmap glad_glGenerateTextureMipmap +typedef void (APIENTRYP PFNGLBINDTEXTUREUNITPROC)(GLuint unit, GLuint texture); +GLAPI PFNGLBINDTEXTUREUNITPROC glad_glBindTextureUnit; +#define glBindTextureUnit glad_glBindTextureUnit +typedef void (APIENTRYP PFNGLGETTEXTUREIMAGEPROC)(GLuint texture, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +GLAPI PFNGLGETTEXTUREIMAGEPROC glad_glGetTextureImage; +#define glGetTextureImage glad_glGetTextureImage +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTUREIMAGEPROC)(GLuint texture, GLint level, GLsizei bufSize, void *pixels); +GLAPI PFNGLGETCOMPRESSEDTEXTUREIMAGEPROC glad_glGetCompressedTextureImage; +#define glGetCompressedTextureImage glad_glGetCompressedTextureImage +typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERFVPROC)(GLuint texture, GLint level, GLenum pname, GLfloat *params); +GLAPI PFNGLGETTEXTURELEVELPARAMETERFVPROC glad_glGetTextureLevelParameterfv; +#define glGetTextureLevelParameterfv glad_glGetTextureLevelParameterfv +typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERIVPROC)(GLuint texture, GLint level, GLenum pname, GLint *params); +GLAPI PFNGLGETTEXTURELEVELPARAMETERIVPROC glad_glGetTextureLevelParameteriv; +#define glGetTextureLevelParameteriv glad_glGetTextureLevelParameteriv +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERFVPROC)(GLuint texture, GLenum pname, GLfloat *params); +GLAPI PFNGLGETTEXTUREPARAMETERFVPROC glad_glGetTextureParameterfv; +#define glGetTextureParameterfv glad_glGetTextureParameterfv +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIIVPROC)(GLuint texture, GLenum pname, GLint *params); +GLAPI PFNGLGETTEXTUREPARAMETERIIVPROC glad_glGetTextureParameterIiv; +#define glGetTextureParameterIiv glad_glGetTextureParameterIiv +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIUIVPROC)(GLuint texture, GLenum pname, GLuint *params); +GLAPI PFNGLGETTEXTUREPARAMETERIUIVPROC glad_glGetTextureParameterIuiv; +#define glGetTextureParameterIuiv glad_glGetTextureParameterIuiv +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIVPROC)(GLuint texture, GLenum pname, GLint *params); +GLAPI PFNGLGETTEXTUREPARAMETERIVPROC glad_glGetTextureParameteriv; +#define glGetTextureParameteriv glad_glGetTextureParameteriv +typedef void (APIENTRYP PFNGLCREATEVERTEXARRAYSPROC)(GLsizei n, GLuint *arrays); +GLAPI PFNGLCREATEVERTEXARRAYSPROC glad_glCreateVertexArrays; +#define glCreateVertexArrays glad_glCreateVertexArrays +typedef void (APIENTRYP PFNGLDISABLEVERTEXARRAYATTRIBPROC)(GLuint vaobj, GLuint index); +GLAPI PFNGLDISABLEVERTEXARRAYATTRIBPROC glad_glDisableVertexArrayAttrib; +#define glDisableVertexArrayAttrib glad_glDisableVertexArrayAttrib +typedef void (APIENTRYP PFNGLENABLEVERTEXARRAYATTRIBPROC)(GLuint vaobj, GLuint index); +GLAPI PFNGLENABLEVERTEXARRAYATTRIBPROC glad_glEnableVertexArrayAttrib; +#define glEnableVertexArrayAttrib glad_glEnableVertexArrayAttrib +typedef void (APIENTRYP PFNGLVERTEXARRAYELEMENTBUFFERPROC)(GLuint vaobj, GLuint buffer); +GLAPI PFNGLVERTEXARRAYELEMENTBUFFERPROC glad_glVertexArrayElementBuffer; +#define glVertexArrayElementBuffer glad_glVertexArrayElementBuffer +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXBUFFERPROC)(GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +GLAPI PFNGLVERTEXARRAYVERTEXBUFFERPROC glad_glVertexArrayVertexBuffer; +#define glVertexArrayVertexBuffer glad_glVertexArrayVertexBuffer +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXBUFFERSPROC)(GLuint vaobj, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); +GLAPI PFNGLVERTEXARRAYVERTEXBUFFERSPROC glad_glVertexArrayVertexBuffers; +#define glVertexArrayVertexBuffers glad_glVertexArrayVertexBuffers +typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBBINDINGPROC)(GLuint vaobj, GLuint attribindex, GLuint bindingindex); +GLAPI PFNGLVERTEXARRAYATTRIBBINDINGPROC glad_glVertexArrayAttribBinding; +#define glVertexArrayAttribBinding glad_glVertexArrayAttribBinding +typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBFORMATPROC)(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +GLAPI PFNGLVERTEXARRAYATTRIBFORMATPROC glad_glVertexArrayAttribFormat; +#define glVertexArrayAttribFormat glad_glVertexArrayAttribFormat +typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBIFORMATPROC)(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI PFNGLVERTEXARRAYATTRIBIFORMATPROC glad_glVertexArrayAttribIFormat; +#define glVertexArrayAttribIFormat glad_glVertexArrayAttribIFormat +typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBLFORMATPROC)(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI PFNGLVERTEXARRAYATTRIBLFORMATPROC glad_glVertexArrayAttribLFormat; +#define glVertexArrayAttribLFormat glad_glVertexArrayAttribLFormat +typedef void (APIENTRYP PFNGLVERTEXARRAYBINDINGDIVISORPROC)(GLuint vaobj, GLuint bindingindex, GLuint divisor); +GLAPI PFNGLVERTEXARRAYBINDINGDIVISORPROC glad_glVertexArrayBindingDivisor; +#define glVertexArrayBindingDivisor glad_glVertexArrayBindingDivisor +typedef void (APIENTRYP PFNGLGETVERTEXARRAYIVPROC)(GLuint vaobj, GLenum pname, GLint *param); +GLAPI PFNGLGETVERTEXARRAYIVPROC glad_glGetVertexArrayiv; +#define glGetVertexArrayiv glad_glGetVertexArrayiv +typedef void (APIENTRYP PFNGLGETVERTEXARRAYINDEXEDIVPROC)(GLuint vaobj, GLuint index, GLenum pname, GLint *param); +GLAPI PFNGLGETVERTEXARRAYINDEXEDIVPROC glad_glGetVertexArrayIndexediv; +#define glGetVertexArrayIndexediv glad_glGetVertexArrayIndexediv +typedef void (APIENTRYP PFNGLGETVERTEXARRAYINDEXED64IVPROC)(GLuint vaobj, GLuint index, GLenum pname, GLint64 *param); +GLAPI PFNGLGETVERTEXARRAYINDEXED64IVPROC glad_glGetVertexArrayIndexed64iv; +#define glGetVertexArrayIndexed64iv glad_glGetVertexArrayIndexed64iv +typedef void (APIENTRYP PFNGLCREATESAMPLERSPROC)(GLsizei n, GLuint *samplers); +GLAPI PFNGLCREATESAMPLERSPROC glad_glCreateSamplers; +#define glCreateSamplers glad_glCreateSamplers +typedef void (APIENTRYP PFNGLCREATEPROGRAMPIPELINESPROC)(GLsizei n, GLuint *pipelines); +GLAPI PFNGLCREATEPROGRAMPIPELINESPROC glad_glCreateProgramPipelines; +#define glCreateProgramPipelines glad_glCreateProgramPipelines +typedef void (APIENTRYP PFNGLCREATEQUERIESPROC)(GLenum target, GLsizei n, GLuint *ids); +GLAPI PFNGLCREATEQUERIESPROC glad_glCreateQueries; +#define glCreateQueries glad_glCreateQueries +typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTI64VPROC)(GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +GLAPI PFNGLGETQUERYBUFFEROBJECTI64VPROC glad_glGetQueryBufferObjecti64v; +#define glGetQueryBufferObjecti64v glad_glGetQueryBufferObjecti64v +typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTIVPROC)(GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +GLAPI PFNGLGETQUERYBUFFEROBJECTIVPROC glad_glGetQueryBufferObjectiv; +#define glGetQueryBufferObjectiv glad_glGetQueryBufferObjectiv +typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTUI64VPROC)(GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +GLAPI PFNGLGETQUERYBUFFEROBJECTUI64VPROC glad_glGetQueryBufferObjectui64v; +#define glGetQueryBufferObjectui64v glad_glGetQueryBufferObjectui64v +typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTUIVPROC)(GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +GLAPI PFNGLGETQUERYBUFFEROBJECTUIVPROC glad_glGetQueryBufferObjectuiv; +#define glGetQueryBufferObjectuiv glad_glGetQueryBufferObjectuiv +typedef void (APIENTRYP PFNGLMEMORYBARRIERBYREGIONPROC)(GLbitfield barriers); +GLAPI PFNGLMEMORYBARRIERBYREGIONPROC glad_glMemoryBarrierByRegion; +#define glMemoryBarrierByRegion glad_glMemoryBarrierByRegion +typedef void (APIENTRYP PFNGLGETTEXTURESUBIMAGEPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +GLAPI PFNGLGETTEXTURESUBIMAGEPROC glad_glGetTextureSubImage; +#define glGetTextureSubImage glad_glGetTextureSubImage +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei bufSize, void *pixels); +GLAPI PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC glad_glGetCompressedTextureSubImage; +#define glGetCompressedTextureSubImage glad_glGetCompressedTextureSubImage +typedef GLenum (APIENTRYP PFNGLGETGRAPHICSRESETSTATUSPROC)(); +GLAPI PFNGLGETGRAPHICSRESETSTATUSPROC glad_glGetGraphicsResetStatus; +#define glGetGraphicsResetStatus glad_glGetGraphicsResetStatus +typedef void (APIENTRYP PFNGLGETNCOMPRESSEDTEXIMAGEPROC)(GLenum target, GLint lod, GLsizei bufSize, void *pixels); +GLAPI PFNGLGETNCOMPRESSEDTEXIMAGEPROC glad_glGetnCompressedTexImage; +#define glGetnCompressedTexImage glad_glGetnCompressedTexImage +typedef void (APIENTRYP PFNGLGETNTEXIMAGEPROC)(GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +GLAPI PFNGLGETNTEXIMAGEPROC glad_glGetnTexImage; +#define glGetnTexImage glad_glGetnTexImage +typedef void (APIENTRYP PFNGLGETNUNIFORMDVPROC)(GLuint program, GLint location, GLsizei bufSize, GLdouble *params); +GLAPI PFNGLGETNUNIFORMDVPROC glad_glGetnUniformdv; +#define glGetnUniformdv glad_glGetnUniformdv +typedef void (APIENTRYP PFNGLGETNUNIFORMFVPROC)(GLuint program, GLint location, GLsizei bufSize, GLfloat *params); +GLAPI PFNGLGETNUNIFORMFVPROC glad_glGetnUniformfv; +#define glGetnUniformfv glad_glGetnUniformfv +typedef void (APIENTRYP PFNGLGETNUNIFORMIVPROC)(GLuint program, GLint location, GLsizei bufSize, GLint *params); +GLAPI PFNGLGETNUNIFORMIVPROC glad_glGetnUniformiv; +#define glGetnUniformiv glad_glGetnUniformiv +typedef void (APIENTRYP PFNGLGETNUNIFORMUIVPROC)(GLuint program, GLint location, GLsizei bufSize, GLuint *params); +GLAPI PFNGLGETNUNIFORMUIVPROC glad_glGetnUniformuiv; +#define glGetnUniformuiv glad_glGetnUniformuiv +typedef void (APIENTRYP PFNGLREADNPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); +GLAPI PFNGLREADNPIXELSPROC glad_glReadnPixels; +#define glReadnPixels glad_glReadnPixels +typedef void (APIENTRYP PFNGLGETNMAPDVPROC)(GLenum target, GLenum query, GLsizei bufSize, GLdouble *v); +GLAPI PFNGLGETNMAPDVPROC glad_glGetnMapdv; +#define glGetnMapdv glad_glGetnMapdv +typedef void (APIENTRYP PFNGLGETNMAPFVPROC)(GLenum target, GLenum query, GLsizei bufSize, GLfloat *v); +GLAPI PFNGLGETNMAPFVPROC glad_glGetnMapfv; +#define glGetnMapfv glad_glGetnMapfv +typedef void (APIENTRYP PFNGLGETNMAPIVPROC)(GLenum target, GLenum query, GLsizei bufSize, GLint *v); +GLAPI PFNGLGETNMAPIVPROC glad_glGetnMapiv; +#define glGetnMapiv glad_glGetnMapiv +typedef void (APIENTRYP PFNGLGETNPIXELMAPFVPROC)(GLenum map, GLsizei bufSize, GLfloat *values); +GLAPI PFNGLGETNPIXELMAPFVPROC glad_glGetnPixelMapfv; +#define glGetnPixelMapfv glad_glGetnPixelMapfv +typedef void (APIENTRYP PFNGLGETNPIXELMAPUIVPROC)(GLenum map, GLsizei bufSize, GLuint *values); +GLAPI PFNGLGETNPIXELMAPUIVPROC glad_glGetnPixelMapuiv; +#define glGetnPixelMapuiv glad_glGetnPixelMapuiv +typedef void (APIENTRYP PFNGLGETNPIXELMAPUSVPROC)(GLenum map, GLsizei bufSize, GLushort *values); +GLAPI PFNGLGETNPIXELMAPUSVPROC glad_glGetnPixelMapusv; +#define glGetnPixelMapusv glad_glGetnPixelMapusv +typedef void (APIENTRYP PFNGLGETNPOLYGONSTIPPLEPROC)(GLsizei bufSize, GLubyte *pattern); +GLAPI PFNGLGETNPOLYGONSTIPPLEPROC glad_glGetnPolygonStipple; +#define glGetnPolygonStipple glad_glGetnPolygonStipple +typedef void (APIENTRYP PFNGLGETNCOLORTABLEPROC)(GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *table); +GLAPI PFNGLGETNCOLORTABLEPROC glad_glGetnColorTable; +#define glGetnColorTable glad_glGetnColorTable +typedef void (APIENTRYP PFNGLGETNCONVOLUTIONFILTERPROC)(GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *image); +GLAPI PFNGLGETNCONVOLUTIONFILTERPROC glad_glGetnConvolutionFilter; +#define glGetnConvolutionFilter glad_glGetnConvolutionFilter +typedef void (APIENTRYP PFNGLGETNSEPARABLEFILTERPROC)(GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span); +GLAPI PFNGLGETNSEPARABLEFILTERPROC glad_glGetnSeparableFilter; +#define glGetnSeparableFilter glad_glGetnSeparableFilter +typedef void (APIENTRYP PFNGLGETNHISTOGRAMPROC)(GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +GLAPI PFNGLGETNHISTOGRAMPROC glad_glGetnHistogram; +#define glGetnHistogram glad_glGetnHistogram +typedef void (APIENTRYP PFNGLGETNMINMAXPROC)(GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +GLAPI PFNGLGETNMINMAXPROC glad_glGetnMinmax; +#define glGetnMinmax glad_glGetnMinmax +typedef void (APIENTRYP PFNGLTEXTUREBARRIERPROC)(); +GLAPI PFNGLTEXTUREBARRIERPROC glad_glTextureBarrier; +#define glTextureBarrier glad_glTextureBarrier +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/third_party/glad/src/glad.c b/third_party/glad/src/glad.c new file mode 100644 index 0000000000..cc5d472bdf --- /dev/null +++ b/third_party/glad/src/glad.c @@ -0,0 +1,1780 @@ +/* + + OpenGL loader generated by glad 0.1.12a0 on Tue Aug 16 10:59:45 2016. + + Language/Generator: C/C++ + Specification: gl + APIs: gl=4.5 + Profile: core + Extensions: + + Loader: True + Local files: False + Omit khrplatform: False + + Commandline: + --profile="core" --api="gl=4.5" --generator="c" --spec="gl" --extensions="" + Online: + http://glad.dav1d.de/#profile=core&language=c&specification=gl&loader=on&api=gl%3D4.5 +*/ + +#include +#include +#include +#include + +static void* get_proc(const char *namez); + +#ifdef _WIN32 +#include +static HMODULE libGL; + +typedef void* (APIENTRYP PFNWGLGETPROCADDRESSPROC_PRIVATE)(const char*); +PFNWGLGETPROCADDRESSPROC_PRIVATE gladGetProcAddressPtr; + +static +int open_gl(void) { + libGL = LoadLibraryW(L"opengl32.dll"); + if(libGL != NULL) { + gladGetProcAddressPtr = (PFNWGLGETPROCADDRESSPROC_PRIVATE)GetProcAddress( + libGL, "wglGetProcAddress"); + return gladGetProcAddressPtr != NULL; + } + + return 0; +} + +static +void close_gl(void) { + if(libGL != NULL) { + FreeLibrary(libGL); + libGL = NULL; + } +} +#else +#include +static void* libGL; + +#ifndef __APPLE__ +typedef void* (APIENTRYP PFNGLXGETPROCADDRESSPROC_PRIVATE)(const char*); +PFNGLXGETPROCADDRESSPROC_PRIVATE gladGetProcAddressPtr; +#endif + +static +int open_gl(void) { +#ifdef __APPLE__ + static const char *NAMES[] = { + "../Frameworks/OpenGL.framework/OpenGL", + "/Library/Frameworks/OpenGL.framework/OpenGL", + "/System/Library/Frameworks/OpenGL.framework/OpenGL", + "/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL" + }; +#else + static const char *NAMES[] = {"libGL.so.1", "libGL.so"}; +#endif + + unsigned int index = 0; + for(index = 0; index < (sizeof(NAMES) / sizeof(NAMES[0])); index++) { + libGL = dlopen(NAMES[index], RTLD_NOW | RTLD_GLOBAL); + + if(libGL != NULL) { +#ifdef __APPLE__ + return 1; +#else + gladGetProcAddressPtr = (PFNGLXGETPROCADDRESSPROC_PRIVATE)dlsym(libGL, + "glXGetProcAddressARB"); + return gladGetProcAddressPtr != NULL; +#endif + } + } + + return 0; +} + +static +void close_gl() { + if(libGL != NULL) { + dlclose(libGL); + libGL = NULL; + } +} +#endif + +static +void* get_proc(const char *namez) { + void* result = NULL; + if(libGL == NULL) return NULL; + +#ifndef __APPLE__ + if(gladGetProcAddressPtr != NULL) { + result = gladGetProcAddressPtr(namez); + } +#endif + if(result == NULL) { +#ifdef _WIN32 + result = (void*)GetProcAddress(libGL, namez); +#else + result = dlsym(libGL, namez); +#endif + } + + return result; +} + +int gladLoadGL(void) { + int status = 0; + + if(open_gl()) { + status = gladLoadGLLoader(&get_proc); + close_gl(); + } + + return status; +} + +struct gladGLversionStruct GLVersion; + +#if defined(GL_ES_VERSION_3_0) || defined(GL_VERSION_3_0) +#define _GLAD_IS_SOME_NEW_VERSION 1 +#endif + +static int max_loaded_major; +static int max_loaded_minor; + +static const char *exts = NULL; +static int num_exts_i = 0; +static const char **exts_i = NULL; + +static int get_exts(void) { +#ifdef _GLAD_IS_SOME_NEW_VERSION + if(max_loaded_major < 3) { +#endif + exts = (const char *)glGetString(GL_EXTENSIONS); +#ifdef _GLAD_IS_SOME_NEW_VERSION + } else { + int index; + + num_exts_i = 0; + glGetIntegerv(GL_NUM_EXTENSIONS, &num_exts_i); + if (num_exts_i > 0) { + exts_i = (const char **)realloc((void *)exts_i, num_exts_i * sizeof *exts_i); + } + + if (exts_i == NULL) { + return 0; + } + + for(index = 0; index < num_exts_i; index++) { + exts_i[index] = (const char*)glGetStringi(GL_EXTENSIONS, index); + } + } +#endif + return 1; +} + +static void free_exts(void) { + if (exts_i != NULL) { + free((char **)exts_i); + exts_i = NULL; + } +} + +static int has_ext(const char *ext) { +#ifdef _GLAD_IS_SOME_NEW_VERSION + if(max_loaded_major < 3) { +#endif + const char *extensions; + const char *loc; + const char *terminator; + extensions = exts; + if(extensions == NULL || ext == NULL) { + return 0; + } + + while(1) { + loc = strstr(extensions, ext); + if(loc == NULL) { + return 0; + } + + terminator = loc + strlen(ext); + if((loc == extensions || *(loc - 1) == ' ') && + (*terminator == ' ' || *terminator == '\0')) { + return 1; + } + extensions = terminator; + } +#ifdef _GLAD_IS_SOME_NEW_VERSION + } else { + int index; + + for(index = 0; index < num_exts_i; index++) { + const char *e = exts_i[index]; + + if(strcmp(e, ext) == 0) { + return 1; + } + } + } +#endif + + return 0; +} +int GLAD_GL_VERSION_1_0; +int GLAD_GL_VERSION_1_1; +int GLAD_GL_VERSION_1_2; +int GLAD_GL_VERSION_1_3; +int GLAD_GL_VERSION_1_4; +int GLAD_GL_VERSION_1_5; +int GLAD_GL_VERSION_2_0; +int GLAD_GL_VERSION_2_1; +int GLAD_GL_VERSION_3_0; +int GLAD_GL_VERSION_3_1; +int GLAD_GL_VERSION_3_2; +int GLAD_GL_VERSION_3_3; +int GLAD_GL_VERSION_4_0; +int GLAD_GL_VERSION_4_1; +int GLAD_GL_VERSION_4_2; +int GLAD_GL_VERSION_4_3; +int GLAD_GL_VERSION_4_4; +int GLAD_GL_VERSION_4_5; +PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D; +PFNGLVERTEXATTRIBI3UIPROC glad_glVertexAttribI3ui; +PFNGLVERTEXARRAYELEMENTBUFFERPROC glad_glVertexArrayElementBuffer; +PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate; +PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC glad_glTextureStorage3DMultisample; +PFNGLTEXTUREPARAMETERFVPROC glad_glTextureParameterfv; +PFNGLMINSAMPLESHADINGPROC glad_glMinSampleShading; +PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer; +PFNGLUNIFORMSUBROUTINESUIVPROC glad_glUniformSubroutinesuiv; +PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D; +PFNGLTEXCOORDP3UIVPROC glad_glTexCoordP3uiv; +PFNGLGETDOUBLEI_VPROC glad_glGetDoublei_v; +PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv; +PFNGLVERTEXARRAYVERTEXBUFFERSPROC glad_glVertexArrayVertexBuffers; +PFNGLBINDSAMPLERPROC glad_glBindSampler; +PFNGLLINEWIDTHPROC glad_glLineWidth; +PFNGLCOLORP3UIVPROC glad_glColorP3uiv; +PFNGLGETINTEGERI_VPROC glad_glGetIntegeri_v; +PFNGLCOMPILESHADERPROC glad_glCompileShader; +PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glad_glGetTransformFeedbackVarying; +PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC glad_glCompressedTextureSubImage3D; +PFNGLGETCOMPRESSEDTEXTUREIMAGEPROC glad_glGetCompressedTextureImage; +PFNGLGETNMAPFVPROC glad_glGetnMapfv; +PFNGLTRANSFORMFEEDBACKBUFFERRANGEPROC glad_glTransformFeedbackBufferRange; +PFNGLGETTEXTUREIMAGEPROC glad_glGetTextureImage; +PFNGLDEPTHRANGEFPROC glad_glDepthRangef; +PFNGLVERTEXATTRIBIPOINTERPROC glad_glVertexAttribIPointer; +PFNGLMULTITEXCOORDP3UIPROC glad_glMultiTexCoordP3ui; +PFNGLGETNAMEDBUFFERPARAMETERIVPROC glad_glGetNamedBufferParameteriv; +PFNGLVERTEXP4UIPROC glad_glVertexP4ui; +PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC glad_glDrawElementsInstancedBaseInstance; +PFNGLENABLEIPROC glad_glEnablei; +PFNGLVERTEXATTRIBP4UIPROC glad_glVertexAttribP4ui; +PFNGLCREATESHADERPROC glad_glCreateShader; +PFNGLISBUFFERPROC glad_glIsBuffer; +PFNGLGETMULTISAMPLEFVPROC glad_glGetMultisamplefv; +PFNGLPROGRAMUNIFORMMATRIX2DVPROC glad_glProgramUniformMatrix2dv; +PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers; +PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D; +PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D; +PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f; +PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate; +PFNGLPROGRAMUNIFORMMATRIX4FVPROC glad_glProgramUniformMatrix4fv; +PFNGLCLEARNAMEDFRAMEBUFFERFIPROC glad_glClearNamedFramebufferfi; +PFNGLGETQUERYBUFFEROBJECTUIVPROC glad_glGetQueryBufferObjectuiv; +PFNGLHINTPROC glad_glHint; +PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s; +PFNGLSAMPLEMASKIPROC glad_glSampleMaski; +PFNGLVERTEXP2UIPROC glad_glVertexP2ui; +PFNGLUNIFORMMATRIX3X2FVPROC glad_glUniformMatrix3x2fv; +PFNGLDEBUGMESSAGECONTROLPROC glad_glDebugMessageControl; +PFNGLPOINTSIZEPROC glad_glPointSize; +PFNGLBINDTEXTUREUNITPROC glad_glBindTextureUnit; +PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv; +PFNGLDELETEPROGRAMPROC glad_glDeleteProgram; +PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv; +PFNGLTEXSTORAGE2DPROC glad_glTexStorage2D; +PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage; +PFNGLWAITSYNCPROC glad_glWaitSync; +PFNGLUNIFORMMATRIX4X3FVPROC glad_glUniformMatrix4x3fv; +PFNGLUNIFORM3IPROC glad_glUniform3i; +PFNGLCLEARBUFFERFVPROC glad_glClearBufferfv; +PFNGLPROGRAMUNIFORM1UIPROC glad_glProgramUniform1ui; +PFNGLBLENDEQUATIONSEPARATEIPROC glad_glBlendEquationSeparatei; +PFNGLGETNMAPIVPROC glad_glGetnMapiv; +PFNGLTEXTUREBARRIERPROC glad_glTextureBarrier; +PFNGLUNIFORM3DPROC glad_glUniform3d; +PFNGLUNIFORM3FPROC glad_glUniform3f; +PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv; +PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv; +PFNGLTEXCOORDP2UIPROC glad_glTexCoordP2ui; +PFNGLCOLORMASKIPROC glad_glColorMaski; +PFNGLCLEARBUFFERFIPROC glad_glClearBufferfi; +PFNGLDRAWARRAYSINDIRECTPROC glad_glDrawArraysIndirect; +PFNGLGENVERTEXARRAYSPROC glad_glGenVertexArrays; +PFNGLPAUSETRANSFORMFEEDBACKPROC glad_glPauseTransformFeedback; +PFNGLMULTITEXCOORDP2UIPROC glad_glMultiTexCoordP2ui; +PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC glad_glProgramUniformMatrix3x2dv; +PFNGLCOPYNAMEDBUFFERSUBDATAPROC glad_glCopyNamedBufferSubData; +PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC glad_glProgramUniformMatrix3x2fv; +PFNGLGETSAMPLERPARAMETERIIVPROC glad_glGetSamplerParameterIiv; +PFNGLGETFRAGDATAINDEXPROC glad_glGetFragDataIndex; +PFNGLVERTEXATTRIBL4DPROC glad_glVertexAttribL4d; +PFNGLBINDIMAGETEXTUREPROC glad_glBindImageTexture; +PFNGLTEXTUREPARAMETERIVPROC glad_glTextureParameteriv; +PFNGLGETQUERYBUFFEROBJECTI64VPROC glad_glGetQueryBufferObjecti64v; +PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv; +PFNGLACTIVESHADERPROGRAMPROC glad_glActiveShaderProgram; +PFNGLUNIFORMMATRIX3X4FVPROC glad_glUniformMatrix3x4fv; +PFNGLUNIFORMMATRIX3DVPROC glad_glUniformMatrix3dv; +PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC glad_glProgramUniformMatrix3x4dv; +PFNGLNAMEDFRAMEBUFFERTEXTUREPROC glad_glNamedFramebufferTexture; +PFNGLGETTEXTUREPARAMETERFVPROC glad_glGetTextureParameterfv; +PFNGLINVALIDATEBUFFERSUBDATAPROC glad_glInvalidateBufferSubData; +PFNGLRESUMETRANSFORMFEEDBACKPROC glad_glResumeTransformFeedback; +PFNGLMULTITEXCOORDP4UIPROC glad_glMultiTexCoordP4ui; +PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC glad_glProgramUniformMatrix4x3fv; +PFNGLVIEWPORTARRAYVPROC glad_glViewportArrayv; +PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers; +PFNGLDRAWARRAYSPROC glad_glDrawArrays; +PFNGLUNIFORM1UIPROC glad_glUniform1ui; +PFNGLPROGRAMUNIFORM2UIVPROC glad_glProgramUniform2uiv; +PFNGLVERTEXATTRIBI2IPROC glad_glVertexAttribI2i; +PFNGLTEXCOORDP3UIPROC glad_glTexCoordP3ui; +PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d; +PFNGLCLEARPROC glad_glClear; +PFNGLPROGRAMPARAMETERIPROC glad_glProgramParameteri; +PFNGLGETACTIVEUNIFORMNAMEPROC glad_glGetActiveUniformName; +PFNGLMEMORYBARRIERPROC glad_glMemoryBarrier; +PFNGLGETGRAPHICSRESETSTATUSPROC glad_glGetGraphicsResetStatus; +PFNGLISENABLEDPROC glad_glIsEnabled; +PFNGLSTENCILOPPROC glad_glStencilOp; +PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D; +PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv; +PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub; +PFNGLMAPNAMEDBUFFERRANGEPROC glad_glMapNamedBufferRange; +PFNGLGETFRAGDATALOCATIONPROC glad_glGetFragDataLocation; +PFNGLGETTEXTUREPARAMETERIIVPROC glad_glGetTextureParameterIiv; +PFNGLTEXIMAGE1DPROC glad_glTexImage1D; +PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv; +PFNGLVERTEXARRAYATTRIBIFORMATPROC glad_glVertexArrayAttribIFormat; +PFNGLVERTEXARRAYVERTEXBUFFERPROC glad_glVertexArrayVertexBuffer; +PFNGLGETTEXIMAGEPROC glad_glGetTexImage; +PFNGLGETQUERYOBJECTI64VPROC glad_glGetQueryObjecti64v; +PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers; +PFNGLCREATETEXTURESPROC glad_glCreateTextures; +PFNGLTRANSFORMFEEDBACKBUFFERBASEPROC glad_glTransformFeedbackBufferBase; +PFNGLCLEARTEXSUBIMAGEPROC glad_glClearTexSubImage; +PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders; +PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer; +PFNGLDELETEVERTEXARRAYSPROC glad_glDeleteVertexArrays; +PFNGLBINDVERTEXBUFFERSPROC glad_glBindVertexBuffers; +PFNGLPROGRAMUNIFORM1UIVPROC glad_glProgramUniform1uiv; +PFNGLISVERTEXARRAYPROC glad_glIsVertexArray; +PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray; +PFNGLPROGRAMUNIFORM2IVPROC glad_glProgramUniform2iv; +PFNGLGETQUERYIVPROC glad_glGetQueryiv; +PFNGLGETTRANSFORMFEEDBACKIVPROC glad_glGetTransformFeedbackiv; +PFNGLBLITNAMEDFRAMEBUFFERPROC glad_glBlitNamedFramebuffer; +PFNGLVERTEXARRAYATTRIBLFORMATPROC glad_glVertexArrayAttribLFormat; +PFNGLCREATEQUERIESPROC glad_glCreateQueries; +PFNGLGETSAMPLERPARAMETERFVPROC glad_glGetSamplerParameterfv; +PFNGLSHADERSTORAGEBLOCKBINDINGPROC glad_glShaderStorageBlockBinding; +PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC glad_glProgramUniformMatrix4x2dv; +PFNGLGETUNIFORMINDICESPROC glad_glGetUniformIndices; +PFNGLISSHADERPROC glad_glIsShader; +PFNGLVERTEXATTRIBI4UBVPROC glad_glVertexAttribI4ubv; +PFNGLBEGINQUERYINDEXEDPROC glad_glBeginQueryIndexed; +PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv; +PFNGLENABLEPROC glad_glEnable; +PFNGLGETACTIVEUNIFORMSIVPROC glad_glGetActiveUniformsiv; +PFNGLVERTEXARRAYATTRIBBINDINGPROC glad_glVertexArrayAttribBinding; +PFNGLTEXTURESTORAGE1DPROC glad_glTextureStorage1D; +PFNGLMEMORYBARRIERBYREGIONPROC glad_glMemoryBarrierByRegion; +PFNGLBLENDEQUATIONIPROC glad_glBlendEquationi; +PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation; +PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv; +PFNGLGETTEXTUREPARAMETERIVPROC glad_glGetTextureParameteriv; +PFNGLGETPROGRAMINTERFACEIVPROC glad_glGetProgramInterfaceiv; +PFNGLUNIFORM2DVPROC glad_glUniform2dv; +PFNGLMAPNAMEDBUFFERPROC glad_glMapNamedBuffer; +PFNGLMULTITEXCOORDP3UIVPROC glad_glMultiTexCoordP3uiv; +PFNGLVERTEXATTRIBP3UIPROC glad_glVertexAttribP3ui; +PFNGLVERTEXATTRIBL1DVPROC glad_glVertexAttribL1dv; +PFNGLTEXTUREBUFFERRANGEPROC glad_glTextureBufferRange; +PFNGLGETNUNIFORMDVPROC glad_glGetnUniformdv; +PFNGLPROGRAMUNIFORM3UIPROC glad_glProgramUniform3ui; +PFNGLVERTEXBINDINGDIVISORPROC glad_glVertexBindingDivisor; +PFNGLGETUNIFORMFVPROC glad_glGetUniformfv; +PFNGLGETUNIFORMUIVPROC glad_glGetUniformuiv; +PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC glad_glProgramUniformMatrix2x3fv; +PFNGLGETVERTEXATTRIBIIVPROC glad_glGetVertexAttribIiv; +PFNGLVERTEXARRAYBINDINGDIVISORPROC glad_glVertexArrayBindingDivisor; +PFNGLDRAWBUFFERPROC glad_glDrawBuffer; +PFNGLENDQUERYINDEXEDPROC glad_glEndQueryIndexed; +PFNGLGETNPIXELMAPUSVPROC glad_glGetnPixelMapusv; +PFNGLCLEARBUFFERUIVPROC glad_glClearBufferuiv; +PFNGLDRAWELEMENTSINSTANCEDPROC glad_glDrawElementsInstanced; +PFNGLPROGRAMUNIFORM1IPROC glad_glProgramUniform1i; +PFNGLPATCHPARAMETERIPROC glad_glPatchParameteri; +PFNGLPROGRAMUNIFORM1DPROC glad_glProgramUniform1d; +PFNGLPROGRAMUNIFORM1FPROC glad_glProgramUniform1f; +PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVPROC glad_glGetNamedFramebufferParameteriv; +PFNGLFLUSHPROC glad_glFlush; +PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv; +PFNGLPROGRAMUNIFORM3IVPROC glad_glProgramUniform3iv; +PFNGLGETDEBUGMESSAGELOGPROC glad_glGetDebugMessageLog; +PFNGLNAMEDRENDERBUFFERSTORAGEPROC glad_glNamedRenderbufferStorage; +PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetNamedFramebufferAttachmentParameteriv; +PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv; +PFNGLFENCESYNCPROC glad_glFenceSync; +PFNGLCOLORP3UIPROC glad_glColorP3ui; +PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC glad_glDrawElementsInstancedBaseVertexBaseInstance; +PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv; +PFNGLBEGINCONDITIONALRENDERPROC glad_glBeginConditionalRender; +PFNGLVALIDATEPROGRAMPIPELINEPROC glad_glValidateProgramPipeline; +PFNGLGETNMINMAXPROC glad_glGetnMinmax; +PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv; +PFNGLMULTITEXCOORDP4UIVPROC glad_glMultiTexCoordP4uiv; +PFNGLTEXSTORAGE3DMULTISAMPLEPROC glad_glTexStorage3DMultisample; +PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate; +PFNGLDISABLEVERTEXARRAYATTRIBPROC glad_glDisableVertexArrayAttrib; +PFNGLGENSAMPLERSPROC glad_glGenSamplers; +PFNGLCLAMPCOLORPROC glad_glClampColor; +PFNGLUNIFORM4IVPROC glad_glUniform4iv; +PFNGLCLEARSTENCILPROC glad_glClearStencil; +PFNGLTEXCOORDP1UIVPROC glad_glTexCoordP1uiv; +PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC glad_glGetNamedRenderbufferParameteriv; +PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC glad_glDrawTransformFeedbackInstanced; +PFNGLGENTEXTURESPROC glad_glGenTextures; +PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC glad_glTextureStorage2DMultisample; +PFNGLDRAWTRANSFORMFEEDBACKPROC glad_glDrawTransformFeedback; +PFNGLUNIFORM1DVPROC glad_glUniform1dv; +PFNGLGETTEXPARAMETERIUIVPROC glad_glGetTexParameterIuiv; +PFNGLGETTRANSFORMFEEDBACKI_VPROC glad_glGetTransformFeedbacki_v; +PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv; +PFNGLCLEARNAMEDFRAMEBUFFERUIVPROC glad_glClearNamedFramebufferuiv; +PFNGLISSYNCPROC glad_glIsSync; +PFNGLCLEARNAMEDFRAMEBUFFERIVPROC glad_glClearNamedFramebufferiv; +PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glad_glGetActiveUniformBlockName; +PFNGLUNIFORM2IPROC glad_glUniform2i; +PFNGLUNIFORM2FPROC glad_glUniform2f; +PFNGLUNIFORM2DPROC glad_glUniform2d; +PFNGLTEXCOORDP4UIPROC glad_glTexCoordP4ui; +PFNGLGETPROGRAMIVPROC glad_glGetProgramiv; +PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer; +PFNGLFRAMEBUFFERTEXTURELAYERPROC glad_glFramebufferTextureLayer; +PFNGLPROGRAMUNIFORM4FVPROC glad_glProgramUniform4fv; +PFNGLGETOBJECTPTRLABELPROC glad_glGetObjectPtrLabel; +PFNGLTEXTUREPARAMETERIPROC glad_glTextureParameteri; +PFNGLTEXTUREPARAMETERFPROC glad_glTextureParameterf; +PFNGLFLUSHMAPPEDBUFFERRANGEPROC glad_glFlushMappedBufferRange; +PFNGLPROGRAMUNIFORM2FVPROC glad_glProgramUniform2fv; +PFNGLUNIFORMMATRIX2X3DVPROC glad_glUniformMatrix2x3dv; +PFNGLPROGRAMUNIFORMMATRIX4DVPROC glad_glProgramUniformMatrix4dv; +PFNGLVERTEXATTRIBL3DPROC glad_glVertexAttribL3d; +PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC glad_glProgramUniformMatrix2x4dv; +PFNGLDISPATCHCOMPUTEPROC glad_glDispatchCompute; +PFNGLGENQUERIESPROC glad_glGenQueries; +PFNGLVERTEXATTRIBP1UIPROC glad_glVertexAttribP1ui; +PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D; +PFNGLGETINTEGER64I_VPROC glad_glGetInteger64i_v; +PFNGLDELETESAMPLERSPROC glad_glDeleteSamplers; +PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D; +PFNGLGETTEXTURESUBIMAGEPROC glad_glGetTextureSubImage; +PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer; +PFNGLISENABLEDIPROC glad_glIsEnabledi; +PFNGLBINDBUFFERSRANGEPROC glad_glBindBuffersRange; +PFNGLSECONDARYCOLORP3UIPROC glad_glSecondaryColorP3ui; +PFNGLBINDFRAGDATALOCATIONINDEXEDPROC glad_glBindFragDataLocationIndexed; +PFNGLCOPYIMAGESUBDATAPROC glad_glCopyImageSubData; +PFNGLUNIFORM2IVPROC glad_glUniform2iv; +PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv; +PFNGLUNIFORM4UIVPROC glad_glUniform4uiv; +PFNGLPROGRAMUNIFORM2DVPROC glad_glProgramUniform2dv; +PFNGLTEXTURESUBIMAGE3DPROC glad_glTextureSubImage3D; +PFNGLFRAMEBUFFERTEXTURE1DPROC glad_glFramebufferTexture1D; +PFNGLGETSHADERIVPROC glad_glGetShaderiv; +PFNGLPROGRAMUNIFORMMATRIX3FVPROC glad_glProgramUniformMatrix3fv; +PFNGLOBJECTPTRLABELPROC glad_glObjectPtrLabel; +PFNGLINVALIDATEFRAMEBUFFERPROC glad_glInvalidateFramebuffer; +PFNGLBINDTEXTURESPROC glad_glBindTextures; +PFNGLBINDFRAGDATALOCATIONPROC glad_glBindFragDataLocation; +PFNGLNAMEDBUFFERSTORAGEPROC glad_glNamedBufferStorage; +PFNGLSCISSORARRAYVPROC glad_glScissorArrayv; +PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset; +PFNGLGETDOUBLEVPROC glad_glGetDoublev; +PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d; +PFNGLUNIFORM4DVPROC glad_glUniform4dv; +PFNGLPROGRAMUNIFORM3DVPROC glad_glProgramUniform3dv; +PFNGLGETUNIFORMIVPROC glad_glGetUniformiv; +PFNGLINVALIDATEBUFFERDATAPROC glad_glInvalidateBufferData; +PFNGLGETNCOLORTABLEPROC glad_glGetnColorTable; +PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC glad_glCompressedTextureSubImage1D; +PFNGLMULTITEXCOORDP1UIVPROC glad_glMultiTexCoordP1uiv; +PFNGLUNIFORM3FVPROC glad_glUniform3fv; +PFNGLMULTIDRAWELEMENTSINDIRECTPROC glad_glMultiDrawElementsIndirect; +PFNGLDEPTHRANGEPROC glad_glDepthRange; +PFNGLINVALIDATESUBFRAMEBUFFERPROC glad_glInvalidateSubFramebuffer; +PFNGLMAPBUFFERPROC glad_glMapBuffer; +PFNGLCLEARTEXIMAGEPROC glad_glClearTexImage; +PFNGLVERTEXATTRIBLFORMATPROC glad_glVertexAttribLFormat; +PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D; +PFNGLDELETESYNCPROC glad_glDeleteSync; +PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D; +PFNGLGETTRANSFORMFEEDBACKI64_VPROC glad_glGetTransformFeedbacki64_v; +PFNGLUNIFORMMATRIX4DVPROC glad_glUniformMatrix4dv; +PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv; +PFNGLUNIFORMMATRIX4X2DVPROC glad_glUniformMatrix4x2dv; +PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements; +PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv; +PFNGLUNIFORM3IVPROC glad_glUniform3iv; +PFNGLPOLYGONMODEPROC glad_glPolygonMode; +PFNGLDRAWBUFFERSPROC glad_glDrawBuffers; +PFNGLGETNHISTOGRAMPROC glad_glGetnHistogram; +PFNGLGETACTIVEUNIFORMBLOCKIVPROC glad_glGetActiveUniformBlockiv; +PFNGLNAMEDFRAMEBUFFERREADBUFFERPROC glad_glNamedFramebufferReadBuffer; +PFNGLPROGRAMUNIFORM4IVPROC glad_glProgramUniform4iv; +PFNGLGETPROGRAMBINARYPROC glad_glGetProgramBinary; +PFNGLUSEPROGRAMPROC glad_glUseProgram; +PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog; +PFNGLBINDTRANSFORMFEEDBACKPROC glad_glBindTransformFeedback; +PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray; +PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers; +PFNGLGENERATETEXTUREMIPMAPPROC glad_glGenerateTextureMipmap; +PFNGLSAMPLERPARAMETERIIVPROC glad_glSamplerParameterIiv; +PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glad_glMultiDrawElementsBaseVertex; +PFNGLNAMEDBUFFERSUBDATAPROC glad_glNamedBufferSubData; +PFNGLTEXTURESTORAGE2DPROC glad_glTextureStorage2D; +PFNGLGETNCONVOLUTIONFILTERPROC glad_glGetnConvolutionFilter; +PFNGLUNIFORM2UIVPROC glad_glUniform2uiv; +PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D; +PFNGLFINISHPROC glad_glFinish; +PFNGLDEPTHRANGEINDEXEDPROC glad_glDepthRangeIndexed; +PFNGLDELETESHADERPROC glad_glDeleteShader; +PFNGLGETINTERNALFORMATI64VPROC glad_glGetInternalformati64v; +PFNGLCOPYTEXTURESUBIMAGE1DPROC glad_glCopyTextureSubImage1D; +PFNGLPUSHDEBUGGROUPPROC glad_glPushDebugGroup; +PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv; +PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC glad_glGetProgramResourceLocationIndex; +PFNGLTEXTUREPARAMETERIUIVPROC glad_glTextureParameterIuiv; +PFNGLVIEWPORTPROC glad_glViewport; +PFNGLUNIFORM1UIVPROC glad_glUniform1uiv; +PFNGLTRANSFORMFEEDBACKVARYINGSPROC glad_glTransformFeedbackVaryings; +PFNGLUNIFORM2UIPROC glad_glUniform2ui; +PFNGLGETNMAPDVPROC glad_glGetnMapdv; +PFNGLDEBUGMESSAGECALLBACKPROC glad_glDebugMessageCallback; +PFNGLVERTEXATTRIBI3IPROC glad_glVertexAttribI3i; +PFNGLINVALIDATETEXIMAGEPROC glad_glInvalidateTexImage; +PFNGLVERTEXATTRIBFORMATPROC glad_glVertexAttribFormat; +PFNGLCLEARDEPTHPROC glad_glClearDepth; +PFNGLVERTEXATTRIBI4USVPROC glad_glVertexAttribI4usv; +PFNGLTEXPARAMETERFPROC glad_glTexParameterf; +PFNGLVERTEXATTRIBBINDINGPROC glad_glVertexAttribBinding; +PFNGLTEXPARAMETERIPROC glad_glTexParameteri; +PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC glad_glGetActiveSubroutineUniformiv; +PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource; +PFNGLGETNTEXIMAGEPROC glad_glGetnTexImage; +PFNGLTEXBUFFERPROC glad_glTexBuffer; +PFNGLPIXELSTOREIPROC glad_glPixelStorei; +PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram; +PFNGLPIXELSTOREFPROC glad_glPixelStoref; +PFNGLCREATEBUFFERSPROC glad_glCreateBuffers; +PFNGLGETBOOLEANI_VPROC glad_glGetBooleani_v; +PFNGLCLIPCONTROLPROC glad_glClipControl; +PFNGLMULTITEXCOORDP2UIVPROC glad_glMultiTexCoordP2uiv; +PFNGLGENPROGRAMPIPELINESPROC glad_glGenProgramPipelines; +PFNGLGETINTERNALFORMATIVPROC glad_glGetInternalformativ; +PFNGLCOPYTEXTURESUBIMAGE3DPROC glad_glCopyTextureSubImage3D; +PFNGLVERTEXATTRIBP1UIVPROC glad_glVertexAttribP1uiv; +PFNGLLINKPROGRAMPROC glad_glLinkProgram; +PFNGLBINDTEXTUREPROC glad_glBindTexture; +PFNGLMULTIDRAWARRAYSINDIRECTPROC glad_glMultiDrawArraysIndirect; +PFNGLGETOBJECTLABELPROC glad_glGetObjectLabel; +PFNGLGETPROGRAMPIPELINEINFOLOGPROC glad_glGetProgramPipelineInfoLog; +PFNGLGETSTRINGPROC glad_glGetString; +PFNGLVERTEXATTRIBP2UIVPROC glad_glVertexAttribP2uiv; +PFNGLDETACHSHADERPROC glad_glDetachShader; +PFNGLPROGRAMUNIFORM3IPROC glad_glProgramUniform3i; +PFNGLUNIFORMMATRIX3X4DVPROC glad_glUniformMatrix3x4dv; +PFNGLENDQUERYPROC glad_glEndQuery; +PFNGLNORMALP3UIPROC glad_glNormalP3ui; +PFNGLFRAMEBUFFERPARAMETERIPROC glad_glFramebufferParameteri; +PFNGLGETPROGRAMRESOURCENAMEPROC glad_glGetProgramResourceName; +PFNGLUNIFORMMATRIX4X3DVPROC glad_glUniformMatrix4x3dv; +PFNGLDEPTHRANGEARRAYVPROC glad_glDepthRangeArrayv; +PFNGLVERTEXATTRIBI2UIPROC glad_glVertexAttribI2ui; +PFNGLGETPROGRAMRESOURCELOCATIONPROC glad_glGetProgramResourceLocation; +PFNGLDELETETEXTURESPROC glad_glDeleteTextures; +PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC glad_glGetActiveAtomicCounterBufferiv; +PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate; +PFNGLDELETEQUERIESPROC glad_glDeleteQueries; +PFNGLNORMALP3UIVPROC glad_glNormalP3uiv; +PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f; +PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d; +PFNGLVIEWPORTINDEXEDFVPROC glad_glViewportIndexedfv; +PFNGLBINDBUFFERSBASEPROC glad_glBindBuffersBase; +PFNGLVERTEXATTRIBL4DVPROC glad_glVertexAttribL4dv; +PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv; +PFNGLCREATEVERTEXARRAYSPROC glad_glCreateVertexArrays; +PFNGLPROGRAMUNIFORM1DVPROC glad_glProgramUniform1dv; +PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s; +PFNGLDRAWELEMENTSBASEVERTEXPROC glad_glDrawElementsBaseVertex; +PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage; +PFNGLSAMPLERPARAMETERIPROC glad_glSamplerParameteri; +PFNGLCLEARBUFFERSUBDATAPROC glad_glClearBufferSubData; +PFNGLSAMPLERPARAMETERFPROC glad_glSamplerParameterf; +PFNGLTEXSTORAGE1DPROC glad_glTexStorage1D; +PFNGLUNIFORM1FPROC glad_glUniform1f; +PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv; +PFNGLUNIFORM1DPROC glad_glUniform1d; +PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage; +PFNGLGETNCOMPRESSEDTEXIMAGEPROC glad_glGetnCompressedTexImage; +PFNGLUNIFORM1IPROC glad_glUniform1i; +PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib; +PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D; +PFNGLDISABLEPROC glad_glDisable; +PFNGLLOGICOPPROC glad_glLogicOp; +PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC glad_glProgramUniformMatrix3x4fv; +PFNGLGETTEXTUREPARAMETERIUIVPROC glad_glGetTextureParameterIuiv; +PFNGLPROGRAMUNIFORM4UIVPROC glad_glProgramUniform4uiv; +PFNGLUNIFORM4UIPROC glad_glUniform4ui; +PFNGLCOPYTEXTURESUBIMAGE2DPROC glad_glCopyTextureSubImage2D; +PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer; +PFNGLCULLFACEPROC glad_glCullFace; +PFNGLPROGRAMUNIFORM4IPROC glad_glProgramUniform4i; +PFNGLPROGRAMUNIFORM4FPROC glad_glProgramUniform4f; +PFNGLVIEWPORTINDEXEDFPROC glad_glViewportIndexedf; +PFNGLPROGRAMUNIFORM4DPROC glad_glProgramUniform4d; +PFNGLTEXTUREPARAMETERIIVPROC glad_glTextureParameterIiv; +PFNGLGETSTRINGIPROC glad_glGetStringi; +PFNGLTEXTURESUBIMAGE2DPROC glad_glTextureSubImage2D; +PFNGLSCISSORINDEXEDPROC glad_glScissorIndexed; +PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC glad_glDrawTransformFeedbackStream; +PFNGLATTACHSHADERPROC glad_glAttachShader; +PFNGLQUERYCOUNTERPROC glad_glQueryCounter; +PFNGLPROVOKINGVERTEXPROC glad_glProvokingVertex; +PFNGLSHADERBINARYPROC glad_glShaderBinary; +PFNGLUNMAPNAMEDBUFFERPROC glad_glUnmapNamedBuffer; +PFNGLDRAWELEMENTSPROC glad_glDrawElements; +PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glNamedRenderbufferStorageMultisample; +PFNGLVERTEXATTRIBI4SVPROC glad_glVertexAttribI4sv; +PFNGLCLEARNAMEDBUFFERDATAPROC glad_glClearNamedBufferData; +PFNGLUNIFORM1IVPROC glad_glUniform1iv; +PFNGLCREATESHADERPROGRAMVPROC glad_glCreateShaderProgramv; +PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv; +PFNGLREADBUFFERPROC glad_glReadBuffer; +PFNGLTEXPARAMETERIUIVPROC glad_glTexParameterIuiv; +PFNGLDRAWARRAYSINSTANCEDPROC glad_glDrawArraysInstanced; +PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap; +PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC glad_glCompressedTextureSubImage2D; +PFNGLPROGRAMUNIFORMMATRIX2FVPROC glad_glProgramUniformMatrix2fv; +PFNGLSAMPLERPARAMETERIVPROC glad_glSamplerParameteriv; +PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f; +PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv; +PFNGLPOINTPARAMETERIPROC glad_glPointParameteri; +PFNGLBLENDCOLORPROC glad_glBlendColor; +PFNGLSAMPLERPARAMETERIUIVPROC glad_glSamplerParameterIuiv; +PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC glad_glCheckNamedFramebufferStatus; +PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer; +PFNGLPOINTPARAMETERFPROC glad_glPointParameterf; +PFNGLPROGRAMUNIFORM1IVPROC glad_glProgramUniform1iv; +PFNGLGETVERTEXARRAYIVPROC glad_glGetVertexArrayiv; +PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s; +PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer; +PFNGLVERTEXATTRIBP4UIVPROC glad_glVertexAttribP4uiv; +PFNGLGETPROGRAMSTAGEIVPROC glad_glGetProgramStageiv; +PFNGLISPROGRAMPROC glad_glIsProgram; +PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv; +PFNGLTEXTURESTORAGE3DPROC glad_glTextureStorage3D; +PFNGLUNIFORMMATRIX3X2DVPROC glad_glUniformMatrix3x2dv; +PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv; +PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC glad_glProgramUniformMatrix2x3dv; +PFNGLISTRANSFORMFEEDBACKPROC glad_glIsTransformFeedback; +PFNGLUNIFORM4IPROC glad_glUniform4i; +PFNGLACTIVETEXTUREPROC glad_glActiveTexture; +PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray; +PFNGLISPROGRAMPIPELINEPROC glad_glIsProgramPipeline; +PFNGLREADPIXELSPROC glad_glReadPixels; +PFNGLVERTEXATTRIBI3IVPROC glad_glVertexAttribI3iv; +PFNGLUNIFORM4FPROC glad_glUniform4f; +PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glRenderbufferStorageMultisample; +PFNGLCREATEPROGRAMPIPELINESPROC glad_glCreateProgramPipelines; +PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv; +PFNGLVERTEXATTRIBLPOINTERPROC glad_glVertexAttribLPointer; +PFNGLGETNUNIFORMFVPROC glad_glGetnUniformfv; +PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex; +PFNGLVERTEXATTRIBL2DVPROC glad_glVertexAttribL2dv; +PFNGLENABLEVERTEXARRAYATTRIBPROC glad_glEnableVertexArrayAttrib; +PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC glad_glDrawTransformFeedbackStreamInstanced; +PFNGLGETACTIVESUBROUTINENAMEPROC glad_glGetActiveSubroutineName; +PFNGLVERTEXATTRIBL2DPROC glad_glVertexAttribL2d; +PFNGLSTENCILFUNCPROC glad_glStencilFunc; +PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC glad_glInvalidateNamedFramebufferData; +PFNGLPOPDEBUGGROUPPROC glad_glPopDebugGroup; +PFNGLUNIFORMBLOCKBINDINGPROC glad_glUniformBlockBinding; +PFNGLGETVERTEXARRAYINDEXEDIVPROC glad_glGetVertexArrayIndexediv; +PFNGLCOLORP4UIPROC glad_glColorP4ui; +PFNGLUSEPROGRAMSTAGESPROC glad_glUseProgramStages; +PFNGLPROGRAMUNIFORM3FPROC glad_glProgramUniform3f; +PFNGLPROGRAMUNIFORM3DPROC glad_glProgramUniform3d; +PFNGLVERTEXATTRIBI4IVPROC glad_glVertexAttribI4iv; +PFNGLGETPROGRAMPIPELINEIVPROC glad_glGetProgramPipelineiv; +PFNGLTEXSTORAGE3DPROC glad_glTexStorage3D; +PFNGLNAMEDFRAMEBUFFERDRAWBUFFERPROC glad_glNamedFramebufferDrawBuffer; +PFNGLGETQUERYINDEXEDIVPROC glad_glGetQueryIndexediv; +PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog; +PFNGLOBJECTLABELPROC glad_glObjectLabel; +PFNGLVERTEXATTRIBI4IPROC glad_glVertexAttribI4i; +PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData; +PFNGLGETVERTEXATTRIBLDVPROC glad_glGetVertexAttribLdv; +PFNGLGETNUNIFORMUIVPROC glad_glGetnUniformuiv; +PFNGLGETQUERYBUFFEROBJECTIVPROC glad_glGetQueryBufferObjectiv; +PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate; +PFNGLVERTEXATTRIBI1UIPROC glad_glVertexAttribI1ui; +PFNGLGENBUFFERSPROC glad_glGenBuffers; +PFNGLGETSUBROUTINEINDEXPROC glad_glGetSubroutineIndex; +PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv; +PFNGLGETNPOLYGONSTIPPLEPROC glad_glGetnPolygonStipple; +PFNGLBLENDFUNCPROC glad_glBlendFunc; +PFNGLCREATEPROGRAMPROC glad_glCreateProgram; +PFNGLTEXIMAGE3DPROC glad_glTexImage3D; +PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer; +PFNGLCLEARNAMEDFRAMEBUFFERFVPROC glad_glClearNamedFramebufferfv; +PFNGLGETNAMEDBUFFERSUBDATAPROC glad_glGetNamedBufferSubData; +PFNGLPRIMITIVERESTARTINDEXPROC glad_glPrimitiveRestartIndex; +PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEPROC glad_glFlushMappedNamedBufferRange; +PFNGLINVALIDATETEXSUBIMAGEPROC glad_glInvalidateTexSubImage; +PFNGLBINDIMAGETEXTURESPROC glad_glBindImageTextures; +PFNGLGETINTEGER64VPROC glad_glGetInteger64v; +PFNGLBINDPROGRAMPIPELINEPROC glad_glBindProgramPipeline; +PFNGLSCISSORPROC glad_glScissor; +PFNGLTEXCOORDP4UIVPROC glad_glTexCoordP4uiv; +PFNGLGETBOOLEANVPROC glad_glGetBooleanv; +PFNGLNAMEDFRAMEBUFFERRENDERBUFFERPROC glad_glNamedFramebufferRenderbuffer; +PFNGLVERTEXP2UIVPROC glad_glVertexP2uiv; +PFNGLUNIFORM3UIVPROC glad_glUniform3uiv; +PFNGLCLEARCOLORPROC glad_glClearColor; +PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv; +PFNGLCLEARBUFFERIVPROC glad_glClearBufferiv; +PFNGLGETBUFFERPARAMETERI64VPROC glad_glGetBufferParameteri64v; +PFNGLPROGRAMUNIFORM4DVPROC glad_glProgramUniform4dv; +PFNGLCOLORP4UIVPROC glad_glColorP4uiv; +PFNGLGETTEXTURELEVELPARAMETERIVPROC glad_glGetTextureLevelParameteriv; +PFNGLGETNUNIFORMIVPROC glad_glGetnUniformiv; +PFNGLVERTEXATTRIBI2UIVPROC glad_glVertexAttribI2uiv; +PFNGLUNIFORM3UIPROC glad_glUniform3ui; +PFNGLPROGRAMUNIFORM3UIVPROC glad_glProgramUniform3uiv; +PFNGLVERTEXATTRIBI4UIVPROC glad_glVertexAttribI4uiv; +PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv; +PFNGLUNIFORM2FVPROC glad_glUniform2fv; +PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC glad_glGetActiveSubroutineUniformName; +PFNGLGETPROGRAMRESOURCEINDEXPROC glad_glGetProgramResourceIndex; +PFNGLDRAWELEMENTSINDIRECTPROC glad_glDrawElementsIndirect; +PFNGLGETTEXTURELEVELPARAMETERFVPROC glad_glGetTextureLevelParameterfv; +PFNGLGETNAMEDBUFFERPOINTERVPROC glad_glGetNamedBufferPointerv; +PFNGLDISPATCHCOMPUTEINDIRECTPROC glad_glDispatchComputeIndirect; +PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC glad_glInvalidateNamedFramebufferSubData; +PFNGLGETSAMPLERPARAMETERIUIVPROC glad_glGetSamplerParameterIuiv; +PFNGLBINDBUFFERRANGEPROC glad_glBindBufferRange; +PFNGLTEXTURESUBIMAGE1DPROC glad_glTextureSubImage1D; +PFNGLVERTEXATTRIBL3DVPROC glad_glVertexAttribL3dv; +PFNGLGETUNIFORMDVPROC glad_glGetUniformdv; +PFNGLGETQUERYBUFFEROBJECTUI64VPROC glad_glGetQueryBufferObjectui64v; +PFNGLCLEARDEPTHFPROC glad_glClearDepthf; +PFNGLCREATERENDERBUFFERSPROC glad_glCreateRenderbuffers; +PFNGLUNIFORMMATRIX2X3FVPROC glad_glUniformMatrix2x3fv; +PFNGLGENTRANSFORMFEEDBACKSPROC glad_glGenTransformFeedbacks; +PFNGLGETVERTEXATTRIBIUIVPROC glad_glGetVertexAttribIuiv; +PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv; +PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC glad_glProgramUniformMatrix4x3dv; +PFNGLDEPTHFUNCPROC glad_glDepthFunc; +PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D; +PFNGLPROGRAMBINARYPROC glad_glProgramBinary; +PFNGLVERTEXATTRIBI4BVPROC glad_glVertexAttribI4bv; +PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv; +PFNGLMULTITEXCOORDP1UIPROC glad_glMultiTexCoordP1ui; +PFNGLBUFFERSTORAGEPROC glad_glBufferStorage; +PFNGLCLIENTWAITSYNCPROC glad_glClientWaitSync; +PFNGLVERTEXATTRIBI4UIPROC glad_glVertexAttribI4ui; +PFNGLGETFLOATI_VPROC glad_glGetFloati_v; +PFNGLCOLORMASKPROC glad_glColorMask; +PFNGLTEXTUREBUFFERPROC glad_glTextureBuffer; +PFNGLTEXPARAMETERIIVPROC glad_glTexParameterIiv; +PFNGLBLENDEQUATIONPROC glad_glBlendEquation; +PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation; +PFNGLUNIFORMMATRIX2X4DVPROC glad_glUniformMatrix2x4dv; +PFNGLVERTEXARRAYATTRIBFORMATPROC glad_glVertexArrayAttribFormat; +PFNGLREADNPIXELSPROC glad_glReadnPixels; +PFNGLNAMEDFRAMEBUFFERDRAWBUFFERSPROC glad_glNamedFramebufferDrawBuffers; +PFNGLENDTRANSFORMFEEDBACKPROC glad_glEndTransformFeedback; +PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv; +PFNGLGETUNIFORMSUBROUTINEUIVPROC glad_glGetUniformSubroutineuiv; +PFNGLUNIFORM4FVPROC glad_glUniform4fv; +PFNGLBINDVERTEXBUFFERPROC glad_glBindVertexBuffer; +PFNGLDEBUGMESSAGEINSERTPROC glad_glDebugMessageInsert; +PFNGLCREATESAMPLERSPROC glad_glCreateSamplers; +PFNGLGETPROGRAMRESOURCEIVPROC glad_glGetProgramResourceiv; +PFNGLCLEARBUFFERDATAPROC glad_glClearBufferData; +PFNGLBEGINTRANSFORMFEEDBACKPROC glad_glBeginTransformFeedback; +PFNGLVERTEXATTRIBI1IVPROC glad_glVertexAttribI1iv; +PFNGLISSAMPLERPROC glad_glIsSampler; +PFNGLVERTEXP3UIPROC glad_glVertexP3ui; +PFNGLVERTEXATTRIBDIVISORPROC glad_glVertexAttribDivisor; +PFNGLBINDSAMPLERSPROC glad_glBindSamplers; +PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D; +PFNGLDELETETRANSFORMFEEDBACKSPROC glad_glDeleteTransformFeedbacks; +PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D; +PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glad_glDrawRangeElementsBaseVertex; +PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus; +PFNGLENDCONDITIONALRENDERPROC glad_glEndConditionalRender; +PFNGLVERTEXP3UIVPROC glad_glVertexP3uiv; +PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation; +PFNGLUNIFORMMATRIX4X2FVPROC glad_glUniformMatrix4x2fv; +PFNGLUNIFORMMATRIX2DVPROC glad_glUniformMatrix2dv; +PFNGLBLENDFUNCIPROC glad_glBlendFunci; +PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv; +PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements; +PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv; +PFNGLBINDBUFFERBASEPROC glad_glBindBufferBase; +PFNGLBUFFERSUBDATAPROC glad_glBufferSubData; +PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv; +PFNGLMAPBUFFERRANGEPROC glad_glMapBufferRange; +PFNGLFRAMEBUFFERTEXTUREPROC glad_glFramebufferTexture; +PFNGLBLENDFUNCSEPARATEIPROC glad_glBlendFuncSeparatei; +PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC glad_glProgramUniformMatrix4x2fv; +PFNGLVERTEXATTRIBL1DPROC glad_glVertexAttribL1d; +PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays; +PFNGLVERTEXP4UIVPROC glad_glVertexP4uiv; +PFNGLVERTEXATTRIBI2IVPROC glad_glVertexAttribI2iv; +PFNGLGETSHADERPRECISIONFORMATPROC glad_glGetShaderPrecisionFormat; +PFNGLTEXTUREVIEWPROC glad_glTextureView; +PFNGLDISABLEIPROC glad_glDisablei; +PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC glad_glProgramUniformMatrix2x4fv; +PFNGLSHADERSOURCEPROC glad_glShaderSource; +PFNGLGETNSEPARABLEFILTERPROC glad_glGetnSeparableFilter; +PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers; +PFNGLVERTEXATTRIBI3UIVPROC glad_glVertexAttribI3uiv; +PFNGLRELEASESHADERCOMPILERPROC glad_glReleaseShaderCompiler; +PFNGLVERTEXATTRIBIFORMATPROC glad_glVertexAttribIFormat; +PFNGLCREATEFRAMEBUFFERSPROC glad_glCreateFramebuffers; +PFNGLGETSYNCIVPROC glad_glGetSynciv; +PFNGLGETNPIXELMAPFVPROC glad_glGetnPixelMapfv; +PFNGLTEXCOORDP2UIVPROC glad_glTexCoordP2uiv; +PFNGLPATCHPARAMETERFVPROC glad_glPatchParameterfv; +PFNGLPROGRAMUNIFORM2IPROC glad_glProgramUniform2i; +PFNGLGETNAMEDBUFFERPARAMETERI64VPROC glad_glGetNamedBufferParameteri64v; +PFNGLBEGINQUERYPROC glad_glBeginQuery; +PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv; +PFNGLBINDBUFFERPROC glad_glBindBuffer; +PFNGLTEXSTORAGE2DMULTISAMPLEPROC glad_glTexStorage2DMultisample; +PFNGLPROGRAMUNIFORM2DPROC glad_glProgramUniform2d; +PFNGLPROGRAMUNIFORM2FPROC glad_glProgramUniform2f; +PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv; +PFNGLUNIFORMMATRIX2X4FVPROC glad_glUniformMatrix2x4fv; +PFNGLBUFFERDATAPROC glad_glBufferData; +PFNGLGETTEXPARAMETERIIVPROC glad_glGetTexParameterIiv; +PFNGLTEXCOORDP1UIPROC glad_glTexCoordP1ui; +PFNGLGETERRORPROC glad_glGetError; +PFNGLCREATETRANSFORMFEEDBACKSPROC glad_glCreateTransformFeedbacks; +PFNGLVERTEXATTRIBP2UIPROC glad_glVertexAttribP2ui; +PFNGLGETFLOATVPROC glad_glGetFloatv; +PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D; +PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv; +PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv; +PFNGLVERTEXATTRIBI1IPROC glad_glVertexAttribI1i; +PFNGLVERTEXATTRIBP3UIVPROC glad_glVertexAttribP3uiv; +PFNGLUNIFORM4DPROC glad_glUniform4d; +PFNGLSECONDARYCOLORP3UIVPROC glad_glSecondaryColorP3uiv; +PFNGLGETINTEGERVPROC glad_glGetIntegerv; +PFNGLGETVERTEXARRAYINDEXED64IVPROC glad_glGetVertexArrayIndexed64iv; +PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv; +PFNGLPROGRAMUNIFORMMATRIX3DVPROC glad_glProgramUniformMatrix3dv; +PFNGLFRAMEBUFFERTEXTURE3DPROC glad_glFramebufferTexture3D; +PFNGLISQUERYPROC glad_glIsQuery; +PFNGLPROGRAMUNIFORM2UIPROC glad_glProgramUniform2ui; +PFNGLPROGRAMUNIFORM4UIPROC glad_glProgramUniform4ui; +PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv; +PFNGLTEXIMAGE2DPROC glad_glTexImage2D; +PFNGLSTENCILMASKPROC glad_glStencilMask; +PFNGLSAMPLERPARAMETERFVPROC glad_glSamplerParameterfv; +PFNGLISTEXTUREPROC glad_glIsTexture; +PFNGLNAMEDBUFFERDATAPROC glad_glNamedBufferData; +PFNGLUNIFORM1FVPROC glad_glUniform1fv; +PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv; +PFNGLCLEARNAMEDBUFFERSUBDATAPROC glad_glClearNamedBufferSubData; +PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv; +PFNGLSCISSORINDEXEDVPROC glad_glScissorIndexedv; +PFNGLUNIFORM3DVPROC glad_glUniform3dv; +PFNGLGETNPIXELMAPUIVPROC glad_glGetnPixelMapuiv; +PFNGLPROGRAMUNIFORM3FVPROC glad_glProgramUniform3fv; +PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC glad_glGetSubroutineUniformLocation; +PFNGLGETFRAMEBUFFERPARAMETERIVPROC glad_glGetFramebufferParameteriv; +PFNGLGETSAMPLERPARAMETERIVPROC glad_glGetSamplerParameteriv; +PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC glad_glGetCompressedTextureSubImage; +PFNGLCOPYBUFFERSUBDATAPROC glad_glCopyBufferSubData; +PFNGLVERTEXATTRIBI1UIVPROC glad_glVertexAttribI1uiv; +PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d; +PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f; +PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv; +PFNGLGETQUERYOBJECTUI64VPROC glad_glGetQueryObjectui64v; +PFNGLDEPTHMASKPROC glad_glDepthMask; +PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s; +PFNGLTEXIMAGE3DMULTISAMPLEPROC glad_glTexImage3DMultisample; +PFNGLPROGRAMUNIFORM1FVPROC glad_glProgramUniform1fv; +PFNGLGETUNIFORMBLOCKINDEXPROC glad_glGetUniformBlockIndex; +PFNGLTEXIMAGE2DMULTISAMPLEPROC glad_glTexImage2DMultisample; +PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform; +PFNGLFRONTFACEPROC glad_glFrontFace; +PFNGLTEXBUFFERRANGEPROC glad_glTexBufferRange; +PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC glad_glNamedFramebufferTextureLayer; +PFNGLNAMEDFRAMEBUFFERPARAMETERIPROC glad_glNamedFramebufferParameteri; +PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC glad_glDrawArraysInstancedBaseInstance; +PFNGLDELETEPROGRAMPIPELINESPROC glad_glDeleteProgramPipelines; +static void load_GL_VERSION_1_0(GLADloadproc load) { + if(!GLAD_GL_VERSION_1_0) return; + glad_glCullFace = (PFNGLCULLFACEPROC)load("glCullFace"); + glad_glFrontFace = (PFNGLFRONTFACEPROC)load("glFrontFace"); + glad_glHint = (PFNGLHINTPROC)load("glHint"); + glad_glLineWidth = (PFNGLLINEWIDTHPROC)load("glLineWidth"); + glad_glPointSize = (PFNGLPOINTSIZEPROC)load("glPointSize"); + glad_glPolygonMode = (PFNGLPOLYGONMODEPROC)load("glPolygonMode"); + glad_glScissor = (PFNGLSCISSORPROC)load("glScissor"); + glad_glTexParameterf = (PFNGLTEXPARAMETERFPROC)load("glTexParameterf"); + glad_glTexParameterfv = (PFNGLTEXPARAMETERFVPROC)load("glTexParameterfv"); + glad_glTexParameteri = (PFNGLTEXPARAMETERIPROC)load("glTexParameteri"); + glad_glTexParameteriv = (PFNGLTEXPARAMETERIVPROC)load("glTexParameteriv"); + glad_glTexImage1D = (PFNGLTEXIMAGE1DPROC)load("glTexImage1D"); + glad_glTexImage2D = (PFNGLTEXIMAGE2DPROC)load("glTexImage2D"); + glad_glDrawBuffer = (PFNGLDRAWBUFFERPROC)load("glDrawBuffer"); + glad_glClear = (PFNGLCLEARPROC)load("glClear"); + glad_glClearColor = (PFNGLCLEARCOLORPROC)load("glClearColor"); + glad_glClearStencil = (PFNGLCLEARSTENCILPROC)load("glClearStencil"); + glad_glClearDepth = (PFNGLCLEARDEPTHPROC)load("glClearDepth"); + glad_glStencilMask = (PFNGLSTENCILMASKPROC)load("glStencilMask"); + glad_glColorMask = (PFNGLCOLORMASKPROC)load("glColorMask"); + glad_glDepthMask = (PFNGLDEPTHMASKPROC)load("glDepthMask"); + glad_glDisable = (PFNGLDISABLEPROC)load("glDisable"); + glad_glEnable = (PFNGLENABLEPROC)load("glEnable"); + glad_glFinish = (PFNGLFINISHPROC)load("glFinish"); + glad_glFlush = (PFNGLFLUSHPROC)load("glFlush"); + glad_glBlendFunc = (PFNGLBLENDFUNCPROC)load("glBlendFunc"); + glad_glLogicOp = (PFNGLLOGICOPPROC)load("glLogicOp"); + glad_glStencilFunc = (PFNGLSTENCILFUNCPROC)load("glStencilFunc"); + glad_glStencilOp = (PFNGLSTENCILOPPROC)load("glStencilOp"); + glad_glDepthFunc = (PFNGLDEPTHFUNCPROC)load("glDepthFunc"); + glad_glPixelStoref = (PFNGLPIXELSTOREFPROC)load("glPixelStoref"); + glad_glPixelStorei = (PFNGLPIXELSTOREIPROC)load("glPixelStorei"); + glad_glReadBuffer = (PFNGLREADBUFFERPROC)load("glReadBuffer"); + glad_glReadPixels = (PFNGLREADPIXELSPROC)load("glReadPixels"); + glad_glGetBooleanv = (PFNGLGETBOOLEANVPROC)load("glGetBooleanv"); + glad_glGetDoublev = (PFNGLGETDOUBLEVPROC)load("glGetDoublev"); + glad_glGetError = (PFNGLGETERRORPROC)load("glGetError"); + glad_glGetFloatv = (PFNGLGETFLOATVPROC)load("glGetFloatv"); + glad_glGetIntegerv = (PFNGLGETINTEGERVPROC)load("glGetIntegerv"); + glad_glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); + glad_glGetTexImage = (PFNGLGETTEXIMAGEPROC)load("glGetTexImage"); + glad_glGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC)load("glGetTexParameterfv"); + glad_glGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC)load("glGetTexParameteriv"); + glad_glGetTexLevelParameterfv = (PFNGLGETTEXLEVELPARAMETERFVPROC)load("glGetTexLevelParameterfv"); + glad_glGetTexLevelParameteriv = (PFNGLGETTEXLEVELPARAMETERIVPROC)load("glGetTexLevelParameteriv"); + glad_glIsEnabled = (PFNGLISENABLEDPROC)load("glIsEnabled"); + glad_glDepthRange = (PFNGLDEPTHRANGEPROC)load("glDepthRange"); + glad_glViewport = (PFNGLVIEWPORTPROC)load("glViewport"); +} +static void load_GL_VERSION_1_1(GLADloadproc load) { + if(!GLAD_GL_VERSION_1_1) return; + glad_glDrawArrays = (PFNGLDRAWARRAYSPROC)load("glDrawArrays"); + glad_glDrawElements = (PFNGLDRAWELEMENTSPROC)load("glDrawElements"); + glad_glPolygonOffset = (PFNGLPOLYGONOFFSETPROC)load("glPolygonOffset"); + glad_glCopyTexImage1D = (PFNGLCOPYTEXIMAGE1DPROC)load("glCopyTexImage1D"); + glad_glCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC)load("glCopyTexImage2D"); + glad_glCopyTexSubImage1D = (PFNGLCOPYTEXSUBIMAGE1DPROC)load("glCopyTexSubImage1D"); + glad_glCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC)load("glCopyTexSubImage2D"); + glad_glTexSubImage1D = (PFNGLTEXSUBIMAGE1DPROC)load("glTexSubImage1D"); + glad_glTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC)load("glTexSubImage2D"); + glad_glBindTexture = (PFNGLBINDTEXTUREPROC)load("glBindTexture"); + glad_glDeleteTextures = (PFNGLDELETETEXTURESPROC)load("glDeleteTextures"); + glad_glGenTextures = (PFNGLGENTEXTURESPROC)load("glGenTextures"); + glad_glIsTexture = (PFNGLISTEXTUREPROC)load("glIsTexture"); +} +static void load_GL_VERSION_1_2(GLADloadproc load) { + if(!GLAD_GL_VERSION_1_2) return; + glad_glDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC)load("glDrawRangeElements"); + glad_glTexImage3D = (PFNGLTEXIMAGE3DPROC)load("glTexImage3D"); + glad_glTexSubImage3D = (PFNGLTEXSUBIMAGE3DPROC)load("glTexSubImage3D"); + glad_glCopyTexSubImage3D = (PFNGLCOPYTEXSUBIMAGE3DPROC)load("glCopyTexSubImage3D"); +} +static void load_GL_VERSION_1_3(GLADloadproc load) { + if(!GLAD_GL_VERSION_1_3) return; + glad_glActiveTexture = (PFNGLACTIVETEXTUREPROC)load("glActiveTexture"); + glad_glSampleCoverage = (PFNGLSAMPLECOVERAGEPROC)load("glSampleCoverage"); + glad_glCompressedTexImage3D = (PFNGLCOMPRESSEDTEXIMAGE3DPROC)load("glCompressedTexImage3D"); + glad_glCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)load("glCompressedTexImage2D"); + glad_glCompressedTexImage1D = (PFNGLCOMPRESSEDTEXIMAGE1DPROC)load("glCompressedTexImage1D"); + glad_glCompressedTexSubImage3D = (PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)load("glCompressedTexSubImage3D"); + glad_glCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)load("glCompressedTexSubImage2D"); + glad_glCompressedTexSubImage1D = (PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)load("glCompressedTexSubImage1D"); + glad_glGetCompressedTexImage = (PFNGLGETCOMPRESSEDTEXIMAGEPROC)load("glGetCompressedTexImage"); +} +static void load_GL_VERSION_1_4(GLADloadproc load) { + if(!GLAD_GL_VERSION_1_4) return; + glad_glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)load("glBlendFuncSeparate"); + glad_glMultiDrawArrays = (PFNGLMULTIDRAWARRAYSPROC)load("glMultiDrawArrays"); + glad_glMultiDrawElements = (PFNGLMULTIDRAWELEMENTSPROC)load("glMultiDrawElements"); + glad_glPointParameterf = (PFNGLPOINTPARAMETERFPROC)load("glPointParameterf"); + glad_glPointParameterfv = (PFNGLPOINTPARAMETERFVPROC)load("glPointParameterfv"); + glad_glPointParameteri = (PFNGLPOINTPARAMETERIPROC)load("glPointParameteri"); + glad_glPointParameteriv = (PFNGLPOINTPARAMETERIVPROC)load("glPointParameteriv"); + glad_glBlendColor = (PFNGLBLENDCOLORPROC)load("glBlendColor"); + glad_glBlendEquation = (PFNGLBLENDEQUATIONPROC)load("glBlendEquation"); +} +static void load_GL_VERSION_1_5(GLADloadproc load) { + if(!GLAD_GL_VERSION_1_5) return; + glad_glGenQueries = (PFNGLGENQUERIESPROC)load("glGenQueries"); + glad_glDeleteQueries = (PFNGLDELETEQUERIESPROC)load("glDeleteQueries"); + glad_glIsQuery = (PFNGLISQUERYPROC)load("glIsQuery"); + glad_glBeginQuery = (PFNGLBEGINQUERYPROC)load("glBeginQuery"); + glad_glEndQuery = (PFNGLENDQUERYPROC)load("glEndQuery"); + glad_glGetQueryiv = (PFNGLGETQUERYIVPROC)load("glGetQueryiv"); + glad_glGetQueryObjectiv = (PFNGLGETQUERYOBJECTIVPROC)load("glGetQueryObjectiv"); + glad_glGetQueryObjectuiv = (PFNGLGETQUERYOBJECTUIVPROC)load("glGetQueryObjectuiv"); + glad_glBindBuffer = (PFNGLBINDBUFFERPROC)load("glBindBuffer"); + glad_glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)load("glDeleteBuffers"); + glad_glGenBuffers = (PFNGLGENBUFFERSPROC)load("glGenBuffers"); + glad_glIsBuffer = (PFNGLISBUFFERPROC)load("glIsBuffer"); + glad_glBufferData = (PFNGLBUFFERDATAPROC)load("glBufferData"); + glad_glBufferSubData = (PFNGLBUFFERSUBDATAPROC)load("glBufferSubData"); + glad_glGetBufferSubData = (PFNGLGETBUFFERSUBDATAPROC)load("glGetBufferSubData"); + glad_glMapBuffer = (PFNGLMAPBUFFERPROC)load("glMapBuffer"); + glad_glUnmapBuffer = (PFNGLUNMAPBUFFERPROC)load("glUnmapBuffer"); + glad_glGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC)load("glGetBufferParameteriv"); + glad_glGetBufferPointerv = (PFNGLGETBUFFERPOINTERVPROC)load("glGetBufferPointerv"); +} +static void load_GL_VERSION_2_0(GLADloadproc load) { + if(!GLAD_GL_VERSION_2_0) return; + glad_glBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)load("glBlendEquationSeparate"); + glad_glDrawBuffers = (PFNGLDRAWBUFFERSPROC)load("glDrawBuffers"); + glad_glStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)load("glStencilOpSeparate"); + glad_glStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)load("glStencilFuncSeparate"); + glad_glStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC)load("glStencilMaskSeparate"); + glad_glAttachShader = (PFNGLATTACHSHADERPROC)load("glAttachShader"); + glad_glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)load("glBindAttribLocation"); + glad_glCompileShader = (PFNGLCOMPILESHADERPROC)load("glCompileShader"); + glad_glCreateProgram = (PFNGLCREATEPROGRAMPROC)load("glCreateProgram"); + glad_glCreateShader = (PFNGLCREATESHADERPROC)load("glCreateShader"); + glad_glDeleteProgram = (PFNGLDELETEPROGRAMPROC)load("glDeleteProgram"); + glad_glDeleteShader = (PFNGLDELETESHADERPROC)load("glDeleteShader"); + glad_glDetachShader = (PFNGLDETACHSHADERPROC)load("glDetachShader"); + glad_glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)load("glDisableVertexAttribArray"); + glad_glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)load("glEnableVertexAttribArray"); + glad_glGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC)load("glGetActiveAttrib"); + glad_glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)load("glGetActiveUniform"); + glad_glGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)load("glGetAttachedShaders"); + glad_glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)load("glGetAttribLocation"); + glad_glGetProgramiv = (PFNGLGETPROGRAMIVPROC)load("glGetProgramiv"); + glad_glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)load("glGetProgramInfoLog"); + glad_glGetShaderiv = (PFNGLGETSHADERIVPROC)load("glGetShaderiv"); + glad_glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)load("glGetShaderInfoLog"); + glad_glGetShaderSource = (PFNGLGETSHADERSOURCEPROC)load("glGetShaderSource"); + glad_glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)load("glGetUniformLocation"); + glad_glGetUniformfv = (PFNGLGETUNIFORMFVPROC)load("glGetUniformfv"); + glad_glGetUniformiv = (PFNGLGETUNIFORMIVPROC)load("glGetUniformiv"); + glad_glGetVertexAttribdv = (PFNGLGETVERTEXATTRIBDVPROC)load("glGetVertexAttribdv"); + glad_glGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC)load("glGetVertexAttribfv"); + glad_glGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC)load("glGetVertexAttribiv"); + glad_glGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC)load("glGetVertexAttribPointerv"); + glad_glIsProgram = (PFNGLISPROGRAMPROC)load("glIsProgram"); + glad_glIsShader = (PFNGLISSHADERPROC)load("glIsShader"); + glad_glLinkProgram = (PFNGLLINKPROGRAMPROC)load("glLinkProgram"); + glad_glShaderSource = (PFNGLSHADERSOURCEPROC)load("glShaderSource"); + glad_glUseProgram = (PFNGLUSEPROGRAMPROC)load("glUseProgram"); + glad_glUniform1f = (PFNGLUNIFORM1FPROC)load("glUniform1f"); + glad_glUniform2f = (PFNGLUNIFORM2FPROC)load("glUniform2f"); + glad_glUniform3f = (PFNGLUNIFORM3FPROC)load("glUniform3f"); + glad_glUniform4f = (PFNGLUNIFORM4FPROC)load("glUniform4f"); + glad_glUniform1i = (PFNGLUNIFORM1IPROC)load("glUniform1i"); + glad_glUniform2i = (PFNGLUNIFORM2IPROC)load("glUniform2i"); + glad_glUniform3i = (PFNGLUNIFORM3IPROC)load("glUniform3i"); + glad_glUniform4i = (PFNGLUNIFORM4IPROC)load("glUniform4i"); + glad_glUniform1fv = (PFNGLUNIFORM1FVPROC)load("glUniform1fv"); + glad_glUniform2fv = (PFNGLUNIFORM2FVPROC)load("glUniform2fv"); + glad_glUniform3fv = (PFNGLUNIFORM3FVPROC)load("glUniform3fv"); + glad_glUniform4fv = (PFNGLUNIFORM4FVPROC)load("glUniform4fv"); + glad_glUniform1iv = (PFNGLUNIFORM1IVPROC)load("glUniform1iv"); + glad_glUniform2iv = (PFNGLUNIFORM2IVPROC)load("glUniform2iv"); + glad_glUniform3iv = (PFNGLUNIFORM3IVPROC)load("glUniform3iv"); + glad_glUniform4iv = (PFNGLUNIFORM4IVPROC)load("glUniform4iv"); + glad_glUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC)load("glUniformMatrix2fv"); + glad_glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)load("glUniformMatrix3fv"); + glad_glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)load("glUniformMatrix4fv"); + glad_glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)load("glValidateProgram"); + glad_glVertexAttrib1d = (PFNGLVERTEXATTRIB1DPROC)load("glVertexAttrib1d"); + glad_glVertexAttrib1dv = (PFNGLVERTEXATTRIB1DVPROC)load("glVertexAttrib1dv"); + glad_glVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)load("glVertexAttrib1f"); + glad_glVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)load("glVertexAttrib1fv"); + glad_glVertexAttrib1s = (PFNGLVERTEXATTRIB1SPROC)load("glVertexAttrib1s"); + glad_glVertexAttrib1sv = (PFNGLVERTEXATTRIB1SVPROC)load("glVertexAttrib1sv"); + glad_glVertexAttrib2d = (PFNGLVERTEXATTRIB2DPROC)load("glVertexAttrib2d"); + glad_glVertexAttrib2dv = (PFNGLVERTEXATTRIB2DVPROC)load("glVertexAttrib2dv"); + glad_glVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC)load("glVertexAttrib2f"); + glad_glVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)load("glVertexAttrib2fv"); + glad_glVertexAttrib2s = (PFNGLVERTEXATTRIB2SPROC)load("glVertexAttrib2s"); + glad_glVertexAttrib2sv = (PFNGLVERTEXATTRIB2SVPROC)load("glVertexAttrib2sv"); + glad_glVertexAttrib3d = (PFNGLVERTEXATTRIB3DPROC)load("glVertexAttrib3d"); + glad_glVertexAttrib3dv = (PFNGLVERTEXATTRIB3DVPROC)load("glVertexAttrib3dv"); + glad_glVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC)load("glVertexAttrib3f"); + glad_glVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)load("glVertexAttrib3fv"); + glad_glVertexAttrib3s = (PFNGLVERTEXATTRIB3SPROC)load("glVertexAttrib3s"); + glad_glVertexAttrib3sv = (PFNGLVERTEXATTRIB3SVPROC)load("glVertexAttrib3sv"); + glad_glVertexAttrib4Nbv = (PFNGLVERTEXATTRIB4NBVPROC)load("glVertexAttrib4Nbv"); + glad_glVertexAttrib4Niv = (PFNGLVERTEXATTRIB4NIVPROC)load("glVertexAttrib4Niv"); + glad_glVertexAttrib4Nsv = (PFNGLVERTEXATTRIB4NSVPROC)load("glVertexAttrib4Nsv"); + glad_glVertexAttrib4Nub = (PFNGLVERTEXATTRIB4NUBPROC)load("glVertexAttrib4Nub"); + glad_glVertexAttrib4Nubv = (PFNGLVERTEXATTRIB4NUBVPROC)load("glVertexAttrib4Nubv"); + glad_glVertexAttrib4Nuiv = (PFNGLVERTEXATTRIB4NUIVPROC)load("glVertexAttrib4Nuiv"); + glad_glVertexAttrib4Nusv = (PFNGLVERTEXATTRIB4NUSVPROC)load("glVertexAttrib4Nusv"); + glad_glVertexAttrib4bv = (PFNGLVERTEXATTRIB4BVPROC)load("glVertexAttrib4bv"); + glad_glVertexAttrib4d = (PFNGLVERTEXATTRIB4DPROC)load("glVertexAttrib4d"); + glad_glVertexAttrib4dv = (PFNGLVERTEXATTRIB4DVPROC)load("glVertexAttrib4dv"); + glad_glVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC)load("glVertexAttrib4f"); + glad_glVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)load("glVertexAttrib4fv"); + glad_glVertexAttrib4iv = (PFNGLVERTEXATTRIB4IVPROC)load("glVertexAttrib4iv"); + glad_glVertexAttrib4s = (PFNGLVERTEXATTRIB4SPROC)load("glVertexAttrib4s"); + glad_glVertexAttrib4sv = (PFNGLVERTEXATTRIB4SVPROC)load("glVertexAttrib4sv"); + glad_glVertexAttrib4ubv = (PFNGLVERTEXATTRIB4UBVPROC)load("glVertexAttrib4ubv"); + glad_glVertexAttrib4uiv = (PFNGLVERTEXATTRIB4UIVPROC)load("glVertexAttrib4uiv"); + glad_glVertexAttrib4usv = (PFNGLVERTEXATTRIB4USVPROC)load("glVertexAttrib4usv"); + glad_glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)load("glVertexAttribPointer"); +} +static void load_GL_VERSION_2_1(GLADloadproc load) { + if(!GLAD_GL_VERSION_2_1) return; + glad_glUniformMatrix2x3fv = (PFNGLUNIFORMMATRIX2X3FVPROC)load("glUniformMatrix2x3fv"); + glad_glUniformMatrix3x2fv = (PFNGLUNIFORMMATRIX3X2FVPROC)load("glUniformMatrix3x2fv"); + glad_glUniformMatrix2x4fv = (PFNGLUNIFORMMATRIX2X4FVPROC)load("glUniformMatrix2x4fv"); + glad_glUniformMatrix4x2fv = (PFNGLUNIFORMMATRIX4X2FVPROC)load("glUniformMatrix4x2fv"); + glad_glUniformMatrix3x4fv = (PFNGLUNIFORMMATRIX3X4FVPROC)load("glUniformMatrix3x4fv"); + glad_glUniformMatrix4x3fv = (PFNGLUNIFORMMATRIX4X3FVPROC)load("glUniformMatrix4x3fv"); +} +static void load_GL_VERSION_3_0(GLADloadproc load) { + if(!GLAD_GL_VERSION_3_0) return; + glad_glColorMaski = (PFNGLCOLORMASKIPROC)load("glColorMaski"); + glad_glGetBooleani_v = (PFNGLGETBOOLEANI_VPROC)load("glGetBooleani_v"); + glad_glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)load("glGetIntegeri_v"); + glad_glEnablei = (PFNGLENABLEIPROC)load("glEnablei"); + glad_glDisablei = (PFNGLDISABLEIPROC)load("glDisablei"); + glad_glIsEnabledi = (PFNGLISENABLEDIPROC)load("glIsEnabledi"); + glad_glBeginTransformFeedback = (PFNGLBEGINTRANSFORMFEEDBACKPROC)load("glBeginTransformFeedback"); + glad_glEndTransformFeedback = (PFNGLENDTRANSFORMFEEDBACKPROC)load("glEndTransformFeedback"); + glad_glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)load("glBindBufferRange"); + glad_glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)load("glBindBufferBase"); + glad_glTransformFeedbackVaryings = (PFNGLTRANSFORMFEEDBACKVARYINGSPROC)load("glTransformFeedbackVaryings"); + glad_glGetTransformFeedbackVarying = (PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)load("glGetTransformFeedbackVarying"); + glad_glClampColor = (PFNGLCLAMPCOLORPROC)load("glClampColor"); + glad_glBeginConditionalRender = (PFNGLBEGINCONDITIONALRENDERPROC)load("glBeginConditionalRender"); + glad_glEndConditionalRender = (PFNGLENDCONDITIONALRENDERPROC)load("glEndConditionalRender"); + glad_glVertexAttribIPointer = (PFNGLVERTEXATTRIBIPOINTERPROC)load("glVertexAttribIPointer"); + glad_glGetVertexAttribIiv = (PFNGLGETVERTEXATTRIBIIVPROC)load("glGetVertexAttribIiv"); + glad_glGetVertexAttribIuiv = (PFNGLGETVERTEXATTRIBIUIVPROC)load("glGetVertexAttribIuiv"); + glad_glVertexAttribI1i = (PFNGLVERTEXATTRIBI1IPROC)load("glVertexAttribI1i"); + glad_glVertexAttribI2i = (PFNGLVERTEXATTRIBI2IPROC)load("glVertexAttribI2i"); + glad_glVertexAttribI3i = (PFNGLVERTEXATTRIBI3IPROC)load("glVertexAttribI3i"); + glad_glVertexAttribI4i = (PFNGLVERTEXATTRIBI4IPROC)load("glVertexAttribI4i"); + glad_glVertexAttribI1ui = (PFNGLVERTEXATTRIBI1UIPROC)load("glVertexAttribI1ui"); + glad_glVertexAttribI2ui = (PFNGLVERTEXATTRIBI2UIPROC)load("glVertexAttribI2ui"); + glad_glVertexAttribI3ui = (PFNGLVERTEXATTRIBI3UIPROC)load("glVertexAttribI3ui"); + glad_glVertexAttribI4ui = (PFNGLVERTEXATTRIBI4UIPROC)load("glVertexAttribI4ui"); + glad_glVertexAttribI1iv = (PFNGLVERTEXATTRIBI1IVPROC)load("glVertexAttribI1iv"); + glad_glVertexAttribI2iv = (PFNGLVERTEXATTRIBI2IVPROC)load("glVertexAttribI2iv"); + glad_glVertexAttribI3iv = (PFNGLVERTEXATTRIBI3IVPROC)load("glVertexAttribI3iv"); + glad_glVertexAttribI4iv = (PFNGLVERTEXATTRIBI4IVPROC)load("glVertexAttribI4iv"); + glad_glVertexAttribI1uiv = (PFNGLVERTEXATTRIBI1UIVPROC)load("glVertexAttribI1uiv"); + glad_glVertexAttribI2uiv = (PFNGLVERTEXATTRIBI2UIVPROC)load("glVertexAttribI2uiv"); + glad_glVertexAttribI3uiv = (PFNGLVERTEXATTRIBI3UIVPROC)load("glVertexAttribI3uiv"); + glad_glVertexAttribI4uiv = (PFNGLVERTEXATTRIBI4UIVPROC)load("glVertexAttribI4uiv"); + glad_glVertexAttribI4bv = (PFNGLVERTEXATTRIBI4BVPROC)load("glVertexAttribI4bv"); + glad_glVertexAttribI4sv = (PFNGLVERTEXATTRIBI4SVPROC)load("glVertexAttribI4sv"); + glad_glVertexAttribI4ubv = (PFNGLVERTEXATTRIBI4UBVPROC)load("glVertexAttribI4ubv"); + glad_glVertexAttribI4usv = (PFNGLVERTEXATTRIBI4USVPROC)load("glVertexAttribI4usv"); + glad_glGetUniformuiv = (PFNGLGETUNIFORMUIVPROC)load("glGetUniformuiv"); + glad_glBindFragDataLocation = (PFNGLBINDFRAGDATALOCATIONPROC)load("glBindFragDataLocation"); + glad_glGetFragDataLocation = (PFNGLGETFRAGDATALOCATIONPROC)load("glGetFragDataLocation"); + glad_glUniform1ui = (PFNGLUNIFORM1UIPROC)load("glUniform1ui"); + glad_glUniform2ui = (PFNGLUNIFORM2UIPROC)load("glUniform2ui"); + glad_glUniform3ui = (PFNGLUNIFORM3UIPROC)load("glUniform3ui"); + glad_glUniform4ui = (PFNGLUNIFORM4UIPROC)load("glUniform4ui"); + glad_glUniform1uiv = (PFNGLUNIFORM1UIVPROC)load("glUniform1uiv"); + glad_glUniform2uiv = (PFNGLUNIFORM2UIVPROC)load("glUniform2uiv"); + glad_glUniform3uiv = (PFNGLUNIFORM3UIVPROC)load("glUniform3uiv"); + glad_glUniform4uiv = (PFNGLUNIFORM4UIVPROC)load("glUniform4uiv"); + glad_glTexParameterIiv = (PFNGLTEXPARAMETERIIVPROC)load("glTexParameterIiv"); + glad_glTexParameterIuiv = (PFNGLTEXPARAMETERIUIVPROC)load("glTexParameterIuiv"); + glad_glGetTexParameterIiv = (PFNGLGETTEXPARAMETERIIVPROC)load("glGetTexParameterIiv"); + glad_glGetTexParameterIuiv = (PFNGLGETTEXPARAMETERIUIVPROC)load("glGetTexParameterIuiv"); + glad_glClearBufferiv = (PFNGLCLEARBUFFERIVPROC)load("glClearBufferiv"); + glad_glClearBufferuiv = (PFNGLCLEARBUFFERUIVPROC)load("glClearBufferuiv"); + glad_glClearBufferfv = (PFNGLCLEARBUFFERFVPROC)load("glClearBufferfv"); + glad_glClearBufferfi = (PFNGLCLEARBUFFERFIPROC)load("glClearBufferfi"); + glad_glGetStringi = (PFNGLGETSTRINGIPROC)load("glGetStringi"); + glad_glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)load("glIsRenderbuffer"); + glad_glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)load("glBindRenderbuffer"); + glad_glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)load("glDeleteRenderbuffers"); + glad_glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)load("glGenRenderbuffers"); + glad_glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)load("glRenderbufferStorage"); + glad_glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)load("glGetRenderbufferParameteriv"); + glad_glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)load("glIsFramebuffer"); + glad_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)load("glBindFramebuffer"); + glad_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)load("glDeleteFramebuffers"); + glad_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)load("glGenFramebuffers"); + glad_glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)load("glCheckFramebufferStatus"); + glad_glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC)load("glFramebufferTexture1D"); + glad_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)load("glFramebufferTexture2D"); + glad_glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC)load("glFramebufferTexture3D"); + glad_glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)load("glFramebufferRenderbuffer"); + glad_glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)load("glGetFramebufferAttachmentParameteriv"); + glad_glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)load("glGenerateMipmap"); + glad_glBlitFramebuffer = (PFNGLBLITFRAMEBUFFERPROC)load("glBlitFramebuffer"); + glad_glRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)load("glRenderbufferStorageMultisample"); + glad_glFramebufferTextureLayer = (PFNGLFRAMEBUFFERTEXTURELAYERPROC)load("glFramebufferTextureLayer"); + glad_glMapBufferRange = (PFNGLMAPBUFFERRANGEPROC)load("glMapBufferRange"); + glad_glFlushMappedBufferRange = (PFNGLFLUSHMAPPEDBUFFERRANGEPROC)load("glFlushMappedBufferRange"); + glad_glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)load("glBindVertexArray"); + glad_glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)load("glDeleteVertexArrays"); + glad_glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)load("glGenVertexArrays"); + glad_glIsVertexArray = (PFNGLISVERTEXARRAYPROC)load("glIsVertexArray"); +} +static void load_GL_VERSION_3_1(GLADloadproc load) { + if(!GLAD_GL_VERSION_3_1) return; + glad_glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDPROC)load("glDrawArraysInstanced"); + glad_glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDPROC)load("glDrawElementsInstanced"); + glad_glTexBuffer = (PFNGLTEXBUFFERPROC)load("glTexBuffer"); + glad_glPrimitiveRestartIndex = (PFNGLPRIMITIVERESTARTINDEXPROC)load("glPrimitiveRestartIndex"); + glad_glCopyBufferSubData = (PFNGLCOPYBUFFERSUBDATAPROC)load("glCopyBufferSubData"); + glad_glGetUniformIndices = (PFNGLGETUNIFORMINDICESPROC)load("glGetUniformIndices"); + glad_glGetActiveUniformsiv = (PFNGLGETACTIVEUNIFORMSIVPROC)load("glGetActiveUniformsiv"); + glad_glGetActiveUniformName = (PFNGLGETACTIVEUNIFORMNAMEPROC)load("glGetActiveUniformName"); + glad_glGetUniformBlockIndex = (PFNGLGETUNIFORMBLOCKINDEXPROC)load("glGetUniformBlockIndex"); + glad_glGetActiveUniformBlockiv = (PFNGLGETACTIVEUNIFORMBLOCKIVPROC)load("glGetActiveUniformBlockiv"); + glad_glGetActiveUniformBlockName = (PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)load("glGetActiveUniformBlockName"); + glad_glUniformBlockBinding = (PFNGLUNIFORMBLOCKBINDINGPROC)load("glUniformBlockBinding"); + glad_glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)load("glBindBufferRange"); + glad_glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)load("glBindBufferBase"); + glad_glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)load("glGetIntegeri_v"); +} +static void load_GL_VERSION_3_2(GLADloadproc load) { + if(!GLAD_GL_VERSION_3_2) return; + glad_glDrawElementsBaseVertex = (PFNGLDRAWELEMENTSBASEVERTEXPROC)load("glDrawElementsBaseVertex"); + glad_glDrawRangeElementsBaseVertex = (PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)load("glDrawRangeElementsBaseVertex"); + glad_glDrawElementsInstancedBaseVertex = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)load("glDrawElementsInstancedBaseVertex"); + glad_glMultiDrawElementsBaseVertex = (PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)load("glMultiDrawElementsBaseVertex"); + glad_glProvokingVertex = (PFNGLPROVOKINGVERTEXPROC)load("glProvokingVertex"); + glad_glFenceSync = (PFNGLFENCESYNCPROC)load("glFenceSync"); + glad_glIsSync = (PFNGLISSYNCPROC)load("glIsSync"); + glad_glDeleteSync = (PFNGLDELETESYNCPROC)load("glDeleteSync"); + glad_glClientWaitSync = (PFNGLCLIENTWAITSYNCPROC)load("glClientWaitSync"); + glad_glWaitSync = (PFNGLWAITSYNCPROC)load("glWaitSync"); + glad_glGetInteger64v = (PFNGLGETINTEGER64VPROC)load("glGetInteger64v"); + glad_glGetSynciv = (PFNGLGETSYNCIVPROC)load("glGetSynciv"); + glad_glGetInteger64i_v = (PFNGLGETINTEGER64I_VPROC)load("glGetInteger64i_v"); + glad_glGetBufferParameteri64v = (PFNGLGETBUFFERPARAMETERI64VPROC)load("glGetBufferParameteri64v"); + glad_glFramebufferTexture = (PFNGLFRAMEBUFFERTEXTUREPROC)load("glFramebufferTexture"); + glad_glTexImage2DMultisample = (PFNGLTEXIMAGE2DMULTISAMPLEPROC)load("glTexImage2DMultisample"); + glad_glTexImage3DMultisample = (PFNGLTEXIMAGE3DMULTISAMPLEPROC)load("glTexImage3DMultisample"); + glad_glGetMultisamplefv = (PFNGLGETMULTISAMPLEFVPROC)load("glGetMultisamplefv"); + glad_glSampleMaski = (PFNGLSAMPLEMASKIPROC)load("glSampleMaski"); +} +static void load_GL_VERSION_3_3(GLADloadproc load) { + if(!GLAD_GL_VERSION_3_3) return; + glad_glBindFragDataLocationIndexed = (PFNGLBINDFRAGDATALOCATIONINDEXEDPROC)load("glBindFragDataLocationIndexed"); + glad_glGetFragDataIndex = (PFNGLGETFRAGDATAINDEXPROC)load("glGetFragDataIndex"); + glad_glGenSamplers = (PFNGLGENSAMPLERSPROC)load("glGenSamplers"); + glad_glDeleteSamplers = (PFNGLDELETESAMPLERSPROC)load("glDeleteSamplers"); + glad_glIsSampler = (PFNGLISSAMPLERPROC)load("glIsSampler"); + glad_glBindSampler = (PFNGLBINDSAMPLERPROC)load("glBindSampler"); + glad_glSamplerParameteri = (PFNGLSAMPLERPARAMETERIPROC)load("glSamplerParameteri"); + glad_glSamplerParameteriv = (PFNGLSAMPLERPARAMETERIVPROC)load("glSamplerParameteriv"); + glad_glSamplerParameterf = (PFNGLSAMPLERPARAMETERFPROC)load("glSamplerParameterf"); + glad_glSamplerParameterfv = (PFNGLSAMPLERPARAMETERFVPROC)load("glSamplerParameterfv"); + glad_glSamplerParameterIiv = (PFNGLSAMPLERPARAMETERIIVPROC)load("glSamplerParameterIiv"); + glad_glSamplerParameterIuiv = (PFNGLSAMPLERPARAMETERIUIVPROC)load("glSamplerParameterIuiv"); + glad_glGetSamplerParameteriv = (PFNGLGETSAMPLERPARAMETERIVPROC)load("glGetSamplerParameteriv"); + glad_glGetSamplerParameterIiv = (PFNGLGETSAMPLERPARAMETERIIVPROC)load("glGetSamplerParameterIiv"); + glad_glGetSamplerParameterfv = (PFNGLGETSAMPLERPARAMETERFVPROC)load("glGetSamplerParameterfv"); + glad_glGetSamplerParameterIuiv = (PFNGLGETSAMPLERPARAMETERIUIVPROC)load("glGetSamplerParameterIuiv"); + glad_glQueryCounter = (PFNGLQUERYCOUNTERPROC)load("glQueryCounter"); + glad_glGetQueryObjecti64v = (PFNGLGETQUERYOBJECTI64VPROC)load("glGetQueryObjecti64v"); + glad_glGetQueryObjectui64v = (PFNGLGETQUERYOBJECTUI64VPROC)load("glGetQueryObjectui64v"); + glad_glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISORPROC)load("glVertexAttribDivisor"); + glad_glVertexAttribP1ui = (PFNGLVERTEXATTRIBP1UIPROC)load("glVertexAttribP1ui"); + glad_glVertexAttribP1uiv = (PFNGLVERTEXATTRIBP1UIVPROC)load("glVertexAttribP1uiv"); + glad_glVertexAttribP2ui = (PFNGLVERTEXATTRIBP2UIPROC)load("glVertexAttribP2ui"); + glad_glVertexAttribP2uiv = (PFNGLVERTEXATTRIBP2UIVPROC)load("glVertexAttribP2uiv"); + glad_glVertexAttribP3ui = (PFNGLVERTEXATTRIBP3UIPROC)load("glVertexAttribP3ui"); + glad_glVertexAttribP3uiv = (PFNGLVERTEXATTRIBP3UIVPROC)load("glVertexAttribP3uiv"); + glad_glVertexAttribP4ui = (PFNGLVERTEXATTRIBP4UIPROC)load("glVertexAttribP4ui"); + glad_glVertexAttribP4uiv = (PFNGLVERTEXATTRIBP4UIVPROC)load("glVertexAttribP4uiv"); + glad_glVertexP2ui = (PFNGLVERTEXP2UIPROC)load("glVertexP2ui"); + glad_glVertexP2uiv = (PFNGLVERTEXP2UIVPROC)load("glVertexP2uiv"); + glad_glVertexP3ui = (PFNGLVERTEXP3UIPROC)load("glVertexP3ui"); + glad_glVertexP3uiv = (PFNGLVERTEXP3UIVPROC)load("glVertexP3uiv"); + glad_glVertexP4ui = (PFNGLVERTEXP4UIPROC)load("glVertexP4ui"); + glad_glVertexP4uiv = (PFNGLVERTEXP4UIVPROC)load("glVertexP4uiv"); + glad_glTexCoordP1ui = (PFNGLTEXCOORDP1UIPROC)load("glTexCoordP1ui"); + glad_glTexCoordP1uiv = (PFNGLTEXCOORDP1UIVPROC)load("glTexCoordP1uiv"); + glad_glTexCoordP2ui = (PFNGLTEXCOORDP2UIPROC)load("glTexCoordP2ui"); + glad_glTexCoordP2uiv = (PFNGLTEXCOORDP2UIVPROC)load("glTexCoordP2uiv"); + glad_glTexCoordP3ui = (PFNGLTEXCOORDP3UIPROC)load("glTexCoordP3ui"); + glad_glTexCoordP3uiv = (PFNGLTEXCOORDP3UIVPROC)load("glTexCoordP3uiv"); + glad_glTexCoordP4ui = (PFNGLTEXCOORDP4UIPROC)load("glTexCoordP4ui"); + glad_glTexCoordP4uiv = (PFNGLTEXCOORDP4UIVPROC)load("glTexCoordP4uiv"); + glad_glMultiTexCoordP1ui = (PFNGLMULTITEXCOORDP1UIPROC)load("glMultiTexCoordP1ui"); + glad_glMultiTexCoordP1uiv = (PFNGLMULTITEXCOORDP1UIVPROC)load("glMultiTexCoordP1uiv"); + glad_glMultiTexCoordP2ui = (PFNGLMULTITEXCOORDP2UIPROC)load("glMultiTexCoordP2ui"); + glad_glMultiTexCoordP2uiv = (PFNGLMULTITEXCOORDP2UIVPROC)load("glMultiTexCoordP2uiv"); + glad_glMultiTexCoordP3ui = (PFNGLMULTITEXCOORDP3UIPROC)load("glMultiTexCoordP3ui"); + glad_glMultiTexCoordP3uiv = (PFNGLMULTITEXCOORDP3UIVPROC)load("glMultiTexCoordP3uiv"); + glad_glMultiTexCoordP4ui = (PFNGLMULTITEXCOORDP4UIPROC)load("glMultiTexCoordP4ui"); + glad_glMultiTexCoordP4uiv = (PFNGLMULTITEXCOORDP4UIVPROC)load("glMultiTexCoordP4uiv"); + glad_glNormalP3ui = (PFNGLNORMALP3UIPROC)load("glNormalP3ui"); + glad_glNormalP3uiv = (PFNGLNORMALP3UIVPROC)load("glNormalP3uiv"); + glad_glColorP3ui = (PFNGLCOLORP3UIPROC)load("glColorP3ui"); + glad_glColorP3uiv = (PFNGLCOLORP3UIVPROC)load("glColorP3uiv"); + glad_glColorP4ui = (PFNGLCOLORP4UIPROC)load("glColorP4ui"); + glad_glColorP4uiv = (PFNGLCOLORP4UIVPROC)load("glColorP4uiv"); + glad_glSecondaryColorP3ui = (PFNGLSECONDARYCOLORP3UIPROC)load("glSecondaryColorP3ui"); + glad_glSecondaryColorP3uiv = (PFNGLSECONDARYCOLORP3UIVPROC)load("glSecondaryColorP3uiv"); +} +static void load_GL_VERSION_4_0(GLADloadproc load) { + if(!GLAD_GL_VERSION_4_0) return; + glad_glMinSampleShading = (PFNGLMINSAMPLESHADINGPROC)load("glMinSampleShading"); + glad_glBlendEquationi = (PFNGLBLENDEQUATIONIPROC)load("glBlendEquationi"); + glad_glBlendEquationSeparatei = (PFNGLBLENDEQUATIONSEPARATEIPROC)load("glBlendEquationSeparatei"); + glad_glBlendFunci = (PFNGLBLENDFUNCIPROC)load("glBlendFunci"); + glad_glBlendFuncSeparatei = (PFNGLBLENDFUNCSEPARATEIPROC)load("glBlendFuncSeparatei"); + glad_glDrawArraysIndirect = (PFNGLDRAWARRAYSINDIRECTPROC)load("glDrawArraysIndirect"); + glad_glDrawElementsIndirect = (PFNGLDRAWELEMENTSINDIRECTPROC)load("glDrawElementsIndirect"); + glad_glUniform1d = (PFNGLUNIFORM1DPROC)load("glUniform1d"); + glad_glUniform2d = (PFNGLUNIFORM2DPROC)load("glUniform2d"); + glad_glUniform3d = (PFNGLUNIFORM3DPROC)load("glUniform3d"); + glad_glUniform4d = (PFNGLUNIFORM4DPROC)load("glUniform4d"); + glad_glUniform1dv = (PFNGLUNIFORM1DVPROC)load("glUniform1dv"); + glad_glUniform2dv = (PFNGLUNIFORM2DVPROC)load("glUniform2dv"); + glad_glUniform3dv = (PFNGLUNIFORM3DVPROC)load("glUniform3dv"); + glad_glUniform4dv = (PFNGLUNIFORM4DVPROC)load("glUniform4dv"); + glad_glUniformMatrix2dv = (PFNGLUNIFORMMATRIX2DVPROC)load("glUniformMatrix2dv"); + glad_glUniformMatrix3dv = (PFNGLUNIFORMMATRIX3DVPROC)load("glUniformMatrix3dv"); + glad_glUniformMatrix4dv = (PFNGLUNIFORMMATRIX4DVPROC)load("glUniformMatrix4dv"); + glad_glUniformMatrix2x3dv = (PFNGLUNIFORMMATRIX2X3DVPROC)load("glUniformMatrix2x3dv"); + glad_glUniformMatrix2x4dv = (PFNGLUNIFORMMATRIX2X4DVPROC)load("glUniformMatrix2x4dv"); + glad_glUniformMatrix3x2dv = (PFNGLUNIFORMMATRIX3X2DVPROC)load("glUniformMatrix3x2dv"); + glad_glUniformMatrix3x4dv = (PFNGLUNIFORMMATRIX3X4DVPROC)load("glUniformMatrix3x4dv"); + glad_glUniformMatrix4x2dv = (PFNGLUNIFORMMATRIX4X2DVPROC)load("glUniformMatrix4x2dv"); + glad_glUniformMatrix4x3dv = (PFNGLUNIFORMMATRIX4X3DVPROC)load("glUniformMatrix4x3dv"); + glad_glGetUniformdv = (PFNGLGETUNIFORMDVPROC)load("glGetUniformdv"); + glad_glGetSubroutineUniformLocation = (PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC)load("glGetSubroutineUniformLocation"); + glad_glGetSubroutineIndex = (PFNGLGETSUBROUTINEINDEXPROC)load("glGetSubroutineIndex"); + glad_glGetActiveSubroutineUniformiv = (PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC)load("glGetActiveSubroutineUniformiv"); + glad_glGetActiveSubroutineUniformName = (PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC)load("glGetActiveSubroutineUniformName"); + glad_glGetActiveSubroutineName = (PFNGLGETACTIVESUBROUTINENAMEPROC)load("glGetActiveSubroutineName"); + glad_glUniformSubroutinesuiv = (PFNGLUNIFORMSUBROUTINESUIVPROC)load("glUniformSubroutinesuiv"); + glad_glGetUniformSubroutineuiv = (PFNGLGETUNIFORMSUBROUTINEUIVPROC)load("glGetUniformSubroutineuiv"); + glad_glGetProgramStageiv = (PFNGLGETPROGRAMSTAGEIVPROC)load("glGetProgramStageiv"); + glad_glPatchParameteri = (PFNGLPATCHPARAMETERIPROC)load("glPatchParameteri"); + glad_glPatchParameterfv = (PFNGLPATCHPARAMETERFVPROC)load("glPatchParameterfv"); + glad_glBindTransformFeedback = (PFNGLBINDTRANSFORMFEEDBACKPROC)load("glBindTransformFeedback"); + glad_glDeleteTransformFeedbacks = (PFNGLDELETETRANSFORMFEEDBACKSPROC)load("glDeleteTransformFeedbacks"); + glad_glGenTransformFeedbacks = (PFNGLGENTRANSFORMFEEDBACKSPROC)load("glGenTransformFeedbacks"); + glad_glIsTransformFeedback = (PFNGLISTRANSFORMFEEDBACKPROC)load("glIsTransformFeedback"); + glad_glPauseTransformFeedback = (PFNGLPAUSETRANSFORMFEEDBACKPROC)load("glPauseTransformFeedback"); + glad_glResumeTransformFeedback = (PFNGLRESUMETRANSFORMFEEDBACKPROC)load("glResumeTransformFeedback"); + glad_glDrawTransformFeedback = (PFNGLDRAWTRANSFORMFEEDBACKPROC)load("glDrawTransformFeedback"); + glad_glDrawTransformFeedbackStream = (PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC)load("glDrawTransformFeedbackStream"); + glad_glBeginQueryIndexed = (PFNGLBEGINQUERYINDEXEDPROC)load("glBeginQueryIndexed"); + glad_glEndQueryIndexed = (PFNGLENDQUERYINDEXEDPROC)load("glEndQueryIndexed"); + glad_glGetQueryIndexediv = (PFNGLGETQUERYINDEXEDIVPROC)load("glGetQueryIndexediv"); +} +static void load_GL_VERSION_4_1(GLADloadproc load) { + if(!GLAD_GL_VERSION_4_1) return; + glad_glReleaseShaderCompiler = (PFNGLRELEASESHADERCOMPILERPROC)load("glReleaseShaderCompiler"); + glad_glShaderBinary = (PFNGLSHADERBINARYPROC)load("glShaderBinary"); + glad_glGetShaderPrecisionFormat = (PFNGLGETSHADERPRECISIONFORMATPROC)load("glGetShaderPrecisionFormat"); + glad_glDepthRangef = (PFNGLDEPTHRANGEFPROC)load("glDepthRangef"); + glad_glClearDepthf = (PFNGLCLEARDEPTHFPROC)load("glClearDepthf"); + glad_glGetProgramBinary = (PFNGLGETPROGRAMBINARYPROC)load("glGetProgramBinary"); + glad_glProgramBinary = (PFNGLPROGRAMBINARYPROC)load("glProgramBinary"); + glad_glProgramParameteri = (PFNGLPROGRAMPARAMETERIPROC)load("glProgramParameteri"); + glad_glUseProgramStages = (PFNGLUSEPROGRAMSTAGESPROC)load("glUseProgramStages"); + glad_glActiveShaderProgram = (PFNGLACTIVESHADERPROGRAMPROC)load("glActiveShaderProgram"); + glad_glCreateShaderProgramv = (PFNGLCREATESHADERPROGRAMVPROC)load("glCreateShaderProgramv"); + glad_glBindProgramPipeline = (PFNGLBINDPROGRAMPIPELINEPROC)load("glBindProgramPipeline"); + glad_glDeleteProgramPipelines = (PFNGLDELETEPROGRAMPIPELINESPROC)load("glDeleteProgramPipelines"); + glad_glGenProgramPipelines = (PFNGLGENPROGRAMPIPELINESPROC)load("glGenProgramPipelines"); + glad_glIsProgramPipeline = (PFNGLISPROGRAMPIPELINEPROC)load("glIsProgramPipeline"); + glad_glGetProgramPipelineiv = (PFNGLGETPROGRAMPIPELINEIVPROC)load("glGetProgramPipelineiv"); + glad_glProgramUniform1i = (PFNGLPROGRAMUNIFORM1IPROC)load("glProgramUniform1i"); + glad_glProgramUniform1iv = (PFNGLPROGRAMUNIFORM1IVPROC)load("glProgramUniform1iv"); + glad_glProgramUniform1f = (PFNGLPROGRAMUNIFORM1FPROC)load("glProgramUniform1f"); + glad_glProgramUniform1fv = (PFNGLPROGRAMUNIFORM1FVPROC)load("glProgramUniform1fv"); + glad_glProgramUniform1d = (PFNGLPROGRAMUNIFORM1DPROC)load("glProgramUniform1d"); + glad_glProgramUniform1dv = (PFNGLPROGRAMUNIFORM1DVPROC)load("glProgramUniform1dv"); + glad_glProgramUniform1ui = (PFNGLPROGRAMUNIFORM1UIPROC)load("glProgramUniform1ui"); + glad_glProgramUniform1uiv = (PFNGLPROGRAMUNIFORM1UIVPROC)load("glProgramUniform1uiv"); + glad_glProgramUniform2i = (PFNGLPROGRAMUNIFORM2IPROC)load("glProgramUniform2i"); + glad_glProgramUniform2iv = (PFNGLPROGRAMUNIFORM2IVPROC)load("glProgramUniform2iv"); + glad_glProgramUniform2f = (PFNGLPROGRAMUNIFORM2FPROC)load("glProgramUniform2f"); + glad_glProgramUniform2fv = (PFNGLPROGRAMUNIFORM2FVPROC)load("glProgramUniform2fv"); + glad_glProgramUniform2d = (PFNGLPROGRAMUNIFORM2DPROC)load("glProgramUniform2d"); + glad_glProgramUniform2dv = (PFNGLPROGRAMUNIFORM2DVPROC)load("glProgramUniform2dv"); + glad_glProgramUniform2ui = (PFNGLPROGRAMUNIFORM2UIPROC)load("glProgramUniform2ui"); + glad_glProgramUniform2uiv = (PFNGLPROGRAMUNIFORM2UIVPROC)load("glProgramUniform2uiv"); + glad_glProgramUniform3i = (PFNGLPROGRAMUNIFORM3IPROC)load("glProgramUniform3i"); + glad_glProgramUniform3iv = (PFNGLPROGRAMUNIFORM3IVPROC)load("glProgramUniform3iv"); + glad_glProgramUniform3f = (PFNGLPROGRAMUNIFORM3FPROC)load("glProgramUniform3f"); + glad_glProgramUniform3fv = (PFNGLPROGRAMUNIFORM3FVPROC)load("glProgramUniform3fv"); + glad_glProgramUniform3d = (PFNGLPROGRAMUNIFORM3DPROC)load("glProgramUniform3d"); + glad_glProgramUniform3dv = (PFNGLPROGRAMUNIFORM3DVPROC)load("glProgramUniform3dv"); + glad_glProgramUniform3ui = (PFNGLPROGRAMUNIFORM3UIPROC)load("glProgramUniform3ui"); + glad_glProgramUniform3uiv = (PFNGLPROGRAMUNIFORM3UIVPROC)load("glProgramUniform3uiv"); + glad_glProgramUniform4i = (PFNGLPROGRAMUNIFORM4IPROC)load("glProgramUniform4i"); + glad_glProgramUniform4iv = (PFNGLPROGRAMUNIFORM4IVPROC)load("glProgramUniform4iv"); + glad_glProgramUniform4f = (PFNGLPROGRAMUNIFORM4FPROC)load("glProgramUniform4f"); + glad_glProgramUniform4fv = (PFNGLPROGRAMUNIFORM4FVPROC)load("glProgramUniform4fv"); + glad_glProgramUniform4d = (PFNGLPROGRAMUNIFORM4DPROC)load("glProgramUniform4d"); + glad_glProgramUniform4dv = (PFNGLPROGRAMUNIFORM4DVPROC)load("glProgramUniform4dv"); + glad_glProgramUniform4ui = (PFNGLPROGRAMUNIFORM4UIPROC)load("glProgramUniform4ui"); + glad_glProgramUniform4uiv = (PFNGLPROGRAMUNIFORM4UIVPROC)load("glProgramUniform4uiv"); + glad_glProgramUniformMatrix2fv = (PFNGLPROGRAMUNIFORMMATRIX2FVPROC)load("glProgramUniformMatrix2fv"); + glad_glProgramUniformMatrix3fv = (PFNGLPROGRAMUNIFORMMATRIX3FVPROC)load("glProgramUniformMatrix3fv"); + glad_glProgramUniformMatrix4fv = (PFNGLPROGRAMUNIFORMMATRIX4FVPROC)load("glProgramUniformMatrix4fv"); + glad_glProgramUniformMatrix2dv = (PFNGLPROGRAMUNIFORMMATRIX2DVPROC)load("glProgramUniformMatrix2dv"); + glad_glProgramUniformMatrix3dv = (PFNGLPROGRAMUNIFORMMATRIX3DVPROC)load("glProgramUniformMatrix3dv"); + glad_glProgramUniformMatrix4dv = (PFNGLPROGRAMUNIFORMMATRIX4DVPROC)load("glProgramUniformMatrix4dv"); + glad_glProgramUniformMatrix2x3fv = (PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC)load("glProgramUniformMatrix2x3fv"); + glad_glProgramUniformMatrix3x2fv = (PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC)load("glProgramUniformMatrix3x2fv"); + glad_glProgramUniformMatrix2x4fv = (PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC)load("glProgramUniformMatrix2x4fv"); + glad_glProgramUniformMatrix4x2fv = (PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC)load("glProgramUniformMatrix4x2fv"); + glad_glProgramUniformMatrix3x4fv = (PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC)load("glProgramUniformMatrix3x4fv"); + glad_glProgramUniformMatrix4x3fv = (PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC)load("glProgramUniformMatrix4x3fv"); + glad_glProgramUniformMatrix2x3dv = (PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC)load("glProgramUniformMatrix2x3dv"); + glad_glProgramUniformMatrix3x2dv = (PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC)load("glProgramUniformMatrix3x2dv"); + glad_glProgramUniformMatrix2x4dv = (PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC)load("glProgramUniformMatrix2x4dv"); + glad_glProgramUniformMatrix4x2dv = (PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC)load("glProgramUniformMatrix4x2dv"); + glad_glProgramUniformMatrix3x4dv = (PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC)load("glProgramUniformMatrix3x4dv"); + glad_glProgramUniformMatrix4x3dv = (PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC)load("glProgramUniformMatrix4x3dv"); + glad_glValidateProgramPipeline = (PFNGLVALIDATEPROGRAMPIPELINEPROC)load("glValidateProgramPipeline"); + glad_glGetProgramPipelineInfoLog = (PFNGLGETPROGRAMPIPELINEINFOLOGPROC)load("glGetProgramPipelineInfoLog"); + glad_glVertexAttribL1d = (PFNGLVERTEXATTRIBL1DPROC)load("glVertexAttribL1d"); + glad_glVertexAttribL2d = (PFNGLVERTEXATTRIBL2DPROC)load("glVertexAttribL2d"); + glad_glVertexAttribL3d = (PFNGLVERTEXATTRIBL3DPROC)load("glVertexAttribL3d"); + glad_glVertexAttribL4d = (PFNGLVERTEXATTRIBL4DPROC)load("glVertexAttribL4d"); + glad_glVertexAttribL1dv = (PFNGLVERTEXATTRIBL1DVPROC)load("glVertexAttribL1dv"); + glad_glVertexAttribL2dv = (PFNGLVERTEXATTRIBL2DVPROC)load("glVertexAttribL2dv"); + glad_glVertexAttribL3dv = (PFNGLVERTEXATTRIBL3DVPROC)load("glVertexAttribL3dv"); + glad_glVertexAttribL4dv = (PFNGLVERTEXATTRIBL4DVPROC)load("glVertexAttribL4dv"); + glad_glVertexAttribLPointer = (PFNGLVERTEXATTRIBLPOINTERPROC)load("glVertexAttribLPointer"); + glad_glGetVertexAttribLdv = (PFNGLGETVERTEXATTRIBLDVPROC)load("glGetVertexAttribLdv"); + glad_glViewportArrayv = (PFNGLVIEWPORTARRAYVPROC)load("glViewportArrayv"); + glad_glViewportIndexedf = (PFNGLVIEWPORTINDEXEDFPROC)load("glViewportIndexedf"); + glad_glViewportIndexedfv = (PFNGLVIEWPORTINDEXEDFVPROC)load("glViewportIndexedfv"); + glad_glScissorArrayv = (PFNGLSCISSORARRAYVPROC)load("glScissorArrayv"); + glad_glScissorIndexed = (PFNGLSCISSORINDEXEDPROC)load("glScissorIndexed"); + glad_glScissorIndexedv = (PFNGLSCISSORINDEXEDVPROC)load("glScissorIndexedv"); + glad_glDepthRangeArrayv = (PFNGLDEPTHRANGEARRAYVPROC)load("glDepthRangeArrayv"); + glad_glDepthRangeIndexed = (PFNGLDEPTHRANGEINDEXEDPROC)load("glDepthRangeIndexed"); + glad_glGetFloati_v = (PFNGLGETFLOATI_VPROC)load("glGetFloati_v"); + glad_glGetDoublei_v = (PFNGLGETDOUBLEI_VPROC)load("glGetDoublei_v"); +} +static void load_GL_VERSION_4_2(GLADloadproc load) { + if(!GLAD_GL_VERSION_4_2) return; + glad_glDrawArraysInstancedBaseInstance = (PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC)load("glDrawArraysInstancedBaseInstance"); + glad_glDrawElementsInstancedBaseInstance = (PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC)load("glDrawElementsInstancedBaseInstance"); + glad_glDrawElementsInstancedBaseVertexBaseInstance = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC)load("glDrawElementsInstancedBaseVertexBaseInstance"); + glad_glGetInternalformativ = (PFNGLGETINTERNALFORMATIVPROC)load("glGetInternalformativ"); + glad_glGetActiveAtomicCounterBufferiv = (PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC)load("glGetActiveAtomicCounterBufferiv"); + glad_glBindImageTexture = (PFNGLBINDIMAGETEXTUREPROC)load("glBindImageTexture"); + glad_glMemoryBarrier = (PFNGLMEMORYBARRIERPROC)load("glMemoryBarrier"); + glad_glTexStorage1D = (PFNGLTEXSTORAGE1DPROC)load("glTexStorage1D"); + glad_glTexStorage2D = (PFNGLTEXSTORAGE2DPROC)load("glTexStorage2D"); + glad_glTexStorage3D = (PFNGLTEXSTORAGE3DPROC)load("glTexStorage3D"); + glad_glDrawTransformFeedbackInstanced = (PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC)load("glDrawTransformFeedbackInstanced"); + glad_glDrawTransformFeedbackStreamInstanced = (PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC)load("glDrawTransformFeedbackStreamInstanced"); +} +static void load_GL_VERSION_4_3(GLADloadproc load) { + if(!GLAD_GL_VERSION_4_3) return; + glad_glClearBufferData = (PFNGLCLEARBUFFERDATAPROC)load("glClearBufferData"); + glad_glClearBufferSubData = (PFNGLCLEARBUFFERSUBDATAPROC)load("glClearBufferSubData"); + glad_glDispatchCompute = (PFNGLDISPATCHCOMPUTEPROC)load("glDispatchCompute"); + glad_glDispatchComputeIndirect = (PFNGLDISPATCHCOMPUTEINDIRECTPROC)load("glDispatchComputeIndirect"); + glad_glCopyImageSubData = (PFNGLCOPYIMAGESUBDATAPROC)load("glCopyImageSubData"); + glad_glFramebufferParameteri = (PFNGLFRAMEBUFFERPARAMETERIPROC)load("glFramebufferParameteri"); + glad_glGetFramebufferParameteriv = (PFNGLGETFRAMEBUFFERPARAMETERIVPROC)load("glGetFramebufferParameteriv"); + glad_glGetInternalformati64v = (PFNGLGETINTERNALFORMATI64VPROC)load("glGetInternalformati64v"); + glad_glInvalidateTexSubImage = (PFNGLINVALIDATETEXSUBIMAGEPROC)load("glInvalidateTexSubImage"); + glad_glInvalidateTexImage = (PFNGLINVALIDATETEXIMAGEPROC)load("glInvalidateTexImage"); + glad_glInvalidateBufferSubData = (PFNGLINVALIDATEBUFFERSUBDATAPROC)load("glInvalidateBufferSubData"); + glad_glInvalidateBufferData = (PFNGLINVALIDATEBUFFERDATAPROC)load("glInvalidateBufferData"); + glad_glInvalidateFramebuffer = (PFNGLINVALIDATEFRAMEBUFFERPROC)load("glInvalidateFramebuffer"); + glad_glInvalidateSubFramebuffer = (PFNGLINVALIDATESUBFRAMEBUFFERPROC)load("glInvalidateSubFramebuffer"); + glad_glMultiDrawArraysIndirect = (PFNGLMULTIDRAWARRAYSINDIRECTPROC)load("glMultiDrawArraysIndirect"); + glad_glMultiDrawElementsIndirect = (PFNGLMULTIDRAWELEMENTSINDIRECTPROC)load("glMultiDrawElementsIndirect"); + glad_glGetProgramInterfaceiv = (PFNGLGETPROGRAMINTERFACEIVPROC)load("glGetProgramInterfaceiv"); + glad_glGetProgramResourceIndex = (PFNGLGETPROGRAMRESOURCEINDEXPROC)load("glGetProgramResourceIndex"); + glad_glGetProgramResourceName = (PFNGLGETPROGRAMRESOURCENAMEPROC)load("glGetProgramResourceName"); + glad_glGetProgramResourceiv = (PFNGLGETPROGRAMRESOURCEIVPROC)load("glGetProgramResourceiv"); + glad_glGetProgramResourceLocation = (PFNGLGETPROGRAMRESOURCELOCATIONPROC)load("glGetProgramResourceLocation"); + glad_glGetProgramResourceLocationIndex = (PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC)load("glGetProgramResourceLocationIndex"); + glad_glShaderStorageBlockBinding = (PFNGLSHADERSTORAGEBLOCKBINDINGPROC)load("glShaderStorageBlockBinding"); + glad_glTexBufferRange = (PFNGLTEXBUFFERRANGEPROC)load("glTexBufferRange"); + glad_glTexStorage2DMultisample = (PFNGLTEXSTORAGE2DMULTISAMPLEPROC)load("glTexStorage2DMultisample"); + glad_glTexStorage3DMultisample = (PFNGLTEXSTORAGE3DMULTISAMPLEPROC)load("glTexStorage3DMultisample"); + glad_glTextureView = (PFNGLTEXTUREVIEWPROC)load("glTextureView"); + glad_glBindVertexBuffer = (PFNGLBINDVERTEXBUFFERPROC)load("glBindVertexBuffer"); + glad_glVertexAttribFormat = (PFNGLVERTEXATTRIBFORMATPROC)load("glVertexAttribFormat"); + glad_glVertexAttribIFormat = (PFNGLVERTEXATTRIBIFORMATPROC)load("glVertexAttribIFormat"); + glad_glVertexAttribLFormat = (PFNGLVERTEXATTRIBLFORMATPROC)load("glVertexAttribLFormat"); + glad_glVertexAttribBinding = (PFNGLVERTEXATTRIBBINDINGPROC)load("glVertexAttribBinding"); + glad_glVertexBindingDivisor = (PFNGLVERTEXBINDINGDIVISORPROC)load("glVertexBindingDivisor"); + glad_glDebugMessageControl = (PFNGLDEBUGMESSAGECONTROLPROC)load("glDebugMessageControl"); + glad_glDebugMessageInsert = (PFNGLDEBUGMESSAGEINSERTPROC)load("glDebugMessageInsert"); + glad_glDebugMessageCallback = (PFNGLDEBUGMESSAGECALLBACKPROC)load("glDebugMessageCallback"); + glad_glGetDebugMessageLog = (PFNGLGETDEBUGMESSAGELOGPROC)load("glGetDebugMessageLog"); + glad_glPushDebugGroup = (PFNGLPUSHDEBUGGROUPPROC)load("glPushDebugGroup"); + glad_glPopDebugGroup = (PFNGLPOPDEBUGGROUPPROC)load("glPopDebugGroup"); + glad_glObjectLabel = (PFNGLOBJECTLABELPROC)load("glObjectLabel"); + glad_glGetObjectLabel = (PFNGLGETOBJECTLABELPROC)load("glGetObjectLabel"); + glad_glObjectPtrLabel = (PFNGLOBJECTPTRLABELPROC)load("glObjectPtrLabel"); + glad_glGetObjectPtrLabel = (PFNGLGETOBJECTPTRLABELPROC)load("glGetObjectPtrLabel"); +} +static void load_GL_VERSION_4_4(GLADloadproc load) { + if(!GLAD_GL_VERSION_4_4) return; + glad_glBufferStorage = (PFNGLBUFFERSTORAGEPROC)load("glBufferStorage"); + glad_glClearTexImage = (PFNGLCLEARTEXIMAGEPROC)load("glClearTexImage"); + glad_glClearTexSubImage = (PFNGLCLEARTEXSUBIMAGEPROC)load("glClearTexSubImage"); + glad_glBindBuffersBase = (PFNGLBINDBUFFERSBASEPROC)load("glBindBuffersBase"); + glad_glBindBuffersRange = (PFNGLBINDBUFFERSRANGEPROC)load("glBindBuffersRange"); + glad_glBindTextures = (PFNGLBINDTEXTURESPROC)load("glBindTextures"); + glad_glBindSamplers = (PFNGLBINDSAMPLERSPROC)load("glBindSamplers"); + glad_glBindImageTextures = (PFNGLBINDIMAGETEXTURESPROC)load("glBindImageTextures"); + glad_glBindVertexBuffers = (PFNGLBINDVERTEXBUFFERSPROC)load("glBindVertexBuffers"); +} +static void load_GL_VERSION_4_5(GLADloadproc load) { + if(!GLAD_GL_VERSION_4_5) return; + glad_glClipControl = (PFNGLCLIPCONTROLPROC)load("glClipControl"); + glad_glCreateTransformFeedbacks = (PFNGLCREATETRANSFORMFEEDBACKSPROC)load("glCreateTransformFeedbacks"); + glad_glTransformFeedbackBufferBase = (PFNGLTRANSFORMFEEDBACKBUFFERBASEPROC)load("glTransformFeedbackBufferBase"); + glad_glTransformFeedbackBufferRange = (PFNGLTRANSFORMFEEDBACKBUFFERRANGEPROC)load("glTransformFeedbackBufferRange"); + glad_glGetTransformFeedbackiv = (PFNGLGETTRANSFORMFEEDBACKIVPROC)load("glGetTransformFeedbackiv"); + glad_glGetTransformFeedbacki_v = (PFNGLGETTRANSFORMFEEDBACKI_VPROC)load("glGetTransformFeedbacki_v"); + glad_glGetTransformFeedbacki64_v = (PFNGLGETTRANSFORMFEEDBACKI64_VPROC)load("glGetTransformFeedbacki64_v"); + glad_glCreateBuffers = (PFNGLCREATEBUFFERSPROC)load("glCreateBuffers"); + glad_glNamedBufferStorage = (PFNGLNAMEDBUFFERSTORAGEPROC)load("glNamedBufferStorage"); + glad_glNamedBufferData = (PFNGLNAMEDBUFFERDATAPROC)load("glNamedBufferData"); + glad_glNamedBufferSubData = (PFNGLNAMEDBUFFERSUBDATAPROC)load("glNamedBufferSubData"); + glad_glCopyNamedBufferSubData = (PFNGLCOPYNAMEDBUFFERSUBDATAPROC)load("glCopyNamedBufferSubData"); + glad_glClearNamedBufferData = (PFNGLCLEARNAMEDBUFFERDATAPROC)load("glClearNamedBufferData"); + glad_glClearNamedBufferSubData = (PFNGLCLEARNAMEDBUFFERSUBDATAPROC)load("glClearNamedBufferSubData"); + glad_glMapNamedBuffer = (PFNGLMAPNAMEDBUFFERPROC)load("glMapNamedBuffer"); + glad_glMapNamedBufferRange = (PFNGLMAPNAMEDBUFFERRANGEPROC)load("glMapNamedBufferRange"); + glad_glUnmapNamedBuffer = (PFNGLUNMAPNAMEDBUFFERPROC)load("glUnmapNamedBuffer"); + glad_glFlushMappedNamedBufferRange = (PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEPROC)load("glFlushMappedNamedBufferRange"); + glad_glGetNamedBufferParameteriv = (PFNGLGETNAMEDBUFFERPARAMETERIVPROC)load("glGetNamedBufferParameteriv"); + glad_glGetNamedBufferParameteri64v = (PFNGLGETNAMEDBUFFERPARAMETERI64VPROC)load("glGetNamedBufferParameteri64v"); + glad_glGetNamedBufferPointerv = (PFNGLGETNAMEDBUFFERPOINTERVPROC)load("glGetNamedBufferPointerv"); + glad_glGetNamedBufferSubData = (PFNGLGETNAMEDBUFFERSUBDATAPROC)load("glGetNamedBufferSubData"); + glad_glCreateFramebuffers = (PFNGLCREATEFRAMEBUFFERSPROC)load("glCreateFramebuffers"); + glad_glNamedFramebufferRenderbuffer = (PFNGLNAMEDFRAMEBUFFERRENDERBUFFERPROC)load("glNamedFramebufferRenderbuffer"); + glad_glNamedFramebufferParameteri = (PFNGLNAMEDFRAMEBUFFERPARAMETERIPROC)load("glNamedFramebufferParameteri"); + glad_glNamedFramebufferTexture = (PFNGLNAMEDFRAMEBUFFERTEXTUREPROC)load("glNamedFramebufferTexture"); + glad_glNamedFramebufferTextureLayer = (PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC)load("glNamedFramebufferTextureLayer"); + glad_glNamedFramebufferDrawBuffer = (PFNGLNAMEDFRAMEBUFFERDRAWBUFFERPROC)load("glNamedFramebufferDrawBuffer"); + glad_glNamedFramebufferDrawBuffers = (PFNGLNAMEDFRAMEBUFFERDRAWBUFFERSPROC)load("glNamedFramebufferDrawBuffers"); + glad_glNamedFramebufferReadBuffer = (PFNGLNAMEDFRAMEBUFFERREADBUFFERPROC)load("glNamedFramebufferReadBuffer"); + glad_glInvalidateNamedFramebufferData = (PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC)load("glInvalidateNamedFramebufferData"); + glad_glInvalidateNamedFramebufferSubData = (PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC)load("glInvalidateNamedFramebufferSubData"); + glad_glClearNamedFramebufferiv = (PFNGLCLEARNAMEDFRAMEBUFFERIVPROC)load("glClearNamedFramebufferiv"); + glad_glClearNamedFramebufferuiv = (PFNGLCLEARNAMEDFRAMEBUFFERUIVPROC)load("glClearNamedFramebufferuiv"); + glad_glClearNamedFramebufferfv = (PFNGLCLEARNAMEDFRAMEBUFFERFVPROC)load("glClearNamedFramebufferfv"); + glad_glClearNamedFramebufferfi = (PFNGLCLEARNAMEDFRAMEBUFFERFIPROC)load("glClearNamedFramebufferfi"); + glad_glBlitNamedFramebuffer = (PFNGLBLITNAMEDFRAMEBUFFERPROC)load("glBlitNamedFramebuffer"); + glad_glCheckNamedFramebufferStatus = (PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC)load("glCheckNamedFramebufferStatus"); + glad_glGetNamedFramebufferParameteriv = (PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVPROC)load("glGetNamedFramebufferParameteriv"); + glad_glGetNamedFramebufferAttachmentParameteriv = (PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC)load("glGetNamedFramebufferAttachmentParameteriv"); + glad_glCreateRenderbuffers = (PFNGLCREATERENDERBUFFERSPROC)load("glCreateRenderbuffers"); + glad_glNamedRenderbufferStorage = (PFNGLNAMEDRENDERBUFFERSTORAGEPROC)load("glNamedRenderbufferStorage"); + glad_glNamedRenderbufferStorageMultisample = (PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC)load("glNamedRenderbufferStorageMultisample"); + glad_glGetNamedRenderbufferParameteriv = (PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC)load("glGetNamedRenderbufferParameteriv"); + glad_glCreateTextures = (PFNGLCREATETEXTURESPROC)load("glCreateTextures"); + glad_glTextureBuffer = (PFNGLTEXTUREBUFFERPROC)load("glTextureBuffer"); + glad_glTextureBufferRange = (PFNGLTEXTUREBUFFERRANGEPROC)load("glTextureBufferRange"); + glad_glTextureStorage1D = (PFNGLTEXTURESTORAGE1DPROC)load("glTextureStorage1D"); + glad_glTextureStorage2D = (PFNGLTEXTURESTORAGE2DPROC)load("glTextureStorage2D"); + glad_glTextureStorage3D = (PFNGLTEXTURESTORAGE3DPROC)load("glTextureStorage3D"); + glad_glTextureStorage2DMultisample = (PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC)load("glTextureStorage2DMultisample"); + glad_glTextureStorage3DMultisample = (PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC)load("glTextureStorage3DMultisample"); + glad_glTextureSubImage1D = (PFNGLTEXTURESUBIMAGE1DPROC)load("glTextureSubImage1D"); + glad_glTextureSubImage2D = (PFNGLTEXTURESUBIMAGE2DPROC)load("glTextureSubImage2D"); + glad_glTextureSubImage3D = (PFNGLTEXTURESUBIMAGE3DPROC)load("glTextureSubImage3D"); + glad_glCompressedTextureSubImage1D = (PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC)load("glCompressedTextureSubImage1D"); + glad_glCompressedTextureSubImage2D = (PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC)load("glCompressedTextureSubImage2D"); + glad_glCompressedTextureSubImage3D = (PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC)load("glCompressedTextureSubImage3D"); + glad_glCopyTextureSubImage1D = (PFNGLCOPYTEXTURESUBIMAGE1DPROC)load("glCopyTextureSubImage1D"); + glad_glCopyTextureSubImage2D = (PFNGLCOPYTEXTURESUBIMAGE2DPROC)load("glCopyTextureSubImage2D"); + glad_glCopyTextureSubImage3D = (PFNGLCOPYTEXTURESUBIMAGE3DPROC)load("glCopyTextureSubImage3D"); + glad_glTextureParameterf = (PFNGLTEXTUREPARAMETERFPROC)load("glTextureParameterf"); + glad_glTextureParameterfv = (PFNGLTEXTUREPARAMETERFVPROC)load("glTextureParameterfv"); + glad_glTextureParameteri = (PFNGLTEXTUREPARAMETERIPROC)load("glTextureParameteri"); + glad_glTextureParameterIiv = (PFNGLTEXTUREPARAMETERIIVPROC)load("glTextureParameterIiv"); + glad_glTextureParameterIuiv = (PFNGLTEXTUREPARAMETERIUIVPROC)load("glTextureParameterIuiv"); + glad_glTextureParameteriv = (PFNGLTEXTUREPARAMETERIVPROC)load("glTextureParameteriv"); + glad_glGenerateTextureMipmap = (PFNGLGENERATETEXTUREMIPMAPPROC)load("glGenerateTextureMipmap"); + glad_glBindTextureUnit = (PFNGLBINDTEXTUREUNITPROC)load("glBindTextureUnit"); + glad_glGetTextureImage = (PFNGLGETTEXTUREIMAGEPROC)load("glGetTextureImage"); + glad_glGetCompressedTextureImage = (PFNGLGETCOMPRESSEDTEXTUREIMAGEPROC)load("glGetCompressedTextureImage"); + glad_glGetTextureLevelParameterfv = (PFNGLGETTEXTURELEVELPARAMETERFVPROC)load("glGetTextureLevelParameterfv"); + glad_glGetTextureLevelParameteriv = (PFNGLGETTEXTURELEVELPARAMETERIVPROC)load("glGetTextureLevelParameteriv"); + glad_glGetTextureParameterfv = (PFNGLGETTEXTUREPARAMETERFVPROC)load("glGetTextureParameterfv"); + glad_glGetTextureParameterIiv = (PFNGLGETTEXTUREPARAMETERIIVPROC)load("glGetTextureParameterIiv"); + glad_glGetTextureParameterIuiv = (PFNGLGETTEXTUREPARAMETERIUIVPROC)load("glGetTextureParameterIuiv"); + glad_glGetTextureParameteriv = (PFNGLGETTEXTUREPARAMETERIVPROC)load("glGetTextureParameteriv"); + glad_glCreateVertexArrays = (PFNGLCREATEVERTEXARRAYSPROC)load("glCreateVertexArrays"); + glad_glDisableVertexArrayAttrib = (PFNGLDISABLEVERTEXARRAYATTRIBPROC)load("glDisableVertexArrayAttrib"); + glad_glEnableVertexArrayAttrib = (PFNGLENABLEVERTEXARRAYATTRIBPROC)load("glEnableVertexArrayAttrib"); + glad_glVertexArrayElementBuffer = (PFNGLVERTEXARRAYELEMENTBUFFERPROC)load("glVertexArrayElementBuffer"); + glad_glVertexArrayVertexBuffer = (PFNGLVERTEXARRAYVERTEXBUFFERPROC)load("glVertexArrayVertexBuffer"); + glad_glVertexArrayVertexBuffers = (PFNGLVERTEXARRAYVERTEXBUFFERSPROC)load("glVertexArrayVertexBuffers"); + glad_glVertexArrayAttribBinding = (PFNGLVERTEXARRAYATTRIBBINDINGPROC)load("glVertexArrayAttribBinding"); + glad_glVertexArrayAttribFormat = (PFNGLVERTEXARRAYATTRIBFORMATPROC)load("glVertexArrayAttribFormat"); + glad_glVertexArrayAttribIFormat = (PFNGLVERTEXARRAYATTRIBIFORMATPROC)load("glVertexArrayAttribIFormat"); + glad_glVertexArrayAttribLFormat = (PFNGLVERTEXARRAYATTRIBLFORMATPROC)load("glVertexArrayAttribLFormat"); + glad_glVertexArrayBindingDivisor = (PFNGLVERTEXARRAYBINDINGDIVISORPROC)load("glVertexArrayBindingDivisor"); + glad_glGetVertexArrayiv = (PFNGLGETVERTEXARRAYIVPROC)load("glGetVertexArrayiv"); + glad_glGetVertexArrayIndexediv = (PFNGLGETVERTEXARRAYINDEXEDIVPROC)load("glGetVertexArrayIndexediv"); + glad_glGetVertexArrayIndexed64iv = (PFNGLGETVERTEXARRAYINDEXED64IVPROC)load("glGetVertexArrayIndexed64iv"); + glad_glCreateSamplers = (PFNGLCREATESAMPLERSPROC)load("glCreateSamplers"); + glad_glCreateProgramPipelines = (PFNGLCREATEPROGRAMPIPELINESPROC)load("glCreateProgramPipelines"); + glad_glCreateQueries = (PFNGLCREATEQUERIESPROC)load("glCreateQueries"); + glad_glGetQueryBufferObjecti64v = (PFNGLGETQUERYBUFFEROBJECTI64VPROC)load("glGetQueryBufferObjecti64v"); + glad_glGetQueryBufferObjectiv = (PFNGLGETQUERYBUFFEROBJECTIVPROC)load("glGetQueryBufferObjectiv"); + glad_glGetQueryBufferObjectui64v = (PFNGLGETQUERYBUFFEROBJECTUI64VPROC)load("glGetQueryBufferObjectui64v"); + glad_glGetQueryBufferObjectuiv = (PFNGLGETQUERYBUFFEROBJECTUIVPROC)load("glGetQueryBufferObjectuiv"); + glad_glMemoryBarrierByRegion = (PFNGLMEMORYBARRIERBYREGIONPROC)load("glMemoryBarrierByRegion"); + glad_glGetTextureSubImage = (PFNGLGETTEXTURESUBIMAGEPROC)load("glGetTextureSubImage"); + glad_glGetCompressedTextureSubImage = (PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC)load("glGetCompressedTextureSubImage"); + glad_glGetGraphicsResetStatus = (PFNGLGETGRAPHICSRESETSTATUSPROC)load("glGetGraphicsResetStatus"); + glad_glGetnCompressedTexImage = (PFNGLGETNCOMPRESSEDTEXIMAGEPROC)load("glGetnCompressedTexImage"); + glad_glGetnTexImage = (PFNGLGETNTEXIMAGEPROC)load("glGetnTexImage"); + glad_glGetnUniformdv = (PFNGLGETNUNIFORMDVPROC)load("glGetnUniformdv"); + glad_glGetnUniformfv = (PFNGLGETNUNIFORMFVPROC)load("glGetnUniformfv"); + glad_glGetnUniformiv = (PFNGLGETNUNIFORMIVPROC)load("glGetnUniformiv"); + glad_glGetnUniformuiv = (PFNGLGETNUNIFORMUIVPROC)load("glGetnUniformuiv"); + glad_glReadnPixels = (PFNGLREADNPIXELSPROC)load("glReadnPixels"); + glad_glGetnMapdv = (PFNGLGETNMAPDVPROC)load("glGetnMapdv"); + glad_glGetnMapfv = (PFNGLGETNMAPFVPROC)load("glGetnMapfv"); + glad_glGetnMapiv = (PFNGLGETNMAPIVPROC)load("glGetnMapiv"); + glad_glGetnPixelMapfv = (PFNGLGETNPIXELMAPFVPROC)load("glGetnPixelMapfv"); + glad_glGetnPixelMapuiv = (PFNGLGETNPIXELMAPUIVPROC)load("glGetnPixelMapuiv"); + glad_glGetnPixelMapusv = (PFNGLGETNPIXELMAPUSVPROC)load("glGetnPixelMapusv"); + glad_glGetnPolygonStipple = (PFNGLGETNPOLYGONSTIPPLEPROC)load("glGetnPolygonStipple"); + glad_glGetnColorTable = (PFNGLGETNCOLORTABLEPROC)load("glGetnColorTable"); + glad_glGetnConvolutionFilter = (PFNGLGETNCONVOLUTIONFILTERPROC)load("glGetnConvolutionFilter"); + glad_glGetnSeparableFilter = (PFNGLGETNSEPARABLEFILTERPROC)load("glGetnSeparableFilter"); + glad_glGetnHistogram = (PFNGLGETNHISTOGRAMPROC)load("glGetnHistogram"); + glad_glGetnMinmax = (PFNGLGETNMINMAXPROC)load("glGetnMinmax"); + glad_glTextureBarrier = (PFNGLTEXTUREBARRIERPROC)load("glTextureBarrier"); +} +static int find_extensionsGL(void) { + if (!get_exts()) return 0; + free_exts(); + return 1; +} + +static void find_coreGL(void) { + + /* Thank you @elmindreda + * https://github.com/elmindreda/greg/blob/master/templates/greg.c.in#L176 + * https://github.com/glfw/glfw/blob/master/src/context.c#L36 + */ + int i, major, minor; + + const char* version; + const char* prefixes[] = { + "OpenGL ES-CM ", + "OpenGL ES-CL ", + "OpenGL ES ", + NULL + }; + + version = (const char*) glGetString(GL_VERSION); + if (!version) return; + + for (i = 0; prefixes[i]; i++) { + const size_t length = strlen(prefixes[i]); + if (strncmp(version, prefixes[i], length) == 0) { + version += length; + break; + } + } + +/* PR #18 */ +#ifdef _MSC_VER + sscanf_s(version, "%d.%d", &major, &minor); +#else + sscanf(version, "%d.%d", &major, &minor); +#endif + + GLVersion.major = major; GLVersion.minor = minor; + max_loaded_major = major; max_loaded_minor = minor; + GLAD_GL_VERSION_1_0 = (major == 1 && minor >= 0) || major > 1; + GLAD_GL_VERSION_1_1 = (major == 1 && minor >= 1) || major > 1; + GLAD_GL_VERSION_1_2 = (major == 1 && minor >= 2) || major > 1; + GLAD_GL_VERSION_1_3 = (major == 1 && minor >= 3) || major > 1; + GLAD_GL_VERSION_1_4 = (major == 1 && minor >= 4) || major > 1; + GLAD_GL_VERSION_1_5 = (major == 1 && minor >= 5) || major > 1; + GLAD_GL_VERSION_2_0 = (major == 2 && minor >= 0) || major > 2; + GLAD_GL_VERSION_2_1 = (major == 2 && minor >= 1) || major > 2; + GLAD_GL_VERSION_3_0 = (major == 3 && minor >= 0) || major > 3; + GLAD_GL_VERSION_3_1 = (major == 3 && minor >= 1) || major > 3; + GLAD_GL_VERSION_3_2 = (major == 3 && minor >= 2) || major > 3; + GLAD_GL_VERSION_3_3 = (major == 3 && minor >= 3) || major > 3; + GLAD_GL_VERSION_4_0 = (major == 4 && minor >= 0) || major > 4; + GLAD_GL_VERSION_4_1 = (major == 4 && minor >= 1) || major > 4; + GLAD_GL_VERSION_4_2 = (major == 4 && minor >= 2) || major > 4; + GLAD_GL_VERSION_4_3 = (major == 4 && minor >= 3) || major > 4; + GLAD_GL_VERSION_4_4 = (major == 4 && minor >= 4) || major > 4; + GLAD_GL_VERSION_4_5 = (major == 4 && minor >= 5) || major > 4; + if (GLVersion.major > 4 || (GLVersion.major >= 4 && GLVersion.minor >= 5)) { + max_loaded_major = 4; + max_loaded_minor = 5; + } +} + +int gladLoadGLLoader(GLADloadproc load) { + GLVersion.major = 0; GLVersion.minor = 0; + glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); + if(glGetString == NULL) return 0; + if(glGetString(GL_VERSION) == NULL) return 0; + find_coreGL(); + load_GL_VERSION_1_0(load); + load_GL_VERSION_1_1(load); + load_GL_VERSION_1_2(load); + load_GL_VERSION_1_3(load); + load_GL_VERSION_1_4(load); + load_GL_VERSION_1_5(load); + load_GL_VERSION_2_0(load); + load_GL_VERSION_2_1(load); + load_GL_VERSION_3_0(load); + load_GL_VERSION_3_1(load); + load_GL_VERSION_3_2(load); + load_GL_VERSION_3_3(load); + load_GL_VERSION_4_0(load); + load_GL_VERSION_4_1(load); + load_GL_VERSION_4_2(load); + load_GL_VERSION_4_3(load); + load_GL_VERSION_4_4(load); + load_GL_VERSION_4_5(load); + + if (!find_extensionsGL()) return 0; + return GLVersion.major != 0 || GLVersion.minor != 0; +} + diff --git a/third_party/glfw b/third_party/glfw new file mode 160000 index 0000000000..096efdf798 --- /dev/null +++ b/third_party/glfw @@ -0,0 +1 @@ +Subproject commit 096efdf798896cff80a0b2db08d7398b703406fe diff --git a/third_party/glm b/third_party/glm new file mode 160000 index 0000000000..06f084063f --- /dev/null +++ b/third_party/glm @@ -0,0 +1 @@ +Subproject commit 06f084063fd6d9aa2ef6904517650700ae47b63d diff --git a/third_party/glslang b/third_party/glslang new file mode 160000 index 0000000000..f00c245a5f --- /dev/null +++ b/third_party/glslang @@ -0,0 +1 @@ +Subproject commit f00c245a5f697cde2257e1280969429314a84958 diff --git a/third_party/googletest b/third_party/googletest new file mode 160000 index 0000000000..ec44c6c167 --- /dev/null +++ b/third_party/googletest @@ -0,0 +1 @@ +Subproject commit ec44c6c1675c25b9827aacd08c02433cccde7780 diff --git a/third_party/picojson/picojson.h b/third_party/picojson/picojson.h new file mode 100644 index 0000000000..045dc537ba --- /dev/null +++ b/third_party/picojson/picojson.h @@ -0,0 +1,1039 @@ +/* + * Copyright 2009-2010 Cybozu Labs, Inc. + * Copyright 2011-2014 Kazuho Oku + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef picojson_h +#define picojson_h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// for isnan/isinf +#if __cplusplus>=201103L +# include +#else +extern "C" { +# ifdef _MSC_VER +# include +# elif defined(__INTEL_COMPILER) +# include +# else +# include +# endif +} +#endif + +#ifndef PICOJSON_USE_RVALUE_REFERENCE +# if (defined(__cpp_rvalue_references) && __cpp_rvalue_references >= 200610) || (defined(_MSC_VER) && _MSC_VER >= 1600) +# define PICOJSON_USE_RVALUE_REFERENCE 1 +# else +# define PICOJSON_USE_RVALUE_REFERENCE 0 +# endif +#endif//PICOJSON_USE_RVALUE_REFERENCE + + +// experimental support for int64_t (see README.mkdn for detail) +#ifdef PICOJSON_USE_INT64 +# define __STDC_FORMAT_MACROS +# include +# include +#endif + +// to disable the use of localeconv(3), set PICOJSON_USE_LOCALE to 0 +#ifndef PICOJSON_USE_LOCALE +# define PICOJSON_USE_LOCALE 1 +#endif +#if PICOJSON_USE_LOCALE +extern "C" { +# include +} +#endif + +#ifndef PICOJSON_ASSERT +# define PICOJSON_ASSERT(e) do { if (! (e)) throw std::runtime_error(#e); } while (0) +#endif + +#ifdef _MSC_VER + #define SNPRINTF _snprintf_s + #pragma warning(push) + #pragma warning(disable : 4244) // conversion from int to char + #pragma warning(disable : 4127) // conditional expression is constant + #pragma warning(disable : 4702) // unreachable code +#else + #define SNPRINTF snprintf +#endif + +namespace picojson { + + enum { + null_type, + boolean_type, + number_type, + string_type, + array_type, + object_type +#ifdef PICOJSON_USE_INT64 + , int64_type +#endif + }; + + enum { + INDENT_WIDTH = 2 + }; + + struct null {}; + + class value { + public: + typedef std::vector array; + typedef std::map object; + union _storage { + bool boolean_; + double number_; +#ifdef PICOJSON_USE_INT64 + int64_t int64_; +#endif + std::string* string_; + array* array_; + object* object_; + }; + protected: + int type_; + _storage u_; + public: + value(); + value(int type, bool); + explicit value(bool b); +#ifdef PICOJSON_USE_INT64 + explicit value(int64_t i); +#endif + explicit value(double n); + explicit value(const std::string& s); + explicit value(const array& a); + explicit value(const object& o); + explicit value(const char* s); + value(const char* s, size_t len); + ~value(); + value(const value& x); + value& operator=(const value& x); +#if PICOJSON_USE_RVALUE_REFERENCE + value(value&& x)throw(); + value& operator=(value&& x)throw(); +#endif + void swap(value& x)throw(); + template bool is() const; + template const T& get() const; + template T& get(); + bool evaluate_as_boolean() const; + const value& get(size_t idx) const; + const value& get(const std::string& key) const; + value& get(size_t idx); + value& get(const std::string& key); + + bool contains(size_t idx) const; + bool contains(const std::string& key) const; + std::string to_str() const; + template void serialize(Iter os, bool prettify = false) const; + std::string serialize(bool prettify = false) const; + private: + template value(const T*); // intentionally defined to block implicit conversion of pointer to bool + template static void _indent(Iter os, int indent); + template void _serialize(Iter os, int indent) const; + std::string _serialize(int indent) const; + }; + + typedef value::array array; + typedef value::object object; + + inline value::value() : type_(null_type) {} + + inline value::value(int type, bool) : type_(type) { + switch (type) { +#define INIT(p, v) case p##type: u_.p = v; break + INIT(boolean_, false); + INIT(number_, 0.0); +#ifdef PICOJSON_USE_INT64 + INIT(int64_, 0); +#endif + INIT(string_, new std::string()); + INIT(array_, new array()); + INIT(object_, new object()); +#undef INIT + default: break; + } + } + + inline value::value(bool b) : type_(boolean_type) { + u_.boolean_ = b; + } + +#ifdef PICOJSON_USE_INT64 + inline value::value(int64_t i) : type_(int64_type) { + u_.int64_ = i; + } +#endif + + inline value::value(double n) : type_(number_type) { + if ( +#ifdef _MSC_VER + ! _finite(n) +#elif __cplusplus>=201103L || !(defined(isnan) && defined(isinf)) + std::isnan(n) || std::isinf(n) +#else + isnan(n) || isinf(n) +#endif + ) { + throw std::overflow_error(""); + } + u_.number_ = n; + } + + inline value::value(const std::string& s) : type_(string_type) { + u_.string_ = new std::string(s); + } + + inline value::value(const array& a) : type_(array_type) { + u_.array_ = new array(a); + } + + inline value::value(const object& o) : type_(object_type) { + u_.object_ = new object(o); + } + + inline value::value(const char* s) : type_(string_type) { + u_.string_ = new std::string(s); + } + + inline value::value(const char* s, size_t len) : type_(string_type) { + u_.string_ = new std::string(s, len); + } + + inline value::~value() { + switch (type_) { +#define DEINIT(p) case p##type: delete u_.p; break + DEINIT(string_); + DEINIT(array_); + DEINIT(object_); +#undef DEINIT + default: break; + } + } + + inline value::value(const value& x) : type_(x.type_) { + switch (type_) { +#define INIT(p, v) case p##type: u_.p = v; break + INIT(string_, new std::string(*x.u_.string_)); + INIT(array_, new array(*x.u_.array_)); + INIT(object_, new object(*x.u_.object_)); +#undef INIT + default: + u_ = x.u_; + break; + } + } + + inline value& value::operator=(const value& x) { + if (this != &x) { + value t(x); + swap(t); + } + return *this; + } + +#if PICOJSON_USE_RVALUE_REFERENCE + inline value::value(value&& x)throw() : type_(null_type) { + swap(x); + } + inline value& value::operator=(value&& x)throw() { + swap(x); + return *this; + } +#endif + inline void value::swap(value& x)throw() { + std::swap(type_, x.type_); + std::swap(u_, x.u_); + } + +#define IS(ctype, jtype) \ + template <> inline bool value::is() const { \ + return type_ == jtype##_type; \ + } + IS(null, null) + IS(bool, boolean) +#ifdef PICOJSON_USE_INT64 + IS(int64_t, int64) +#endif + IS(std::string, string) + IS(array, array) + IS(object, object) +#undef IS + template <> inline bool value::is() const { + return type_ == number_type +#ifdef PICOJSON_USE_INT64 + || type_ == int64_type +#endif + ; + } + +#define GET(ctype, var) \ + template <> inline const ctype& value::get() const { \ + PICOJSON_ASSERT("type mismatch! call is() before get()" \ + && is()); \ + return var; \ + } \ + template <> inline ctype& value::get() { \ + PICOJSON_ASSERT("type mismatch! call is() before get()" \ + && is()); \ + return var; \ + } + GET(bool, u_.boolean_) + GET(std::string, *u_.string_) + GET(array, *u_.array_) + GET(object, *u_.object_) +#ifdef PICOJSON_USE_INT64 + GET(double, (type_ == int64_type && (const_cast(this)->type_ = number_type, const_cast(this)->u_.number_ = u_.int64_), u_.number_)) + GET(int64_t, u_.int64_) +#else + GET(double, u_.number_) +#endif +#undef GET + + inline bool value::evaluate_as_boolean() const { + switch (type_) { + case null_type: + return false; + case boolean_type: + return u_.boolean_; + case number_type: + return u_.number_ != 0; +#ifdef PICOJSON_USE_INT64 + case int64_type: + return u_.int64_ != 0; +#endif + case string_type: + return ! u_.string_->empty(); + default: + return true; + } + } + + inline const value& value::get(size_t idx) const { + static value s_null; + PICOJSON_ASSERT(is()); + return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null; + } + + inline value& value::get(size_t idx) { + static value s_null; + PICOJSON_ASSERT(is()); + return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null; + } + + inline const value& value::get(const std::string& key) const { + static value s_null; + PICOJSON_ASSERT(is()); + object::const_iterator i = u_.object_->find(key); + return i != u_.object_->end() ? i->second : s_null; + } + + inline value& value::get(const std::string& key) { + static value s_null; + PICOJSON_ASSERT(is()); + object::iterator i = u_.object_->find(key); + return i != u_.object_->end() ? i->second : s_null; + } + + inline bool value::contains(size_t idx) const { + PICOJSON_ASSERT(is()); + return idx < u_.array_->size(); + } + + inline bool value::contains(const std::string& key) const { + PICOJSON_ASSERT(is()); + object::const_iterator i = u_.object_->find(key); + return i != u_.object_->end(); + } + + inline std::string value::to_str() const { + switch (type_) { + case null_type: return "null"; + case boolean_type: return u_.boolean_ ? "true" : "false"; +#ifdef PICOJSON_USE_INT64 + case int64_type: { + char buf[sizeof("-9223372036854775808")]; + SNPRINTF(buf, sizeof(buf), "%" PRId64, u_.int64_); + return buf; + } +#endif + case number_type: { + char buf[256]; + double tmp; + SNPRINTF(buf, sizeof(buf), fabs(u_.number_) < (1ULL << 53) && modf(u_.number_, &tmp) == 0 ? "%.f" : "%.17g", u_.number_); +#if PICOJSON_USE_LOCALE + char *decimal_point = localeconv()->decimal_point; + if (strcmp(decimal_point, ".") != 0) { + size_t decimal_point_len = strlen(decimal_point); + for (char *p = buf; *p != '\0'; ++p) { + if (strncmp(p, decimal_point, decimal_point_len) == 0) { + return std::string(buf, p) + "." + (p + decimal_point_len); + } + } + } +#endif + return buf; + } + case string_type: return *u_.string_; + case array_type: return "array"; + case object_type: return "object"; + default: PICOJSON_ASSERT(0); +#ifdef _MSC_VER + __assume(0); +#endif + } + return std::string(); + } + + template void copy(const std::string& s, Iter oi) { + std::copy(s.begin(), s.end(), oi); + } + + template void serialize_str(const std::string& s, Iter oi) { + *oi++ = '"'; + for (std::string::const_iterator i = s.begin(); i != s.end(); ++i) { + switch (*i) { +#define MAP(val, sym) case val: copy(sym, oi); break + MAP('"', "\\\""); + MAP('\\', "\\\\"); + MAP('/', "\\/"); + MAP('\b', "\\b"); + MAP('\f', "\\f"); + MAP('\n', "\\n"); + MAP('\r', "\\r"); + MAP('\t', "\\t"); +#undef MAP + default: + if (static_cast(*i) < 0x20 || *i == 0x7f) { + char buf[7]; + SNPRINTF(buf, sizeof(buf), "\\u%04x", *i & 0xff); + copy(buf, buf + 6, oi); + } else { + *oi++ = *i; + } + break; + } + } + *oi++ = '"'; + } + + template void value::serialize(Iter oi, bool prettify) const { + return _serialize(oi, prettify ? 0 : -1); + } + + inline std::string value::serialize(bool prettify) const { + return _serialize(prettify ? 0 : -1); + } + + template void value::_indent(Iter oi, int indent) { + *oi++ = '\n'; + for (int i = 0; i < indent * INDENT_WIDTH; ++i) { + *oi++ = ' '; + } + } + + template void value::_serialize(Iter oi, int indent) const { + switch (type_) { + case string_type: + serialize_str(*u_.string_, oi); + break; + case array_type: { + *oi++ = '['; + if (indent != -1) { + ++indent; + } + for (array::const_iterator i = u_.array_->begin(); + i != u_.array_->end(); + ++i) { + if (i != u_.array_->begin()) { + *oi++ = ','; + } + if (indent != -1) { + _indent(oi, indent); + } + i->_serialize(oi, indent); + } + if (indent != -1) { + --indent; + if (! u_.array_->empty()) { + _indent(oi, indent); + } + } + *oi++ = ']'; + break; + } + case object_type: { + *oi++ = '{'; + if (indent != -1) { + ++indent; + } + for (object::const_iterator i = u_.object_->begin(); + i != u_.object_->end(); + ++i) { + if (i != u_.object_->begin()) { + *oi++ = ','; + } + if (indent != -1) { + _indent(oi, indent); + } + serialize_str(i->first, oi); + *oi++ = ':'; + if (indent != -1) { + *oi++ = ' '; + } + i->second._serialize(oi, indent); + } + if (indent != -1) { + --indent; + if (! u_.object_->empty()) { + _indent(oi, indent); + } + } + *oi++ = '}'; + break; + } + default: + copy(to_str(), oi); + break; + } + if (indent == 0) { + *oi++ = '\n'; + } + } + + inline std::string value::_serialize(int indent) const { + std::string s; + _serialize(std::back_inserter(s), indent); + return s; + } + + template class input { + protected: + Iter cur_, end_; + int last_ch_; + bool ungot_; + int line_; + public: + input(const Iter& first, const Iter& last) : cur_(first), end_(last), last_ch_(-1), ungot_(false), line_(1) {} + int getc() { + if (ungot_) { + ungot_ = false; + return last_ch_; + } + if (cur_ == end_) { + last_ch_ = -1; + return -1; + } + if (last_ch_ == '\n') { + line_++; + } + last_ch_ = *cur_ & 0xff; + ++cur_; + return last_ch_; + } + void ungetc() { + if (last_ch_ != -1) { + PICOJSON_ASSERT(! ungot_); + ungot_ = true; + } + } + Iter cur() const { return cur_; } + int line() const { return line_; } + void skip_ws() { + while (1) { + int ch = getc(); + if (! (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')) { + ungetc(); + break; + } + } + } + bool expect(int expect) { + skip_ws(); + if (getc() != expect) { + ungetc(); + return false; + } + return true; + } + bool match(const std::string& pattern) { + for (std::string::const_iterator pi(pattern.begin()); + pi != pattern.end(); + ++pi) { + if (getc() != *pi) { + ungetc(); + return false; + } + } + return true; + } + }; + + template inline int _parse_quadhex(input &in) { + int uni_ch = 0, hex; + for (int i = 0; i < 4; i++) { + if ((hex = in.getc()) == -1) { + return -1; + } + if ('0' <= hex && hex <= '9') { + hex -= '0'; + } else if ('A' <= hex && hex <= 'F') { + hex -= 'A' - 0xa; + } else if ('a' <= hex && hex <= 'f') { + hex -= 'a' - 0xa; + } else { + in.ungetc(); + return -1; + } + uni_ch = uni_ch * 16 + hex; + } + return uni_ch; + } + + template inline bool _parse_codepoint(String& out, input& in) { + int uni_ch; + if ((uni_ch = _parse_quadhex(in)) == -1) { + return false; + } + if (0xd800 <= uni_ch && uni_ch <= 0xdfff) { + if (0xdc00 <= uni_ch) { + // a second 16-bit of a surrogate pair appeared + return false; + } + // first 16-bit of surrogate pair, get the next one + if (in.getc() != '\\' || in.getc() != 'u') { + in.ungetc(); + return false; + } + int second = _parse_quadhex(in); + if (! (0xdc00 <= second && second <= 0xdfff)) { + return false; + } + uni_ch = ((uni_ch - 0xd800) << 10) | ((second - 0xdc00) & 0x3ff); + uni_ch += 0x10000; + } + if (uni_ch < 0x80) { + out.push_back(uni_ch); + } else { + if (uni_ch < 0x800) { + out.push_back(0xc0 | (uni_ch >> 6)); + } else { + if (uni_ch < 0x10000) { + out.push_back(0xe0 | (uni_ch >> 12)); + } else { + out.push_back(0xf0 | (uni_ch >> 18)); + out.push_back(0x80 | ((uni_ch >> 12) & 0x3f)); + } + out.push_back(0x80 | ((uni_ch >> 6) & 0x3f)); + } + out.push_back(0x80 | (uni_ch & 0x3f)); + } + return true; + } + + template inline bool _parse_string(String& out, input& in) { + while (1) { + int ch = in.getc(); + if (ch < ' ') { + in.ungetc(); + return false; + } else if (ch == '"') { + return true; + } else if (ch == '\\') { + if ((ch = in.getc()) == -1) { + return false; + } + switch (ch) { +#define MAP(sym, val) case sym: out.push_back(val); break + MAP('"', '\"'); + MAP('\\', '\\'); + MAP('/', '/'); + MAP('b', '\b'); + MAP('f', '\f'); + MAP('n', '\n'); + MAP('r', '\r'); + MAP('t', '\t'); +#undef MAP + case 'u': + if (! _parse_codepoint(out, in)) { + return false; + } + break; + default: + return false; + } + } else { + out.push_back(ch); + } + } + return false; + } + + template inline bool _parse_array(Context& ctx, input& in) { + if (! ctx.parse_array_start()) { + return false; + } + size_t idx = 0; + if (in.expect(']')) { + return ctx.parse_array_stop(idx); + } + do { + if (! ctx.parse_array_item(in, idx)) { + return false; + } + idx++; + } while (in.expect(',')); + return in.expect(']') && ctx.parse_array_stop(idx); + } + + template inline bool _parse_object(Context& ctx, input& in) { + if (! ctx.parse_object_start()) { + return false; + } + if (in.expect('}')) { + return true; + } + do { + std::string key; + if (! in.expect('"') + || ! _parse_string(key, in) + || ! in.expect(':')) { + return false; + } + if (! ctx.parse_object_item(in, key)) { + return false; + } + } while (in.expect(',')); + return in.expect('}'); + } + + template inline std::string _parse_number(input& in) { + std::string num_str; + while (1) { + int ch = in.getc(); + if (('0' <= ch && ch <= '9') || ch == '+' || ch == '-' + || ch == 'e' || ch == 'E') { + num_str.push_back(ch); + } else if (ch == '.') { +#if PICOJSON_USE_LOCALE + num_str += localeconv()->decimal_point; +#else + num_str.push_back('.'); +#endif + } else { + in.ungetc(); + break; + } + } + return num_str; + } + + template inline bool _parse(Context& ctx, input& in) { + in.skip_ws(); + int ch = in.getc(); + switch (ch) { +#define IS(ch, text, op) case ch: \ + if (in.match(text) && op) { \ + return true; \ + } else { \ + return false; \ + } + IS('n', "ull", ctx.set_null()); + IS('f', "alse", ctx.set_bool(false)); + IS('t', "rue", ctx.set_bool(true)); +#undef IS + case '"': + return ctx.parse_string(in); + case '[': + return _parse_array(ctx, in); + case '{': + return _parse_object(ctx, in); + default: + if (('0' <= ch && ch <= '9') || ch == '-') { + double f; + char *endp; + in.ungetc(); + std::string num_str = _parse_number(in); + if (num_str.empty()) { + return false; + } +#ifdef PICOJSON_USE_INT64 + { + errno = 0; + intmax_t ival = strtoimax(num_str.c_str(), &endp, 10); + if (errno == 0 + && std::numeric_limits::min() <= ival + && ival <= std::numeric_limits::max() + && endp == num_str.c_str() + num_str.size()) { + ctx.set_int64(ival); + return true; + } + } +#endif + f = strtod(num_str.c_str(), &endp); + if (endp == num_str.c_str() + num_str.size()) { + ctx.set_number(f); + return true; + } + return false; + } + break; + } + in.ungetc(); + return false; + } + + class deny_parse_context { + public: + bool set_null() { return false; } + bool set_bool(bool) { return false; } +#ifdef PICOJSON_USE_INT64 + bool set_int64(int64_t) { return false; } +#endif + bool set_number(double) { return false; } + template bool parse_string(input&) { return false; } + bool parse_array_start() { return false; } + template bool parse_array_item(input&, size_t) { + return false; + } + bool parse_array_stop(size_t) { return false; } + bool parse_object_start() { return false; } + template bool parse_object_item(input&, const std::string&) { + return false; + } + }; + + class default_parse_context { + protected: + value* out_; + public: + default_parse_context(value* out) : out_(out) {} + bool set_null() { + *out_ = value(); + return true; + } + bool set_bool(bool b) { + *out_ = value(b); + return true; + } +#ifdef PICOJSON_USE_INT64 + bool set_int64(int64_t i) { + *out_ = value(i); + return true; + } +#endif + bool set_number(double f) { + *out_ = value(f); + return true; + } + template bool parse_string(input& in) { + *out_ = value(string_type, false); + return _parse_string(out_->get(), in); + } + bool parse_array_start() { + *out_ = value(array_type, false); + return true; + } + template bool parse_array_item(input& in, size_t) { + array& a = out_->get(); + a.push_back(value()); + default_parse_context ctx(&a.back()); + return _parse(ctx, in); + } + bool parse_array_stop(size_t) { return true; } + bool parse_object_start() { + *out_ = value(object_type, false); + return true; + } + template bool parse_object_item(input& in, const std::string& key) { + object& o = out_->get(); + default_parse_context ctx(&o[key]); + return _parse(ctx, in); + } + private: + default_parse_context(const default_parse_context&); + default_parse_context& operator=(const default_parse_context&); + }; + + class null_parse_context { + public: + struct dummy_str { + void push_back(int) {} + }; + public: + null_parse_context() {} + bool set_null() { return true; } + bool set_bool(bool) { return true; } +#ifdef PICOJSON_USE_INT64 + bool set_int64(int64_t) { return true; } +#endif + bool set_number(double) { return true; } + template bool parse_string(input& in) { + dummy_str s; + return _parse_string(s, in); + } + bool parse_array_start() { return true; } + template bool parse_array_item(input& in, size_t) { + return _parse(*this, in); + } + bool parse_array_stop(size_t) { return true; } + bool parse_object_start() { return true; } + template bool parse_object_item(input& in, const std::string&) { + return _parse(*this, in); + } + private: + null_parse_context(const null_parse_context&); + null_parse_context& operator=(const null_parse_context&); + }; + + // obsolete, use the version below + template inline std::string parse(value& out, Iter& pos, const Iter& last) { + std::string err; + pos = parse(out, pos, last, &err); + return err; + } + + template inline Iter _parse(Context& ctx, const Iter& first, const Iter& last, std::string* err) { + input in(first, last); + if (! _parse(ctx, in) && err != NULL) { + char buf[64]; + SNPRINTF(buf, sizeof(buf), "syntax error at line %d near: ", in.line()); + *err = buf; + while (1) { + int ch = in.getc(); + if (ch == -1 || ch == '\n') { + break; + } else if (ch >= ' ') { + err->push_back(ch); + } + } + } + return in.cur(); + } + + template inline Iter parse(value& out, const Iter& first, const Iter& last, std::string* err) { + default_parse_context ctx(&out); + return _parse(ctx, first, last, err); + } + + inline std::string parse(value& out, const std::string& s) { + std::string err; + parse(out, s.begin(), s.end(), &err); + return err; + } + + inline std::string parse(value& out, std::istream& is) { + std::string err; + parse(out, std::istreambuf_iterator(is.rdbuf()), + std::istreambuf_iterator(), &err); + return err; + } + + template struct last_error_t { + static std::string s; + }; + template std::string last_error_t::s; + + inline void set_last_error(const std::string& s) { + last_error_t::s = s; + } + + inline const std::string& get_last_error() { + return last_error_t::s; + } + + inline bool operator==(const value& x, const value& y) { + if (x.is()) + return y.is(); +#define PICOJSON_CMP(type) \ + if (x.is()) \ + return y.is() && x.get() == y.get() + PICOJSON_CMP(bool); + PICOJSON_CMP(double); + PICOJSON_CMP(std::string); + PICOJSON_CMP(array); + PICOJSON_CMP(object); +#undef PICOJSON_CMP + PICOJSON_ASSERT(0); +#ifdef _MSC_VER + __assume(0); +#endif + return false; + } + + inline bool operator!=(const value& x, const value& y) { + return ! (x == y); + } +} + +#if !PICOJSON_USE_RVALUE_REFERENCE +namespace std { + template<> inline void swap(picojson::value& x, picojson::value& y) + { + x.swap(y); + } +} +#endif + +inline std::istream& operator>>(std::istream& is, picojson::value& x) +{ + picojson::set_last_error(std::string()); + std::string err = picojson::parse(x, is); + if (! err.empty()) { + picojson::set_last_error(err); + is.setstate(std::ios::failbit); + } + return is; +} + +inline std::ostream& operator<<(std::ostream& os, const picojson::value& x) +{ + x.serialize(std::ostream_iterator(os)); + return os; +} +#ifdef _MSC_VER + #pragma warning(pop) +#endif + +#endif diff --git a/third_party/shaderc b/third_party/shaderc new file mode 160000 index 0000000000..f6767fc2df --- /dev/null +++ b/third_party/shaderc @@ -0,0 +1 @@ +Subproject commit f6767fc2df4651d5c6a1d022ea24c946325e8be3 diff --git a/third_party/spirv-cross b/third_party/spirv-cross new file mode 160000 index 0000000000..bd7c47a071 --- /dev/null +++ b/third_party/spirv-cross @@ -0,0 +1 @@ +Subproject commit bd7c47a0711c3551820ca8c994ff468c143a2e20 diff --git a/third_party/spirv-headers b/third_party/spirv-headers new file mode 160000 index 0000000000..90dbe74b1f --- /dev/null +++ b/third_party/spirv-headers @@ -0,0 +1 @@ +Subproject commit 90dbe74b1f182aed7c4bd1cdccf1426df1032c49 diff --git a/third_party/spirv-tools b/third_party/spirv-tools new file mode 160000 index 0000000000..f92e87a8f8 --- /dev/null +++ b/third_party/spirv-tools @@ -0,0 +1 @@ +Subproject commit f92e87a8f85915e8e0cbd39d0ca7fb004c0da05e diff --git a/third_party/stb b/third_party/stb new file mode 160000 index 0000000000..3e7f2d6ebd --- /dev/null +++ b/third_party/stb @@ -0,0 +1 @@ +Subproject commit 3e7f2d6ebddfe54bd9a9491db1349513a357bfe5 diff --git a/third_party/tinygltfloader/tiny_gltf_loader.h b/third_party/tinygltfloader/tiny_gltf_loader.h new file mode 100644 index 0000000000..4792721120 --- /dev/null +++ b/third_party/tinygltfloader/tiny_gltf_loader.h @@ -0,0 +1,2656 @@ +// +// Tiny glTF loader. +// +// +// The MIT License (MIT) +// +// Copyright (c) 2015 - 2016 Syoyo Fujita and many contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +// Version: +// - v0.9.5 Support parsing `extras` parameter. +// - v0.9.4 Support parsing `shader`, `program` and `tecnique` thanks to +// @lukesanantonio +// - v0.9.3 Support binary glTF +// - v0.9.2 Support parsing `texture` +// - v0.9.1 Support loading glTF asset from memory +// - v0.9.0 Initial +// +// Tiny glTF loader is using following third party libraries: +// +// - picojson: C++ JSON library. +// - base64: base64 decode/encode library. +// - stb_image: Image loading library. +// +#ifndef TINY_GLTF_LOADER_H_ +#define TINY_GLTF_LOADER_H_ + +#include +#include +#include +#include +#include + +namespace tinygltf { + +#define TINYGLTF_MODE_POINTS (0) +#define TINYGLTF_MODE_LINE (1) +#define TINYGLTF_MODE_LINE_LOOP (2) +#define TINYGLTF_MODE_TRIANGLES (4) +#define TINYGLTF_MODE_TRIANGLE_STRIP (5) +#define TINYGLTF_MODE_TRIANGLE_FAN (6) + +#define TINYGLTF_COMPONENT_TYPE_BYTE (5120) +#define TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE (5121) +#define TINYGLTF_COMPONENT_TYPE_SHORT (5122) +#define TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT (5123) +#define TINYGLTF_COMPONENT_TYPE_INT (5124) +#define TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT (5125) +#define TINYGLTF_COMPONENT_TYPE_FLOAT (5126) +#define TINYGLTF_COMPONENT_TYPE_DOUBLE (5127) + +#define TINYGLTF_TEXTURE_FILTER_NEAREST (9728) +#define TINYGLTF_TEXTURE_FILTER_LINEAR (9729) +#define TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_NEAREST (9984) +#define TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_NEAREST (9985) +#define TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_LINEAR (9986) +#define TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_LINEAR (9987) + +#define TINYGLTF_TEXTURE_WRAP_RPEAT (10497) +#define TINYGLTF_TEXTURE_WRAP_CLAMP_TO_EDGE (33071) +#define TINYGLTF_TEXTURE_WRAP_MIRRORED_REPEAT (33648) + +// Redeclarations of the above for technique.parameters. +#define TINYGLTF_PARAMETER_TYPE_BYTE (5120) +#define TINYGLTF_PARAMETER_TYPE_UNSIGNED_BYTE (5121) +#define TINYGLTF_PARAMETER_TYPE_SHORT (5122) +#define TINYGLTF_PARAMETER_TYPE_UNSIGNED_SHORT (5123) +#define TINYGLTF_PARAMETER_TYPE_INT (5124) +#define TINYGLTF_PARAMETER_TYPE_UNSIGNED_INT (5125) +#define TINYGLTF_PARAMETER_TYPE_FLOAT (5126) + +#define TINYGLTF_PARAMETER_TYPE_FLOAT_VEC2 (35664) +#define TINYGLTF_PARAMETER_TYPE_FLOAT_VEC3 (35665) +#define TINYGLTF_PARAMETER_TYPE_FLOAT_VEC4 (35666) + +#define TINYGLTF_PARAMETER_TYPE_INT_VEC2 (35667) +#define TINYGLTF_PARAMETER_TYPE_INT_VEC3 (35668) +#define TINYGLTF_PARAMETER_TYPE_INT_VEC4 (35669) + +#define TINYGLTF_PARAMETER_TYPE_BOOL (35670) +#define TINYGLTF_PARAMETER_TYPE_BOOL_VEC2 (35671) +#define TINYGLTF_PARAMETER_TYPE_BOOL_VEC3 (35672) +#define TINYGLTF_PARAMETER_TYPE_BOOL_VEC4 (35673) + +#define TINYGLTF_PARAMETER_TYPE_FLOAT_MAT2 (35674) +#define TINYGLTF_PARAMETER_TYPE_FLOAT_MAT3 (35675) +#define TINYGLTF_PARAMETER_TYPE_FLOAT_MAT4 (35676) + +#define TINYGLTF_PARAMETER_TYPE_SAMPLER_2D (35678) + +// End parameter types + +#define TINYGLTF_TYPE_VEC2 (2) +#define TINYGLTF_TYPE_VEC3 (3) +#define TINYGLTF_TYPE_VEC4 (4) +#define TINYGLTF_TYPE_MAT2 (32 + 2) +#define TINYGLTF_TYPE_MAT3 (32 + 3) +#define TINYGLTF_TYPE_MAT4 (32 + 4) +#define TINYGLTF_TYPE_SCALAR (64 + 1) +#define TINYGLTF_TYPE_VECTOR (64 + 4) +#define TINYGLTF_TYPE_MATRIX (64 + 16) + +#define TINYGLTF_IMAGE_FORMAT_JPEG (0) +#define TINYGLTF_IMAGE_FORMAT_PNG (1) +#define TINYGLTF_IMAGE_FORMAT_BMP (2) +#define TINYGLTF_IMAGE_FORMAT_GIF (3) + +#define TINYGLTF_TEXTURE_FORMAT_ALPHA (6406) +#define TINYGLTF_TEXTURE_FORMAT_RGB (6407) +#define TINYGLTF_TEXTURE_FORMAT_RGBA (6408) +#define TINYGLTF_TEXTURE_FORMAT_LUMINANCE (6409) +#define TINYGLTF_TEXTURE_FORMAT_LUMINANCE_ALPHA (6410) + +#define TINYGLTF_TEXTURE_TARGET_TEXTURE2D (3553) +#define TINYGLTF_TEXTURE_TYPE_UNSIGNED_BYTE (5121) + +#define TINYGLTF_TARGET_ARRAY_BUFFER (34962) +#define TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER (34963) + +#define TINYGLTF_SHADER_TYPE_VERTEX_SHADER (35633) +#define TINYGLTF_SHADER_TYPE_FRAGMENT_SHADER (35632) + +typedef enum { + NULL_TYPE = 0, + NUMBER_TYPE = 1, + INT_TYPE = 2, + BOOL_TYPE = 3, + STRING_TYPE = 4, + ARRAY_TYPE = 5, + BINARY_TYPE = 6, + OBJECT_TYPE = 7 +} Type; + +// Simple class to represent JSON object +class Value { + public: + typedef std::vector Array; + typedef std::map Object; + + Value() : type_(NULL_TYPE) {} + + explicit Value(bool b) : type_(BOOL_TYPE) { boolean_value_ = b; } + explicit Value(int i) : type_(INT_TYPE) { int_value_ = i; } + explicit Value(double n) : type_(NUMBER_TYPE) { number_value_ = n; } + explicit Value(const std::string &s) : type_(STRING_TYPE) { + string_value_ = s; + } + explicit Value(const unsigned char *p, size_t n) : type_(BINARY_TYPE) { + binary_value_.resize(n); + memcpy(binary_value_.data(), p, n); + } + explicit Value(const Array &a) : type_(ARRAY_TYPE) { + array_value_ = Array(a); + } + explicit Value(const Object &o) : type_(OBJECT_TYPE) { + object_value_ = Object(o); + } + + char Type() const { return static_cast(type_); } + + bool IsBool() const { return (type_ == BOOL_TYPE); } + + bool IsInt() const { return (type_ == INT_TYPE); } + + bool IsNumber() const { return (type_ == NUMBER_TYPE); } + + bool IsString() const { return (type_ == STRING_TYPE); } + + bool IsBinary() const { return (type_ == BINARY_TYPE); } + + bool IsArray() const { return (type_ == ARRAY_TYPE); } + + bool IsObject() const { return (type_ == OBJECT_TYPE); } + + // Accessor + template + const T &Get() const; + template + T &Get(); + + // Lookup value from an array + const Value &Get(int idx) const { + static Value &null_value = *(new Value()); + assert(IsArray()); + assert(idx >= 0); + return (static_cast(idx) < array_value_.size()) + ? array_value_[static_cast(idx)] + : null_value; + } + + // Lookup value from a key-value pair + const Value &Get(const std::string &key) const { + static Value &null_value = *(new Value()); + assert(IsObject()); + Object::const_iterator it = object_value_.find(key); + return (it != object_value_.end()) ? it->second : null_value; + } + + size_t ArrayLen() const { + if (!IsArray()) return 0; + return array_value_.size(); + } + + // Valid only for object type. + bool Has(const std::string &key) const { + if (!IsObject()) return false; + Object::const_iterator it = object_value_.find(key); + return (it != object_value_.end()) ? true : false; + } + + // List keys + std::vector Keys() const { + std::vector keys; + if (!IsObject()) return keys; // empty + + for (Object::const_iterator it = object_value_.begin(); + it != object_value_.end(); ++it) { + keys.push_back(it->first); + } + + return keys; + } + + protected: + int type_; + + int int_value_; + double number_value_; + std::string string_value_; + std::vector binary_value_; + Array array_value_; + Object object_value_; + bool boolean_value_; + char pad[3]; + + int pad0; +}; + +#define TINYGLTF_VALUE_GET(ctype, var) \ + template <> \ + inline const ctype &Value::Get() const { \ + return var; \ + } \ + template <> \ + inline ctype &Value::Get() { \ + return var; \ + } +TINYGLTF_VALUE_GET(bool, boolean_value_) +TINYGLTF_VALUE_GET(double, number_value_) +TINYGLTF_VALUE_GET(int, int_value_) +TINYGLTF_VALUE_GET(std::string, string_value_) +TINYGLTF_VALUE_GET(std::vector, binary_value_) +TINYGLTF_VALUE_GET(Value::Array, array_value_) +TINYGLTF_VALUE_GET(Value::Object, object_value_) +#undef TINYGLTF_VALUE_GET + +typedef struct { + std::string string_value; + std::vector number_array; +} Parameter; + +typedef std::map ParameterMap; + +typedef struct { + std::string sampler; + std::string target_id; + std::string target_path; + Value extras; +} AnimationChannel; + +typedef struct { + std::string input; + std::string interpolation; + std::string output; + Value extras; +} AnimationSampler; + +typedef struct { + std::string name; + std::vector channels; + std::map samplers; + ParameterMap parameters; + Value extras; +} Animation; + +typedef struct { + std::string name; + int minFilter; + int magFilter; + int wrapS; + int wrapT; + int wrapR; // TinyGLTF extension + int pad0; + Value extras; +} Sampler; + +typedef struct { + std::string name; + int width; + int height; + int component; + int pad0; + std::vector image; + + std::string bufferView; // KHR_binary_glTF extenstion. + std::string mimeType; // KHR_binary_glTF extenstion. + + Value extras; +} Image; + +typedef struct { + int format; + int internalFormat; + std::string sampler; // Required + std::string source; // Required + int target; + int type; + std::string name; + Value extras; +} Texture; + +typedef struct { + std::string name; + std::string technique; + ParameterMap values; + + Value extras; +} Material; + +typedef struct { + std::string name; + std::string buffer; // Required + size_t byteOffset; // Required + size_t byteLength; // default: 0 + int target; + int pad0; + Value extras; +} BufferView; + +typedef struct { + std::string bufferView; + std::string name; + size_t byteOffset; + size_t byteStride; + int componentType; // One of TINYGLTF_COMPONENT_TYPE_*** + int pad0; + size_t count; + int type; // One of TINYGLTF_TYPE_*** + int pad1; + std::vector minValues; // Optional + std::vector maxValues; // Optional + Value extras; +} Accessor; + +class Camera { + public: + Camera() {} + ~Camera() {} + + std::string name; + bool isOrthographic; // false = perspective. + + // Some common properties. + float aspectRatio; + float yFov; + float zFar; + float zNear; +}; + +typedef struct { + std::map attributes; // A dictionary object of + // strings, where each string + // is the ID of the accessor + // containing an attribute. + std::string material; // The ID of the material to apply to this primitive + // when rendering. + std::string indices; // The ID of the accessor that contains the indices. + int mode; // one of TINYGLTF_MODE_*** + int pad0; + + Value extras; // "extra" property +} Primitive; + +typedef struct { + std::string name; + std::vector primitives; + Value extras; +} Mesh; + +class Node { + public: + Node() {} + ~Node() {} + + std::string camera; // camera object referenced by this node. + + std::string name; + std::vector children; + std::vector rotation; // length must be 0 or 4 + std::vector scale; // length must be 0 or 3 + std::vector translation; // length must be 0 or 3 + std::vector matrix; // length must be 0 or 16 + std::vector meshes; + + Value extras; +}; + +typedef struct { + std::string name; + std::vector data; + Value extras; +} Buffer; + +typedef struct { + std::string name; + int type; + int pad0; + std::vector source; + + Value extras; +} Shader; + +typedef struct { + std::string name; + std::string vertexShader; + std::string fragmentShader; + std::vector attributes; + + Value extras; +} Program; + +typedef struct { + int count; + int pad0; + std::string node; + std::string semantic; + int type; + int pad1; + Parameter value; +} TechniqueParameter; + +typedef struct { + std::string name; + std::string program; + std::map parameters; + std::map attributes; + std::map uniforms; + + Value extras; +} Technique; + +typedef struct { + std::string generator; + std::string version; + std::string profile_api; + std::string profile_version; + bool premultipliedAlpha; + char pad[7]; + Value extras; +} Asset; + +class Scene { + public: + Scene() {} + ~Scene() {} + + std::map accessors; + std::map animations; + std::map buffers; + std::map bufferViews; + std::map materials; + std::map meshes; + std::map nodes; + std::map textures; + std::map images; + std::map shaders; + std::map programs; + std::map techniques; + std::map samplers; + std::map > scenes; // list of nodes + + std::string defaultScene; + + Asset asset; + + Value extras; +}; + +enum SectionCheck { + NO_REQUIRE = 0x00, + REQUIRE_SCENE = 0x01, + REQUIRE_SCENES = 0x02, + REQUIRE_NODES = 0x04, + REQUIRE_ACCESSORS = 0x08, + REQUIRE_BUFFERS = 0x10, + REQUIRE_BUFFER_VIEWS = 0x20, + REQUIRE_ALL = 0x3f +}; + +class TinyGLTFLoader { + public: + TinyGLTFLoader() : bin_data_(NULL), bin_size_(0), is_binary_(false) { + pad[0] = pad[1] = pad[2] = pad[3] = pad[4] = pad[5] = pad[6] = 0; + } + ~TinyGLTFLoader() {} + + /// Loads glTF ASCII asset from a file. + /// Returns false and set error string to `err` if there's an error. + bool LoadASCIIFromFile(Scene *scene, std::string *err, + const std::string &filename, + unsigned int check_sections = REQUIRE_ALL); + + /// Loads glTF ASCII asset from string(memory). + /// `length` = strlen(str); + /// Returns false and set error string to `err` if there's an error. + bool LoadASCIIFromString(Scene *scene, std::string *err, const char *str, + const unsigned int length, + const std::string &base_dir, + unsigned int check_sections = REQUIRE_ALL); + + /// Loads glTF binary asset from a file. + /// Returns false and set error string to `err` if there's an error. + bool LoadBinaryFromFile(Scene *scene, std::string *err, + const std::string &filename, + unsigned int check_sections = REQUIRE_ALL); + + /// Loads glTF binary asset from memory. + /// `length` = strlen(str); + /// Returns false and set error string to `err` if there's an error. + bool LoadBinaryFromMemory(Scene *scene, std::string *err, + const unsigned char *bytes, + const unsigned int length, + const std::string &base_dir = "", + unsigned int check_sections = REQUIRE_ALL); + + private: + /// Loads glTF asset from string(memory). + /// `length` = strlen(str); + /// Returns false and set error string to `err` if there's an error. + bool LoadFromString(Scene *scene, std::string *err, const char *str, + const unsigned int length, const std::string &base_dir, + unsigned int check_sections); + + const unsigned char *bin_data_; + size_t bin_size_; + bool is_binary_; + char pad[7]; +}; + +} // namespace tinygltf + +#ifdef TINYGLTF_LOADER_IMPLEMENTATION +#include +//#include +#include +#include + +#ifdef __clang__ +// Disable some warnings for external files. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wfloat-equal" +#pragma clang diagnostic ignored "-Wexit-time-destructors" +#pragma clang diagnostic ignored "-Wconversion" +#pragma clang diagnostic ignored "-Wold-style-cast" +#pragma clang diagnostic ignored "-Wdouble-promotion" +#pragma clang diagnostic ignored "-Wglobal-constructors" +#pragma clang diagnostic ignored "-Wreserved-id-macro" +#pragma clang diagnostic ignored "-Wdisabled-macro-expansion" +#pragma clang diagnostic ignored "-Wpadded" +#endif + +#define PICOJSON_USE_INT64 +#include "picojson/picojson.h" +#include "stb/stb_image.h" +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#ifdef _WIN32 +#include +#else +#include +#endif + +#if defined(__sparcv9) +// Big endian +#else +#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU +#define TINYGLTF_LITTLE_ENDIAN 1 +#endif +#endif + +namespace tinygltf { + +static void swap4(unsigned int *val) { +#ifdef TINYGLTF_LITTLE_ENDIAN + (void)val; +#else + unsigned int tmp = *val; + unsigned char *dst = reinterpret_cast(val); + unsigned char *src = reinterpret_cast(&tmp); + + dst[0] = src[3]; + dst[1] = src[2]; + dst[2] = src[1]; + dst[3] = src[0]; +#endif +} + +static bool FileExists(const std::string &abs_filename) { + bool ret; +#ifdef _WIN32 + FILE *fp; + errno_t err = fopen_s(&fp, abs_filename.c_str(), "rb"); + if (err != 0) { + return false; + } +#else + FILE *fp = fopen(abs_filename.c_str(), "rb"); +#endif + if (fp) { + ret = true; + fclose(fp); + } else { + ret = false; + } + + return ret; +} + +static std::string ExpandFilePath(const std::string &filepath) { +#ifdef _WIN32 + DWORD len = ExpandEnvironmentStringsA(filepath.c_str(), NULL, 0); + char *str = new char[len]; + ExpandEnvironmentStringsA(filepath.c_str(), str, len); + + std::string s(str); + + delete[] str; + + return s; +#else + +#if defined(TARGET_OS_IPHONE) || defined(TARGET_IPHONE_SIMULATOR) + // no expansion + std::string s = filepath; +#else + std::string s; + wordexp_t p; + + if (filepath.empty()) { + return ""; + } + + // char** w; + int ret = wordexp(filepath.c_str(), &p, 0); + if (ret) { + // err + s = filepath; + return s; + } + + // Use first element only. + if (p.we_wordv) { + s = std::string(p.we_wordv[0]); + wordfree(&p); + } else { + s = filepath; + } + +#endif + + return s; +#endif +} + +static std::string JoinPath(const std::string &path0, + const std::string &path1) { + if (path0.empty()) { + return path1; + } else { + // check '/' + char lastChar = *path0.rbegin(); + if (lastChar != '/') { + return path0 + std::string("/") + path1; + } else { + return path0 + path1; + } + } +} + +static std::string FindFile(const std::vector &paths, + const std::string &filepath) { + for (size_t i = 0; i < paths.size(); i++) { + std::string absPath = ExpandFilePath(JoinPath(paths[i], filepath)); + if (FileExists(absPath)) { + return absPath; + } + } + + return std::string(); +} + +// std::string GetFilePathExtension(const std::string& FileName) +//{ +// if(FileName.find_last_of(".") != std::string::npos) +// return FileName.substr(FileName.find_last_of(".")+1); +// return ""; +//} + +static std::string GetBaseDir(const std::string &filepath) { + if (filepath.find_last_of("/\\") != std::string::npos) + return filepath.substr(0, filepath.find_last_of("/\\")); + return ""; +} + +// std::string base64_encode(unsigned char const* , unsigned int len); +std::string base64_decode(std::string const &s); + +/* + base64.cpp and base64.h + + Copyright (C) 2004-2008 René Nyffenegger + + This source code is provided 'as-is', without any express or implied + warranty. In no event will the author 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 source code must not be misrepresented; you must not + claim that you wrote the original source code. If you use this source code + 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 source code. + + 3. This notice may not be removed or altered from any source distribution. + + René Nyffenegger rene.nyffenegger@adp-gmbh.ch + +*/ + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wexit-time-destructors" +#pragma clang diagnostic ignored "-Wglobal-constructors" +#pragma clang diagnostic ignored "-Wsign-conversion" +#pragma clang diagnostic ignored "-Wconversion" +#endif +static const std::string base64_chars = + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + +static inline bool is_base64(unsigned char c) { + return (isalnum(c) || (c == '+') || (c == '/')); +} + +std::string base64_decode(std::string const &encoded_string) { + int in_len = static_cast(encoded_string.size()); + int i = 0; + int j = 0; + int in_ = 0; + unsigned char char_array_4[4], char_array_3[3]; + std::string ret; + + while (in_len-- && (encoded_string[in_] != '=') && + is_base64(encoded_string[in_])) { + char_array_4[i++] = encoded_string[in_]; + in_++; + if (i == 4) { + for (i = 0; i < 4; i++) + char_array_4[i] = + static_cast(base64_chars.find(char_array_4[i])); + + char_array_3[0] = + (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = + ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + + for (i = 0; (i < 3); i++) ret += char_array_3[i]; + i = 0; + } + } + + if (i) { + for (j = i; j < 4; j++) char_array_4[j] = 0; + + for (j = 0; j < 4; j++) + char_array_4[j] = + static_cast(base64_chars.find(char_array_4[j])); + + char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = + ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + + for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; + } + + return ret; +} +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +static bool LoadExternalFile(std::vector *out, std::string *err, + const std::string &filename, + const std::string &basedir, size_t reqBytes, + bool checkSize) { + out->clear(); + + std::vector paths; + paths.push_back(basedir); + paths.push_back("."); + + std::string filepath = FindFile(paths, filename); + if (filepath.empty()) { + if (err) { + (*err) += "File not found : " + filename + "\n"; + } + return false; + } + + std::ifstream f(filepath.c_str(), std::ifstream::binary); + if (!f) { + if (err) { + (*err) += "File open error : " + filepath + "\n"; + } + return false; + } + + f.seekg(0, f.end); + size_t sz = static_cast(f.tellg()); + std::vector buf(sz); + + f.seekg(0, f.beg); + f.read(reinterpret_cast(&buf.at(0)), + static_cast(sz)); + f.close(); + + if (checkSize) { + if (reqBytes == sz) { + out->swap(buf); + return true; + } else { + std::stringstream ss; + ss << "File size mismatch : " << filepath << ", requestedBytes " + << reqBytes << ", but got " << sz << std::endl; + if (err) { + (*err) += ss.str(); + } + return false; + } + } + + out->swap(buf); + return true; +} + +static bool LoadImageData(Image *image, std::string *err, int req_width, + int req_height, const unsigned char *bytes, + int size) { + int w, h, comp; + unsigned char *data = stbi_load_from_memory(bytes, size, &w, &h, &comp, 0); + if (!data) { + if (err) { + (*err) += "Unknown image format.\n"; + } + return false; + } + + if (w < 1 || h < 1) { + free(data); + if (err) { + (*err) += "Unknown image format.\n"; + } + return false; + } + + if (req_width > 0) { + if (req_width != w) { + free(data); + if (err) { + (*err) += "Image width mismatch.\n"; + } + return false; + } + } + + if (req_height > 0) { + if (req_height != h) { + free(data); + if (err) { + (*err) += "Image height mismatch.\n"; + } + return false; + } + } + + image->width = w; + image->height = h; + image->component = comp; + image->image.resize(static_cast(w * h * comp)); + std::copy(data, data + w * h * comp, image->image.begin()); + + free(data); + + return true; +} + +static bool IsDataURI(const std::string &in) { + std::string header = "data:application/octet-stream;base64,"; + if (in.find(header) == 0) { + return true; + } + + header = "data:image/png;base64,"; + if (in.find(header) == 0) { + return true; + } + + header = "data:image/jpeg;base64,"; + if (in.find(header) == 0) { + return true; + } + + header = "data:text/plain;base64,"; + if (in.find(header) == 0) { + return true; + } + + return false; +} + +static bool DecodeDataURI(std::vector *out, + const std::string &in, size_t reqBytes, + bool checkSize) { + std::string header = "data:application/octet-stream;base64,"; + std::string data; + if (in.find(header) == 0) { + data = base64_decode(in.substr(header.size())); // cut mime string. + } + + if (data.empty()) { + header = "data:image/jpeg;base64,"; + if (in.find(header) == 0) { + data = base64_decode(in.substr(header.size())); // cut mime string. + } + } + + if (data.empty()) { + header = "data:image/png;base64,"; + if (in.find(header) == 0) { + data = base64_decode(in.substr(header.size())); // cut mime string. + } + } + + if (data.empty()) { + header = "data:text/plain;base64,"; + if (in.find(header) == 0) { + data = base64_decode(in.substr(header.size())); + } + } + + if (data.empty()) { + return false; + } + + if (checkSize) { + if (data.size() != reqBytes) { + return false; + } + out->resize(reqBytes); + } else { + out->resize(data.size()); + } + std::copy(data.begin(), data.end(), out->begin()); + return true; +} + +static void ParseObjectProperty(Value *ret, const picojson::object &o) { + tinygltf::Value::Object vo; + picojson::object::const_iterator it(o.begin()); + picojson::object::const_iterator itEnd(o.end()); + + for (; it != itEnd; it++) { + picojson::value v = it->second; + + if (v.is()) { + vo[it->first] = tinygltf::Value(v.get()); + } else if (v.is()) { + vo[it->first] = tinygltf::Value(v.get()); + } else if (v.is()) { + vo[it->first] = + tinygltf::Value(static_cast(v.get())); // truncate + } else if (v.is()) { + vo[it->first] = tinygltf::Value(v.get()); + } else if (v.is()) { + tinygltf::Value child_value; + ParseObjectProperty(&child_value, v.get()); + } + // TODO(syoyo) binary, array + } + + (*ret) = tinygltf::Value(vo); +} + +static bool ParseExtrasProperty(Value *ret, const picojson::object &o) { + picojson::object::const_iterator it = o.find("extras"); + if (it == o.end()) { + return false; + } + + // FIXME(syoyo) Currently we only support `object` type for extras property. + if (!it->second.is()) { + return false; + } + + ParseObjectProperty(ret, it->second.get()); + + return true; +} + +static bool ParseBooleanProperty(bool *ret, std::string *err, + const picojson::object &o, + const std::string &property, bool required) { + picojson::object::const_iterator it = o.find(property); + if (it == o.end()) { + if (required) { + if (err) { + (*err) += "'" + property + "' property is missing.\n"; + } + } + return false; + } + + if (!it->second.is()) { + if (required) { + if (err) { + (*err) += "'" + property + "' property is not a bool type.\n"; + } + } + return false; + } + + if (ret) { + (*ret) = it->second.get(); + } + + return true; +} + +static bool ParseNumberProperty(double *ret, std::string *err, + const picojson::object &o, + const std::string &property, bool required) { + picojson::object::const_iterator it = o.find(property); + if (it == o.end()) { + if (required) { + if (err) { + (*err) += "'" + property + "' property is missing.\n"; + } + } + return false; + } + + if (!it->second.is()) { + if (required) { + if (err) { + (*err) += "'" + property + "' property is not a number type.\n"; + } + } + return false; + } + + if (ret) { + (*ret) = it->second.get(); + } + + return true; +} + +static bool ParseNumberArrayProperty(std::vector *ret, std::string *err, + const picojson::object &o, + const std::string &property, + bool required) { + picojson::object::const_iterator it = o.find(property); + if (it == o.end()) { + if (required) { + if (err) { + (*err) += "'" + property + "' property is missing.\n"; + } + } + return false; + } + + if (!it->second.is()) { + if (required) { + if (err) { + (*err) += "'" + property + "' property is not an array.\n"; + } + } + return false; + } + + ret->clear(); + const picojson::array &arr = it->second.get(); + for (size_t i = 0; i < arr.size(); i++) { + if (!arr[i].is()) { + if (required) { + if (err) { + (*err) += "'" + property + "' property is not a number.\n"; + } + } + return false; + } + ret->push_back(arr[i].get()); + } + + return true; +} + +static bool ParseStringProperty( + std::string *ret, std::string *err, const picojson::object &o, + const std::string &property, bool required, + const std::string &parent_node = std::string()) { + picojson::object::const_iterator it = o.find(property); + if (it == o.end()) { + if (required) { + if (err) { + (*err) += "'" + property + "' property is missing"; + if (parent_node.empty()) { + (*err) += ".\n"; + } else { + (*err) += " in `" + parent_node + "'.\n"; + } + } + } + return false; + } + + if (!it->second.is()) { + if (required) { + if (err) { + (*err) += "'" + property + "' property is not a string type.\n"; + } + } + return false; + } + + if (ret) { + (*ret) = it->second.get(); + } + + return true; +} + +static bool ParseStringArrayProperty(std::vector *ret, + std::string *err, + const picojson::object &o, + const std::string &property, + bool required) { + picojson::object::const_iterator it = o.find(property); + if (it == o.end()) { + if (required) { + if (err) { + (*err) += "'" + property + "' property is missing.\n"; + } + } + return false; + } + + if (!it->second.is()) { + if (required) { + if (err) { + (*err) += "'" + property + "' property is not an array.\n"; + } + } + return false; + } + + ret->clear(); + const picojson::array &arr = it->second.get(); + for (size_t i = 0; i < arr.size(); i++) { + if (!arr[i].is()) { + if (required) { + if (err) { + (*err) += "'" + property + "' property is not a string.\n"; + } + } + return false; + } + ret->push_back(arr[i].get()); + } + + return true; +} + +static bool ParseStringMapProperty(std::map *ret, + std::string *err, const picojson::object &o, + const std::string &property, bool required) { + picojson::object::const_iterator it = o.find(property); + if (it == o.end()) { + if (required) { + if (err) { + (*err) += "'" + property + "' property is missing.\n"; + } + } + return false; + } + + // Make sure we are dealing with an object / dictionary. + if (!it->second.is()) { + if (required) { + if (err) { + (*err) += "'" + property + "' property is not an object.\n"; + } + } + return false; + } + + ret->clear(); + const picojson::object &dict = it->second.get(); + + picojson::object::const_iterator dictIt(dict.begin()); + picojson::object::const_iterator dictItEnd(dict.end()); + + for (; dictIt != dictItEnd; ++dictIt) { + // Check that the value is a string. + if (!dictIt->second.is()) { + if (required) { + if (err) { + (*err) += "'" + property + "' value is not a string.\n"; + } + } + return false; + } + + // Insert into the list. + (*ret)[dictIt->first] = dictIt->second.get(); + } + return true; +} + +static bool ParseKHRBinaryExtension(const picojson::object &o, std::string *err, + std::string *buffer_view, + std::string *mime_type, int *image_width, + int *image_height) { + picojson::object j = o; + + if (j.find("extensions") == j.end()) { + if (err) { + (*err) += "`extensions' property is missing.\n"; + } + return false; + } + + if (!(j["extensions"].is())) { + if (err) { + (*err) += "Invalid `extensions' property.\n"; + } + return false; + } + + picojson::object ext = j["extensions"].get(); + + if (ext.find("KHR_binary_glTF") == ext.end()) { + if (err) { + (*err) += + "`KHR_binary_glTF' property is missing in extension property.\n"; + } + return false; + } + + if (!(ext["KHR_binary_glTF"].is())) { + if (err) { + (*err) += "Invalid `KHR_binary_glTF' property.\n"; + } + return false; + } + + picojson::object k = ext["KHR_binary_glTF"].get(); + + if (!ParseStringProperty(buffer_view, err, k, "bufferView", true)) { + return false; + } + + if (mime_type) { + ParseStringProperty(mime_type, err, k, "mimeType", false); + } + + if (image_width) { + double width = 0.0; + if (ParseNumberProperty(&width, err, k, "width", false)) { + (*image_width) = static_cast(width); + } + } + + if (image_height) { + double height = 0.0; + if (ParseNumberProperty(&height, err, k, "height", false)) { + (*image_height) = static_cast(height); + } + } + + return true; +} + +static bool ParseAsset(Asset *asset, std::string *err, + const picojson::object &o) { + ParseStringProperty(&asset->generator, err, o, "generator", false); + ParseBooleanProperty(&asset->premultipliedAlpha, err, o, "premultipliedAlpha", + false); + + ParseStringProperty(&asset->version, err, o, "version", false); + + picojson::object::const_iterator profile = o.find("profile"); + if (profile != o.end()) { + const picojson::value &v = profile->second; + if (v.contains("api") & v.get("api").is()) { + asset->profile_api = v.get("api").get(); + } + if (v.contains("version") & v.get("version").is()) { + asset->profile_version = v.get("version").get(); + } + } + + return true; +} + +static bool ParseImage(Image *image, std::string *err, + const picojson::object &o, const std::string &basedir, + bool is_binary, const unsigned char *bin_data, + size_t bin_size) { + std::string uri; + if (!ParseStringProperty(&uri, err, o, "uri", true)) { + return false; + } + + ParseStringProperty(&image->name, err, o, "name", false); + + std::vector img; + + if (is_binary) { + // Still binary glTF accepts external dataURI. First try external resources. + bool loaded = false; + if (IsDataURI(uri)) { + loaded = DecodeDataURI(&img, uri, 0, false); + } else { + // Assume external .bin file. + loaded = LoadExternalFile(&img, err, uri, basedir, 0, false); + } + + if (!loaded) { + // load data from (embedded) binary data + + if ((bin_size == 0) || (bin_data == NULL)) { + if (err) { + (*err) += "Invalid binary data.\n"; + } + return false; + } + + // There should be "extensions" property. + // "extensions":{"KHR_binary_glTF":{"bufferView": "id", ... + + std::string buffer_view; + std::string mime_type; + int image_width; + int image_height; + bool ret = ParseKHRBinaryExtension(o, err, &buffer_view, &mime_type, + &image_width, &image_height); + if (!ret) { + return false; + } + + if (uri.compare("data:,") == 0) { + // ok + } else { + if (err) { + (*err) += "Invalid URI for binary data.\n"; + } + return false; + } + + // Just only save some information here. Loading actual image data from + // bufferView is done in other place. + image->bufferView = buffer_view; + image->mimeType = mime_type; + image->width = image_width; + image->height = image_height; + + return true; + } + } else { + if (IsDataURI(uri)) { + if (!DecodeDataURI(&img, uri, 0, false)) { + if (err) { + (*err) += "Failed to decode 'uri' for image parameter.\n"; + } + return false; + } + } else { + // Assume external file + if (!LoadExternalFile(&img, err, uri, basedir, 0, false)) { + if (err) { + (*err) += "Failed to load external 'uri'. for image parameter\n"; + } + return false; + } + if (img.empty()) { + if (err) { + (*err) += "Image is empty.\n"; + } + return false; + } + } + } + + return LoadImageData(image, err, 0, 0, &img.at(0), + static_cast(img.size())); +} + +static bool ParseTexture(Texture *texture, std::string *err, + const picojson::object &o, + const std::string &basedir) { + (void)basedir; + + if (!ParseStringProperty(&texture->sampler, err, o, "sampler", true)) { + return false; + } + + if (!ParseStringProperty(&texture->source, err, o, "source", true)) { + return false; + } + + ParseStringProperty(&texture->name, err, o, "name", false); + + double format = TINYGLTF_TEXTURE_FORMAT_RGBA; + ParseNumberProperty(&format, err, o, "format", false); + + double internalFormat = TINYGLTF_TEXTURE_FORMAT_RGBA; + ParseNumberProperty(&internalFormat, err, o, "internalFormat", false); + + double target = TINYGLTF_TEXTURE_TARGET_TEXTURE2D; + ParseNumberProperty(&target, err, o, "target", false); + + double type = TINYGLTF_TEXTURE_TYPE_UNSIGNED_BYTE; + ParseNumberProperty(&type, err, o, "type", false); + + texture->format = static_cast(format); + texture->internalFormat = static_cast(internalFormat); + texture->target = static_cast(target); + texture->type = static_cast(type); + + return true; +} + +static bool ParseBuffer(Buffer *buffer, std::string *err, + const picojson::object &o, const std::string &basedir, + bool is_binary = false, + const unsigned char *bin_data = NULL, + size_t bin_size = 0) { + double byteLength; + if (!ParseNumberProperty(&byteLength, err, o, "byteLength", true)) { + return false; + } + + std::string uri; + if (!ParseStringProperty(&uri, err, o, "uri", true)) { + return false; + } + + picojson::object::const_iterator type = o.find("type"); + if (type != o.end()) { + if (type->second.is()) { + const std::string &ty = (type->second).get(); + if (ty.compare("arraybuffer") == 0) { + // buffer.type = "arraybuffer"; + } + } + } + + size_t bytes = static_cast(byteLength); + if (is_binary) { + // Still binary glTF accepts external dataURI. First try external resources. + bool loaded = false; + if (IsDataURI(uri)) { + loaded = DecodeDataURI(&buffer->data, uri, bytes, true); + } else { + // Assume external .bin file. + loaded = LoadExternalFile(&buffer->data, err, uri, basedir, bytes, true); + } + + if (!loaded) { + // load data from (embedded) binary data + + if ((bin_size == 0) || (bin_data == NULL)) { + if (err) { + (*err) += "Invalid binary data.\n"; + } + return false; + } + + if (byteLength > bin_size) { + if (err) { + std::stringstream ss; + ss << "Invalid `byteLength'. Must be equal or less than binary size: " + "`byteLength' = " + << byteLength << ", binary size = " << bin_size << std::endl; + (*err) += ss.str(); + } + return false; + } + + if (uri.compare("data:,") == 0) { + // @todo { check uri } + buffer->data.resize(static_cast(byteLength)); + memcpy(&(buffer->data.at(0)), bin_data, + static_cast(byteLength)); + + } else { + if (err) { + (*err) += "Invalid URI for binary data.\n"; + } + return false; + } + } + + } else { + if (IsDataURI(uri)) { + if (!DecodeDataURI(&buffer->data, uri, bytes, true)) { + if (err) { + (*err) += "Failed to decode 'uri'.\n"; + } + return false; + } + } else { + // Assume external .bin file. + if (!LoadExternalFile(&buffer->data, err, uri, basedir, bytes, true)) { + return false; + } + } + } + + ParseStringProperty(&buffer->name, err, o, "name", false); + + return true; +} + +static bool ParseBufferView(BufferView *bufferView, std::string *err, + const picojson::object &o) { + std::string buffer; + if (!ParseStringProperty(&buffer, err, o, "buffer", true)) { + return false; + } + + double byteOffset; + if (!ParseNumberProperty(&byteOffset, err, o, "byteOffset", true)) { + return false; + } + + double byteLength = 0.0; + ParseNumberProperty(&byteLength, err, o, "byteLength", false); + + double target = 0.0; + ParseNumberProperty(&target, err, o, "target", false); + int targetValue = static_cast(target); + if ((targetValue == TINYGLTF_TARGET_ARRAY_BUFFER) || + (targetValue == TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER)) { + // OK + } else { + targetValue = 0; + } + bufferView->target = targetValue; + + ParseStringProperty(&bufferView->name, err, o, "name", false); + + bufferView->buffer = buffer; + bufferView->byteOffset = static_cast(byteOffset); + bufferView->byteLength = static_cast(byteLength); + + return true; +} + +static bool ParseAccessor(Accessor *accessor, std::string *err, + const picojson::object &o) { + std::string bufferView; + if (!ParseStringProperty(&bufferView, err, o, "bufferView", true)) { + return false; + } + + double byteOffset; + if (!ParseNumberProperty(&byteOffset, err, o, "byteOffset", true)) { + return false; + } + + double componentType; + if (!ParseNumberProperty(&componentType, err, o, "componentType", true)) { + return false; + } + + double count = 0.0; + if (!ParseNumberProperty(&count, err, o, "count", true)) { + return false; + } + + std::string type; + if (!ParseStringProperty(&type, err, o, "type", true)) { + return false; + } + + if (type.compare("SCALAR") == 0) { + accessor->type = TINYGLTF_TYPE_SCALAR; + } else if (type.compare("VEC2") == 0) { + accessor->type = TINYGLTF_TYPE_VEC2; + } else if (type.compare("VEC3") == 0) { + accessor->type = TINYGLTF_TYPE_VEC3; + } else if (type.compare("VEC4") == 0) { + accessor->type = TINYGLTF_TYPE_VEC4; + } else if (type.compare("MAT2") == 0) { + accessor->type = TINYGLTF_TYPE_MAT2; + } else if (type.compare("MAT3") == 0) { + accessor->type = TINYGLTF_TYPE_MAT3; + } else if (type.compare("MAT4") == 0) { + accessor->type = TINYGLTF_TYPE_MAT4; + } else { + std::stringstream ss; + ss << "Unsupported `type` for accessor object. Got \"" << type << "\"\n"; + if (err) { + (*err) += ss.str(); + } + return false; + } + + double byteStride = 0.0; + ParseNumberProperty(&byteStride, err, o, "byteStride", false); + + ParseStringProperty(&accessor->name, err, o, "name", false); + + accessor->minValues.clear(); + accessor->maxValues.clear(); + ParseNumberArrayProperty(&accessor->minValues, err, o, "min", false); + ParseNumberArrayProperty(&accessor->maxValues, err, o, "max", false); + + accessor->count = static_cast(count); + accessor->bufferView = bufferView; + accessor->byteOffset = static_cast(byteOffset); + accessor->byteStride = static_cast(byteStride); + + { + int comp = static_cast(componentType); + if (comp >= TINYGLTF_COMPONENT_TYPE_BYTE && + comp <= TINYGLTF_COMPONENT_TYPE_DOUBLE) { + // OK + accessor->componentType = comp; + } else { + std::stringstream ss; + ss << "Invalid `componentType` in accessor. Got " << comp << "\n"; + if (err) { + (*err) += ss.str(); + } + return false; + } + } + + ParseExtrasProperty(&(accessor->extras), o); + + return true; +} + +static bool ParsePrimitive(Primitive *primitive, std::string *err, + const picojson::object &o) { + if (!ParseStringProperty(&primitive->material, err, o, "material", true, + "mesh.primitive")) { + return false; + } + + double mode = static_cast(TINYGLTF_MODE_TRIANGLES); + ParseNumberProperty(&mode, err, o, "mode", false); + + int primMode = static_cast(mode); + primitive->mode = primMode; + + primitive->indices = ""; + ParseStringProperty(&primitive->indices, err, o, "indices", false); + + ParseStringMapProperty(&primitive->attributes, err, o, "attributes", false); + + ParseExtrasProperty(&(primitive->extras), o); + + return true; +} + +static bool ParseMesh(Mesh *mesh, std::string *err, const picojson::object &o) { + ParseStringProperty(&mesh->name, err, o, "name", false); + + mesh->primitives.clear(); + picojson::object::const_iterator primObject = o.find("primitives"); + if ((primObject != o.end()) && (primObject->second).is()) { + const picojson::array &primArray = + (primObject->second).get(); + for (size_t i = 0; i < primArray.size(); i++) { + Primitive primitive; + if (ParsePrimitive(&primitive, err, + primArray[i].get())) { + // Only add the primitive if the parsing succeeds. + mesh->primitives.push_back(primitive); + } + } + } + + ParseExtrasProperty(&(mesh->extras), o); + + return true; +} + +static bool ParseNode(Node *node, std::string *err, const picojson::object &o) { + ParseStringProperty(&node->name, err, o, "name", false); + + ParseNumberArrayProperty(&node->rotation, err, o, "rotation", false); + ParseNumberArrayProperty(&node->scale, err, o, "scale", false); + ParseNumberArrayProperty(&node->translation, err, o, "translation", false); + ParseNumberArrayProperty(&node->matrix, err, o, "matrix", false); + ParseStringArrayProperty(&node->meshes, err, o, "meshes", false); + + node->children.clear(); + picojson::object::const_iterator childrenObject = o.find("children"); + if ((childrenObject != o.end()) && + (childrenObject->second).is()) { + const picojson::array &childrenArray = + (childrenObject->second).get(); + for (size_t i = 0; i < childrenArray.size(); i++) { + if (!childrenArray[i].is()) { + if (err) { + (*err) += "Invalid `children` array.\n"; + } + return false; + } + const std::string &childrenNode = childrenArray[i].get(); + node->children.push_back(childrenNode); + } + } + + ParseExtrasProperty(&(node->extras), o); + + return true; +} + +static bool ParseParameterProperty(Parameter *param, std::string *err, + const picojson::object &o, + const std::string &prop, bool required) { + double num_val; + + // A parameter value can either be a string or an array of either a boolean or + // a number. Booleans of any kind aren't supported here. Granted, it + // complicates the Parameter structure and breaks it semantically in the sense + // that the client probably works off the assumption that if the string is + // empty the vector is used, etc. Would a tagged union work? + if (ParseStringProperty(¶m->string_value, err, o, prop, false)) { + // Found string property. + return true; + } else if (ParseNumberArrayProperty(¶m->number_array, err, o, prop, + false)) { + // Found a number array. + return true; + } else if (ParseNumberProperty(&num_val, err, o, prop, false)) { + param->number_array.push_back(num_val); + return true; + } else { + if (required) { + if (err) { + (*err) += "parameter must be a string or number / number array.\n"; + } + } + return false; + } +} + +static bool ParseMaterial(Material *material, std::string *err, + const picojson::object &o) { + ParseStringProperty(&material->name, err, o, "name", false); + ParseStringProperty(&material->technique, err, o, "technique", false); + + material->values.clear(); + picojson::object::const_iterator valuesIt = o.find("values"); + + if ((valuesIt != o.end()) && (valuesIt->second).is()) { + const picojson::object &values_object = + (valuesIt->second).get(); + + picojson::object::const_iterator it(values_object.begin()); + picojson::object::const_iterator itEnd(values_object.end()); + + for (; it != itEnd; it++) { + Parameter param; + if (ParseParameterProperty(¶m, err, values_object, it->first, + false)) { + material->values[it->first] = param; + } + } + } + + ParseExtrasProperty(&(material->extras), o); + + return true; +} + +static bool ParseShader(Shader *shader, std::string *err, + const picojson::object &o, const std::string &basedir, + bool is_binary = false, + const unsigned char *bin_data = NULL, + size_t bin_size = 0) { + std::string uri; + if (!ParseStringProperty(&uri, err, o, "uri", true)) { + return false; + } + + if (is_binary) { + // Still binary glTF accepts external dataURI. First try external resources. + bool loaded = false; + if (IsDataURI(uri)) { + loaded = DecodeDataURI(&shader->source, uri, 0, false); + } else { + // Assume external .bin file. + loaded = LoadExternalFile(&shader->source, err, uri, basedir, 0, false); + } + + if (!loaded) { + // load data from (embedded) binary data + + if ((bin_size == 0) || (bin_data == NULL)) { + if (err) { + (*err) += "Invalid binary data.\n"; + } + return false; + } + + // There should be "extensions" property. + // "extensions":{"KHR_binary_glTF":{"bufferView": "id", ... + + std::string buffer_view; + std::string mime_type; + int image_width; + int image_height; + bool ret = ParseKHRBinaryExtension(o, err, &buffer_view, &mime_type, + &image_width, &image_height); + if (!ret) { + return false; + } + + if (uri.compare("data:,") == 0) { + // ok + } else { + if (err) { + (*err) += "Invalid URI for binary data.\n"; + } + return false; + } + } + } else { + // Load shader source from data uri + // TODO(syoyo): Support ascii or utf-8 data uris. + if (IsDataURI(uri)) { + if (!DecodeDataURI(&shader->source, uri, 0, false)) { + if (err) { + (*err) += "Failed to decode 'uri' for shader parameter.\n"; + } + return false; + } + } else { + // Assume external file + if (!LoadExternalFile(&shader->source, err, uri, basedir, 0, false)) { + if (err) { + (*err) += "Failed to load external 'uri' for shader parameter.\n"; + } + return false; + } + if (shader->source.empty()) { + if (err) { + (*err) += "shader is empty.\n"; // This may be OK? + } + return false; + } + } + } + + double type; + if (!ParseNumberProperty(&type, err, o, "type", true)) { + return false; + } + + shader->type = static_cast(type); + + ParseExtrasProperty(&(shader->extras), o); + + return true; +} + +static bool ParseProgram(Program *program, std::string *err, + const picojson::object &o) { + ParseStringProperty(&program->name, err, o, "name", false); + + if (!ParseStringProperty(&program->vertexShader, err, o, "vertexShader", + true)) { + return false; + } + if (!ParseStringProperty(&program->fragmentShader, err, o, "fragmentShader", + true)) { + return false; + } + + // I suppose the list of attributes isn't needed, but a technique doesn't + // really make sense without it. + ParseStringArrayProperty(&program->attributes, err, o, "attributes", false); + + ParseExtrasProperty(&(program->extras), o); + + return true; +} + +static bool ParseTechniqueParameter(TechniqueParameter *param, std::string *err, + const picojson::object &o) { + double count = 1; + ParseNumberProperty(&count, err, o, "count", false); + + double type; + if (!ParseNumberProperty(&type, err, o, "type", true)) { + return false; + } + + ParseStringProperty(¶m->node, err, o, "node", false); + ParseStringProperty(¶m->semantic, err, o, "semantic", false); + + ParseParameterProperty(¶m->value, err, o, "value", false); + + param->count = static_cast(count); + param->type = static_cast(type); + + return true; +} + +static bool ParseTechnique(Technique *technique, std::string *err, + const picojson::object &o) { + ParseStringProperty(&technique->name, err, o, "name", false); + + if (!ParseStringProperty(&technique->program, err, o, "program", true)) { + return false; + } + + ParseStringMapProperty(&technique->attributes, err, o, "attributes", false); + ParseStringMapProperty(&technique->uniforms, err, o, "uniforms", false); + + technique->parameters.clear(); + picojson::object::const_iterator paramsIt = o.find("parameters"); + + // Verify parameters is an object + if ((paramsIt != o.end()) && (paramsIt->second).is()) { + // For each parameter in params_object. + const picojson::object ¶ms_object = + (paramsIt->second).get(); + + picojson::object::const_iterator it(params_object.begin()); + picojson::object::const_iterator itEnd(params_object.end()); + + for (; it != itEnd; it++) { + TechniqueParameter param; + + // Skip non-objects + if (!it->second.is()) continue; + + // Parse the technique parameter + const picojson::object ¶m_obj = it->second.get(); + if (ParseTechniqueParameter(¶m, err, param_obj)) { + // Add if successful + technique->parameters[it->first] = param; + } + } + } + + ParseExtrasProperty(&(technique->extras), o); + + return true; +} + +static bool ParseAnimationChannel(AnimationChannel *channel, std::string *err, + const picojson::object &o) { + if (!ParseStringProperty(&channel->sampler, err, o, "sampler", true)) { + if (err) { + (*err) += "`sampler` field is missing in animation channels\n"; + } + return false; + } + + picojson::object::const_iterator targetIt = o.find("target"); + if ((targetIt != o.end()) && (targetIt->second).is()) { + const picojson::object &target_object = + (targetIt->second).get(); + + if (!ParseStringProperty(&channel->target_id, err, target_object, "id", + true)) { + if (err) { + (*err) += "`id` field is missing in animation.channels.target\n"; + } + return false; + } + + if (!ParseStringProperty(&channel->target_path, err, target_object, "path", + true)) { + if (err) { + (*err) += "`path` field is missing in animation.channels.target\n"; + } + return false; + } + } + + ParseExtrasProperty(&(channel->extras), o); + + return true; +} + +static bool ParseAnimation(Animation *animation, std::string *err, + const picojson::object &o) { + { + picojson::object::const_iterator channelsIt = o.find("channels"); + if ((channelsIt != o.end()) && (channelsIt->second).is()) { + const picojson::array &channelArray = + (channelsIt->second).get(); + for (size_t i = 0; i < channelArray.size(); i++) { + AnimationChannel channel; + if (ParseAnimationChannel(&channel, err, + channelArray[i].get())) { + // Only add the channel if the parsing succeeds. + animation->channels.push_back(channel); + } + } + } + } + + { + picojson::object::const_iterator samplerIt = o.find("samplers"); + if ((samplerIt != o.end()) && (samplerIt->second).is()) { + const picojson::object &sampler_object = + (samplerIt->second).get(); + + picojson::object::const_iterator it = sampler_object.begin(); + picojson::object::const_iterator itEnd = sampler_object.end(); + + for (; it != itEnd; it++) { + // Skip non-objects + if (!it->second.is()) continue; + + const picojson::object &s = it->second.get(); + + AnimationSampler sampler; + if (!ParseStringProperty(&sampler.input, err, s, "input", true)) { + if (err) { + (*err) += "`input` field is missing in animation.sampler\n"; + } + return false; + } + if (!ParseStringProperty(&sampler.interpolation, err, s, + "interpolation", true)) { + if (err) { + (*err) += "`interpolation` field is missing in animation.sampler\n"; + } + return false; + } + if (!ParseStringProperty(&sampler.output, err, s, "output", true)) { + if (err) { + (*err) += "`output` field is missing in animation.sampler\n"; + } + return false; + } + + animation->samplers[it->first] = sampler; + } + } + } + + picojson::object::const_iterator parametersIt = o.find("parameters"); + if ((parametersIt != o.end()) && + (parametersIt->second).is()) { + const picojson::object ¶meters_object = + (parametersIt->second).get(); + + picojson::object::const_iterator it(parameters_object.begin()); + picojson::object::const_iterator itEnd(parameters_object.end()); + + for (; it != itEnd; it++) { + Parameter param; + if (ParseParameterProperty(¶m, err, parameters_object, it->first, + false)) { + animation->parameters[it->first] = param; + } + } + } + ParseStringProperty(&animation->name, err, o, "name", false); + + ParseExtrasProperty(&(animation->extras), o); + + return true; +} + +static bool ParseSampler(Sampler *sampler, std::string *err, + const picojson::object &o) { + ParseStringProperty(&sampler->name, err, o, "name", false); + + double minFilter = + static_cast(TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_LINEAR); + double magFilter = static_cast(TINYGLTF_TEXTURE_FILTER_LINEAR); + double wrapS = static_cast(TINYGLTF_TEXTURE_WRAP_RPEAT); + double wrapT = static_cast(TINYGLTF_TEXTURE_WRAP_RPEAT); + ParseNumberProperty(&minFilter, err, o, "minFilter", false); + ParseNumberProperty(&magFilter, err, o, "magFilter", false); + ParseNumberProperty(&wrapS, err, o, "wrapS", false); + ParseNumberProperty(&wrapT, err, o, "wrapT", false); + + sampler->minFilter = static_cast(minFilter); + sampler->magFilter = static_cast(magFilter); + sampler->wrapS = static_cast(wrapS); + sampler->wrapT = static_cast(wrapT); + + ParseExtrasProperty(&(sampler->extras), o); + + return true; +} + +bool TinyGLTFLoader::LoadFromString(Scene *scene, std::string *err, + const char *str, unsigned int length, + const std::string &base_dir, + unsigned int check_sections) { + picojson::value v; + std::string perr = picojson::parse(v, str, str + length); + + if (!perr.empty()) { + if (err) { + (*err) = perr; + } + return false; + } + + if (v.contains("scene") && v.get("scene").is()) { + // OK + } else if (check_sections & REQUIRE_SCENE) { + if (err) { + (*err) += "\"scene\" object not found in .gltf\n"; + } + return false; + } + + if (v.contains("scenes") && v.get("scenes").is()) { + // OK + } else if (check_sections & REQUIRE_SCENES) { + if (err) { + (*err) += "\"scenes\" object not found in .gltf\n"; + } + return false; + } + + if (v.contains("nodes") && v.get("nodes").is()) { + // OK + } else if (check_sections & REQUIRE_NODES) { + if (err) { + (*err) += "\"nodes\" object not found in .gltf\n"; + } + return false; + } + + if (v.contains("accessors") && v.get("accessors").is()) { + // OK + } else if (check_sections & REQUIRE_ACCESSORS) { + if (err) { + (*err) += "\"accessors\" object not found in .gltf\n"; + } + return false; + } + + if (v.contains("buffers") && v.get("buffers").is()) { + // OK + } else if (check_sections & REQUIRE_BUFFERS) { + if (err) { + (*err) += "\"buffers\" object not found in .gltf\n"; + } + return false; + } + + if (v.contains("bufferViews") && + v.get("bufferViews").is()) { + // OK + } else if (check_sections & REQUIRE_BUFFER_VIEWS) { + if (err) { + (*err) += "\"bufferViews\" object not found in .gltf\n"; + } + return false; + } + + scene->buffers.clear(); + scene->bufferViews.clear(); + scene->accessors.clear(); + scene->meshes.clear(); + scene->nodes.clear(); + scene->defaultScene = ""; + + // 0. Parse Asset + if (v.contains("asset") && v.get("asset").is()) { + const picojson::object &root = v.get("asset").get(); + + ParseAsset(&scene->asset, err, root); + } + + // 1. Parse Buffer + if (v.contains("buffers") && v.get("buffers").is()) { + const picojson::object &root = v.get("buffers").get(); + + picojson::object::const_iterator it(root.begin()); + picojson::object::const_iterator itEnd(root.end()); + for (; it != itEnd; it++) { + Buffer buffer; + if (!ParseBuffer(&buffer, err, (it->second).get(), + base_dir, is_binary_, bin_data_, bin_size_)) { + return false; + } + + scene->buffers[it->first] = buffer; + } + } + + // 2. Parse BufferView + if (v.contains("bufferViews") && + v.get("bufferViews").is()) { + const picojson::object &root = v.get("bufferViews").get(); + + picojson::object::const_iterator it(root.begin()); + picojson::object::const_iterator itEnd(root.end()); + for (; it != itEnd; it++) { + BufferView bufferView; + if (!ParseBufferView(&bufferView, err, + (it->second).get())) { + return false; + } + + scene->bufferViews[it->first] = bufferView; + } + } + + // 3. Parse Accessor + if (v.contains("accessors") && v.get("accessors").is()) { + const picojson::object &root = v.get("accessors").get(); + + picojson::object::const_iterator it(root.begin()); + picojson::object::const_iterator itEnd(root.end()); + for (; it != itEnd; it++) { + Accessor accessor; + if (!ParseAccessor(&accessor, err, + (it->second).get())) { + return false; + } + + scene->accessors[it->first] = accessor; + } + } + + // 4. Parse Mesh + if (v.contains("meshes") && v.get("meshes").is()) { + const picojson::object &root = v.get("meshes").get(); + + picojson::object::const_iterator it(root.begin()); + picojson::object::const_iterator itEnd(root.end()); + for (; it != itEnd; it++) { + Mesh mesh; + if (!ParseMesh(&mesh, err, (it->second).get())) { + return false; + } + + scene->meshes[it->first] = mesh; + } + } + + // 5. Parse Node + if (v.contains("nodes") && v.get("nodes").is()) { + const picojson::object &root = v.get("nodes").get(); + + picojson::object::const_iterator it(root.begin()); + picojson::object::const_iterator itEnd(root.end()); + for (; it != itEnd; it++) { + Node node; + if (!ParseNode(&node, err, (it->second).get())) { + return false; + } + + scene->nodes[it->first] = node; + } + } + + // 6. Parse scenes. + if (v.contains("scenes") && v.get("scenes").is()) { + const picojson::object &root = v.get("scenes").get(); + + picojson::object::const_iterator it(root.begin()); + picojson::object::const_iterator itEnd(root.end()); + for (; it != itEnd; it++) { + if (!((it->second).is())) { + if (err) { + (*err) += "`scenes' does not contain an object."; + } + return false; + } + const picojson::object &o = (it->second).get(); + std::vector nodes; + if (!ParseStringArrayProperty(&nodes, err, o, "nodes", false)) { + return false; + } + + scene->scenes[it->first] = nodes; + } + } + + // 7. Parse default scenes. + if (v.contains("scene") && v.get("scene").is()) { + const std::string defaultScene = v.get("scene").get(); + + scene->defaultScene = defaultScene; + } + + // 8. Parse Material + if (v.contains("materials") && v.get("materials").is()) { + const picojson::object &root = v.get("materials").get(); + + picojson::object::const_iterator it(root.begin()); + picojson::object::const_iterator itEnd(root.end()); + for (; it != itEnd; it++) { + Material material; + if (!ParseMaterial(&material, err, + (it->second).get())) { + return false; + } + + scene->materials[it->first] = material; + } + } + + // 9. Parse Image + if (v.contains("images") && v.get("images").is()) { + const picojson::object &root = v.get("images").get(); + + picojson::object::const_iterator it(root.begin()); + picojson::object::const_iterator itEnd(root.end()); + for (; it != itEnd; it++) { + Image image; + if (!ParseImage(&image, err, (it->second).get(), + base_dir, is_binary_, bin_data_, bin_size_)) { + return false; + } + + if (!image.bufferView.empty()) { + // Load image from the buffer view. + if (scene->bufferViews.find(image.bufferView) == + scene->bufferViews.end()) { + if (err) { + std::stringstream ss; + ss << "bufferView \"" << image.bufferView + << "\" not found in the scene." << std::endl; + (*err) += ss.str(); + } + return false; + } + + const BufferView &bufferView = scene->bufferViews[image.bufferView]; + const Buffer &buffer = scene->buffers[bufferView.buffer]; + + bool ret = LoadImageData(&image, err, image.width, image.height, + &buffer.data[bufferView.byteOffset], + static_cast(bufferView.byteLength)); + if (!ret) { + return false; + } + } + + scene->images[it->first] = image; + } + } + + // 10. Parse Texture + if (v.contains("textures") && v.get("textures").is()) { + const picojson::object &root = v.get("textures").get(); + + picojson::object::const_iterator it(root.begin()); + picojson::object::const_iterator itEnd(root.end()); + for (; it != itEnd; it++) { + Texture texture; + if (!ParseTexture(&texture, err, (it->second).get(), + base_dir)) { + return false; + } + + scene->textures[it->first] = texture; + } + } + + // 11. Parse Shader + if (v.contains("shaders") && v.get("shaders").is()) { + const picojson::object &root = v.get("shaders").get(); + + picojson::object::const_iterator it(root.begin()); + picojson::object::const_iterator itEnd(root.end()); + for (; it != itEnd; ++it) { + Shader shader; + if (!ParseShader(&shader, err, (it->second).get(), + base_dir, is_binary_, bin_data_, bin_size_)) { + return false; + } + + scene->shaders[it->first] = shader; + } + } + + // 12. Parse Program + if (v.contains("programs") && v.get("programs").is()) { + const picojson::object &root = v.get("programs").get(); + + picojson::object::const_iterator it(root.begin()); + picojson::object::const_iterator itEnd(root.end()); + for (; it != itEnd; ++it) { + Program program; + if (!ParseProgram(&program, err, (it->second).get())) { + return false; + } + + scene->programs[it->first] = program; + } + } + + // 13. Parse Technique + if (v.contains("techniques") && v.get("techniques").is()) { + const picojson::object &root = v.get("techniques").get(); + + picojson::object::const_iterator it(root.begin()); + picojson::object::const_iterator itEnd(root.end()); + for (; it != itEnd; ++it) { + Technique technique; + if (!ParseTechnique(&technique, err, + (it->second).get())) { + return false; + } + + scene->techniques[it->first] = technique; + } + } + + // 14. Parse Animation + if (v.contains("animations") && v.get("animations").is()) { + const picojson::object &root = v.get("animations").get(); + + picojson::object::const_iterator it(root.begin()); + picojson::object::const_iterator itEnd(root.end()); + for (; it != itEnd; ++it) { + Animation animation; + if (!ParseAnimation(&animation, err, + (it->second).get())) { + return false; + } + + scene->animations[it->first] = animation; + } + } + + // 15. Parse Sampler + if (v.contains("samplers") && v.get("samplers").is()) { + const picojson::object &root = v.get("samplers").get(); + + picojson::object::const_iterator it(root.begin()); + picojson::object::const_iterator itEnd(root.end()); + for (; it != itEnd; ++it) { + Sampler sampler; + if (!ParseSampler(&sampler, err, (it->second).get())) { + return false; + } + + scene->samplers[it->first] = sampler; + } + } + return true; +} + +bool TinyGLTFLoader::LoadASCIIFromString(Scene *scene, std::string *err, + const char *str, unsigned int length, + const std::string &base_dir, + unsigned int check_sections) { + is_binary_ = false; + bin_data_ = NULL; + bin_size_ = 0; + + return LoadFromString(scene, err, str, length, base_dir, check_sections); +} + +bool TinyGLTFLoader::LoadASCIIFromFile(Scene *scene, std::string *err, + const std::string &filename, + unsigned int check_sections) { + std::stringstream ss; + + std::ifstream f(filename.c_str()); + if (!f) { + ss << "Failed to open file: " << filename << std::endl; + if (err) { + (*err) = ss.str(); + } + return false; + } + + f.seekg(0, f.end); + size_t sz = static_cast(f.tellg()); + std::vector buf(sz); + + if (sz == 0) { + if (err) { + (*err) = "Empty file."; + } + return false; + } + + f.seekg(0, f.beg); + f.read(&buf.at(0), static_cast(sz)); + f.close(); + + std::string basedir = GetBaseDir(filename); + + bool ret = LoadASCIIFromString(scene, err, &buf.at(0), + static_cast(buf.size()), basedir, + check_sections); + + return ret; +} + +bool TinyGLTFLoader::LoadBinaryFromMemory(Scene *scene, std::string *err, + const unsigned char *bytes, + unsigned int size, + const std::string &base_dir, + unsigned int check_sections) { + if (size < 20) { + if (err) { + (*err) = "Too short data size for glTF Binary."; + } + return false; + } + + if (bytes[0] == 'g' && bytes[1] == 'l' && bytes[2] == 'T' && + bytes[3] == 'F') { + // ok + } else { + if (err) { + (*err) = "Invalid magic."; + } + return false; + } + + unsigned int version; // 4 bytes + unsigned int length; // 4 bytes + unsigned int scene_length; // 4 bytes + unsigned int scene_format; // 4 bytes; + + // @todo { Endian swap for big endian machine. } + memcpy(&version, bytes + 4, 4); + swap4(&version); + memcpy(&length, bytes + 8, 4); + swap4(&length); + memcpy(&scene_length, bytes + 12, 4); + swap4(&scene_length); + memcpy(&scene_format, bytes + 16, 4); + swap4(&scene_format); + + if ((20 + scene_length >= size) || (scene_length < 1) || + (scene_format != 0)) { // 0 = JSON format. + if (err) { + (*err) = "Invalid glTF binary."; + } + return false; + } + + // Extract JSON string. + std::string jsonString(reinterpret_cast(&bytes[20]), + scene_length); + + is_binary_ = true; + bin_data_ = bytes + 20 + scene_length; + bin_size_ = + length - (20 + scene_length); // extract header + JSON scene data. + + bool ret = + LoadFromString(scene, err, reinterpret_cast(&bytes[20]), + scene_length, base_dir, check_sections); + if (!ret) { + return ret; + } + + return true; +} + +bool TinyGLTFLoader::LoadBinaryFromFile(Scene *scene, std::string *err, + const std::string &filename, + unsigned int check_sections) { + std::stringstream ss; + + std::ifstream f(filename.c_str(), std::ios::binary); + if (!f) { + ss << "Failed to open file: " << filename << std::endl; + if (err) { + (*err) = ss.str(); + } + return false; + } + + f.seekg(0, f.end); + size_t sz = static_cast(f.tellg()); + std::vector buf(sz); + + f.seekg(0, f.beg); + f.read(&buf.at(0), static_cast(sz)); + f.close(); + + std::string basedir = GetBaseDir(filename); + + bool ret = LoadBinaryFromMemory( + scene, err, reinterpret_cast(&buf.at(0)), + static_cast(buf.size()), basedir, check_sections); + + return ret; +} + +} // namespace tinygltf + +#endif // TINYGLTF_LOADER_IMPLEMENTATION + +#endif // TINY_GLTF_LOADER_H_